text stringlengths 1 1.05M |
|---|
#include <iostream>
#include <time.h>
#include <cstdlib>
int main()
{
srand(time(NULL));
int randomNum = std::rand() % 9;
std::cout << "Pomysl i wpisz dowolna liczbe od 0 do 9: ";
int num;
std::cin >> num;
std::cout << "Komputer pomyslal " << randomNum << "\n";
(randomNum == num) ? (std::cout << "Brawo! Zgadles jaka liczbe pomyslal komputer") : (std::cout << "Niestety nie zgadles liczby, ktora pomslal komputer");
return 0;
} |
/*
This file is a part of
QVGE - Qt Visual Graph Editor
(c) 2016-2020 Ars L. Masiuk (ars.masiuk@gmail.com)
It can be used freely, maintaining the information above.
*/
#include <QGraphicsSceneMouseEvent>
#include "CPolyEdge.h"
#include "CNode.h"
#include "CControlPoint.h"
CPolyEdge::CPolyEdge(QGraphicsItem *parent): Super(parent)
{
}
void CPolyEdge::setPoints(const QList<QPointF> &points)
{
m_polyPoints = points;
onParentGeometryChanged();
}
bool CPolyEdge::insertPointAt(const QPointF &pos)
{
// no points yet
if (m_polyPoints.isEmpty())
{
m_polyPoints.append(pos);
update();
return true;
}
// find segment for this point
auto points = m_polyPoints;
points.prepend(m_firstNode->pos());
points.append(m_lastNode->pos());
for (int i = 0; i < points.size() - 1; ++i)
{
qreal l1 = QLineF(points.at(i), points.at(i + 1)).length();
qreal l2 = QLineF(points.at(i), pos).length();
qreal l3 = QLineF(pos, points.at(i + 1)).length();
if (qAbs(l1 - (l2 + l3)) < 1)
{
m_polyPoints.insert(i, pos);
update();
return true;
}
}
return false;
}
// reimp
CEdge* CPolyEdge::clone()
{
CPolyEdge* c = new CPolyEdge(parentItem());
// assign directly!
c->m_firstNode = m_firstNode;
c->m_firstPortId = m_firstPortId;
c->m_lastNode = m_lastNode;
c->m_lastPortId = m_lastPortId;
c->m_polyPoints = m_polyPoints;
if (scene())
scene()->addItem(c);
c->copyDataFrom(this);
return c;
}
void CPolyEdge::reverse()
{
std::reverse(m_polyPoints.begin(), m_polyPoints.end());
std::reverse(m_controlPoints.begin(), m_controlPoints.end());
Super::reverse();
}
void CPolyEdge::transform(const QRectF & oldRect, const QRectF & newRect,
double xc, double yc,
bool changeSize, bool changePos)
{
Super::transform(oldRect, newRect, xc, yc, changeSize, changePos);
// snap
//auto scene = getScene();
// transform subpoints as well
for (auto &point : m_polyPoints)
{
double xp = (point.x() - oldRect.left()) * xc + newRect.left();
double yp = (point.y() - oldRect.top()) * yc + newRect.top();
//if (scene)
//{
// QPointF psnap = scene->getSnapped(QPointF(xp,yp));
// point.setX(psnap.x());
// point.setY(psnap.y());
//}
//else
{
point.setX(xp);
point.setY(yp);
}
}
createControlPoints();
updateShapeFromPoints();
}
// attributes
bool CPolyEdge::hasLocalAttribute(const QByteArray& attrId) const
{
if (attrId == "points")
return true;
else
return Super::hasLocalAttribute(attrId);
}
bool CPolyEdge::setAttribute(const QByteArray& attrId, const QVariant& v)
{
if (attrId == "points")
{
QString pointStr = v.toString();
setPoints(CUtils::pointsFromString(pointStr));
return true;
}
return Super::setAttribute(attrId, v);
}
bool CPolyEdge::removeAttribute(const QByteArray& attrId)
{
if (attrId == "points")
{
setPoints({});
return true;
}
return Super::removeAttribute(attrId);
}
// serialization
bool CPolyEdge::storeTo(QDataStream& out, quint64 version64) const
{
Super::storeTo(out, version64);
out << m_polyPoints;
return true;
}
bool CPolyEdge::restoreFrom(QDataStream& out, quint64 version64)
{
if (Super::restoreFrom(out, version64))
{
dropControlPoints();
m_polyPoints.clear();
out >> m_polyPoints;
return true;
}
return false;
}
// mousing
bool CPolyEdge::onDoubleClickDrag(QGraphicsSceneMouseEvent* /*mouseEvent*/, const QPointF &clickPos)
{
// create control point at click pos
if (insertPointAt(clickPos))
{
createControlPoints();
// start drag of the inserted point
for (auto cp : m_controlPoints)
{
if (cp->scenePos() == clickPos)
{
getScene()->startDrag(cp);
return true;
}
}
return false;
}
return false;
}
void CPolyEdge::onControlPointMoved(CControlPoint* /*controlPoint*/, const QPointF& /*pos*/)
{
updateShapeFromPoints();
}
void CPolyEdge::onControlPointDelete(CControlPoint* controlPoint)
{
int index = m_controlPoints.indexOf(controlPoint);
Q_ASSERT(index >= 0);
m_controlPoints.removeAt(index);
delete controlPoint;
updateShapeFromPoints();
addUndoState();
}
// selection
void CPolyEdge::onItemSelected(bool state)
{
Super::onItemSelected(state);
if (!state)
dropControlPoints();
else
createControlPoints();
}
// moving
void CPolyEdge::onItemMoved(const QPointF& delta)
{
for (auto &p : m_polyPoints)
{
p += delta;
}
for (auto cp : m_controlPoints)
{
cp->moveBy(delta.x(), delta.y());
}
}
// drawing
void CPolyEdge::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
// straight line
if (m_polyPoints.isEmpty())
{
Super::paint(painter, option, widget);
return;
}
// selection
drawSelection(painter, option);
// polyline
setupPainter(painter, option, widget);
painter->setClipRect(boundingRect());
painter->save();
painter->setBrush(Qt::NoBrush);
painter->drawPath(m_shapeCachePath);
painter->restore();
qreal r = qMax(3.0, painter->pen().widthF());
painter->setBrush(painter->pen().brush());
for (const QPointF &p : m_polyPoints)
painter->drawEllipse(p, r, r);
// arrows
if (m_itemFlags & CF_Start_Arrow)
{
QLineF arrowLine(m_polyPoints.first(), line().p1());
if (arrowLine.length() > ARROW_SIZE * 2)
drawArrow(painter, option, true, arrowLine);
}
if (m_itemFlags & CF_End_Arrow)
{
QLineF arrowLine(m_polyPoints.last(), line().p2());
if (arrowLine.length() > ARROW_SIZE * 2)
drawArrow(painter, option, true, arrowLine);
}
}
// callbacks
void CPolyEdge::onParentGeometryChanged()
{
// straight line
if (m_polyPoints.isEmpty())
{
Super::onParentGeometryChanged();
return;
}
// optimize: no update while restoring
if (s_duringRestore)
return;
// polyline
if (!m_firstNode || !m_lastNode)
return;
prepareGeometryChange();
// update line position
QPointF p1c = m_firstNode->pos();
if (m_firstPortId.size() && m_firstNode->getPort(m_firstPortId))
p1c = m_firstNode->getPort(m_firstPortId)->scenePos();
QPointF p2c = m_lastNode->pos();
if (m_lastPortId.size() && m_lastNode->getPort(m_lastPortId))
p2c = m_lastNode->getPort(m_lastPortId)->scenePos();
QLineF l1(p1c, m_polyPoints.first());
QPointF p1 = m_firstNode->getIntersectionPoint(l1, m_firstPortId);
QLineF l2(p2c, m_polyPoints.last());
QPointF p2 = m_lastNode->getIntersectionPoint(l2, m_lastPortId);
QLineF l(p1, p2);
setLine(l);
// shift line by arrows
double arrowSize = getVisibleWeight() + ARROW_SIZE;
l1 = QLineF(p1, m_polyPoints.first());
if (l1.length() < 5)
p1 = m_polyPoints.first();
else if (m_itemFlags & CF_Start_Arrow)
{
l1 = CUtils::extendLine(l1, -arrowSize, 0);
p1 = l1.p1();
}
l2 = QLineF(m_polyPoints.last(), p2);
if (l2.length() < 5)
p2 = m_polyPoints.last();
else if (m_itemFlags & CF_End_Arrow)
{
l2 = CUtils::extendLine(l2, 0, arrowSize);
p2 = l2.p2();
}
// update shape path
m_shapeCachePath = QPainterPath();
m_shapeCachePath.moveTo(p1);
for (const QPointF &p : m_polyPoints)
m_shapeCachePath.lineTo(p);
m_shapeCachePath.lineTo(p2);
m_controlPoint = m_shapeCachePath.pointAtPercent(0.5);
QPainterPathStroker stroker;
stroker.setWidth(6);
m_selectionShapePath = stroker.createStroke(m_shapeCachePath);
update();
// update text label
if (getScene() && getScene()->itemLabelsEnabled())
{
updateLabelPosition();
updateLabelDecoration();
}
}
// private
void CPolyEdge::dropControlPoints()
{
qDeleteAll(m_controlPoints);
m_controlPoints.clear();
}
void CPolyEdge::createControlPoints()
{
dropControlPoints();
for (const QPointF &point: m_polyPoints)
{
auto cp = new CControlPoint(this);
// first set position, then flags (to avoid recursion)
cp->setPos(point);
cp->setFlags(ItemIsMovable | ItemSendsGeometryChanges);
m_controlPoints.append(cp);
}
}
void CPolyEdge::updateShapeFromPoints()
{
m_polyPoints.clear();
for (auto cp : m_controlPoints)
{
m_polyPoints.append(cp->scenePos());
}
onParentGeometryChanged();
}
|
#pragma once
#include "ompu/game/game_fwd.hpp"
#include <boost/variant/variant.hpp>
#include <boost/variant/static_visitor.hpp>
#include <boost/preprocessor/stringize.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/seq/enum.hpp>
namespace ompu { namespace game {
namespace scenes {
#define OMPU_GAME_SCENES_DEF \
(Noop)(Title)(Single)
// (Session)
#define OMPU_DEF(r, data, elem) \
struct elem {};
BOOST_PP_SEQ_FOR_EACH(OMPU_DEF, _, OMPU_GAME_SCENES_DEF)
#undef OMPU_DEF
using all_type = boost::variant<
BOOST_PP_SEQ_ENUM(OMPU_GAME_SCENES_DEF)
>;
} // scenes
class SceneNameVisitor : public boost::static_visitor<char const*>
{
public:
using return_type = char const*;
#define OMPU_DEF(r, data, elem) \
return_type operator()(scenes::elem const&) const noexcept \
{ \
return BOOST_PP_STRINGIZE(elem); \
}
BOOST_PP_SEQ_FOR_EACH(OMPU_DEF, _, OMPU_GAME_SCENES_DEF)
#undef OMPU_DEF
};
}} // ompu
|
[global _readr]
[section .text]
_readr:
push edi
push ebp
mov ebp,esp
sub esp,byte 96
push dword 80
lea edi,[ebp + (-80)]
push dword edi
call _readln
add esp,8
mov edi,eax
cmp edi,0
jne near L2
mov eax,0
jmp L1
L2:
lea edi,[ebp + (-80)]
push dword edi
call _atod
add esp,4
fstp qword [ebp + (-96)]
fld qword [ebp + (-96)]
fstp dword [ebp + (-84)]
mov edi,dword [ebp + (-84)]
mov dword [ebp + (-88)],edi
mov eax,dword [ebp + (-88)]
L1:
mov esp,ebp
pop ebp
pop edi
ret
[global _printr]
_printr:
push edi
push ebp
mov ebp,esp
%define P_i 12
sub esp,byte 84
mov edi,dword [ebp + (P_i)]
mov dword [ebp + (-4)],edi
lea edi,[ebp + (-84)]
push dword edi
push dword 7
fld dword [ebp + (-4)]
sub esp,8
fstp qword [esp]
call _dtoa
add esp,16
mov edi,eax
push dword edi
call _prints
add esp,4
L4:
mov esp,ebp
pop ebp
pop edi
ret
[global _readd]
_readd:
push edi
push ebp
mov ebp,esp
sub esp,byte 96
push dword 80
lea edi,[ebp + (-80)]
push dword edi
call _readln
add esp,8
mov edi,eax
cmp edi,0
jne near L6
fld qword [(L8)]
jmp L5
L6:
lea edi,[ebp + (-80)]
push dword edi
call _atod
add esp,4
fstp qword [ebp + (-96)]
fld qword [ebp + (-96)]
fstp qword [ebp + (-88)]
fld qword [ebp + (-88)]
L5:
mov esp,ebp
pop ebp
pop edi
ret
[global _printd]
_printd:
push edi
push ebp
mov ebp,esp
%define P_d 12
sub esp,byte 80
lea edi,[ebp + (-80)]
push dword edi
push dword 7
fld qword [ebp + (P_d)]
sub esp,8
fstp qword [esp]
call _dtoa
add esp,16
mov edi,eax
push dword edi
call _prints
add esp,4
L9:
mov esp,ebp
pop ebp
pop edi
ret
[global _atod]
_atod:
push esi
push edi
push ebp
mov ebp,esp
%define P_s 16
sub esp,byte 20
fld qword [(L8)]
fstp qword [ebp + (-8)]
mov dword [ebp + (-12)],0
mov dword [ebp + (-16)],0
mov dword [ebp + (-20)],1
jmp L12
L11:
inc dword [ebp + (P_s)]
L12:
mov edi,dword [ebp + (P_s)]
movsx edi,byte [edi]
cmp edi,32
je near L11
mov edi,dword [ebp + (P_s)]
movsx edi,byte [edi]
cmp edi,45
jne near L17
mov dword [ebp + (-20)],-1
inc dword [ebp + (P_s)]
jmp L17
L16:
inc dword [ebp + (P_s)]
L17:
mov edi,dword [ebp + (P_s)]
movsx edi,byte [edi]
cmp edi,48
je near L16
jmp L20
L19:
mov edi,dword [ebp + (P_s)]
lea esi,[edi + (1)]
mov dword [ebp + (P_s)],esi
fld qword [(L22)]
fmul qword [ebp + (-8)]
movsx edi,byte [edi]
sub edi,48
push edi
fild dword [esp]
add esp,4
faddp st1
fstp qword [ebp + (-8)]
L20:
mov edi,dword [ebp + (P_s)]
movsx edi,byte [edi]
cmp edi,48
jl near L23
cmp edi,57
jle near L19
L23:
mov edi,dword [ebp + (P_s)]
movsx edi,byte [edi]
cmp edi,46
jne near L24
inc dword [ebp + (P_s)]
jmp L27
L26:
mov edi,dword [ebp + (P_s)]
lea esi,[edi + (1)]
mov dword [ebp + (P_s)],esi
fld qword [(L22)]
fmul qword [ebp + (-8)]
movsx edi,byte [edi]
sub edi,48
push edi
fild dword [esp]
add esp,4
faddp st1
fstp qword [ebp + (-8)]
cmp dword [ebp + (-16)],0
jg near L29
dec dword [ebp + (-16)]
L29:
L27:
mov edi,dword [ebp + (P_s)]
movsx edi,byte [edi]
cmp edi,48
jl near L31
cmp edi,57
jle near L26
L31:
L24:
mov edi,dword [ebp + (P_s)]
movsx edi,byte [edi]
cmp edi,69
je near L34
cmp edi,101
jne near L32
L34:
mov edi,dword [ebp + (P_s)]
lea edi,[edi + (1)]
push dword edi
call _atoi
add esp,4
mov dword [ebp + (-12)],eax
L32:
mov edi,dword [ebp + (-16)]
add dword [ebp + (-12)],edi
cmp dword [ebp + (-12)],0
jle near L41
jmp L38
L37:
fld qword [(L22)]
fmul qword [ebp + (-8)]
fstp qword [ebp + (-8)]
L38:
mov edi,dword [ebp + (-12)]
mov esi,edi
sub esi,1
mov dword [ebp + (-12)],esi
cmp edi,0
jg near L37
jmp L36
L40:
fld qword [ebp + (-8)]
fdiv qword [(L22)]
fstp qword [ebp + (-8)]
L41:
mov edi,dword [ebp + (-12)]
lea esi,[edi + (1)]
mov dword [ebp + (-12)],esi
cmp edi,0
jl near L40
L36:
cmp dword [ebp + (-20)],0
jge near L43
fld qword [ebp + (-8)]
fchs
fstp qword [ebp + (-8)]
L43:
fld qword [ebp + (-8)]
L10:
mov esp,ebp
pop ebp
pop edi
pop esi
ret
[section .bss]
resb ($-$$) & 0
L46:
resb 32
[global _dtoa]
[section .text]
_dtoa:
push ebx
push esi
push edi
push ebp
mov ebp,esp
%define P_d 20
%define P_ndig 28
%define P_s 32
sub esp,byte 24
mov dword [ebp + (-4)],0
mov edi,dword [ebp + (P_s)]
cmp edi,0
jne near L47
lea edi,[(L46)]
mov dword [ebp + (P_s)],edi
L47:
fld qword [(L8)]
fcomp qword [ebp + (P_d)]
fstsw ax
sahf
jne near L49
mov edi,dword [ebp + (P_s)]
mov byte [edi],48
mov edi,dword [ebp + (P_s)]
mov byte [edi + (1)],0
mov eax,dword [ebp + (P_s)]
jmp L45
L49:
fld qword [(L8)]
fcomp qword [ebp + (P_d)]
fstsw ax
sahf
jbe near L51
mov edi,dword [ebp + (-4)]
lea esi,[edi + (1)]
mov dword [ebp + (-4)],esi
mov esi,dword [ebp + (P_s)]
mov byte [esi + edi],45
fld qword [ebp + (P_d)]
fchs
fstp qword [ebp + (P_d)]
L51:
fld qword [(L55)]
fcomp qword [ebp + (P_d)]
fstsw ax
sahf
ja near L53
fld qword [(L55)]
fstp qword [ebp + (-12)]
mov dword [ebp + (-20)],0
jmp L59
L56:
fld qword [(L22)]
fmul qword [ebp + (-12)]
fld qword [ebp + (P_d)]
fcompp
fstsw ax
sahf
jae near L60
jmp L54
L60:
L57:
fld qword [(L22)]
fmul qword [ebp + (-12)]
fstp qword [ebp + (-12)]
inc dword [ebp + (-20)]
L59:
fld qword [(L62)]
fcomp qword [ebp + (-12)]
fstsw ax
sahf
ja near L56
jmp L54
L53:
fld qword [(L67)]
fstp qword [ebp + (-12)]
mov dword [ebp + (-20)],-1
jmp L66
L63:
fld qword [ebp + (P_d)]
fcomp qword [ebp + (-12)]
fstsw ax
sahf
jb near L68
jmp L65
L68:
L64:
fld qword [ebp + (-12)]
fdiv qword [(L22)]
fstp qword [ebp + (-12)]
dec dword [ebp + (-20)]
L66:
fld qword [(L8)]
fcomp qword [ebp + (-12)]
fstsw ax
sahf
jb near L63
L65:
L54:
fld qword [ebp + (P_d)]
fdiv qword [ebp + (-12)]
fstp qword [ebp + (P_d)]
mov dword [ebp + (-16)],0
jmp L73
L70:
fld qword [ebp + (P_d)]
sub esp,byte 4
fistp dword [esp]
pop eax
mov dword [ebp + (-24)],eax
fild dword [ebp + (-24)]
fld qword [ebp + (P_d)]
fcompp
fstsw ax
sahf
jae near L74
dec dword [ebp + (-24)]
L74:
mov edi,dword [ebp + (-4)]
lea esi,[edi + (1)]
mov dword [ebp + (-4)],esi
mov esi,dword [ebp + (P_s)]
mov ebx,dword [ebp + (-24)]
lea ebx,[ebx + (48)]
mov byte [esi + edi],bl
cmp dword [ebp + (-16)],0
jne near L76
mov edi,dword [ebp + (-4)]
lea esi,[edi + (1)]
mov dword [ebp + (-4)],esi
mov esi,dword [ebp + (P_s)]
mov byte [esi + edi],46
L76:
fld qword [(L22)]
fld qword [ebp + (P_d)]
fild dword [ebp + (-24)]
fsubp st1
fmulp st1
fstp qword [ebp + (P_d)]
L71:
inc dword [ebp + (-16)]
L73:
mov edi,dword [ebp + (P_ndig)]
cmp dword [ebp + (-16)],edi
jge near L78
fld qword [(L8)]
fcomp qword [ebp + (P_d)]
fstsw ax
sahf
jne near L70
L78:
fld qword [(L81)]
fcomp qword [ebp + (P_d)]
fstsw ax
sahf
ja near L90
jmp L83
L82:
dec dword [ebp + (-4)]
L83:
mov edi,dword [ebp + (-4)]
sub edi,1
mov esi,dword [ebp + (P_s)]
movsx edi,byte [esi + edi]
cmp edi,57
je near L82
mov edi,dword [ebp + (-4)]
sub edi,1
mov esi,dword [ebp + (P_s)]
movsx edi,byte [esi + edi]
cmp edi,46
je near L85
mov edi,dword [ebp + (-4)]
sub edi,1
mov esi,dword [ebp + (P_s)]
lea edi,[esi + edi]
movsx esi,byte [edi]
lea esi,[esi + (1)]
mov ebx,esi
mov byte [edi],bl
jmp L80
L85:
dec dword [ebp + (-4)]
mov edi,dword [ebp + (-4)]
sub edi,1
mov esi,dword [ebp + (P_s)]
movsx edi,byte [esi + edi]
cmp edi,57
je near L87
mov edi,dword [ebp + (-4)]
sub edi,1
mov esi,dword [ebp + (P_s)]
lea edi,[esi + edi]
movsx esi,byte [edi]
lea esi,[esi + (1)]
mov ebx,esi
mov byte [edi],bl
jmp L80
L87:
mov edi,dword [ebp + (-4)]
sub edi,1
mov esi,dword [ebp + (P_s)]
mov byte [esi + edi],49
inc dword [ebp + (-20)]
jmp L80
L89:
dec dword [ebp + (-4)]
L90:
mov edi,dword [ebp + (-4)]
sub edi,1
mov esi,dword [ebp + (P_s)]
movsx edi,byte [esi + edi]
cmp edi,48
je near L89
L80:
mov edi,dword [ebp + (-4)]
sub edi,1
mov esi,dword [ebp + (P_s)]
movsx edi,byte [esi + edi]
cmp edi,46
jne near L92
dec dword [ebp + (-4)]
L92:
cmp dword [ebp + (-20)],0
je near L94
mov edi,dword [ebp + (-4)]
lea esi,[edi + (1)]
mov dword [ebp + (-4)],esi
mov esi,dword [ebp + (P_s)]
mov byte [esi + edi],69
cmp dword [ebp + (-20)],0
jge near L96
mov edi,dword [ebp + (-4)]
lea esi,[edi + (1)]
mov dword [ebp + (-4)],esi
mov esi,dword [ebp + (P_s)]
mov byte [esi + edi],45
neg dword [ebp + (-20)]
L96:
cmp dword [ebp + (-20)],100
jle near L98
mov edi,dword [ebp + (-4)]
lea esi,[edi + (1)]
mov dword [ebp + (-4)],esi
mov esi,dword [ebp + (P_s)]
mov eax,dword [ebp + (-20)]
mov ebx,100
cdq
idiv ebx
lea ebx,[eax + (48)]
mov byte [esi + edi],bl
mov eax,dword [ebp + (-20)]
mov edi,100
cdq
idiv edi
mov dword [ebp + (-20)],edx
mov edi,dword [ebp + (-4)]
lea esi,[edi + (1)]
mov dword [ebp + (-4)],esi
mov esi,dword [ebp + (P_s)]
mov eax,dword [ebp + (-20)]
mov ebx,10
cdq
idiv ebx
lea ebx,[eax + (48)]
mov byte [esi + edi],bl
mov eax,dword [ebp + (-20)]
mov edi,10
cdq
idiv edi
mov dword [ebp + (-20)],edx
mov edi,dword [ebp + (-4)]
lea esi,[edi + (1)]
mov dword [ebp + (-4)],esi
mov esi,dword [ebp + (P_s)]
mov ebx,dword [ebp + (-20)]
lea ebx,[ebx + (48)]
mov byte [esi + edi],bl
jmp L99
L98:
cmp dword [ebp + (-20)],10
jle near L100
mov edi,dword [ebp + (-4)]
lea esi,[edi + (1)]
mov dword [ebp + (-4)],esi
mov esi,dword [ebp + (P_s)]
mov eax,dword [ebp + (-20)]
mov ebx,10
cdq
idiv ebx
lea ebx,[eax + (48)]
mov byte [esi + edi],bl
mov eax,dword [ebp + (-20)]
mov edi,10
cdq
idiv edi
mov dword [ebp + (-20)],edx
mov edi,dword [ebp + (-4)]
lea esi,[edi + (1)]
mov dword [ebp + (-4)],esi
mov esi,dword [ebp + (P_s)]
mov ebx,dword [ebp + (-20)]
lea ebx,[ebx + (48)]
mov byte [esi + edi],bl
jmp L101
L100:
mov edi,dword [ebp + (-4)]
lea esi,[edi + (1)]
mov dword [ebp + (-4)],esi
mov esi,dword [ebp + (P_s)]
mov ebx,dword [ebp + (-20)]
lea ebx,[ebx + (48)]
mov byte [esi + edi],bl
L101:
L99:
L94:
mov edi,dword [ebp + (-4)]
mov esi,dword [ebp + (P_s)]
mov byte [esi + edi],0
mov eax,dword [ebp + (P_s)]
L45:
mov esp,ebp
pop ebp
pop edi
pop esi
pop ebx
ret
[global _atof]
_atof:
push edi
push ebp
mov ebp,esp
%define P_s 12
sub esp,byte 8
mov edi,dword [ebp + (P_s)]
push dword edi
call _atod
add esp,4
fstp qword [ebp + (-8)]
fld qword [ebp + (-8)]
sub esp,4
fstp dword [esp]
fld dword [esp]
add esp,4
L102:
mov esp,ebp
pop ebp
pop edi
ret
[global _ftoa]
_ftoa:
push edi
push ebp
mov ebp,esp
%define P_f 12
%define P_ndig 16
%define P_s 20
mov edi,dword [ebp + (P_s)]
push dword edi
mov edi,dword [ebp + (P_ndig)]
push dword edi
fld dword [ebp + (P_f)]
sub esp,8
fstp qword [esp]
call _dtoa
add esp,16
mov edi,eax
L103:
mov esp,ebp
pop ebp
pop edi
ret
[extern _prints]
[extern _readln]
[extern _atoi]
[section .data]
times ($-$$) & 3 db 0
L81:
dd 00H
dd 040140000H
times ($-$$) & 3 db 0
L67:
dd 09999999aH
dd 03fb99999H
times ($-$$) & 3 db 0
L62:
dd 0fffffffeH
dd 07fefffffH
times ($-$$) & 3 db 0
L55:
dd 00H
dd 03ff00000H
times ($-$$) & 3 db 0
L22:
dd 00H
dd 040240000H
times ($-$$) & 3 db 0
L8:
dd 00H
dd 00H
|
.386
.MODEL FLAT
include common.inc
;
; Extern functions.
;
EXTRN _AvmRdtscEmulationTrap0D@4:PROC
EXTRN _AvmpRdtscEmulationTrap0DOriginalHandler:DWORD
; ;
; ------------------------------------------------------------------- ;
; CODE SECTION ;
; ------------------------------------------------------------------- ;
; ;
.CODE
_AvmpRdtscEmulationTrap0D PROC PUBLIC
TRAP_ENTRY
;
; Call our new trap function.
;
push esp
call _AvmRdtscEmulationTrap0D@4
;
; If our trap did not handle the fault,
; pass it to the original trap handler.
;
cmp eax, 0
jz OldHandler
;
; Fault has been handled,
; return from the interrupt handler.
;
TRAP_END
add esp, 4
iretd
OldHandler:
TRAP_END
jmp dword ptr [_AvmpRdtscEmulationTrap0DOriginalHandler]
_AvmpRdtscEmulationTrap0D ENDP
END
|
#include <cmath>
#include <vector>
#include <iostream>
#include <algorithm>
#include "DataFormats/MuonDetId/interface/CSCDetId.h"
#include "DataFormats/MuonDetId/interface/RPCDetId.h"
#include "DataFormats/MuonDetId/interface/DTChamberId.h"
#include "DataFormats/MuonDetId/interface/MuonSubdetId.h"
#include "L1Trigger/L1TMuonOverlap/interface/OMTFinputMaker.h"
#include "L1Trigger/L1TMuonOverlap/interface/OMTFinput.h"
#include "L1Trigger/L1TMuonOverlap/interface/OMTFConfiguration.h"
#include "L1Trigger/L1TMuonOverlap/interface/AngleConverter.h"
#include "L1Trigger/CSCCommonTrigger/interface/CSCConstants.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
///////////////////////////////////////
///////////////////////////////////////
OMTFinputMaker::OMTFinputMaker() {}
///////////////////////////////////////
///////////////////////////////////////
void OMTFinputMaker::initialize(const edm::EventSetup& es, const OMTFConfiguration *omtfConfig){
myAngleConverter.checkAndUpdateGeometry(es, omtfConfig->nPhiBins());
myOmtfConfig = omtfConfig;
}
///////////////////////////////////////
///////////////////////////////////////
OMTFinputMaker::~OMTFinputMaker(){ }
///////////////////////////////////////
///////////////////////////////////////
bool OMTFinputMaker::acceptDigi(uint32_t rawId,
unsigned int iProcessor,
l1t::tftype type){
unsigned int aMin = myOmtfConfig->getBarrelMin()[iProcessor];
unsigned int aMax = myOmtfConfig->getBarrelMax()[iProcessor];
unsigned int aSector = 99;
///Clean up digis. Remove unconnected detectors
DetId detId(rawId);
if (detId.det() != DetId::Muon)
edm::LogError("Critical OMTFinputMaker") << "PROBLEM: hit in unknown Det, detID: "<<detId.det()<<std::endl;
switch (detId.subdetId()) {
case MuonSubdetId::RPC: {
RPCDetId aId(rawId);
///Select RPC chambers connected to OMTF
if(type==l1t::tftype::omtf_pos &&
(aId.region()<0 ||
(aId.region()==0 && aId.ring()!=2) ||
(aId.region()==0 && aId.station()==4) ||
(aId.region()==0 && aId.station()==2 && aId.layer()==2 && aId.roll()==1) ||
(aId.region()==0 && aId.station()==3 && aId.roll()==1) ||
(aId.region()==1 && aId.station()==4) ||
///RPC RE1/2 temporarily not used (aId.region()==1 && aId.station()==1 && aId.ring()<2) ||
(aId.region()==1 && aId.station()>0 && aId.ring()<3))
) return false;
if(type==l1t::tftype::omtf_neg &&
(aId.region()>0 ||
(aId.region()==0 && aId.ring()!=-2) ||
(aId.region()==0 && aId.station()==4) ||
(aId.region()==0 && aId.station()==2 && aId.layer()==2 && aId.roll()==1) ||
(aId.region()==0 && aId.station()==3 && aId.roll()==1) ||
(aId.region()==-1 && aId.station()==4) ||
//RPC RE1/2 temporarily not used (aId.region()==1 && aId.station()==1 && aId.ring()<2) ||
(aId.region()==-1 && aId.station()>0 && aId.ring()<3))
) return false;
if(type==l1t::tftype::bmtf && aId.region()!=0) return false;
if(type==l1t::tftype::emtf_pos &&
(aId.region()<=0 ||
(aId.station()==1 && aId.ring()==3))) return false;
if(type==l1t::tftype::emtf_neg &&
(aId.region()>=0 ||
(aId.station()==1 && aId.ring()==3))) return false;
////////////////
if(aId.region()==0) aSector = aId.sector();
if(aId.region()!=0){
aSector = (aId.sector()-1)*6+aId.subsector();
aMin = myOmtfConfig->getEndcap10DegMin()[iProcessor];
aMax = myOmtfConfig->getEndcap10DegMax()[iProcessor];
}
break;
}
case MuonSubdetId::DT: {
DTChamberId dt(rawId);
if(type==l1t::tftype::omtf_pos && dt.wheel()!=2) return false;
if(type==l1t::tftype::omtf_neg && dt.wheel()!=-2) return false;
if(type==l1t::tftype::emtf_pos || type==l1t::tftype::emtf_neg) return false;
aSector = dt.sector();
break;
}
case MuonSubdetId::CSC: {
CSCDetId csc(rawId);
if(type==l1t::tftype::omtf_pos &&
(csc.endcap()==2 || csc.ring()==1 || csc.station()==4)) return false;
if(type==l1t::tftype::omtf_neg &&
(csc.endcap()==1 || csc.ring()==1 || csc.station()==4)) return false;
if(type==l1t::tftype::emtf_pos &&
(csc.endcap()==2 || (csc.station()==1 && csc.ring()==3))
) return false;
if(type==l1t::tftype::emtf_neg &&
(csc.endcap()==1 || (csc.station()==1 && csc.ring()==3))
) return false;
aSector = csc.chamber();
aMin = myOmtfConfig->getEndcap10DegMin()[iProcessor];
aMax = myOmtfConfig->getEndcap10DegMax()[iProcessor];
if( (type==l1t::tftype::emtf_pos || type==l1t::tftype::emtf_neg) &&
csc.station()>1 && csc.ring()==1){
aMin = myOmtfConfig->getEndcap20DegMin()[iProcessor];
aMax = myOmtfConfig->getEndcap20DegMax()[iProcessor];
}
break;
}
}
if(aMax>aMin && aSector>=aMin && aSector<=aMax) return true;
if(aMax<aMin && (aSector>=aMin || aSector<=aMax)) return true;
return false;
}
///////////////////////////////////////
///////////////////////////////////////
unsigned int OMTFinputMaker::getInputNumber(unsigned int rawId,
unsigned int iProcessor,
l1t::tftype type){
unsigned int iInput = 99;
unsigned int aSector = 99;
int aMin = myOmtfConfig->getBarrelMin()[iProcessor];
int iRoll = 1;
int nInputsPerSector = 2;
DetId detId(rawId);
if (detId.det() != DetId::Muon) edm::LogError("Critical OMTFinputMaker") << "PROBLEM: hit in unknown Det, detID: "<<detId.det()<<std::endl;
switch (detId.subdetId()) {
case MuonSubdetId::RPC: {
RPCDetId rpc(rawId);
if(rpc.region()==0){
nInputsPerSector = 4;
aSector = rpc.sector();
///on the 0-2pi border we need to add 1 30 deg sector
///to get the correct index
if(iProcessor==5 && aSector<3) aMin = -1;
//Use division into rolls
iRoll = rpc.roll();
///Set roll number by hand to keep common input
///number shift formula for all stations
if(rpc.station()==2 && rpc.layer()==2 && rpc.roll()==2) iRoll = 1;
///Only one roll from station 3 is connected.
if(rpc.station()==3){
iRoll = 1;
nInputsPerSector = 2;
}
///At the moment do not use RPC chambers splitting into rolls for bmtf part
if(type==l1t::tftype::bmtf)iRoll = 1;
}
if(rpc.region()!=0){
aSector = (rpc.sector()-1)*6+rpc.subsector();
aMin = myOmtfConfig->getEndcap10DegMin()[iProcessor];
///on the 0-2pi border we need to add 4 10 deg sectors
///to get the correct index
if(iProcessor==5 && aSector<5) aMin = -4;
}
break;
}
case MuonSubdetId::DT: {
DTChamberId dt(rawId);
aSector = dt.sector();
///on the 0-2pi border we need to add 1 30 deg sector
///to get the correct index
if(iProcessor==5 && aSector<3) aMin = -1;
break;
}
case MuonSubdetId::CSC: {
CSCDetId csc(rawId);
aSector = csc.chamber();
aMin = myOmtfConfig->getEndcap10DegMin()[iProcessor];
///on the 0-2pi border we need to add 4 10deg sectors
///to get the correct index
if(iProcessor==5 && aSector<5) aMin = -4;
///Endcap region covers algo 10 deg sectors
///on the 0-2pi border we need to add 2 20deg sectors
///to get the correct index
if( (type==l1t::tftype::emtf_pos || type==l1t::tftype::emtf_neg) &&
csc.station()>1 && csc.ring()==1){
aMin = myOmtfConfig->getEndcap20DegMin()[iProcessor];
if(iProcessor==5 && aSector<3) aMin = -2;
}
break;
}
}
///Assume 2 hits per chamber
iInput = (aSector - aMin)*nInputsPerSector;
///Chambers divided into two rolls have rolls number 1 and 3
iInput+=iRoll-1;
return iInput;
}
////////////////////////////////////////////
////////////////////////////////////////////
OMTFinput OMTFinputMaker::processDT(const L1MuDTChambPhContainer *dtPhDigis,
const L1MuDTChambThContainer *dtThDigis,
unsigned int iProcessor,
l1t::tftype type, int bxTrg)
{
OMTFinput result(myOmtfConfig);
if(!dtPhDigis) return result;
for (const auto digiIt: *dtPhDigis->getContainer()) {
DTChamberId detid(digiIt.whNum(),digiIt.stNum(),digiIt.scNum()+1);
///Check it the data fits into given processor input range
if(!acceptDigi(detid.rawId(), iProcessor, type)) continue;
///Check Trigger primitive quality
///Ts2Tag() == 0 - take only first track from DT Trigger Server
///BxCnt() == 0 - ??
///code()>=3 - take only double layer hits, HH, HL and LL
// FIXME (MK): at least Ts2Tag selection is not correct! Check it
// if (digiIt.bxNum()!= 0 || digiIt.BxCnt()!= 0 || digiIt.Ts2Tag()!= 0 || digiIt.code()<4) continue;
if (digiIt.bxNum()!= bxTrg) continue;
if (myOmtfConfig->fwVersion() <= 4) {
if (digiIt.code() != 4 && digiIt.code() != 5 && digiIt.code() != 6) continue;
} else {
if (digiIt.code() != 2 && digiIt.code() != 3 && digiIt.code() != 4 && digiIt.code() != 5 && digiIt.code() != 6) continue;
}
unsigned int hwNumber = myOmtfConfig->getLayerNumber(detid.rawId());
if(myOmtfConfig->getHwToLogicLayer().find(hwNumber)==myOmtfConfig->getHwToLogicLayer().end()) continue;
auto iter = myOmtfConfig->getHwToLogicLayer().find(hwNumber);
unsigned int iLayer = iter->second;
int iPhi = myAngleConverter.getProcessorPhi(iProcessor, type, digiIt);
int iEta = myAngleConverter.getGlobalEta(detid.rawId(), digiIt, dtThDigis);
unsigned int iInput= getInputNumber(detid.rawId(), iProcessor, type);
bool allowOverwrite = false;
result.addLayerHit(iLayer,iInput,iPhi,iEta, allowOverwrite);
result.addLayerHit(iLayer+1,iInput,digiIt.phiB(),iEta, allowOverwrite);
}
return result;
}
////////////////////////////////////////////
////////////////////////////////////////////
OMTFinput OMTFinputMaker::processCSC(const CSCCorrelatedLCTDigiCollection *cscDigis,
unsigned int iProcessor,
l1t::tftype type, int bxTrg){
OMTFinput result(myOmtfConfig);
if(!cscDigis) return result;
auto chamber = cscDigis->begin();
auto chend = cscDigis->end();
for( ; chamber != chend; ++chamber ) {
unsigned int rawid = (*chamber).first;
///Check it the data fits into given processor input range
if(!acceptDigi(rawid, iProcessor, type)) continue;
auto digi = (*chamber).second.first;
auto dend = (*chamber).second.second;
for( ; digi != dend; ++digi ) {
///Check if LCT trigger primitive has the right BX.
if (digi->getBX()-CSCConstants::LCT_CENTRAL_BX != bxTrg) continue;
unsigned int hwNumber = myOmtfConfig->getLayerNumber(rawid);
if(myOmtfConfig->getHwToLogicLayer().find(hwNumber)==myOmtfConfig->getHwToLogicLayer().end()) continue;
unsigned int iLayer = myOmtfConfig->getHwToLogicLayer().at(hwNumber);
int iPhi = myAngleConverter.getProcessorPhi(iProcessor, type, CSCDetId(rawid), *digi);
int iEta = myAngleConverter.getGlobalEta(rawid, *digi);
///Accept CSC digis only up to eta=1.26.
///The nominal OMTF range is up to 1.24, but cutting at 1.24
///kill efficnency at the edge. 1.26 is one eta bin above nominal.
//if(abs(iEta)>1.26/2.61*240) continue;
//if (abs(iEta) > 115) continue;
unsigned int iInput= getInputNumber(rawid, iProcessor, type);
// std::cout <<" ADDING CSC hit, proc: "<<iProcessor<<" iPhi : " << iPhi <<" iEta: "<< iEta << std::endl;
bool allowOverwrite = false;
result.addLayerHit(iLayer,iInput,iPhi,iEta,allowOverwrite);
}
}
return result;
}
////////////////////////////////////////////
////////////////////////////////////////////
bool rpcPrimitiveCmp(const RPCDigi &a, const RPCDigi &b) { return a.strip() < b.strip(); };
////////////////////////////////////////////
////////////////////////////////////////////
OMTFinput OMTFinputMaker::processRPC(const RPCDigiCollection *rpcDigis,
unsigned int iProcessor,
l1t::tftype type, int bxTrg){
OMTFinput result(myOmtfConfig);
if(!rpcDigis) return result;
std::stringstream str;
// std::cout <<" RPC HITS, processor : " << iProcessor << std::endl;
const RPCDigiCollection & rpcDigiCollection = *rpcDigis;
for (auto rollDigis : rpcDigiCollection) {
RPCDetId roll = rollDigis.first;
unsigned int rawid = roll.rawId();
int nClusters = 0;
if(!acceptDigi(rawid, iProcessor, type)) continue;
///Find clusters of consecutive fired strips.
///Have to copy the digis in chamber to sort them (not optimal).
///NOTE: when copying I select only digis with bx== //FIXME: find a better place/way to filtering digi against quality/BX etc.
// for (auto tdigi = rollDigis.second.first; tdigi != rollDigis.second.second; tdigi++) { std::cout << "RPC DIGIS: " << roll.rawId()<< " "<<roll<<" digi: " << tdigi->strip() <<" bx: " << tdigi->bx() << std::endl; }
std::vector<RPCDigi> digisCopy;
// std::copy_if(rollDigis.second.first, rollDigis.second.second, std::back_inserter(digisCopy), [](const RPCDigi & aDigi){return (aDigi.bx()==0);} );
for (auto pDigi=rollDigis.second.first; pDigi != rollDigis.second.second; pDigi++) { if (pDigi->bx()==bxTrg) digisCopy.push_back( *pDigi); }
std::sort(digisCopy.begin(),digisCopy.end(),rpcPrimitiveCmp);
typedef std::pair<unsigned int, unsigned int> Cluster;
std::vector<Cluster> clusters;
for(auto & digi: digisCopy) {
if(clusters.empty()) clusters.push_back(Cluster(digi.strip(),digi.strip()));
else if (digi.strip() - clusters.back().second == 1) clusters.back().second = digi.strip();
else if (digi.strip() - clusters.back().second > 1) clusters.push_back(Cluster(digi.strip(),digi.strip()));
}
for (auto & cluster: clusters) {
// int iPhiHalfStrip1 = myAngleConverter.getProcessorPhi(iProcessor, type, roll, cluster.first);
// int iPhiHalfStrip2 = myAngleConverter.getProcessorPhi(iProcessor, type, roll, cluster.second);
int iPhi = myAngleConverter.getProcessorPhi(iProcessor, type, roll, cluster.first, cluster.second);
int cSize = abs(int(cluster.first)-int(cluster.second))+1;
// std::cout << " HStrip_1: " << iPhiHalfStrip1 <<" HStrip_2: "<<iPhiHalfStrip2<<" iPhi: " << iPhi << " cluster: ["<< cluster.first << ", "<< cluster.second <<"]"<< std::endl;
if (cSize>3) continue;
int iEta = myAngleConverter.getGlobalEta(rawid, cluster.first);
unsigned int hwNumber = myOmtfConfig->getLayerNumber(rawid);
unsigned int iLayer = myOmtfConfig->getHwToLogicLayer().at(hwNumber);
unsigned int iInput= getInputNumber(rawid, iProcessor, type);
// std::cout <<"ADDING HIT: iLayer = " << iLayer << " iInput: " << iInput << " iPhi: " << iPhi << std::endl;
if (iLayer==17 && (iInput==0 || iInput==1)) continue; // FIXME (MK) there is no RPC link for that input, because it is taken by DAQ link
bool outres =
result.addLayerHit(iLayer,iInput,iPhi,iEta);
// if (cSize>2) flag |= 2;
// if (!outres) flag |= 1;
nClusters++;
str <<" RPC halfDigi "
<<" begin: "<<cluster.first<<" end: "<<cluster.second
<<" iPhi: "<<iPhi
<<" iEta: "<<iEta
<<" hwNumber: "<<hwNumber
<<" iInput: "<<iInput
<<" iLayer: "<<iLayer
<<" out: " << outres
<<std::endl;
}
// if (nClusters > 2) flag=1;
}
edm::LogInfo("OMTFInputMaker")<<str.str();
return result;
}
////////////////////////////////////////////
////////////////////////////////////////////
OMTFinput OMTFinputMaker::buildInputForProcessor(const L1MuDTChambPhContainer *dtPhDigis,
const L1MuDTChambThContainer *dtThDigis,
const CSCCorrelatedLCTDigiCollection *cscDigis,
const RPCDigiCollection *rpcDigis,
unsigned int iProcessor,
l1t::tftype type,
int bx){
OMTFinput result(myOmtfConfig);
result += processDT(dtPhDigis, dtThDigis, iProcessor, type, bx);
result += processCSC(cscDigis, iProcessor, type, bx);
result += processRPC(rpcDigis, iProcessor, type, bx);
return result;
}
////////////////////////////////////////////
////////////////////////////////////////////
|
// -*- C++ -*-
// Copyright (C) 2005-2017 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 3, or (at your option) any later
// version.
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL.
// Permission to use, copy, modify, sell, and distribute this software
// is hereby granted without fee, provided that the above copyright
// notice appears in all copies, and that both that copyright notice
// and this permission notice appear in supporting documentation. None
// of the above authors, nor IBM Haifa Research Laboratories, make any
// representation about the suitability of this software for any
// purpose. It is provided "as is" without express or implied
// warranty.
/**
* @file size_policy_string_form.hpp
* Transforms containers into string form.
*/
#ifndef PB_DS_SIZE_POLICY_STRING_FORM_HPP
#define PB_DS_SIZE_POLICY_STRING_FORM_HPP
#include <string>
#include <common_type/assoc/detail/size_policy_string_form.hpp>
#include <common_type/assoc/detail/trigger_policy_string_form.hpp>
#include <common_type/assoc/template_policy.hpp>
#include <io/xml.hpp>
namespace __gnu_pbds
{
namespace test
{
namespace detail
{
template<typename Size_Policy>
struct size_policy_string_form;
template<typename _Alloc>
struct size_policy_string_form<
__gnu_pbds::test::hash_exponential_size_policy_t_<_Alloc> >
{
static std::string
name()
{ return ("exp_"); }
static std::string
desc()
{
return (make_xml_tag("Size_Policy", "value", "hash_exponential_size_policy"));
}
};
template<>
struct size_policy_string_form<
__gnu_pbds::test::hash_prime_size_policy_t_>
{
static std::string
name()
{ return ("prime_"); }
static std::string
desc()
{
return (make_xml_tag("Size_Policy", "value", "hash_prime_size_policy"));
}
};
} // namespace detail
} // namespace test
} // namespace __gnu_pbds
#endif // #ifndef PB_DS_SIZE_POLICY_STRING_FORM_HPP
|
; A158638: a(n) = 48*n^2 + 1.
; 1,49,193,433,769,1201,1729,2353,3073,3889,4801,5809,6913,8113,9409,10801,12289,13873,15553,17329,19201,21169,23233,25393,27649,30001,32449,34993,37633,40369,43201,46129,49153,52273,55489,58801,62209,65713,69313,73009,76801,80689,84673,88753,92929,97201,101569,106033,110593,115249,120001,124849,129793,134833,139969,145201,150529,155953,161473,167089,172801,178609,184513,190513,196609,202801,209089,215473,221953,228529,235201,241969,248833,255793,262849,270001,277249,284593,292033,299569,307201
pow $0,2
mul $0,48
add $0,1
|
; A059867: Number of irreducible representations of the symmetric group S_n that have odd degree.
; 1,2,2,4,4,8,8,8,8,16,16,32,32,64,64,16,16,32,32,64,64,128,128,128,128,256,256,512,512,1024,1024,32,32,64,64,128,128,256,256,256,256,512,512,1024,1024,2048,2048,512,512,1024,1024,2048,2048,4096,4096,4096,4096,8192,8192,16384,16384,32768,32768,64,64,128,128,256,256,512,512,512,512,1024,1024,2048,2048,4096,4096,1024,1024,2048,2048,4096,4096,8192,8192,8192,8192,16384,16384,32768,32768,65536,65536,2048,2048,4096,4096,8192,8192,16384,16384,16384,16384,32768,32768,65536,65536,131072,131072,32768,32768,65536,65536,131072,131072,262144,262144,262144,262144,524288,524288,1048576,1048576,2097152,2097152,128,128,256,256,512,512,1024,1024,1024,1024,2048,2048,4096,4096,8192,8192,2048,2048,4096,4096,8192,8192,16384,16384,16384,16384,32768,32768,65536,65536,131072,131072,4096,4096,8192,8192,16384,16384,32768,32768,32768,32768,65536,65536,131072,131072,262144,262144,65536,65536,131072,131072,262144,262144,524288,524288,524288,524288,1048576,1048576,2097152,2097152,4194304,4194304,8192,8192,16384,16384,32768,32768,65536,65536,65536,65536,131072,131072,262144,262144,524288,524288,131072,131072,262144,262144,524288,524288,1048576,1048576,1048576,1048576,2097152,2097152,4194304,4194304,8388608,8388608,262144,262144,524288,524288,1048576,1048576,2097152,2097152,2097152,2097152,4194304,4194304,8388608,8388608,16777216,16777216,4194304,4194304,8388608,8388608,16777216,16777216,33554432,33554432,33554432,33554432,67108864
cal $0,60960 ; Duplicate of A073642.
cal $0,277988 ; a(n) = 352*2^n + 34.
mul $0,2
add $0,2
dif $0,2
mov $1,$0
sub $1,387
div $1,352
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 g9_DecryptECB_RIJ128pipe_AES_NI
.type g9_DecryptECB_RIJ128pipe_AES_NI, @function
g9_DecryptECB_RIJ128pipe_AES_NI:
push %ebp
mov %esp, %ebp
push %ebx
push %esi
push %edi
movl (8)(%ebp), %esi
movl (12)(%ebp), %edi
movl (20)(%ebp), %ecx
movl (24)(%ebp), %edx
movl (16)(%ebp), %eax
sub $(64), %edx
jl .Lshort_inputgas_1
lea (,%eax,4), %ebx
lea (%ecx,%ebx,4), %ecx
.Lblks_loopgas_1:
movdqa (%ecx), %xmm4
lea (-16)(%ecx), %ebx
movdqu (%esi), %xmm0
movdqu (16)(%esi), %xmm1
movdqu (32)(%esi), %xmm2
movdqu (48)(%esi), %xmm3
add $(64), %esi
pxor %xmm4, %xmm0
pxor %xmm4, %xmm1
pxor %xmm4, %xmm2
pxor %xmm4, %xmm3
movdqa (%ebx), %xmm4
sub $(16), %ebx
movl (16)(%ebp), %eax
sub $(1), %eax
.Lcipher_loopgas_1:
aesdec %xmm4, %xmm0
aesdec %xmm4, %xmm1
aesdec %xmm4, %xmm2
aesdec %xmm4, %xmm3
movdqa (%ebx), %xmm4
sub $(16), %ebx
dec %eax
jnz .Lcipher_loopgas_1
aesdeclast %xmm4, %xmm0
movdqu %xmm0, (%edi)
aesdeclast %xmm4, %xmm1
movdqu %xmm1, (16)(%edi)
aesdeclast %xmm4, %xmm2
movdqu %xmm2, (32)(%edi)
aesdeclast %xmm4, %xmm3
movdqu %xmm3, (48)(%edi)
add $(64), %edi
sub $(64), %edx
jge .Lblks_loopgas_1
.Lshort_inputgas_1:
add $(64), %edx
jz .Lquitgas_1
movl (16)(%ebp), %eax
movl (20)(%ebp), %ecx
lea (,%eax,4), %ebx
lea (%ecx,%ebx,4), %ebx
.Lsingle_blk_loopgas_1:
movdqu (%esi), %xmm0
add $(16), %esi
pxor (%ebx), %xmm0
cmp $(12), %eax
jl .Lkey_128_sgas_1
jz .Lkey_192_sgas_1
.Lkey_256_sgas_1:
aesdec (208)(%ecx), %xmm0
aesdec (192)(%ecx), %xmm0
.Lkey_192_sgas_1:
aesdec (176)(%ecx), %xmm0
aesdec (160)(%ecx), %xmm0
.Lkey_128_sgas_1:
aesdec (144)(%ecx), %xmm0
aesdec (128)(%ecx), %xmm0
aesdec (112)(%ecx), %xmm0
aesdec (96)(%ecx), %xmm0
aesdec (80)(%ecx), %xmm0
aesdec (64)(%ecx), %xmm0
aesdec (48)(%ecx), %xmm0
aesdec (32)(%ecx), %xmm0
aesdec (16)(%ecx), %xmm0
aesdeclast (%ecx), %xmm0
movdqu %xmm0, (%edi)
add $(16), %edi
sub $(16), %edx
jnz .Lsingle_blk_loopgas_1
.Lquitgas_1:
pop %edi
pop %esi
pop %ebx
pop %ebp
ret
.Lfe1:
.size g9_DecryptECB_RIJ128pipe_AES_NI, .Lfe1-(g9_DecryptECB_RIJ128pipe_AES_NI)
|
SaffronCityScript:
jp EnableAutoTextBoxDrawing
SaffronCityTextPointers:
dw SaffronCityText1
dw SaffronCityText2
dw SaffronCityText3
dw SaffronCityText4
dw SaffronCityText5
dw SaffronCityText6
dw SaffronCityText7
dw SaffronCityText8
dw SaffronCityText9
dw SaffronCityText10
dw SaffronCityText11
dw SaffronCityText12
dw SaffronCityText13
dw SaffronCityText14
dw SaffronCityText15
dw SaffronCityText16
dw SaffronCityText17
dw SaffronCityText18
dw MartSignText
dw SaffronCityText20
dw SaffronCityText21
dw SaffronCityText22
dw PokeCenterSignText
dw SaffronCityText24
dw SaffronCityText25
SaffronCityText1:
TX_FAR _SaffronCityText1
db "@"
SaffronCityText2:
TX_FAR _SaffronCityText2
db "@"
SaffronCityText3:
TX_FAR _SaffronCityText3
db "@"
SaffronCityText4:
TX_FAR _SaffronCityText4
db "@"
SaffronCityText5:
TX_FAR _SaffronCityText5
db "@"
SaffronCityText6:
TX_FAR _SaffronCityText6
db "@"
SaffronCityText7:
TX_FAR _SaffronCityText7
db "@"
SaffronCityText8:
TX_FAR _SaffronCityText8
db "@"
SaffronCityText9:
TX_FAR _SaffronCityText9
db "@"
SaffronCityText10:
TX_FAR _SaffronCityText10
db "@"
SaffronCityText11:
TX_FAR _SaffronCityText11
db "@"
SaffronCityText12:
TX_FAR _SaffronCityText12
db $15, "@" ; play PIDGEOT cry from TextCommandSounds
SaffronCityText13:
TX_FAR _SaffronCityText13
db "@"
SaffronCityText14:
TX_FAR _SaffronCityText14
db "@"
SaffronCityText15:
TX_FAR _SaffronCityText15
db "@"
SaffronCityText16:
TX_FAR _SaffronCityText16
db "@"
SaffronCityText17:
TX_FAR _SaffronCityText17
db "@"
SaffronCityText18:
TX_FAR _SaffronCityText18
db "@"
SaffronCityText20:
TX_FAR _SaffronCityText20
db "@"
SaffronCityText21:
TX_FAR _SaffronCityText21
db "@"
SaffronCityText22:
TX_FAR _SaffronCityText22
db "@"
SaffronCityText24:
TX_FAR _SaffronCityText24
db "@"
SaffronCityText25:
TX_FAR _SaffronCityText25
db "@"
|
; $Id: bit_click_mwr.asm,v 1.4 2016-06-11 20:52:25 dom Exp $
;
; 1 bit sound library - version for "memory write" I/O architectures
;
; void bit_click();
;
; Stefano Bodrato - 31/03/2008
;
SECTION code_clib
PUBLIC bit_click
PUBLIC _bit_click
INCLUDE "games/games.inc"
EXTERN __snd_tick
.bit_click
._bit_click
ld a,(__snd_tick)
xor sndbit_mask
ld (sndbit_port),a
ld (__snd_tick),a
ret
|
;bubble sort za listu 8bitnih elemenata
SRT:
LDY #$00 ;postavi zastavicu zamjene na 0
STY $32
LDA ($30),Y ;dohvati broj elemenata...
TAX ;...i spremi ga u x registar
INY ;pokazi na prvi element u listi
DEX ;smanji broj elemenata
NEL:
LDA ($30),Y ;dohvati element
INY ;inkrementiraj Y (pozicija sl elementa)
CMP ($30),Y ;provjeri ako je trenutni veci od sl elementa
BCC KR
BEQ KR
;ako je, zamjeni elemente tako da:
PHA ;spremi manji bit na stog
LDA ($30),Y ;dohvati visi bit
DEY ;spremi ga na nizu adresu
STA ($30),Y
PLA ;povuci manji bit sa stoga
INY ;stavi ga na visu adresu
STA ($30),Y
LDA #$FF ;postavi zastavicu zamjene
STA $32
KR:
DEX ;provjeri ako smo na kraju liste
BNE NEL ; ako ne dohvati sl. element
BIT $32 ; ako da provjeri dali je zastavica zamjene upaljena.
BMI SRT ; ako nije prodi listu jos jednom
RTS ; ako je, lista je sortirana
;---------------------------------------------------------
; Bubble sort je jednostavan ali nepraktican i spor algoritam.
; Radi na principu zamjenje elemenata prema vrhu liste dokle
; god lista ne dode u sortirano stanje. Nagori slucaj je О(n^2)
;---------------------------------------------------------
;objasnjenje komandi (izvadeno iz assembler reference
;https://www.dwheeler.com/6502/oneelkruns/asm1step.html )
; LDY - napuni y registar, LDA - stavi u akumulator
; STY - spremi y registar, STA - spremi akumulator
; TAX - stavi iz akumulatora u x reg.
; INY - Y++, DEX - X--, DEY - Y--
; CMP - usporedi memoriju i akumulator
; BCC - granaj na carry = 0, BEQ - granaj na jednako nula (Z = 1)
; BNE - granaj na ne jednako nula (Z = 0), BMI - granaj na minus (N = 1)
; BIT - testiraj BITove
; PHA - push akumulator na stog, PLA - pull akumulator sa stoga
; RTS - vrati se iz subrutine
;---------------------------------------------------------
|
; A156664: Binomial transform of A052551.
; 1,2,6,16,42,108,274,688,1714,4244,10458,25672,62826,153372,373666,908896,2207842,5357348,12988074,31464568,76179354,184347564,445923058,1078290832,2606699026,6300077492,15223631226,36780894376,88852528842,214620169788,518361303874,1251879648448,3023194342594,7300415817284,17628320944458,42565647640792,102776796095226,248153599569612,599152714711186,1446596467945456,3492620528509042,8432387280777428
mov $2,1
lpb $2,1
sub $2,1
add $3,1
lpb $3,1
sub $3,1
mov $15,2
lpb $15,1
sub $15,1
add $0,$15
sub $0,1
mov $13,2
lpb $13,1
sub $13,1
add $0,$13
sub $0,1
mov $7,$0
mov $9,2
lpb $9,1
mov $0,$7
sub $9,1
add $0,$9
sub $0,1
mov $4,1
mov $5,4
mov $6,1
lpb $0,1
sub $0,1
mov $16,$4
mov $4,$6
sub $5,1
add $6,$16
add $4,$6
add $5,$16
mul $5,2
lpe
mul $5,2
mov $10,$9
mov $16,$5
sub $16,7
div $16,8
mul $16,6
lpb $10,1
mov $8,$16
sub $10,1
lpe
lpe
lpb $7,1
mov $7,0
sub $8,$16
lpe
mov $14,$13
mov $16,$8
lpb $14,1
mov $12,$16
sub $14,1
lpe
lpe
mov $11,$15
mov $16,$12
lpb $11,1
mov $1,$16
sub $11,1
lpe
lpe
lpe
lpe
sub $1,2
div $1,3
add $1,1
|
/*
* Copyright (c) 2017, Alliance for Open Media. All rights reserved
*
* This source code is subject to the terms of the BSD 2 Clause License and
* the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
* was not distributed with this source code in the LICENSE file, you can
* obtain it at www.aomedia.org/license/software. If the Alliance for Open
* Media Patent License 1.0 was not distributed with this source code in the
* PATENTS file, you can obtain it at www.aomedia.org/license/patent.
*/
#include <cstdio>
#include <string>
// TODO(tomfinegan): Remove the aom_config.h include as soon as possible. At
// present it's required because aom_config.h determines if the library writes
// OBUs.
#include "./aom_config.h"
#include "aom/aom_codec.h"
#include "aom/aom_integer.h"
#include "aom_ports/mem_ops.h"
#include "av1/decoder/obu.h"
#include "tools/obu_parser.h"
namespace aom_tools {
// Basic OBU syntax
// 4 bytes: length
// 8 bits: Header
// 7
// forbidden bit
// 6,5,4,3
// type bits
// 2,1
// reserved bits
// 0
// extension bit
const uint32_t kObuForbiddenBitMask = 0x1;
const uint32_t kObuForbiddenBitShift = 7;
const uint32_t kObuTypeBitsMask = 0xF;
const uint32_t kObuTypeBitsShift = 3;
const uint32_t kObuExtensionFlagBitMask = 0x1;
const uint32_t kObuExtensionFlagBitShift = 2;
const uint32_t kObuHasPayloadLengthFlagBitMask = 0x1;
const uint32_t kObuHasPayloadLengthFlagBitShift = 1;
// When extension bit is set:
// 8 bits: extension header
// 7,6,5
// temporal ID
// 4,3
// spatial ID
// 2,1
// quality ID
// 0
// reserved bit
const uint32_t kObuExtTemporalIdBitsMask = 0x7;
const uint32_t kObuExtTemporalIdBitsShift = 5;
const uint32_t kObuExtSpatialIdBitsMask = 0x3;
const uint32_t kObuExtSpatialIdBitsShift = 3;
bool ValidObuType(int obu_type) {
switch (obu_type) {
case OBU_SEQUENCE_HEADER:
case OBU_TEMPORAL_DELIMITER:
case OBU_FRAME_HEADER:
case OBU_TILE_GROUP:
case OBU_REDUNDANT_FRAME_HEADER:
case OBU_FRAME:
case OBU_METADATA:
case OBU_PADDING: return true;
}
return false;
}
bool ParseObuHeader(uint8_t obu_header_byte, ObuHeader *obu_header) {
const int forbidden_bit =
(obu_header_byte >> kObuForbiddenBitShift) & kObuForbiddenBitMask;
if (forbidden_bit) {
fprintf(stderr, "Invalid OBU, forbidden bit set.\n");
return false;
}
obu_header->type = static_cast<OBU_TYPE>(
(obu_header_byte >> kObuTypeBitsShift) & kObuTypeBitsMask);
if (!ValidObuType(obu_header->type)) {
fprintf(stderr, "Invalid OBU type: %d.\n", obu_header->type);
return false;
}
obu_header->has_extension =
(obu_header_byte >> kObuExtensionFlagBitShift) & kObuExtensionFlagBitMask;
obu_header->has_length_field =
(obu_header_byte >> kObuHasPayloadLengthFlagBitShift) &
kObuHasPayloadLengthFlagBitMask;
return true;
}
bool ParseObuExtensionHeader(uint8_t ext_header_byte, ObuHeader *obu_header) {
obu_header->temporal_layer_id =
(ext_header_byte >> kObuExtTemporalIdBitsShift) &
kObuExtTemporalIdBitsMask;
obu_header->enhancement_layer_id =
(ext_header_byte >> kObuExtSpatialIdBitsShift) & kObuExtSpatialIdBitsMask;
return true;
}
void PrintObuHeader(const ObuHeader *header) {
printf(
" OBU type: %s\n"
" extension: %s\n",
aom_obu_type_to_string(static_cast<OBU_TYPE>(header->type)),
header->has_extension ? "yes" : "no");
if (header->has_extension) {
printf(
" temporal_id: %d\n"
" spatial_id: %d\n",
header->temporal_layer_id, header->temporal_layer_id);
}
}
bool DumpObu(const uint8_t *data, int length, int *obu_overhead_bytes) {
const int kObuHeaderLengthSizeBytes = 1;
const int kMinimumBytesRequired = 1 + kObuHeaderLengthSizeBytes;
int consumed = 0;
int obu_overhead = 0;
ObuHeader obu_header;
while (consumed < length) {
const int remaining = length - consumed;
if (remaining < kMinimumBytesRequired) {
if (remaining > 0) {
fprintf(stderr,
"OBU parse error. Did not consume all data, %d bytes "
"remain.\n",
remaining);
}
return false;
}
size_t length_field_size = 0;
int current_obu_length = 0;
int obu_header_size = 0;
obu_overhead += (int)length_field_size;
if (current_obu_length > remaining) {
fprintf(stderr,
"OBU parsing failed at offset %d with bad length of %d "
"and %d bytes left.\n",
consumed, current_obu_length, remaining);
return false;
}
consumed += (int)length_field_size;
memset(&obu_header, 0, sizeof(obu_header));
const uint8_t obu_header_byte = *(data + consumed);
if (!ParseObuHeader(obu_header_byte, &obu_header)) {
fprintf(stderr, "OBU parsing failed at offset %d.\n", consumed);
return false;
}
++obu_overhead;
++obu_header_size;
if (obu_header.has_extension) {
const uint8_t obu_ext_header_byte =
*(data + consumed + kObuHeaderLengthSizeBytes);
if (!ParseObuExtensionHeader(obu_ext_header_byte, &obu_header)) {
fprintf(stderr, "OBU extension parsing failed at offset %d.\n",
consumed);
return false;
}
++obu_overhead;
++obu_header_size;
}
PrintObuHeader(&obu_header);
uint64_t obu_size = 0;
aom_uleb_decode(data + consumed + obu_header_size, remaining, &obu_size,
&length_field_size);
current_obu_length = static_cast<int>(obu_size);
consumed += obu_header_size + length_field_size + current_obu_length;
printf(" length: %d\n",
static_cast<int>(obu_header_size + length_field_size +
current_obu_length));
}
if (obu_overhead_bytes != nullptr) *obu_overhead_bytes = obu_overhead;
printf(" TU size: %d\n", consumed);
return true;
}
} // namespace aom_tools
|
; A144635: a(n) = 5^n*Sum_{ k=0..n } binomial(2*k,k)/5^k.
; Submitted by Jamie Morken(s4)
; 1,7,41,225,1195,6227,32059,163727,831505,4206145,21215481,106782837,536618341,2693492305,13507578125,67693008145,339066121115,1697664211795,8497396194275,42522326235175,212749477704695,1064285646397915,5323532330953295,26625895085494075
mov $1,1
mov $2,1
mov $3,$0
mov $0,2
lpb $3
sub $0,4
mul $1,$0
mul $2,5
sub $3,1
sub $4,1
div $1,$4
add $2,$1
lpe
mov $0,$2
|
; A102480: Triangle read by rows: row n contains the numbers C(n,k)^(k-1) for 0 <= k <= n, n >= 0.
; Submitted by Christian Krause
; 1,1,1,1,1,1,1,1,3,1,1,1,6,16,1,1,1,10,100,125,1,1,1,15,400,3375,1296,1,1,1,21,1225,42875,194481,16807,1,1,1,28,3136,343000,9834496,17210368,262144,1,1,1,36,7056,2000376,252047376,4182119424,2176782336,4782969,1,1,1,45,14400,9261000,4032758016,408410100000,2985984000000,373669453125,100000000,1,1,1,55,27225,35937000,45558341136,21047953604832,1291467969000000,3329565857578125,83733937890625,2357947691,1,1,1,66,48400,121287375,393460125696,673534515354624,246803372284575744,7281760530523359375
lpb $0
add $2,1
sub $0,$2
lpe
bin $2,$0
sub $0,1
pow $2,$0
mov $0,$2
|
; A121578: Values m of number pairs (m,n) which yield associated matching times on the clock with interchanged hour and minute hands for corresponding n in A121577.
; 0,12,24,36,48,60,72,84,96,108,120,132,1,13,25,37,49,61,73,85,97,109,121,133,2,14,26,38,50,62,74,86,98,110,122,134,3,15,27,39,51,63,75,87,99,111,123,135,4,16,28,40,52,64,76,88,100,112,124,136,5,17,29,41,53,65
mul $0,144
mod $0,1716
div $0,12
|
include aasyslib.i
CGROUP group code
code segment dword 'CODE'
assume cs:CGROUP,ds:CGROUP
SYSLIB_JUMP pj_open sysl_pj_open
code ends
end
|
.global s_prepare_buffers
s_prepare_buffers:
push %r13
push %r15
push %r8
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_D_ht+0xcc0b, %rax
clflush (%rax)
nop
nop
nop
xor %rdx, %rdx
movups (%rax), %xmm2
vpextrq $0, %xmm2, %r8
nop
nop
nop
cmp $11279, %r13
lea addresses_D_ht+0x1e38b, %rsi
lea addresses_D_ht+0x743f, %rdi
nop
nop
nop
nop
nop
cmp $9385, %r15
mov $28, %rcx
rep movsl
nop
nop
cmp %rdi, %rdi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r8
pop %r15
pop %r13
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r13
push %rax
push %rbp
push %rdi
push %rdx
// Store
lea addresses_D+0x293b, %rbp
nop
nop
nop
nop
nop
sub %rdi, %rdi
mov $0x5152535455565758, %r13
movq %r13, %xmm0
vmovups %ymm0, (%rbp)
inc %r10
// Faulty Load
lea addresses_UC+0x278b, %rdx
nop
inc %rax
mov (%rdx), %edi
lea oracles, %r12
and $0xff, %rdi
shlq $12, %rdi
mov (%r12,%rdi,1), %rdi
pop %rdx
pop %rdi
pop %rbp
pop %rax
pop %r13
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_UC'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_D'}}
[Faulty Load]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 4, 'NT': False, 'type': 'addresses_UC'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 8, 'same': True, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_D_ht'}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
###############################################################################
# Copyright 2019 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.
###############################################################################
.text
.p2align 6, 0x90
.globl _cpAdd_BNU
_cpAdd_BNU:
movslq %ecx, %rcx
xor %rax, %rax
cmp $(2), %rcx
jge .LADD_GE2gas_1
add %rax, %rax
movq (%rsi), %r8
adcq (%rdx), %r8
movq %r8, (%rdi)
sbb %rax, %rax
jmp .LFINALgas_1
.LADD_GE2gas_1:
jg .LADD_GT2gas_1
add %rax, %rax
movq (%rsi), %r8
adcq (%rdx), %r8
movq (8)(%rsi), %r9
adcq (8)(%rdx), %r9
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
sbb %rax, %rax
jmp .LFINALgas_1
.LADD_GT2gas_1:
cmp $(4), %rcx
jge .LADD_GE4gas_1
add %rax, %rax
movq (%rsi), %r8
adcq (%rdx), %r8
movq (8)(%rsi), %r9
adcq (8)(%rdx), %r9
movq (16)(%rsi), %r10
adcq (16)(%rdx), %r10
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
sbb %rax, %rax
jmp .LFINALgas_1
.LADD_GE4gas_1:
jg .LADD_GT4gas_1
add %rax, %rax
movq (%rsi), %r8
adcq (%rdx), %r8
movq (8)(%rsi), %r9
adcq (8)(%rdx), %r9
movq (16)(%rsi), %r10
adcq (16)(%rdx), %r10
movq (24)(%rsi), %r11
adcq (24)(%rdx), %r11
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
movq %r11, (24)(%rdi)
sbb %rax, %rax
jmp .LFINALgas_1
.LADD_GT4gas_1:
cmp $(6), %rcx
jge .LADD_GE6gas_1
add %rax, %rax
movq (%rsi), %r8
adcq (%rdx), %r8
movq (8)(%rsi), %r9
adcq (8)(%rdx), %r9
movq (16)(%rsi), %r10
adcq (16)(%rdx), %r10
movq (24)(%rsi), %r11
adcq (24)(%rdx), %r11
movq (32)(%rsi), %rcx
adcq (32)(%rdx), %rcx
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
movq %r11, (24)(%rdi)
movq %rcx, (32)(%rdi)
sbb %rax, %rax
jmp .LFINALgas_1
.LADD_GE6gas_1:
jg .LADD_GT6gas_1
add %rax, %rax
movq (%rsi), %r8
adcq (%rdx), %r8
movq (8)(%rsi), %r9
adcq (8)(%rdx), %r9
movq (16)(%rsi), %r10
adcq (16)(%rdx), %r10
movq (24)(%rsi), %r11
adcq (24)(%rdx), %r11
movq (32)(%rsi), %rcx
adcq (32)(%rdx), %rcx
movq (40)(%rsi), %rsi
adcq (40)(%rdx), %rsi
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
movq %r11, (24)(%rdi)
movq %rcx, (32)(%rdi)
movq %rsi, (40)(%rdi)
sbb %rax, %rax
jmp .LFINALgas_1
.LADD_GT6gas_1:
cmp $(8), %rcx
jge .LADD_GE8gas_1
.LADD_EQ7gas_1:
add %rax, %rax
movq (%rsi), %r8
adcq (%rdx), %r8
movq (8)(%rsi), %r9
adcq (8)(%rdx), %r9
movq (16)(%rsi), %r10
adcq (16)(%rdx), %r10
movq (24)(%rsi), %r11
adcq (24)(%rdx), %r11
movq (32)(%rsi), %rcx
adcq (32)(%rdx), %rcx
movq %r8, (%rdi)
movq (40)(%rsi), %r8
adcq (40)(%rdx), %r8
movq (48)(%rsi), %rsi
adcq (48)(%rdx), %rsi
movq %r9, (8)(%rdi)
movq %r10, (16)(%rdi)
movq %r11, (24)(%rdi)
movq %rcx, (32)(%rdi)
movq %r8, (40)(%rdi)
movq %rsi, (48)(%rdi)
sbb %rax, %rax
jmp .LFINALgas_1
.LADD_GE8gas_1:
jg .LADD_GT8gas_1
add %rax, %rax
movq (%rsi), %r8
adcq (%rdx), %r8
movq (8)(%rsi), %r9
adcq (8)(%rdx), %r9
movq (16)(%rsi), %r10
adcq (16)(%rdx), %r10
movq (24)(%rsi), %r11
adcq (24)(%rdx), %r11
movq (32)(%rsi), %rcx
adcq (32)(%rdx), %rcx
movq %r8, (%rdi)
movq (40)(%rsi), %r8
adcq (40)(%rdx), %r8
movq %r9, (8)(%rdi)
movq (48)(%rsi), %r9
adcq (48)(%rdx), %r9
movq (56)(%rsi), %rsi
adcq (56)(%rdx), %rsi
movq %r10, (16)(%rdi)
movq %r11, (24)(%rdi)
movq %rcx, (32)(%rdi)
movq %r8, (40)(%rdi)
movq %r9, (48)(%rdi)
movq %rsi, (56)(%rdi)
sbb %rax, %rax
jmp .LFINALgas_1
.LADD_GT8gas_1:
mov %rax, %r8
mov %rcx, %rax
and $(3), %rcx
xor %rax, %rcx
lea (%rsi,%rcx,8), %rsi
lea (%rdx,%rcx,8), %rdx
lea (%rdi,%rcx,8), %rdi
neg %rcx
add %r8, %r8
jmp .LADD_GLOOPgas_1
.p2align 6, 0x90
.LADD_GLOOPgas_1:
movq (%rsi,%rcx,8), %r8
movq (8)(%rsi,%rcx,8), %r9
movq (16)(%rsi,%rcx,8), %r10
movq (24)(%rsi,%rcx,8), %r11
adcq (%rdx,%rcx,8), %r8
adcq (8)(%rdx,%rcx,8), %r9
adcq (16)(%rdx,%rcx,8), %r10
adcq (24)(%rdx,%rcx,8), %r11
movq %r8, (%rdi,%rcx,8)
movq %r9, (8)(%rdi,%rcx,8)
movq %r10, (16)(%rdi,%rcx,8)
movq %r11, (24)(%rdi,%rcx,8)
lea (4)(%rcx), %rcx
jrcxz .LADD_LLAST0gas_1
jmp .LADD_GLOOPgas_1
.LADD_LLAST0gas_1:
sbb %rcx, %rcx
and $(3), %rax
jz .LFIN0gas_1
.LADD_LLOOPgas_1:
test $(2), %rax
jz .LADD_LLAST1gas_1
add %rcx, %rcx
movq (%rsi), %r8
movq (8)(%rsi), %r9
adcq (%rdx), %r8
adcq (8)(%rdx), %r9
movq %r8, (%rdi)
movq %r9, (8)(%rdi)
sbb %rcx, %rcx
test $(1), %rax
jz .LFIN0gas_1
add $(16), %rsi
add $(16), %rdx
add $(16), %rdi
.LADD_LLAST1gas_1:
add %rcx, %rcx
movq (%rsi), %r8
adcq (%rdx), %r8
movq %r8, (%rdi)
sbb %rcx, %rcx
.LFIN0gas_1:
mov %rcx, %rax
.LFINALgas_1:
neg %rax
vzeroupper
ret
|
; void *p_list_push_back(p_list_t *list, void *item)
SECTION code_clib
SECTION code_adt_p_list
PUBLIC p_list_push_back_callee
EXTERN asm_p_list_push_back
p_list_push_back_callee:
pop hl
pop de
ex (sp),hl
jp asm_p_list_push_back
|
// Copyright (c) 2011-2020 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/signverifymessagedialog.h>
#include <qt/forms/ui_signverifymessagedialog.h>
#include <qt/addressbookpage.h>
#include <qt/guiutil.h>
#include <qt/platformstyle.h>
#include <qt/walletmodel.h>
#include <key_io.h>
#include <validation.h> // For strMessageMagic
#include <wallet/wallet.h>
#include <string>
#include <vector>
#include <QClipboard>
SignVerifyMessageDialog::SignVerifyMessageDialog(const PlatformStyle *_platformStyle, QWidget *parent) :
QDialog(parent),
ui(new Ui::SignVerifyMessageDialog),
model(0),
platformStyle(_platformStyle)
{
ui->setupUi(this);
ui->addressBookButton_SM->setIcon(platformStyle->SingleColorIcon(":/icons/address-book"));
ui->pasteButton_SM->setIcon(platformStyle->SingleColorIcon(":/icons/editpaste"));
ui->copySignatureButton_SM->setIcon(platformStyle->SingleColorIcon(":/icons/editcopy"));
ui->signMessageButton_SM->setIcon(platformStyle->SingleColorIcon(":/icons/edit"));
ui->clearButton_SM->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
ui->addressBookButton_VM->setIcon(platformStyle->SingleColorIcon(":/icons/address-book"));
ui->verifyMessageButton_VM->setIcon(platformStyle->SingleColorIcon(":/icons/transaction_0"));
ui->clearButton_VM->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature"));
GUIUtil::setupAddressWidget(ui->addressIn_SM, this);
GUIUtil::setupAddressWidget(ui->addressIn_VM, this);
ui->addressIn_SM->installEventFilter(this);
ui->messageIn_SM->installEventFilter(this);
ui->signatureOut_SM->installEventFilter(this);
ui->addressIn_VM->installEventFilter(this);
ui->messageIn_VM->installEventFilter(this);
ui->signatureIn_VM->installEventFilter(this);
ui->signatureOut_SM->setFont(GUIUtil::fixedPitchFont());
ui->signatureIn_VM->setFont(GUIUtil::fixedPitchFont());
}
SignVerifyMessageDialog::~SignVerifyMessageDialog()
{
delete ui;
}
void SignVerifyMessageDialog::setModel(WalletModel *_model)
{
this->model = _model;
}
void SignVerifyMessageDialog::setAddress_SM(const QString &address)
{
ui->addressIn_SM->setText(address);
ui->messageIn_SM->setFocus();
}
void SignVerifyMessageDialog::setAddress_VM(const QString &address)
{
ui->addressIn_VM->setText(address);
ui->messageIn_VM->setFocus();
}
void SignVerifyMessageDialog::showTab_SM(bool fShow)
{
ui->tabWidget->setCurrentIndex(0);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::showTab_VM(bool fShow)
{
ui->tabWidget->setCurrentIndex(1);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::on_addressBookButton_SM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_SM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_pasteButton_SM_clicked()
{
setAddress_SM(QApplication::clipboard()->text());
}
void SignVerifyMessageDialog::on_signMessageButton_SM_clicked()
{
if (!model)
return;
/* Clear old signature to ensure users don't get confused on error with an old signature displayed */
ui->signatureOut_SM->clear();
CTxDestination destination = DecodeDestination(ui->addressIn_SM->text().toStdString());
if (!IsValidDestination(destination)) {
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
const CKeyID* keyID = boost::get<CKeyID>(&destination);
if (!keyID) {
ui->addressIn_SM->setValid(false);
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if (!ctx.isValid())
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled."));
return;
}
CKey key;
if (!model->wallet().getPrivKey(*keyID, key))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Private key for the entered address is not available."));
return;
}
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_SM->document()->toPlainText().toStdString();
std::vector<unsigned char> vchSig;
if (!key.SignCompact(ss.GetHash(), vchSig))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>"));
ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(vchSig.data(), vchSig.size())));
}
void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked()
{
GUIUtil::setClipboard(ui->signatureOut_SM->text());
}
void SignVerifyMessageDialog::on_clearButton_SM_clicked()
{
ui->addressIn_SM->clear();
ui->messageIn_SM->clear();
ui->signatureOut_SM->clear();
ui->statusLabel_SM->clear();
ui->addressIn_SM->setFocus();
}
void SignVerifyMessageDialog::on_addressBookButton_VM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_VM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked()
{
CTxDestination destination = DecodeDestination(ui->addressIn_VM->text().toStdString());
if (!IsValidDestination(destination)) {
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
if (!boost::get<CKeyID>(&destination)) {
ui->addressIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
bool fInvalid = false;
std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid);
if (fInvalid)
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
CHashWriter ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_VM->document()->toPlainText().toStdString();
CPubKey pubkey;
if (!pubkey.RecoverCompact(ss.GetHash(), vchSig))
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
if (!(CTxDestination(pubkey.GetID()) == destination)) {
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>"));
}
void SignVerifyMessageDialog::on_clearButton_VM_clicked()
{
ui->addressIn_VM->clear();
ui->signatureIn_VM->clear();
ui->messageIn_VM->clear();
ui->statusLabel_VM->clear();
ui->addressIn_VM->setFocus();
}
bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn)
{
if (ui->tabWidget->currentIndex() == 0)
{
/* Clear status message on focus change */
ui->statusLabel_SM->clear();
/* Select generated signature */
if (object == ui->signatureOut_SM)
{
ui->signatureOut_SM->selectAll();
return true;
}
}
else if (ui->tabWidget->currentIndex() == 1)
{
/* Clear status message on focus change */
ui->statusLabel_VM->clear();
}
}
return QDialog::eventFilter(object, event);
}
|
#include "threepp/math/Frustum.hpp"
#include "threepp/core/BufferGeometry.hpp"
#include "threepp/core/Object3D.hpp"
#include "threepp/math/Matrix4.hpp"
#include "threepp/math/Sphere.hpp"
using namespace threepp;
Frustum::Frustum(Plane p0, Plane p1, Plane p2, Plane p3, Plane p4, Plane p5)
: planes_{p0, p1, p2, p3, p4, p5} {}
Frustum &Frustum::set(const Plane &p0, const Plane &p1, const Plane &p2, const Plane &p3, const Plane &p4, const Plane &p5) {
planes_[0].copy(p0);
planes_[1].copy(p1);
planes_[2].copy(p2);
planes_[3].copy(p3);
planes_[4].copy(p4);
planes_[5].copy(p5);
return *this;
}
Frustum &Frustum::copy(const Frustum &frustum) {
for (int i = 0; i < 6; i++) {
planes_[i].copy(frustum.planes_[i]);
}
return *this;
}
Frustum &Frustum::setFromProjectionMatrix(const Matrix4 &m) {
const auto &me = m.elements;
const float me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
const float me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
const float me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
const float me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
planes_[0].setComponents(me3 - me0, me7 - me4, me11 - me8, me15 - me12).normalize();
planes_[1].setComponents(me3 + me0, me7 + me4, me11 + me8, me15 + me12).normalize();
planes_[2].setComponents(me3 + me1, me7 + me5, me11 + me9, me15 + me13).normalize();
planes_[3].setComponents(me3 - me1, me7 - me5, me11 - me9, me15 - me13).normalize();
planes_[4].setComponents(me3 - me2, me7 - me6, me11 - me10, me15 - me14).normalize();
planes_[5].setComponents(me3 + me2, me7 + me6, me11 + me10, me15 + me14).normalize();
return *this;
}
bool Frustum::intersectsObject(Object3D &object) {
Sphere _sphere{};
auto geometry = object.geometry();
if (!geometry->boundingSphere) geometry->computeBoundingSphere();
_sphere.copy(geometry->boundingSphere.value()).applyMatrix4(*object.matrixWorld);
return this->intersectsSphere(_sphere);
}
bool Frustum::intersectsSphere(const Sphere &sphere) {
const auto ¢er = sphere.center;
const float negRadius = -sphere.radius;
for (int i = 0; i < 6; i++) {
const float distance = planes_[i].distanceToPoint(center);
if (distance < negRadius) {
return false;
}
}
return true;
}
bool Frustum::intersectsBox(const Box3 &box) {
Vector3 _vector{};
for (int i = 0; i < 6; i++) {
const auto &plane = planes_[i];
// corner at max distance
_vector.x = plane.normal.x > 0 ? box.max().x : box.min().x;
_vector.y = plane.normal.y > 0 ? box.max().y : box.min().y;
_vector.z = plane.normal.z > 0 ? box.max().z : box.min().z;
if (plane.distanceToPoint(_vector) < 0) {
return false;
}
}
return true;
}
bool Frustum::containsPoint(const Vector3 &point) {
for (int i = 0; i < 6; i++) {
if (planes_[i].distanceToPoint(point) < 0) {
return false;
}
}
return true;
}
|
; A076662: First differences of A007066.
; 3,3,2,3,3,2,3,2,3,3,2,3,3,2,3,2,3,3,2,3,2,3,3,2,3,3,2,3,2,3,3,2,3,3,2,3,2,3,3,2,3,2,3,3,2,3,3,2,3,2,3,3,2,3,2,3,3,2,3,3,2,3,2,3,3,2,3,3,2,3,2,3,3,2,3,2,3,3,2,3,3,2,3,2,3,3,2,3,3,2,3,2,3,3,2,3,2,3,3,2,3,3,2,3,2
mov $3,$0
mov $5,2
lpb $5,1
mov $0,$3
sub $5,1
add $0,$5
mov $4,$0
pow $0,2
lpb $0,1
sub $0,$4
trn $0,1
add $4,2
lpe
mov $2,$5
mul $4,16
lpb $2,1
mov $1,$4
sub $2,1
lpe
lpe
lpb $3,1
sub $1,$4
mov $3,0
lpe
div $1,32
add $1,2
|
#include <iostream>
using namespace std;
int main()
{
int T;
cin >> T;
int temp = T;
while (T--)
{
if (T != temp - 1)
cout << endl;
int N;
cin >> N;
int sum = 0;
for (int i = 0; i < N; i++)
{
int gas;
cin >> gas;
if (sum < i)
break;
else
sum += gas;
sum--;
}
cout << sum;
}
return 0;
} |
; A066524: a(n) = n*(2^n - 1).
; 0,1,6,21,60,155,378,889,2040,4599,10230,22517,49140,106483,229362,491505,1048560,2228207,4718574,9961453,20971500,44040171,92274666,192937961,402653160,838860775,1744830438,3623878629,7516192740,15569256419,32212254690,66571993057,137438953440,283467841503,584115552222,1202590842845,2473901162460,5085241278427,10445360463834,21440476741593,43980465111000,90159953477591,184717953466326,378231999954901,774056185954260,1583296743997395,3236962232172498,6614661952700369,13510798882111440
mov $1,2
pow $1,$0
sub $1,1
mul $1,$0
mov $0,$1
|
#include "DendyFoundation/ParallelComputing/ThreadManager.h"
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//// - Standard includes section - ////
//// - External includes section - ////
//// -Foundation includes section- ////
#include "DendyFoundation/DebugTools/DebugStack.h"
//// - Internal includes section - ////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//// ---- Namespaces ---- ////
namespace DendyEngine {
namespace DendyFoundation {
namespace ParallelComputing {
//// - Defines and macro section - ////
//// - Using namespace shortcuts - ////
//// - Static const init section - ////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//// Class UThreadManager
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//// ================================================================================================================================ ////
//// ---- Internal methods ----- ////
//// ================================================================================================================================ ////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------------------------------------------------------------------//
//
//----------------------------------------------------------------------------------------------------------------------------------------//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//// ================================================================================================================================ ////
//// ---- Object oriented methods ----- ////
//// ================================================================================================================================ ////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------------------------------------------------------------------//
//
//----------------------------------------------------------------------------------------------------------------------------------------//
TheThreadManager::TheThreadManager() {
DENDYENGINE_CALLSTACK_ENTER;
DENDYENGINE_CALLSTACK_EXIT;
}
//----------------------------------------------------------------------------------------------------------------------------------------//
//
//----------------------------------------------------------------------------------------------------------------------------------------//
TheThreadManager::~TheThreadManager( ) {
DENDYENGINE_CALLSTACK_ENTER;
DENDYENGINE_CALLSTACK_EXIT;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//// ================================================================================================================================ ////
//// ---- Static methods ----- ////
//// ================================================================================================================================ ////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------------------------------------------------------------------//
// Singleton pattern stuff (unique creation only)
//----------------------------------------------------------------------------------------------------------------------------------------//
TheThreadManager& TheThreadManager::getInstance( ) {
static TheThreadManager* debugStack = nullptr;
if ( debugStack == nullptr ) {
debugStack = new TheThreadManager( );
}
return *debugStack;
}
//----------------------------------------------------------------------------------------------------------------------------------------//
// Singleton pattern stuff (destruction)
//----------------------------------------------------------------------------------------------------------------------------------------//
void TheThreadManager::destroyInstance( ) {
static TheThreadManager* debugStack = &getInstance( );
if ( debugStack != nullptr ) {
delete debugStack;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//// ================================================================================================================================ ////
//// ---- Core methods ----- ////
//// ================================================================================================================================ ////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//----------------------------------------------------------------------------------------------------------------------------------------//
//
//----------------------------------------------------------------------------------------------------------------------------------------//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//// ////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
|
// Copyright (c) 2013, ARM Limited. All rights reserved.
//
// This program and the accompanying materials
// are licensed and made available under the terms and conditions of the BSD License
// which accompanies this distribution. The full text of the license may be found at
// http://opensource.org/licenses/bsd-license.php
//
// THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
// WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
//
//
#include <AsmMacroIoLib.h>
#include <Library/ArmLib.h>
#include <AutoGen.h>
INCLUDE AsmMacroIoLib.inc
EXPORT ArmPlatformPeiBootAction
EXPORT ArmPlatformIsPrimaryCore
EXPORT ArmPlatformGetPrimaryCoreMpId
EXPORT ArmPlatformGetCorePosition
IMPORT _gPcd_FixedAtBuild_PcdArmPrimaryCore
IMPORT _gPcd_FixedAtBuild_PcdArmPrimaryCoreMask
AREA CTA9x4Helper, CODE, READONLY
//UINTN
//ArmPlatformGetPrimaryCoreMpId (
// VOID
// );
ArmPlatformGetPrimaryCoreMpId FUNCTION
LoadConstantToReg (_gPcd_FixedAtBuild_PcdArmPrimaryCoreMask, r0)
ldr r0, [r0]
bx lr
ENDFUNC
//UINTN
//ArmPlatformIsPrimaryCore (
// IN UINTN MpId
// );
ArmPlatformIsPrimaryCore FUNCTION
LoadConstantToReg (_gPcd_FixedAtBuild_PcdArmPrimaryCoreMask, r1)
ldr r1, [r1]
and r0, r0, r1
LoadConstantToReg (_gPcd_FixedAtBuild_PcdArmPrimaryCore, r1)
ldr r1, [r1]
cmp r0, r1
moveq r0, #1
movne r0, #0
bx lr
ENDFUNC
//UINTN
//ArmPlatformGetCorePosition (
// IN UINTN MpId
// );
ArmPlatformGetCorePosition FUNCTION
and r0, r0, #ARM_CORE_MASK
bx lr
ENDFUNC
ArmPlatformPeiBootAction FUNCTION
bx lr
ENDFUNC
END
|
/**********************************************************************
* Copyright (c) 2008-2014, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#ifndef GENERATEIDDFACTORY_GENERATEIDDFACTORY_HPP
#define GENERATEIDDFACTORY_GENERATEIDDFACTORY_HPP
#include <generateiddfactory/IddFileFactoryData.hpp>
#include <utilities/core/Path.hpp>
#include <boost/filesystem/fstream.hpp>
#include <vector>
namespace openstudio {
/** Initialize one IddFileFactoryData object per Idd file, based on user input arguments. Throws
* on input error. */
IddFileFactoryDataVector constructIddFileObjects(const std::vector<std::string>& iddArgs);
/** Open the output file streams and start writing the output files. All generated files are
* prefixed with outFileHeader. Call this function before parsing the IDD files. */
void initializeOutFiles(GenerateIddFactoryOutFiles& outFiles,
const std::vector<IddFileFactoryData>& iddFiles);
/** Finish writing the output files. Call this function after parsing all of the IDD files. */
void completeOutFiles(const openstudio::IddFileFactoryDataVector& iddFiles,
GenerateIddFactoryOutFiles& outFiles);
/** Get the IddFileFactoryData object in iddFiles associated with IDD file fileName. Throws if
* the search is unsuccessful. */
openstudio::IddFileFactoryData getFile(const std::string& fileName,
const openstudio::IddFileFactoryDataVector& iddFiles);
} // openstudio
#endif // GENERATEIDDFACTORY_GENERATEIDDFACTORY_HPP
|
; A001093: a(n) = n^3 + 1.
; 0,1,2,9,28,65,126,217,344,513,730,1001,1332,1729,2198,2745,3376,4097,4914,5833,6860,8001,9262,10649,12168,13825,15626,17577,19684,21953,24390,27001,29792,32769,35938,39305,42876,46657,50654,54873,59320,64001,68922,74089,79508,85185,91126,97337,103824,110593,117650,125001,132652,140609,148878,157465,166376,175617,185194,195113,205380,216001,226982,238329,250048,262145,274626,287497,300764,314433,328510,343001,357912,373249,389018,405225,421876,438977,456534,474553,493040,512001,531442,551369,571788,592705,614126,636057,658504,681473,704970,729001,753572,778689,804358,830585,857376,884737,912674,941193,970300,1000001,1030302,1061209,1092728,1124865,1157626,1191017,1225044,1259713,1295030,1331001,1367632,1404929,1442898,1481545,1520876,1560897,1601614,1643033,1685160,1728001,1771562,1815849,1860868,1906625,1953126,2000377,2048384,2097153,2146690,2197001,2248092,2299969,2352638,2406105,2460376,2515457,2571354,2628073,2685620,2744001,2803222,2863289,2924208,2985985,3048626,3112137,3176524,3241793,3307950,3375001,3442952,3511809,3581578,3652265,3723876,3796417,3869894,3944313,4019680,4096001,4173282,4251529,4330748,4410945,4492126,4574297,4657464,4741633,4826810,4913001,5000212,5088449,5177718,5268025,5359376,5451777,5545234,5639753,5735340,5832001,5929742,6028569,6128488,6229505,6331626,6434857,6539204,6644673,6751270,6859001,6967872,7077889,7189058,7301385,7414876,7529537,7645374,7762393,7880600,8000001,8120602,8242409,8365428,8489665,8615126,8741817,8869744,8998913,9129330,9261001,9393932,9528129,9663598,9800345,9938376,10077697,10218314,10360233,10503460,10648001,10793862,10941049,11089568,11239425,11390626,11543177,11697084,11852353,12008990,12167001,12326392,12487169,12649338,12812905,12977876,13144257,13312054,13481273,13651920,13824001,13997522,14172489,14348908,14526785,14706126,14886937,15069224,15252993
sub $0,1
pow $0,3
add $0,1
mov $1,$0
|
//=================================================================================================
/*!
// \file src/mtl/TSMatSMatAdd.cpp
// \brief Source file for the MTL transpose sparse matrix/sparse matrix addition kernel
//
// Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <iostream>
#include <boost/numeric/mtl/mtl.hpp>
#include <blaze/util/Timing.h>
#include <blazemark/mtl/init/Compressed2D.h>
#include <blazemark/mtl/TSMatSMatAdd.h>
#include <blazemark/system/Config.h>
namespace blazemark {
namespace mtl {
//=================================================================================================
//
// KERNEL FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*!\brief MTL transpose sparse matrix/sparse matrix addition kernel.
//
// \param N The number of rows and columns of the matrices.
// \param F The number of non-zero elements in each row/column of the sparse matrices.
// \param steps The number of iteration steps to perform.
// \return Minimum runtime of the kernel function.
//
// This kernel function implements the transpose sparse matrix/sparse matrix addition by means
// of the MTL functionality.
*/
double tsmatsmatadd( size_t N, size_t F, size_t steps )
{
using ::blazemark::element_t;
using row_major = ::mtl::tag::row_major;
using col_major = ::mtl::tag::col_major;
using row_parameters = ::mtl::mat::parameters<row_major>;
using col_parameters = ::mtl::mat::parameters<col_major>;
using row_compressed2D = ::mtl::compressed2D<element_t,row_parameters>;
using col_compressed2D = ::mtl::compressed2D<element_t,col_parameters>;
::blaze::setSeed( seed );
col_compressed2D A( N, N ), C( N, N );
row_compressed2D B( N, N );
::blaze::timing::WcTimer timer;
init( A, F );
init( B, F );
C = A + B;
for( size_t rep=0UL; rep<reps; ++rep )
{
timer.start();
for( size_t step=0UL; step<steps; ++step ) {
C = A + B;
}
timer.end();
if( num_rows(C) != N )
std::cerr << " Line " << __LINE__ << ": ERROR detected!!!\n";
if( timer.last() > maxtime )
break;
}
const double minTime( timer.min() );
const double avgTime( timer.average() );
if( minTime * ( 1.0 + deviation*0.01 ) < avgTime )
std::cerr << " MTL kernel 'tsmatsmatadd': Time deviation too large!!!\n";
return minTime;
}
//*************************************************************************************************
} // namespace mtl
} // namespace blazemark
|
push ebp
mov ebp,esp
push ecx
call dword ptr ds:[4D1BCh]
mov ecx,dword ptr [dev]
shl eax,0Ch
xor eax,ecx
and eax,3F000h
xor eax,ecx
mov dword ptr [dev],eax
mov esp,ebp
pop ebp
ret |
CeruleanCave2F_Script:
jp EnableAutoTextBoxDrawing
CeruleanCave2F_TextPointers:
dw PickUpItemText
dw PickUpItemText
dw PickUpItemText
|
; A333996: Number of composite numbers in the triangular n X n multiplication table.
; 0,1,3,7,11,17,23,31,40,50,60,72,84,98,113,129,145,163,181,201,222,244,266,290,315,341,368,396,424,454,484,516,549,583,618,654,690,728,767,807,847,889,931,975,1020,1066,1112,1160,1209,1259,1310,1362,1414
seq $0,256885 ; a(n) = n*(n + 1)/2 - pi(n), where pi(n) = A000720(n) is the prime counting function.
sub $0,1
|
ORG 100 /PROGRAMMA SCRITTO IN ESADECIMALE
7800
7020
7200
1106
7200
7001
0000
END
|
#include "Dirichlet.h"
#include "Sum.h"
#include "Product.h"
#include <iostream>
long double dirichlet(const vector<long double>& probs,
const vector<int>& obs,
long double s) {
vector<long double> alphas;
for (vector<int>::const_iterator o = obs.begin(); o != obs.end(); ++o)
alphas.push_back(*o + 1 * s);
vector<long double> obsProbs;
vector<long double>::const_iterator a = alphas.begin();
vector<long double>::const_iterator p = probs.begin();
for (; p != probs.end() && a != alphas.end(); ++p, ++a) {
obsProbs.push_back(pow(*p, *a - 1));
}
return 1.0 / beta(alphas) * product(obsProbs);
}
long double dirichletMaximumLikelihoodRatio(const vector<long double>& probs,
const vector<int>& obs,
long double s) {
long double maximizingObs = obs.size() / sum(obs);
vector<int> m(obs.size(), maximizingObs);
return dirichlet(probs, obs, s) / dirichlet(probs, m, s);
}
// XXX the logspace versions are broken
long double dirichletln(const vector<long double>& probs,
const vector<int>& obs,
long double s) {
vector<long double> alphas;
for (vector<int>::const_iterator o = obs.begin(); o != obs.end(); ++o)
alphas.push_back(*o + 1 * s);
vector<long double> obsProbs;
vector<long double>::const_iterator a = alphas.begin();
vector<long double>::const_iterator p = probs.begin();
for (; p != probs.end() && a != alphas.end(); ++p, ++a) {
obsProbs.push_back(powln(log(*p), *a - 1));
}
return log(1.0) - (betaln(alphas) + sum(obsProbs));
}
long double dirichletMaximumLikelihoodRatioln(const vector<long double>& probs,
const vector<int>& obs,
long double s) {
long double maximizingObs = (long double) obs.size() / (long double) sum(obs);
vector<int> m(obs.size(), maximizingObs);
return dirichletln(probs, obs, s) - dirichletln(probs, m, s);
}
|
/*
+----------------------------------------------------------------------+
| Swoole |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| license@swoole.com so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Tianfeng Han <mikan.tenny@gmail.com> |
+----------------------------------------------------------------------+
*/
#include "php_swoole_cxx.h"
#include "swoole_proxy.h"
#include "swoole_mqtt.h"
#include "ext/standard/basic_functions.h"
using swoole::coroutine::Socket;
using swoole::network::Address;
using swoole::Socks5Proxy;
using swoole::HttpProxy;
using swoole::String;
static zend_class_entry *swoole_client_coro_ce;
static zend_object_handlers swoole_client_coro_handlers;
struct ClientCoroObject {
Socket *sock;
zend_object std;
};
SW_EXTERN_C_BEGIN
static PHP_METHOD(swoole_client_coro, __construct);
static PHP_METHOD(swoole_client_coro, __destruct);
static PHP_METHOD(swoole_client_coro, set);
static PHP_METHOD(swoole_client_coro, connect);
static PHP_METHOD(swoole_client_coro, recv);
static PHP_METHOD(swoole_client_coro, peek);
static PHP_METHOD(swoole_client_coro, send);
static PHP_METHOD(swoole_client_coro, sendfile);
static PHP_METHOD(swoole_client_coro, sendto);
static PHP_METHOD(swoole_client_coro, recvfrom);
#ifdef SW_USE_OPENSSL
static PHP_METHOD(swoole_client_coro, enableSSL);
static PHP_METHOD(swoole_client_coro, getPeerCert);
static PHP_METHOD(swoole_client_coro, verifyPeerCert);
#endif
static PHP_METHOD(swoole_client_coro, exportSocket);
static PHP_METHOD(swoole_client_coro, isConnected);
static PHP_METHOD(swoole_client_coro, getsockname);
static PHP_METHOD(swoole_client_coro, getpeername);
static PHP_METHOD(swoole_client_coro, close);
SW_EXTERN_C_END
static Socket *client_coro_new(zval *zobject, int port = 0);
void php_swoole_client_coro_socket_free(Socket *cli);
// clang-format off
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_void, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_construct, 0, 0, 1)
ZEND_ARG_INFO(0, type)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_set, 0, 0, 1)
ZEND_ARG_ARRAY_INFO(0, settings, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_connect, 0, 0, 1)
ZEND_ARG_INFO(0, host)
ZEND_ARG_INFO(0, port)
ZEND_ARG_INFO(0, timeout)
ZEND_ARG_INFO(0, sock_flag)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_recv, 0, 0, 0)
ZEND_ARG_INFO(0, timeout)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_send, 0, 0, 1)
ZEND_ARG_INFO(0, data)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_peek, 0, 0, 0)
ZEND_ARG_INFO(0, length)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_sendfile, 0, 0, 1)
ZEND_ARG_INFO(0, filename)
ZEND_ARG_INFO(0, offset)
ZEND_ARG_INFO(0, length)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_sendto, 0, 0, 3)
ZEND_ARG_INFO(0, address)
ZEND_ARG_INFO(0, port)
ZEND_ARG_INFO(0, data)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_client_coro_recvfrom, 0, 0, 2)
ZEND_ARG_INFO(0, length)
ZEND_ARG_INFO(1, address)
ZEND_ARG_INFO(1, port)
ZEND_END_ARG_INFO()
static const zend_function_entry swoole_client_coro_methods[] =
{
PHP_ME(swoole_client_coro, __construct, arginfo_swoole_client_coro_construct, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, __destruct, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, set, arginfo_swoole_client_coro_set, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, connect, arginfo_swoole_client_coro_connect, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, recv, arginfo_swoole_client_coro_recv, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, peek, arginfo_swoole_client_coro_peek, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, send, arginfo_swoole_client_coro_send, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, sendfile, arginfo_swoole_client_coro_sendfile, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, sendto, arginfo_swoole_client_coro_sendto, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, recvfrom, arginfo_swoole_client_coro_recvfrom, ZEND_ACC_PUBLIC)
#ifdef SW_USE_OPENSSL
PHP_ME(swoole_client_coro, enableSSL, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, getPeerCert, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, verifyPeerCert, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
#endif
PHP_ME(swoole_client_coro, isConnected, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, getsockname, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, getpeername, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, close, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_client_coro, exportSocket, arginfo_swoole_client_coro_void, ZEND_ACC_PUBLIC)
PHP_FE_END
};
// clang-format on
static sw_inline ClientCoroObject *php_swoole_client_coro_fetch_object(zend_object *obj) {
return (ClientCoroObject *) ((char *) obj - swoole_client_coro_handlers.offset);
}
static sw_inline ClientCoroObject *php_swoole_get_client(zval *zobject) {
return php_swoole_client_coro_fetch_object(Z_OBJ_P(zobject));
}
static sw_inline Socket *php_swoole_get_sock(zval *zobject) {
return php_swoole_get_client(zobject)->sock;
}
static void php_swoole_client_coro_free_object(zend_object *object) {
ClientCoroObject *client = php_swoole_client_coro_fetch_object(object);
if (client->sock) {
php_swoole_client_coro_socket_free(client->sock);
}
zend_object_std_dtor(&client->std);
}
static zend_object *php_swoole_client_coro_create_object(zend_class_entry *ce) {
ClientCoroObject *sock_t = (ClientCoroObject *) zend_object_alloc(sizeof(ClientCoroObject), ce);
zend_object_std_init(&sock_t->std, ce);
object_properties_init(&sock_t->std, ce);
sock_t->std.handlers = &swoole_client_coro_handlers;
return &sock_t->std;
}
void php_swoole_client_coro_minit(int module_number) {
SW_INIT_CLASS_ENTRY(
swoole_client_coro, "Swoole\\Coroutine\\Client", nullptr, "Co\\Client", swoole_client_coro_methods);
SW_SET_CLASS_SERIALIZABLE(swoole_client_coro, zend_class_serialize_deny, zend_class_unserialize_deny);
SW_SET_CLASS_CLONEABLE(swoole_client_coro, sw_zend_class_clone_deny);
SW_SET_CLASS_UNSET_PROPERTY_HANDLER(swoole_client_coro, sw_zend_class_unset_property_deny);
SW_SET_CLASS_CUSTOM_OBJECT(
swoole_client_coro, php_swoole_client_coro_create_object, php_swoole_client_coro_free_object, ClientCoroObject, std);
zend_declare_property_long(swoole_client_coro_ce, ZEND_STRL("errCode"), 0, ZEND_ACC_PUBLIC);
zend_declare_property_string(swoole_client_coro_ce, ZEND_STRL("errMsg"), "", ZEND_ACC_PUBLIC);
zend_declare_property_long(swoole_client_coro_ce, ZEND_STRL("fd"), -1, ZEND_ACC_PUBLIC);
zend_declare_property_null(swoole_client_coro_ce, ZEND_STRL("socket"), ZEND_ACC_PRIVATE);
zend_declare_property_long(swoole_client_coro_ce, ZEND_STRL("type"), SW_SOCK_TCP, ZEND_ACC_PUBLIC);
zend_declare_property_null(swoole_client_coro_ce, ZEND_STRL("setting"), ZEND_ACC_PUBLIC);
zend_declare_property_bool(swoole_client_coro_ce, ZEND_STRL("connected"), 0, ZEND_ACC_PUBLIC);
zend_declare_class_constant_long(swoole_client_coro_ce, ZEND_STRL("MSG_OOB"), MSG_OOB);
zend_declare_class_constant_long(swoole_client_coro_ce, ZEND_STRL("MSG_PEEK"), MSG_PEEK);
zend_declare_class_constant_long(swoole_client_coro_ce, ZEND_STRL("MSG_DONTWAIT"), MSG_DONTWAIT);
zend_declare_class_constant_long(swoole_client_coro_ce, ZEND_STRL("MSG_WAITALL"), MSG_WAITALL);
}
static sw_inline Socket *client_get_ptr(zval *zobject, bool silent = false) {
Socket *cli = php_swoole_get_client(zobject)->sock;
if (cli) {
return cli;
} else {
if (!silent) {
zend_update_property_long(
swoole_client_coro_ce, SW_Z8_OBJ_P(zobject), ZEND_STRL("errCode"), SW_ERROR_CLIENT_NO_CONNECTION);
zend_update_property_string(swoole_client_coro_ce,
SW_Z8_OBJ_P(zobject),
ZEND_STRL("errMsg"),
swoole_strerror(SW_ERROR_CLIENT_NO_CONNECTION));
}
return nullptr;
}
}
static Socket *client_coro_new(zval *zobject, int port) {
zval *ztype = sw_zend_read_property_ex(Z_OBJCE_P(zobject), zobject, SW_ZSTR_KNOWN(SW_ZEND_STR_TYPE), 0);
zend_long type = zval_get_long(ztype);
enum swSocket_type sock_type = php_swoole_socktype(type);
if ((sock_type == SW_SOCK_TCP || sock_type == SW_SOCK_TCP6) && (port <= 0 || port > SW_CLIENT_MAX_PORT)) {
php_swoole_fatal_error(E_WARNING, "The port is invalid");
return nullptr;
}
php_swoole_check_reactor();
Socket *cli = new Socket(sock_type);
if (UNEXPECTED(cli->get_fd() < 0)) {
php_swoole_sys_error(E_WARNING, "new Socket() failed");
zend_update_property_long(Z_OBJCE_P(zobject), SW_Z8_OBJ_P(zobject), ZEND_STRL("errCode"), errno);
zend_update_property_string(
Z_OBJCE_P(zobject), SW_Z8_OBJ_P(zobject), ZEND_STRL("errMsg"), swoole_strerror(errno));
delete cli;
return nullptr;
}
zend_update_property_long(Z_OBJCE_P(zobject), SW_Z8_OBJ_P(zobject), ZEND_STRL("fd"), cli->get_fd());
cli->set_buffer_allocator(sw_zend_string_allocator());
cli->set_zero_copy(true);
#ifdef SW_USE_OPENSSL
if (type & SW_SOCK_SSL) {
cli->open_ssl = true;
}
#endif
php_swoole_get_client(zobject)->sock = cli;
return cli;
}
static bool client_coro_close(zval *zobject) {
Socket *cli = php_swoole_get_sock(zobject);
if (cli) {
zend_update_property_bool(Z_OBJCE_P(zobject), SW_Z8_OBJ_P(zobject), ZEND_STRL("connected"), 0);
if (!cli->get_bound_cid()) {
php_swoole_get_client(zobject)->sock = nullptr;
}
php_swoole_client_coro_socket_free(cli);
return true;
}
return false;
}
void php_swoole_client_coro_socket_free(Socket *cli) {
if (!cli->has_bound()) {
if (cli->protocol.private_data) {
sw_zend_fci_cache_discard((zend_fcall_info_cache *) cli->protocol.private_data);
efree(cli->protocol.private_data);
cli->protocol.private_data = nullptr;
}
}
if (cli->close()) {
delete cli;
}
}
bool php_swoole_client_set(Socket *cli, zval *zset) {
HashTable *vht = Z_ARRVAL_P(zset);
zval *ztmp;
bool ret = true;
/**
* timeout
*/
if (php_swoole_array_get_value(vht, "timeout", ztmp)) {
cli->set_timeout(zval_get_double(ztmp));
}
if (php_swoole_array_get_value(vht, "connect_timeout", ztmp)) {
cli->set_timeout(zval_get_double(ztmp), Socket::TIMEOUT_CONNECT);
}
if (php_swoole_array_get_value(vht, "read_timeout", ztmp)) {
cli->set_timeout(zval_get_double(ztmp), Socket::TIMEOUT_READ);
}
if (php_swoole_array_get_value(vht, "write_timeout", ztmp)) {
cli->set_timeout(zval_get_double(ztmp), Socket::TIMEOUT_WRITE);
}
std::string _bind_address;
int _bind_port = 0;
if (php_swoole_array_get_value(vht, "bind_port", ztmp)) {
zend_long v = zval_get_long(ztmp);
_bind_port = SW_MAX(0, SW_MIN(v, UINT16_MAX));
}
if (php_swoole_array_get_value(vht, "bind_address", ztmp)) {
zend::String tmp = ztmp;
_bind_address = tmp.to_std_string();
}
if (!_bind_address.empty() && !cli->bind(_bind_address, _bind_port)) {
ret = false;
}
/**
* socket send/recv buffer size
*/
if (php_swoole_array_get_value(vht, "socket_buffer_size", ztmp)) {
zend_long size = zval_get_long(ztmp);
if (size <= 0) {
php_swoole_fatal_error(E_WARNING, "socket buffer size must be greater than 0, got " ZEND_LONG_FMT, size);
ret = false;
} else {
cli->set_option(SOL_SOCKET, SO_RCVBUF, size) && cli->set_option(SOL_SOCKET, SO_SNDBUF, size);
}
}
/**
* client: tcp_nodelay
*/
if (php_swoole_array_get_value(vht, "open_tcp_nodelay", ztmp)) {
if (cli->get_type() == SW_SOCK_TCP || cli->get_type() != SW_SOCK_TCP6) {
cli->get_socket()->set_tcp_nodelay(zval_is_true(ztmp));
}
}
/**
* openssl and protocol options
*/
if (!php_swoole_socket_set_protocol(cli, zset)) {
ret = false;
}
/**
* socks5 proxy
*/
if (php_swoole_array_get_value(vht, "socks5_host", ztmp)) {
zend::String host(ztmp);
if (php_swoole_array_get_value(vht, "socks5_port", ztmp)) {
if (cli->socks5_proxy == nullptr) {
cli->socks5_proxy = new Socks5Proxy();
}
cli->socks5_proxy->host = host.to_std_string();
cli->socks5_proxy->port = zval_get_long(ztmp);
cli->socks5_proxy->dns_tunnel = 1;
if (php_swoole_array_get_value(vht, "socks5_username", ztmp)) {
zend::String username(ztmp);
if (username.len() > 0 && php_swoole_array_get_value(vht, "socks5_password", ztmp)) {
zend::String password(ztmp);
if (password.len() > 0) {
cli->socks5_proxy->method = 0x02;
cli->socks5_proxy->username = username.to_std_string();
cli->socks5_proxy->password = password.to_std_string();
}
} else {
php_swoole_fatal_error(E_WARNING, "socks5_password should not be null");
ret = false;
}
}
} else {
php_swoole_fatal_error(E_WARNING, "socks5_port should not be null");
ret = false;
}
}
/**
* http proxy
*/
else if (php_swoole_array_get_value(vht, "http_proxy_host", ztmp)) {
zend::String host(ztmp);
if (php_swoole_array_get_value(vht, "http_proxy_port", ztmp)) {
if (cli->http_proxy == nullptr) {
cli->http_proxy = new HttpProxy();
}
cli->http_proxy->proxy_host = host.to_std_string();
cli->http_proxy->proxy_port = zval_get_long(ztmp);
if (php_swoole_array_get_value(vht, "http_proxy_username", ztmp) ||
php_swoole_array_get_value(vht, "http_proxy_user", ztmp)) {
zend::String username(ztmp);
if (username.len() > 0 && php_swoole_array_get_value(vht, "http_proxy_password", ztmp)) {
zend::String password(ztmp);
if (password.len() > 0) {
cli->http_proxy->username = username.to_std_string();
cli->http_proxy->password = password.to_std_string();
}
} else {
php_swoole_fatal_error(E_WARNING, "http_proxy_password should not be null");
ret = false;
}
}
} else {
php_swoole_fatal_error(E_WARNING, "http_proxy_port should not be null");
ret = false;
}
}
return ret;
}
#ifdef SW_USE_OPENSSL
bool php_swoole_socket_set_ssl(Socket *sock, zval *zset) {
HashTable *vht = Z_ARRVAL_P(zset);
zval *ztmp;
bool ret = true;
if (php_swoole_array_get_value(vht, "ssl_protocols", ztmp)) {
zend_long v = zval_get_long(ztmp);
sock->ssl_option.protocols = v;
}
if (php_swoole_array_get_value(vht, "ssl_compress", ztmp)) {
sock->ssl_option.disable_compress = !zval_is_true(ztmp);
} else if (php_swoole_array_get_value(vht, "ssl_disable_compression", ztmp)) {
sock->ssl_option.disable_compress = !zval_is_true(ztmp);
}
if (php_swoole_array_get_value(vht, "ssl_cert_file", ztmp)) {
zend::String str_v(ztmp);
if (sock->ssl_option.cert_file) {
sw_free(sock->ssl_option.cert_file);
sock->ssl_option.cert_file = nullptr;
}
if (access(str_v.val(), R_OK) == 0) {
sock->ssl_option.cert_file = str_v.dup();
} else {
php_swoole_fatal_error(E_WARNING, "ssl cert file[%s] not found", sock->ssl_option.cert_file);
ret = false;
}
}
if (php_swoole_array_get_value(vht, "ssl_key_file", ztmp)) {
zend::String str_v(ztmp);
if (sock->ssl_option.key_file) {
sw_free(sock->ssl_option.key_file);
sock->ssl_option.key_file = nullptr;
}
if (access(str_v.val(), R_OK) == 0) {
sock->ssl_option.key_file = str_v.dup();
} else {
php_swoole_fatal_error(E_WARNING, "ssl key file[%s] not found", sock->ssl_option.key_file);
ret = false;
}
}
if (sock->ssl_option.cert_file && !sock->ssl_option.key_file) {
php_swoole_fatal_error(E_WARNING, "ssl require key file");
} else if (sock->ssl_option.key_file && !sock->ssl_option.cert_file) {
php_swoole_fatal_error(E_WARNING, "ssl require cert file");
}
if (php_swoole_array_get_value(vht, "ssl_passphrase", ztmp)) {
if (sock->ssl_option.passphrase) {
sw_free(sock->ssl_option.passphrase);
}
sock->ssl_option.passphrase = zend::String(ztmp).dup();
}
#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
if (php_swoole_array_get_value(vht, "ssl_host_name", ztmp)) {
if (sock->ssl_option.tls_host_name) {
sw_free(sock->ssl_option.tls_host_name);
}
sock->ssl_option.tls_host_name = zend::String(ztmp).dup();
/* if user set empty ssl_host_name, disable it, otherwise the underlying may set it automatically */
sock->ssl_option.disable_tls_host_name = !sock->ssl_option.tls_host_name;
}
#endif
if (php_swoole_array_get_value(vht, "ssl_verify_peer", ztmp)) {
sock->ssl_option.verify_peer = zval_is_true(ztmp);
}
if (php_swoole_array_get_value(vht, "ssl_allow_self_signed", ztmp)) {
sock->ssl_option.allow_self_signed = zval_is_true(ztmp);
}
if (php_swoole_array_get_value(vht, "ssl_cafile", ztmp)) {
if (sock->ssl_option.cafile) {
sw_free(sock->ssl_option.cafile);
}
sock->ssl_option.cafile = zend::String(ztmp).dup();
}
if (php_swoole_array_get_value(vht, "ssl_capath", ztmp)) {
if (sock->ssl_option.capath) {
sw_free(sock->ssl_option.capath);
}
sock->ssl_option.capath = zend::String(ztmp).dup();
}
if (php_swoole_array_get_value(vht, "ssl_verify_depth", ztmp)) {
zend_long v = zval_get_long(ztmp);
sock->ssl_option.verify_depth = SW_MAX(0, SW_MIN(v, UINT8_MAX));
}
return ret;
}
#endif
static PHP_METHOD(swoole_client_coro, __construct) {
if (php_swoole_get_client(ZEND_THIS)->sock) {
php_swoole_fatal_error(E_ERROR, "Constructor of %s can only be called once", SW_Z_OBJCE_NAME_VAL_P(ZEND_THIS));
}
zend_long type = 0;
ZEND_PARSE_PARAMETERS_START_EX(ZEND_PARSE_PARAMS_THROW, 1, 1)
Z_PARAM_LONG(type)
ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
int client_type = php_swoole_socktype(type);
if (client_type < SW_SOCK_TCP || client_type > SW_SOCK_UNIX_DGRAM) {
const char *space, *class_name = get_active_class_name(&space);
zend_type_error("%s%s%s() expects parameter %d to be client type, unknown type " ZEND_LONG_FMT " given",
class_name,
space,
get_active_function_name(),
1,
type);
RETURN_FALSE;
}
zend_update_property_long(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("type"), type);
RETURN_TRUE;
}
static PHP_METHOD(swoole_client_coro, __destruct) {}
static PHP_METHOD(swoole_client_coro, set) {
Socket *cli = client_get_ptr(ZEND_THIS, true);
zval *zset, *zsetting;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(zset)
ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
if (php_swoole_array_length(zset) == 0) {
RETURN_FALSE;
} else {
zsetting = sw_zend_read_and_convert_property_array(swoole_client_coro_ce, ZEND_THIS, ZEND_STRL("setting"), 0);
php_array_merge(Z_ARRVAL_P(zsetting), Z_ARRVAL_P(zset));
if (cli) {
RETURN_BOOL(php_swoole_client_set(cli, zset));
}
RETURN_TRUE;
}
}
static PHP_METHOD(swoole_client_coro, connect) {
char *host;
size_t host_len;
zend_long port = 0;
double timeout = 0;
zend_long sock_flag = 0;
ZEND_PARSE_PARAMETERS_START(1, 4)
Z_PARAM_STRING(host, host_len)
Z_PARAM_OPTIONAL
Z_PARAM_LONG(port)
Z_PARAM_DOUBLE(timeout)
Z_PARAM_LONG(sock_flag)
ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
if (host_len == 0) {
php_swoole_fatal_error(E_WARNING, "The host is empty");
RETURN_FALSE;
}
Socket *cli = php_swoole_get_sock(ZEND_THIS);
if (cli) {
zend_update_property_long(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errCode"), EISCONN);
zend_update_property_string(
swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errMsg"), swoole_strerror(EISCONN));
RETURN_FALSE;
}
cli = client_coro_new(ZEND_THIS, (int) port);
if (!cli) {
RETURN_FALSE;
}
zval *zset = sw_zend_read_property_ex(swoole_client_coro_ce, ZEND_THIS, SW_ZSTR_KNOWN(SW_ZEND_STR_SETTING), 0);
if (zset && ZVAL_IS_ARRAY(zset)) {
php_swoole_client_set(cli, zset);
}
cli->set_timeout(timeout, Socket::TIMEOUT_CONNECT);
if (!cli->connect(host, port, sock_flag)) {
zend_update_property_long(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errCode"), cli->errCode);
zend_update_property_string(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errMsg"), cli->errMsg);
client_coro_close(ZEND_THIS);
RETURN_FALSE;
}
cli->set_timeout(timeout, Socket::TIMEOUT_RDWR);
zend_update_property_bool(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("connected"), 1);
RETURN_TRUE;
}
static PHP_METHOD(swoole_client_coro, send) {
char *data;
size_t data_len;
double timeout = 0;
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_STRING(data, data_len)
Z_PARAM_OPTIONAL
Z_PARAM_DOUBLE(timeout)
ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
if (data_len == 0) {
php_swoole_fatal_error(E_WARNING, "data to send is empty");
RETURN_FALSE;
}
Socket *cli = client_get_ptr(ZEND_THIS);
if (!cli) {
RETURN_FALSE;
}
Socket::TimeoutSetter ts(cli, timeout, Socket::TIMEOUT_WRITE);
ssize_t ret = cli->send_all(data, data_len);
if (ret < 0) {
zend_update_property_long(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errCode"), cli->errCode);
zend_update_property_string(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errMsg"), cli->errMsg);
RETVAL_FALSE;
} else {
if ((size_t) ret < data_len && cli->errCode) {
zend_update_property_long(
swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errCode"), cli->errCode);
zend_update_property_string(
swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errMsg"), cli->errMsg);
}
RETURN_LONG(ret);
}
}
static PHP_METHOD(swoole_client_coro, sendto) {
char *host;
size_t host_len;
long port;
char *data;
size_t len;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "sls", &host, &host_len, &port, &data, &len) == FAILURE) {
RETURN_FALSE;
}
if (len == 0) {
RETURN_FALSE;
}
Socket *cli = php_swoole_get_sock(ZEND_THIS);
if (!cli) {
cli = client_coro_new(ZEND_THIS, (int) port);
if (!cli) {
RETURN_FALSE;
}
}
ssize_t ret = cli->sendto(std::string(host, host_len), port, data, len);
if (ret < 0) {
zend_update_property_long(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errCode"), cli->errCode);
zend_update_property_string(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errMsg"), cli->errMsg);
RETURN_FALSE;
}
RETURN_TRUE;
}
static PHP_METHOD(swoole_client_coro, recvfrom) {
zend_long length;
zval *address, *port;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "lz/|z/", &length, &address, &port) == FAILURE) {
RETURN_FALSE;
}
if (length <= 0) {
RETURN_FALSE;
}
Socket *cli = php_swoole_get_sock(ZEND_THIS);
if (!cli) {
cli = client_coro_new(ZEND_THIS);
if (!cli) {
RETURN_FALSE;
}
}
zend_string *retval = zend_string_alloc(length, 0);
ssize_t n_bytes = cli->recvfrom(ZSTR_VAL(retval), length);
if (n_bytes < 0) {
zend_string_free(retval);
zend_update_property_long(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errCode"), cli->errCode);
zend_update_property_string(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errMsg"), cli->errMsg);
RETURN_FALSE;
} else {
zval_ptr_dtor(address);
ZVAL_STRING(address, cli->get_ip());
if (port) {
zval_ptr_dtor(port);
ZVAL_LONG(port, cli->get_port());
}
ZSTR_LEN(retval) = n_bytes;
ZSTR_VAL(retval)[ZSTR_LEN(retval)] = '\0';
RETURN_STR(retval);
}
}
static PHP_METHOD(swoole_client_coro, sendfile) {
char *file;
size_t file_len;
zend_long offset = 0;
zend_long length = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|ll", &file, &file_len, &offset, &length) == FAILURE) {
RETURN_FALSE;
}
if (file_len == 0) {
php_swoole_fatal_error(E_WARNING, "file to send is empty");
RETURN_FALSE;
}
Socket *cli = client_get_ptr(ZEND_THIS);
if (!cli) {
RETURN_FALSE;
}
// only stream socket can sendfile
if (!(cli->get_type() == SW_SOCK_TCP || cli->get_type() == SW_SOCK_TCP6 ||
cli->get_type() == SW_SOCK_UNIX_STREAM)) {
zend_update_property_long(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errCode"), EINVAL);
zend_update_property_string(
swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errMsg"), "dgram socket cannot use sendfile");
RETURN_FALSE;
}
if (!cli->sendfile(file, offset, length)) {
zend_update_property_long(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errCode"), cli->errCode);
zend_update_property_string(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errMsg"), cli->errMsg);
RETVAL_FALSE;
} else {
RETVAL_TRUE;
}
}
static PHP_METHOD(swoole_client_coro, recv) {
double timeout = 0;
ZEND_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_DOUBLE(timeout)
ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
Socket *cli = client_get_ptr(ZEND_THIS);
if (!cli) {
RETURN_FALSE;
}
ssize_t retval;
zend_string *result = nullptr;
if (cli->open_length_check || cli->open_eof_check) {
retval = cli->recv_packet(timeout);
if (retval > 0) {
auto strval = cli->pop_packet();
if (strval == nullptr) {
retval = -1;
cli->set_err(ENOMEM);
} else {
result = sw_get_zend_string(strval);
}
}
} else {
result = zend_string_alloc(SW_PHP_CLIENT_BUFFER_SIZE - sizeof(zend_string), 0);
Socket::TimeoutSetter ts(cli, timeout, Socket::TIMEOUT_READ);
retval = cli->recv(ZSTR_VAL(result), SW_PHP_CLIENT_BUFFER_SIZE - sizeof(zend_string));
if (retval <= 0) {
zend_string_free(result);
}
}
if (retval < 0) {
zend_update_property_long(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errCode"), cli->errCode);
zend_update_property_string(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errMsg"), cli->errMsg);
RETURN_FALSE;
} else if (retval == 0) {
RETURN_EMPTY_STRING();
} else {
ZSTR_VAL(result)[retval] = '\0';
ZSTR_LEN(result) = retval;
RETURN_STR(result);
}
}
static PHP_METHOD(swoole_client_coro, peek) {
zend_long buf_len = SW_PHP_CLIENT_BUFFER_SIZE;
int ret;
char *buf = nullptr;
ZEND_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_LONG(buf_len)
ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE);
Socket *cli = client_get_ptr(ZEND_THIS);
if (!cli) {
RETURN_FALSE;
}
buf = (char *) emalloc(buf_len + 1);
ret = cli->peek(buf, buf_len);
if (ret < 0) {
zend_update_property_long(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errCode"), cli->errCode);
zend_update_property_string(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errMsg"), cli->errMsg);
efree(buf);
RETURN_FALSE;
} else {
buf[ret] = 0;
RETVAL_STRINGL(buf, ret);
efree(buf);
}
}
static PHP_METHOD(swoole_client_coro, isConnected) {
Socket *cli = php_swoole_get_sock(ZEND_THIS);
if (cli && cli->is_connect()) {
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
static PHP_METHOD(swoole_client_coro, getsockname) {
Socket *cli = client_get_ptr(ZEND_THIS);
if (!cli) {
RETURN_FALSE;
}
Address sa;
if (!cli->getsockname(&sa)) {
zend_update_property_long(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errCode"), cli->errCode);
zend_update_property_string(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errMsg"), cli->errMsg);
RETURN_FALSE;
}
array_init(return_value);
zval zaddress;
ZVAL_STRING(&zaddress, sa.get_ip());
add_assoc_zval(return_value, "host", &zaddress); /* backward compatibility */
Z_ADDREF(zaddress);
add_assoc_zval(return_value, "address", &zaddress);
add_assoc_long(return_value, "port", sa.get_port());
}
/**
* export Swoole\Coroutine\Socket object
*/
static PHP_METHOD(swoole_client_coro, exportSocket) {
zval rv;
zval *zsocket = zend_read_property(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("socket"), 1, &rv);
if (!ZVAL_IS_NULL(zsocket)) {
RETURN_ZVAL(zsocket, 1, 0);
}
Socket *cli = client_get_ptr(ZEND_THIS);
if (!cli) {
RETURN_FALSE;
}
if (!php_swoole_export_socket(return_value, cli)) {
RETURN_FALSE;
}
zend_update_property(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("socket"), return_value);
}
static PHP_METHOD(swoole_client_coro, getpeername) {
Socket *cli = client_get_ptr(ZEND_THIS);
if (!cli) {
RETURN_FALSE;
}
Address sa;
if (!cli->getpeername(&sa)) {
zend_update_property_long(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errCode"), cli->errCode);
zend_update_property_string(swoole_client_coro_ce, SW_Z8_OBJ_P(ZEND_THIS), ZEND_STRL("errMsg"), cli->errMsg);
RETURN_FALSE;
}
array_init(return_value);
zval zaddress;
ZVAL_STRING(&zaddress, sa.get_ip());
add_assoc_zval(return_value, "host", &zaddress); /* backward compatibility */
Z_ADDREF(zaddress);
add_assoc_zval(return_value, "address", &zaddress);
add_assoc_long(return_value, "port", sa.get_port());
}
static PHP_METHOD(swoole_client_coro, close) {
RETURN_BOOL(client_coro_close(ZEND_THIS));
}
#ifdef SW_USE_OPENSSL
static PHP_METHOD(swoole_client_coro, enableSSL) {
Socket *cli = client_get_ptr(ZEND_THIS);
if (!cli) {
RETURN_FALSE;
}
if (cli->get_type() != SW_SOCK_TCP && cli->get_type() != SW_SOCK_TCP6) {
php_swoole_fatal_error(E_WARNING, "cannot use enableSSL");
RETURN_FALSE;
}
if (cli->get_ssl()) {
php_swoole_fatal_error(E_WARNING, "SSL has been enabled");
RETURN_FALSE;
}
zval *zset = sw_zend_read_property_ex(swoole_client_coro_ce, ZEND_THIS, SW_ZSTR_KNOWN(SW_ZEND_STR_SETTING), 0);
if (php_swoole_array_length_safe(zset) > 0) {
php_swoole_socket_set_ssl(cli, zset);
}
RETURN_BOOL(cli->ssl_handshake());
}
static PHP_METHOD(swoole_client_coro, getPeerCert) {
Socket *cli = client_get_ptr(ZEND_THIS);
if (!cli) {
RETURN_FALSE;
}
if (!cli->get_ssl()) {
php_swoole_fatal_error(E_WARNING, "SSL is not ready");
RETURN_FALSE;
}
if (!cli->get_socket()->ssl_get_peer_certificate(sw_tg_buffer())) {
RETURN_FALSE;
}
RETURN_SW_STRING(sw_tg_buffer());
}
static PHP_METHOD(swoole_client_coro, verifyPeerCert) {
Socket *cli = client_get_ptr(ZEND_THIS);
if (!cli) {
RETURN_FALSE;
}
if (!cli->get_ssl()) {
php_swoole_fatal_error(E_WARNING, "SSL is not ready");
RETURN_FALSE;
}
zend_bool allow_self_signed = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &allow_self_signed) == FAILURE) {
RETURN_FALSE;
}
RETURN_BOOL(cli->ssl_verify(allow_self_signed));
}
#endif
|
COMMENT @----------------------------------------------------------------------
Copyright (c) Berkeley Softworks 1991 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: Text
FILE: rulerClass.asm
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 4/92 Initial version
DESCRIPTION:
This file contains code to implement TextRulerClass
$Id: rulerClass.asm,v 1.1 97/04/07 11:19:46 newdeal Exp $
------------------------------------------------------------------------------@
TextClassStructures segment resource
TextRulerClass
TextClassStructures ends
;---
RulerCommon segment resource
COMMENT @----------------------------------------------------------------------
MESSAGE: TextRulerVisOpen -- MSG_VIS_OPEN for TextRulerClass
DESCRIPTION: Catch VIS-OPEN and add ourself to the appropriate
notification list
PASS:
*ds:si - instance data
es - segment of TextRulerClass (not dgroup)
ax - The message
bp - data
RETURN:
none
DESTROYED:
bx, si, di, ds, es (message handler)
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 4/ 6/92 Initial version
------------------------------------------------------------------------------@
TextRulerVisOpen method dynamic TextRulerClass, MSG_VIS_OPEN
mov di, MSG_META_GCN_LIST_ADD
GOTO OpenCloseCommon
TextRulerVisOpen endm
;---
TextRulerVisClose method dynamic TextRulerClass, MSG_VIS_CLOSE
mov di, MSG_META_GCN_LIST_REMOVE
FALL_THRU OpenCloseCommon
TextRulerVisClose endm
;---
OpenCloseCommon proc far
class TextRulerClass
push di ;save message
mov di, offset TextRulerClass
call ObjCallSuperNoLock
pop ax ;ax = message
sub sp, size GCNListParams ; create stack frame
mov bp, sp
mov ss:[bp].GCNLP_ID.GCNLT_manuf, MANUFACTURER_ID_GEOWORKS
mov ss:[bp].GCNLP_ID.GCNLT_type, GAGCNLT_TEXT_RULER_OBJECTS
mov bx, ds:[LMBH_handle]
mov ss:[bp].GCNLP_optr.handle, bx
mov ss:[bp].GCNLP_optr.chunk, si
mov dx, size GCNListParams ; create stack frame
; add ourself to the list of controlled text rulers
push si
clr bx
call GeodeGetAppObject
mov di, mask MF_STACK
call ObjMessage
pop si
; If we have a content specified then attach to its GCN lists
mov ss:[bp].GCNLP_ID.GCNLT_type,
VCGCNLT_TARGET_NOTIFY_TEXT_PARA_ATTR_CHANGE
mov di, ds:[si]
add di, ds:[di].Vis_offset
mov bx, ds:[di].TRI_gcnContent.handle
tst bx
jz noContentGiven
mov si, ds:[di].TRI_gcnContent.chunk
mov di, mask MF_STACK
call ObjMessage
jmp done
noContentGiven:
tst ds:[di].TRI_gcnContent.chunk
jz sendToParent
; send to the app
mov ss:[bp].GCNLP_ID.GCNLT_type,
GAGCNLT_APP_TARGET_NOTIFY_TEXT_PARA_ATTR_CHANGE
clr bx
call GeodeGetAppObject
mov di, mask MF_STACK
call ObjMessage
jmp done
sendToParent:
push si
mov bx, segment VisContentClass
mov si, offset VisContentClass
mov di, mask MF_STACK or mask MF_RECORD
call ObjMessage ;di = message
mov cx, di
pop si
mov ax, MSG_VIS_VUP_CALL_OBJECT_OF_CLASS
call VisCallParent
done:
add sp, size GCNListParams ; fix stack
ret
OpenCloseCommon endp
COMMENT @----------------------------------------------------------------------
MESSAGE: TextRulerNotifyWithDataBlock -- MSG_META_NOTIFY_WITH_DATA_BLOCK
for TextRulerClass
DESCRIPTION: Handle notification
PASS:
*ds:si - instance data
es - segment of TextRulerClass (not dgroup)
ax - The message
cx.dx - change type ID
bp - handle of block with NotifyTextChange structure
RETURN:
DESTROYED:
bx, si, di, ds, es (message handler)
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 4/ 6/92 Initial version
------------------------------------------------------------------------------@
TextRulerNotifyWithDataBlock method dynamic TextRulerClass,
MSG_META_NOTIFY_WITH_DATA_BLOCK
cmp cx, MANUFACTURER_ID_GEOWORKS
jnz sendToSuper
cmp dx, GWNT_TEXT_PARA_ATTR_CHANGE
jz 5$
sendToSuper:
mov ax, MSG_META_NOTIFY_WITH_DATA_BLOCK
GOTO TR_SendToSuper
5$:
tst bp
jnz valid
mov ds:[di].TRI_valid, BB_FALSE
jmp afterUpdate
valid:
mov ds:[di].TRI_valid, BB_TRUE
; copy in the data
mov bx, bp
call MemLock
mov es, ax
; if "align with page" then zero VRI_offset
push bp
movdw dxcx, es:VTNPAC_regionOffset
clr bp ;dxcx.bp = regionOffset
mov ax, MSG_VIS_RULER_SET_ORIGIN
call ObjCallInstanceNoLock
pop bp
mov di, ds:[si]
add di, ds:[di].Vis_offset
mov ax, es:VTNPAC_selectedTab
mov ds:[di].TRI_selectedTab, ax
mov ax, es:VTNPAC_regionWidth
shl ax
shl ax
shl ax ;convert to 13.3
;
; Check for some really big value, which seems unreasonable...
;
EC < cmp ax, 0xf000 >
EC < ERROR_A REGION_WIDTH_IS_NOT_REASONABLE >
mov ds:[di].TRI_regionWidth, ax
push si, di, ds
segxchg es, ds
lea dx, es:[di].TRI_diffs
lea di, es:[di].TRI_paraAttr
mov si, offset VTNPAC_paraAttr
mov cx, (size VisTextMaxParaAttr) / 2
rep movsw
mov si, offset VTNPAC_paraAttrDiffs
mov di, dx
mov cx, (size VisTextParaAttrDiffs) / 2
rep movsw
pop si, di, ds
; convert right margin to physical
sub ax, ds:[di].TRI_paraAttr.VTMPA_paraAttr.VTPA_rightMargin
mov ds:[di].TRI_paraAttr.VTMPA_paraAttr.VTPA_rightMargin, ax
mov bx, bp
call MemUnlock
afterUpdate:
push bp
call RedrawMarginsAndTabs
pop bp
jmp sendToSuper
TextRulerNotifyWithDataBlock endm
COMMENT @----------------------------------------------------------------------
MESSAGE: TextRulerSetGCNContent -- MSG_TEXT_RULER_SET_GCN_CONTENT
for TextRulerClass
DESCRIPTION: Set the GCN content
PASS:
*ds:si - instance data
es - segment of TextRulerClass (not dgroup)
ax - The message
cx:dx - content
RETURN:
DESTROYED:
bx, si, di, ds, es (message handler)
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 4/ 7/92 Initial version
------------------------------------------------------------------------------@
TextRulerSetGCNContent method dynamic TextRulerClass,
MSG_TEXT_RULER_SET_GCN_CONTENT
movdw ds:[di].TRI_gcnContent, cxdx
ret
TextRulerSetGCNContent endm
COMMENT @----------------------------------------------------------------------
MESSAGE: TextRulerSetControlledAttrs --
MSG_TEXT_RULER_SET_CONTROLLED_ATTRS for TextRulerClass
DESCRIPTION: Set the controller attributes
PASS:
*ds:si - instance data
es - segment of TextRulerClass (not dgroup)
ax - The message
cx - TextRulerControlAttributes
RETURN:
DESTROYED:
bx, si, di, ds, es (message handler)
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 5/21/92 Initial version
------------------------------------------------------------------------------@
TextRulerSetControlledAttrs method dynamic TextRulerClass,
MSG_TEXT_RULER_SET_CONTROLLED_ATTRS
test cx, mask TRCA_ROUND
jz clearRound
ornf ds:[di].TRI_flags, mask TRF_ROUND_COORDINATES
jmp common
clearRound:
andnf ds:[di].TRI_flags, not mask TRF_ROUND_COORDINATES
common:
and cx, mask TRCA_IGNORE_ORIGIN
mov ax, MSG_VIS_RULER_SET_IGNORE_ORIGIN
GOTO ObjCallInstanceNoLock
TextRulerSetControlledAttrs endm
COMMENT @----------------------------------------------------------------------
FUNCTION: RulerCoordToObjectCoord
DESCRIPTION: Translate a ruler coordinate to a object coordinate
CALLED BY: INTERNAL
PASS:
*ds:si - text ruler
ax - position (13.3)
RETURN:
ax - position
DESTROYED:
none
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 4/ 6/92 Initial version
------------------------------------------------------------------------------@
RulerCoordToObjectCoord proc near uses cx, dx, di
class TextRulerClass
.enter
mov_tr cx, ax
clr ax ;cx.ax = position
mov dl, 3
sloop:
shr cx
rcr ax
dec dl
jnz sloop
mov di, ds:[si]
add di, ds:[di].Vis_offset
adddwf dxcxax, ds:[di].VRI_origin
clr dx ;dxcx.ax = position
call RulerScaleDocToWinCoords
add ax, 0x8000
jnc 10$
inc cx
10$:
mov_tr ax, cx ;ax = window position
.leave
ret
RulerCoordToObjectCoord endp
RulerCommon ends
;---
RulerCode segment resource
COMMENT @----------------------------------------------------------------------
FUNCTION: ObjectCoordToRulerCoord
DESCRIPTION: Translate an object coordinate to a ruler coordinate
CALLED BY: INTERNAL
PASS:
*ds:si - text ruler
ss:bp - LargeMouseData
RETURN:
ax - position
DESTROYED:
none
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 4/ 6/92 Initial version
------------------------------------------------------------------------------@
ObjectCoordToRulerCoord proc near uses cx, dx, di
class TextRulerClass
.enter
movdwf dxcxax, ss:[bp].LMD_location.PDF_x
mov di, ds:[si]
add di, ds:[di].Vis_offset
subdwf dxcxax, ds:[di].VRI_origin
;cx.ax = position
mov dl, 3
sloop:
shl ax
rcl cx
dec dl
jnz sloop
add ax, 0x8000
jnc 20$
inc cx
20$:
mov_tr ax, cx
.leave
ret
ObjectCoordToRulerCoord endp
COMMENT @----------------------------------------------------------------------
FUNCTION: RoundCoordinate
DESCRIPTION: Round a coordinate
CALLED BY: INTERNAL
PASS:
*ds:si - VisRuler object
ax - coordinate to round
RETURN:
ax - rounded coordinate
DESTROYED:
none
REGISTER/STACK USAGE:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
Tony 5/22/92 Initial version
------------------------------------------------------------------------------@
TextRulerScaleZones etype byte
TRSZ_UNDER_25_PERCENT enum TextRulerScaleZones ;x <= 25%
TRSZ_25_TO_50_PERCENT enum TextRulerScaleZones ;25% <= x <= 50%
TRSZ_50_TO_75_PERCENT enum TextRulerScaleZones ;50% <= x <= 75%
TRSZ_75_TO_100_PERCENT enum TextRulerScaleZones ;75% <= x <= 100%
TRSZ_100_TO_125_PERCENT enum TextRulerScaleZones ;100% <= x <= 125%
TRSZ_125_TO_150_PERCENT enum TextRulerScaleZones ;125% <= x <= 150%
TRSZ_150_TO_200_PERCENT enum TextRulerScaleZones ;150% <= x <= 200%
TRSZ_OVER_200_PERCENT enum TextRulerScaleZones ;200% <= x
RoundCoordinate proc near uses bx, cx, dx, di
class TextRulerClass
.enter
mov di, ds:[si]
add di, ds:[di].Vis_offset
test ds:[di].TRI_flags, mask TRF_ROUND_COORDINATES
jz done
movdw cxdx, ds:[di].VRI_scale
; calculate the scale factor zone (cx.dx = scale)
mov bx, TRSZ_OVER_200_PERCENT
cmp cx, 2
jae gotScale
shl dx ;multiply by 4
rcl cx
shl dx
rcl cx
adddw cxdx, 0x8000 ;and round
mov bx, cx
gotScale:
clr dx
cmp ds:[di].VRI_type, VRT_CENTIMETERS
jz metric
push ax
shl bx
mov cx, cs:[bx][roundTable] ;get rounding value
div cx ;ax = result, dx = fraction
pop ax
mov ch, cl
shr ch ;cx = rounding value / 2
cmp dl, ch
jle roundDown
; round up
sub dl, cl ;produces negative result
neg dl
add ax, dx
jmp done
roundDown:
sub ax, dx
done:
.leave
ret
; if metric, we either round to:
; 25% - centimeters
; 50%, 75%, 100%, 125% - half centimeters
; 150%, 175%, 200% - millimeters
; 1 cm = 28.3464576 points
; divide (pixels*4096) by (value*2048) to get (result * 2)
; round this, divide by 2 and multiply by (value*2048)
; to get (position*2048)
metric:
mov cx, 4096/8
mul cx ;dx.ax = (pixels*4096)
shl bx ;make bx a word index
div cs:[bx][metricRoundTable] ;ax = result, dx = remainder
inc ax ;round
shr ax, 1 ;ax = result
mul cs:[bx][metricRoundTable] ;dx.ax = position * 2048
add ax, 2048/2 ;round position
adc dx, 0
mov cx, 2048/8 ;divide dx.ax by 2048
div cx
jmp done
RoundCoordinate endp
roundTable label word
word 72*8 ; TRSZ_UNDER_25_PERCENT
word 36*8 ; TRSZ_25_TO_50_PERCENT
word 18*8 ; TRSZ_50_TO_75_PERCENT
word 9*8 ; TRSZ_75_TO_100_PERCENT
word 9*8 ; TRSZ_100_TO_125_PERCENT
word 9*8 ; TRSZ_125_TO_150_PERCENT
word 9*4 ; TRSZ_150_TO_200_PERCENT
word 9*4 ; TRSZ_OVER_200_PERCENT
metricRoundTable label word
word 58053 ;25% -- 1 cm * 2048
word 29027 ;50% -- 1/2 cm * 2048
word 29027 ;75% -- 1/2 cm * 2048
word 29027 ;100% -- 1/2 cm * 2048
word 29027 ;125% -- 1/2 cm * 2048
word 5805 ;150% -- 1 mm * 2048
word 5805 ;175% -- 1 mm * 2048
word 5805 ;200% -- 1 mm * 2048
RulerCode ends
|
#include "Platform.inc"
#include "PollChain.inc"
#include "TestDoubles.inc"
radix decimal
udata
global calledPollAfterTimer0
calledPollAfterTimer0 res 1
PollAfterTimer0Mock code
global initialisePollAfterTimer0Mock
global POLL_AFTER_TIMER0
initialisePollAfterTimer0Mock:
banksel calledPollAfterTimer0
clrf calledPollAfterTimer0
return
POLL_AFTER_TIMER0:
mockCalled calledPollAfterTimer0
return
end
|
C sparc32/arcfour-crypt.asm
ifelse(<
Copyright (C) 2002, 2005 Niels Möller
This file is part of GNU Nettle.
GNU Nettle is free software: you can redistribute it and/or
modify it under the terms of either:
* the GNU Lesser General Public License as published by the Free
Software Foundation; either version 3 of the License, or (at your
option) any later version.
or
* the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your
option) any later version.
or both in parallel, as here.
GNU Nettle is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received copies of the GNU General Public License and
the GNU Lesser General Public License along with this program. If
not, see http://www.gnu.org/licenses/.
>)
C Define to YES, to enable the complex code to special case SRC
C and DST with compatible alignment.
define(<WITH_ALIGN>, <YES>)
C Registers
define(<CTX>, <%i0>)
define(<LENGTH>,<%i1>)
define(<DST>, <%i2>)
define(<SRC>, <%i3>)
define(<I1>, <%i4>)
define(<I2>, <%i5>)
define(<J>, <%g1>)
define(<SI>, <%g2>)
define(<SJ>, <%g3>)
define(<TMP>, <%o0>)
define(<TMP2>, <%o1>)
define(<N>, <%o2>)
define(<DATA>, <%o3>)
C Computes the next byte of the key stream. As input, i must
C already point to the index for the current access, the index
C for the next access is stored in ni. The resulting key byte is
C stored in res.
C ARCFOUR_BYTE(i, ni, res)
define(<ARCFOUR_BYTE>, <
ldub [CTX + $1], SI
add $1, 1, $2
add J, SI, J
and J, 0xff, J
ldub [CTX + J], SJ
and $2, 0xff, $2
stb SI, [CTX + J]
add SI, SJ, SI
and SI, 0xff, SI
stb SJ, [CTX + $1]
ldub [CTX + SI], $3
>)dnl
C FIXME: Consider using the callers window
define(<FRAME_SIZE>, 104)
.file "arcfour-crypt.asm"
C arcfour_crypt(struct arcfour_ctx *ctx,
C size_t length, uint8_t *dst,
C const uint8_t *src)
.section ".text"
.align 16
.proc 020
PROLOGUE(nettle_arcfour_crypt)
save %sp, -FRAME_SIZE, %sp
cmp LENGTH, 0
be .Lend
nop
C Load both I and J
lduh [CTX + ARCFOUR_I], I1
and I1, 0xff, J
srl I1, 8, I1
C We want an even address for DST
andcc DST, 1, %g0
add I1, 1 ,I1
beq .Laligned2
and I1, 0xff, I1
mov I1, I2
ldub [SRC], DATA
ARCFOUR_BYTE(I2, I1, TMP)
subcc LENGTH, 1, LENGTH
add SRC, 1, SRC
xor DATA, TMP, DATA
stb DATA, [DST]
beq .Ldone
add DST, 1, DST
.Laligned2:
cmp LENGTH, 2
blu .Lfinal1
C Harmless delay slot instruction
andcc DST, 2, %g0
beq .Laligned4
nop
ldub [SRC], DATA
ARCFOUR_BYTE(I1, I2, TMP)
ldub [SRC + 1], TMP2
add SRC, 2, SRC
xor DATA, TMP, DATA
sll DATA, 8, DATA
ARCFOUR_BYTE(I2, I1, TMP)
xor TMP2, TMP, TMP
subcc LENGTH, 2, LENGTH
or DATA, TMP, DATA
sth DATA, [DST]
beq .Ldone
add DST, 2, DST
.Laligned4:
cmp LENGTH, 4
blu .Lfinal2
C Harmless delay slot instruction
srl LENGTH, 2, N
.Loop:
C Main loop, with aligned writes
C FIXME: Could check if SRC is aligned, and
C use 32-bit reads in that case.
ldub [SRC], DATA
ARCFOUR_BYTE(I1, I2, TMP)
ldub [SRC + 1], TMP2
xor TMP, DATA, DATA
sll DATA, 8, DATA
ARCFOUR_BYTE(I2, I1, TMP)
xor TMP2, TMP, TMP
ldub [SRC + 2], TMP2
or TMP, DATA, DATA
sll DATA, 8, DATA
ARCFOUR_BYTE(I1, I2, TMP)
xor TMP2, TMP, TMP
ldub [SRC + 3], TMP2
or TMP, DATA, DATA
sll DATA, 8, DATA
ARCFOUR_BYTE(I2, I1, TMP)
xor TMP2, TMP, TMP
or TMP, DATA, DATA
subcc N, 1, N
add SRC, 4, SRC
st DATA, [DST]
bne .Loop
add DST, 4, DST
andcc LENGTH, 3, LENGTH
beq .Ldone
nop
.Lfinal2:
C DST address must be 2-aligned
cmp LENGTH, 2
blu .Lfinal1
nop
ldub [SRC], DATA
ARCFOUR_BYTE(I1, I2, TMP)
ldub [SRC + 1], TMP2
add SRC, 2, SRC
xor DATA, TMP, DATA
sll DATA, 8, DATA
ARCFOUR_BYTE(I2, I1, TMP)
xor TMP2, TMP, TMP
or DATA, TMP, DATA
sth DATA, [DST]
beq .Ldone
add DST, 2, DST
.Lfinal1:
mov I1, I2
ldub [SRC], DATA
ARCFOUR_BYTE(I2, I1, TMP)
xor DATA, TMP, DATA
stb DATA, [DST]
.Ldone:
C Save back I and J
sll I2, 8, I2
or I2, J, I2
stuh I2, [CTX + ARCFOUR_I]
.Lend:
ret
restore
EPILOGUE(nettle_arcfour_crypt)
C Some stats from adriana.lysator.liu.se (SS1000E, 85 MHz), for AES 128
C 1: nettle-1.13 C-code
C 2: First working version of the assembler code
C 3: Moved load of source byte
C 4: Better instruction scheduling
C 5: Special case SRC and DST with compatible alignment
C 6: After bugfix (reorder of ld [CTX+SI+SJ] and st [CTX + SI])
C 7: Unrolled only twice, with byte-accesses
C 8: Unrolled, using 8-bit reads and aligned 32-bit writes.
C MB/s cycles/byte Code size (bytes)
C 1: 6.6 12.4 132
C 2: 5.6 14.5 116
C 3: 6.0 13.5 116
C 4: 6.5 12.4 116
C 5: 7.9 10.4 496
C 6: 8.3 9.7 496
C 7: 6.7 12.1 268
C 8: 8.3 9.8 768
|
; A186224: Adjusted joint rank sequence of (g(i)) and (f(j)) with f(i) before g(j) when f(i)=g(j), where f and g are the triangular numbers and pentagonal numbers. Complement of A186223.
; 2,4,7,10,12,15,18,21,23,26,29,32,34,37,40,42,45,48,51,53,56,59,62,64,67,70,72,75,78,81,83,86,89,92,94,97,100,103,105,108,111,113,116,119,122,124,127,130,133,135,138,141,144,146,149,152,154,157,160,163,165,168,171,174,176,179,182,184,187,190,193,195,198,201,204,206,209,212,215,217,220,223,225,228,231,234,236,239,242,245,247,250,253,256,258,261,264,266,269,272
mov $2,$0
pow $2,2
mov $3,$0
mov $5,$0
lpb $2
lpb $4
sub $2,$4
sub $2,2
sub $4,$4
lpe
mov $0,$3
trn $2,1
add $3,1
add $4,$0
lpe
mov $1,$0
add $1,2
add $1,$5
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r12
push %r13
push %r14
push %rbp
push %rdx
push %rsi
lea addresses_normal_ht+0xf2c7, %r10
nop
nop
nop
nop
nop
inc %rdx
movw $0x6162, (%r10)
nop
nop
nop
nop
cmp $58724, %rsi
lea addresses_normal_ht+0x1cb23, %r14
nop
xor %rbp, %rbp
movb $0x61, (%r14)
nop
cmp $48608, %r10
lea addresses_normal_ht+0x3543, %r13
nop
nop
nop
nop
nop
inc %r12
mov (%r13), %rbp
nop
nop
nop
cmp %r14, %r14
lea addresses_A_ht+0x2d4b, %rsi
sub %r14, %r14
movw $0x6162, (%rsi)
nop
nop
nop
nop
xor %rdx, %rdx
lea addresses_A_ht+0x9323, %r12
nop
nop
dec %r14
mov $0x6162636465666768, %r13
movq %r13, (%r12)
nop
nop
nop
nop
dec %rdx
lea addresses_UC_ht+0x1b723, %rsi
nop
nop
nop
nop
sub $55770, %r10
movb $0x61, (%rsi)
nop
add $20768, %rdx
lea addresses_WC_ht+0x1d65b, %r10
nop
nop
and %rdx, %rdx
mov (%r10), %r13w
nop
cmp %rsi, %rsi
pop %rsi
pop %rdx
pop %rbp
pop %r14
pop %r13
pop %r12
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r14
push %rax
push %rbp
push %rbx
push %rcx
push %rdx
// Store
lea addresses_UC+0x16aa3, %rcx
xor $60318, %rbx
movl $0x51525354, (%rcx)
nop
nop
nop
cmp $23068, %r14
// Store
lea addresses_PSE+0x1e645, %rbp
add $26002, %rax
mov $0x5152535455565758, %r10
movq %r10, %xmm6
movups %xmm6, (%rbp)
and $11778, %rax
// Store
mov $0x26b45900000006c9, %rbp
nop
sub $15164, %rdx
movb $0x51, (%rbp)
nop
nop
nop
cmp %rax, %rax
// Store
lea addresses_WC+0x13323, %r14
nop
sub $13895, %rax
movl $0x51525354, (%r14)
nop
add %r14, %r14
// Faulty Load
lea addresses_WC+0x13323, %rcx
clflush (%rcx)
nop
inc %rax
mov (%rcx), %bx
lea oracles, %r10
and $0xff, %rbx
shlq $12, %rbx
mov (%r10,%rbx,1), %rbx
pop %rdx
pop %rcx
pop %rbx
pop %rbp
pop %rax
pop %r14
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': True, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 7, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': True, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': True, 'congruent': 2, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 10, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 4, 'size': 8, 'same': True, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 3, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 11, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 7, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 3, 'size': 2, 'same': False, 'NT': False}}
{'e2': 1, '54': 21828}
54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54
*/
|
/*
*
* Copyright 2018 gRPC authors.
*
* 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 <grpc/support/port_platform.h>
#include "src/core/tsi/alts/handshaker/alts_shared_resource.h"
#include <grpc/support/log.h>
#include "src/core/tsi/alts/handshaker/alts_handshaker_client.h"
static alts_shared_resource_dedicated g_alts_resource_dedicated;
static alts_shared_resource* g_shared_resources = alts_get_shared_resource();
alts_shared_resource_dedicated* grpc_alts_get_shared_resource_dedicated(void) {
return &g_alts_resource_dedicated;
}
static void thread_worker(void* arg) {
while (true) {
grpc_event event =
grpc_completion_queue_next(g_alts_resource_dedicated.cq,
gpr_inf_future(GPR_CLOCK_REALTIME), nullptr);
GPR_ASSERT(event.type != GRPC_QUEUE_TIMEOUT);
if (event.type == GRPC_QUEUE_SHUTDOWN) {
break;
}
GPR_ASSERT(event.type == GRPC_OP_COMPLETE);
alts_handshaker_client* client =
static_cast<alts_handshaker_client*>(event.tag);
alts_handshaker_client_handle_response(client, event.success);
}
}
void grpc_alts_shared_resource_dedicated_init() {
g_alts_resource_dedicated.cq = nullptr;
}
void grpc_alts_shared_resource_dedicated_start() {
g_alts_resource_dedicated.cq = grpc_completion_queue_create_for_next(nullptr);
g_alts_resource_dedicated.thread =
grpc_core::Thread("alts_tsi_handshaker", &thread_worker, nullptr);
g_alts_resource_dedicated.interested_parties = grpc_pollset_set_create();
grpc_pollset_set_add_pollset(g_alts_resource_dedicated.interested_parties,
grpc_cq_pollset(g_alts_resource_dedicated.cq));
g_alts_resource_dedicated.thread.Start();
}
void grpc_alts_shared_resource_dedicated_shutdown() {
if (g_alts_resource_dedicated.cq != nullptr) {
grpc_pollset_set_del_pollset(g_alts_resource_dedicated.interested_parties,
grpc_cq_pollset(g_alts_resource_dedicated.cq));
grpc_completion_queue_shutdown(g_alts_resource_dedicated.cq);
g_alts_resource_dedicated.thread.Join();
grpc_pollset_set_destroy(g_alts_resource_dedicated.interested_parties);
grpc_completion_queue_destroy(g_alts_resource_dedicated.cq);
}
}
|
/**
* @file src/fileformat/types/visual_basic/visual_basic_object.cpp
* @brief Class visual basic object.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#include "retdec/fileformat/types/visual_basic/visual_basic_object.h"
namespace retdec {
namespace fileformat {
/**
* Get name
* @return name
*/
const std::string &VisualBasicObject::getName() const
{
return name;
}
/**
* Get methods
* @return Object methods
*/
const std::vector<std::string> &VisualBasicObject::getMethods() const
{
return methods;
}
/**
* Get number of methods
* @return number of methods
*/
std::size_t VisualBasicObject::getNumberOfMethods() const
{
return methods.size();
}
/**
* Set name
* @param n Name to set
*/
void VisualBasicObject::setName(const std::string &n)
{
name = n;
}
/**
* Add method
* @param method Method to add
*/
void VisualBasicObject::addMethod(const std::string &method)
{
methods.push_back(method);
}
} // namespace fileformat
} // namespace retdec
|
; Assembly code emitted by HLA compiler
; Version 2.16 build 4413 (prototype)
; HLA compiler written by Randall Hyde
; NASM compatible output
bits 32
%define ExceptionPtr__hla_ [dword fs:0]
global QuitMain__hla_
global DfltExHndlr__hla_
global _HLAMain
global HWexcept__hla_
global start
section .text code align=16
extern STDOUT_PUTI32
extern STDOUT_NEWLN
extern DefaultExceptionHandler__hla_
extern abstract__hla_
extern HardwareException__hla_
extern BuildExcepts__hla_
extern STDOUT_PUTS
extern Raise__hla_
extern shortDfltExcept__hla_
section .text
;/* HWexcept__hla_ gets called when Windows raises the exception. */
; procedure HWexcept__hla_
HWexcept__hla_:
jmp HardwareException__hla_
;HWexcept__hla_ endp
; procedure DfltExHndlr__hla_
DfltExHndlr__hla_:
jmp DefaultExceptionHandler__hla_
;DfltExHndlr__hla_ endp
; procedure _HLAMain
_HLAMain:
nop
; procedure start
start:
;start endp
call BuildExcepts__hla_
; push dword 0
db 06ah ;
db 00h ;
; push ebp
db 055h ;
; push ebp
db 055h ;
; lea ebp, [esp+4]
db 08dh ;
db 06ch ;
db 024h ;
db 04h ;
; push strict dword str__hla_1889
db 068h ;
dd str__hla_1889
call STDOUT_PUTS
; push strict dword str__hla_1890
db 068h ;
dd str__hla_1890
call STDOUT_PUTS
; push dword [Display__hla_1885]
db 0ffh ;
db 035h ;
dd Display__hla_1885
call STDOUT_PUTI32
; push strict dword str__hla_1891
db 068h ;
dd str__hla_1891
call STDOUT_PUTS
; push dword [Display__hla_1885+4]
db 0ffh ;
db 035h ;
dd (Display__hla_1885+4)
call STDOUT_PUTI32
; push strict dword str__hla_1892
db 068h ;
dd str__hla_1892
call STDOUT_PUTS
; push dword [Display__hla_1885+8]
db 0ffh ;
db 035h ;
dd (Display__hla_1885+8)
call STDOUT_PUTI32
call STDOUT_NEWLN
; push strict dword str__hla_1893
db 068h ;
dd str__hla_1893
call STDOUT_PUTS
; push dword [Display__hla_1885+12]
db 0ffh ;
db 035h ;
dd (Display__hla_1885+12)
call STDOUT_PUTI32
QuitMain__hla_:
; push dword 0
db 06ah ;
db 00h ;
; call [__imp__ExitProcess@4]
db 0ffh ;
db 015h ;
dd __imp__ExitProcess@4
;_HLAMain endp
section .text
align (4)
len__hla_1889 dd 0eh
dd 0eh
str__hla_1889:
db "Display point:"
db 0
db 0
align (4)
len__hla_1890 dd 05h
dd 05h
str__hla_1890:
db " x = "
db 0
db 0
db 0
align (4)
len__hla_1891 dd 05h
dd 05h
str__hla_1891:
db " y = "
db 0
db 0
db 0
align (4)
len__hla_1892 dd 05h
dd 05h
str__hla_1892:
db " z = "
db 0
db 0
db 0
align (4)
len__hla_1893 dd 0fh
dd 0fh
str__hla_1893:
db "Display color: "
db 0
section .data data align=16
extern MainPgmCoroutine__hla_
extern __imp__MessageBoxA@16
extern __imp__ExitProcess@4
align (4)
Display__hla_1885:
dd 00h
dd 01h
dd 02h
dd 0ah
|
NAME Data_transfer
TITLE jmp
assume cs:codesg,ds:datasg
; this is add proc ;;
datasg segment
data1 db 1,02h ,101B,'$ 2', 'WoW:),Zp* '
dw 0123h, 0456H,0abch ,0defh,110101001b
msg1 DD 1023, 10001001011001011100B,5C2A57F2H
ARRAY db 10 DUP (1,101b , 'Y') ;?
mgs2 db 3 dup('hello')
dw 3 dup(0ffh, 255)
buff db 'hello world!' ; 65 68
datasg ends
codesg segment ; for
inc ax
start: mov ax, 0123h;;t;sd
mov bx, 0456h
jmp hr1
plc1: jmp near ptr plc2 ;0x10
plc2: jmp far ptr hr2 ;0x11
well: add ax, bx
loop plc2
je well
;org 110B
hr1: add ax, seg well ;0x15
JA plc1
hr2: mov bx, offset plc1 ;0x17
mov ax, buff
mov cx, buff[SI]
test:
mov ax, 4000h
int 21h
codesg ends
end start;adnfg |
#include "ros/ros.h"
#include "geometry_msgs/Twist.h"
#include "ball_chaser/DriveToTarget.h"
// ROS::Publisher motor commands;
ros::Publisher motor_command_publisher;
using namespace std;
// This function should publish the requested linear x and angular velocities to the robot wheel joints
// After publishing the requested velocities, a message feedback should be returned with the requested wheel velocities
bool handle_drive_request(ball_chaser::DriveToTarget::Request& req, ball_chaser::DriveToTarget::Response& res) {
ROS_INFO("DriveToTargetRequest received - linear_x: %1.2f, angular_z: %1.2f", req.linear_x, req.angular_z);
// Create a motor_command object of type geometry_msgs::Twist
geometry_msgs::Twist motor_command;
// Set wheel velocities
motor_command.linear.x = req.linear_x;
motor_command.angular.z = req.angular_z;
// Publish angles to drive the robot
motor_command_publisher.publish(motor_command);
res.msg_feedback = "Velocities were set to: linear_x: " + to_string((double)motor_command.linear.x)
+ ", angular_z: " + to_string((double)motor_command.angular.z);
ROS_INFO_STREAM(res.msg_feedback);
return true;
}
int main(int argc, char** argv)
{
// Initialize a ROS node
ros::init(argc, argv, "drive_bot");
// Create a ROS NodeHandle object
ros::NodeHandle n;
// Inform ROS master that we will be publishing a message of type geometry_msgs::Twist on the robot actuation topic with a publishing queue size of 10
motor_command_publisher = n.advertise<geometry_msgs::Twist>("/cmd_vel", 10);
// ball_chaser/command_robot service with a handle_drive_request callback function
ros::ServiceServer server = n.advertiseService("/ball_chaser/command_robot", handle_drive_request);
ros::spin();
return 0;
} |
; A100381: a(n) = 2^n*binomial(n,2).
; 0,0,4,24,96,320,960,2688,7168,18432,46080,112640,270336,638976,1490944,3440640,7864320,17825792,40108032,89653248,199229440,440401920,968884224,2122317824,4630511616,10066329600,21810380800,47110422528,101468602368,217969590272,467077693440,998579896320,2130303778816,4535485464576,9637906612224,20444044328960,43293270343680,91534343012352,193239168581632,407369058091008,857619069665280,1803199069552640,3786718046060544,7942871999053824
mov $1,2
pow $1,$0
bin $0,2
mul $1,$0
|
; A154514: a(n) = 648*n^2 - 72*n + 1.
; 577,2449,5617,10081,15841,22897,31249,40897,51841,64081,77617,92449,108577,126001,144721,164737,186049,208657,232561,257761,284257,312049,341137,371521,403201,436177,470449,506017,542881,581041,620497,661249,703297,746641,791281,837217,884449,932977,982801,1033921,1086337,1140049,1195057,1251361,1308961,1367857,1428049,1489537,1552321,1616401,1681777,1748449,1816417,1885681,1956241,2028097,2101249,2175697,2251441,2328481,2406817,2486449,2567377,2649601,2733121,2817937,2904049,2991457,3080161,3170161,3261457,3354049,3447937,3543121,3639601,3737377,3836449,3936817,4038481,4141441,4245697,4351249,4458097,4566241,4675681,4786417,4898449,5011777,5126401,5242321,5359537,5478049,5597857,5718961,5841361,5965057,6090049,6216337,6343921,6472801,6602977,6734449,6867217,7001281,7136641,7273297,7411249,7550497,7691041,7832881,7976017,8120449,8266177,8413201,8561521,8711137,8862049,9014257,9167761,9322561,9478657,9636049,9794737,9954721,10116001,10278577,10442449,10607617,10774081,10941841,11110897,11281249,11452897,11625841,11800081,11975617,12152449,12330577,12510001,12690721,12872737,13056049,13240657,13426561,13613761,13802257,13992049,14183137,14375521,14569201,14764177,14960449,15158017,15356881,15557041,15758497,15961249,16165297,16370641,16577281,16785217,16994449,17204977,17416801,17629921,17844337,18060049,18277057,18495361,18714961,18935857,19158049,19381537,19606321,19832401,20059777,20288449,20518417,20749681,20982241,21216097,21451249,21687697,21925441,22164481,22404817,22646449,22889377,23133601,23379121,23625937,23874049,24123457,24374161,24626161,24879457,25134049,25389937,25647121,25905601,26165377,26426449,26688817,26952481,27217441,27483697,27751249,28020097,28290241,28561681,28834417,29108449,29383777,29660401,29938321,30217537,30498049,30779857,31062961,31347361,31633057,31920049,32208337,32497921,32788801,33080977,33374449,33669217,33965281,34262641,34561297,34861249,35162497,35465041,35768881,36074017,36380449,36688177,36997201,37307521,37619137,37932049,38246257,38561761,38878561,39196657,39516049,39836737,40158721,40482001
mov $1,9
mul $1,$0
add $1,17
mul $1,$0
div $1,2
mul $1,144
add $1,577
|
; A175846: Partial sums of ceiling(n^2/15).
; 0,1,2,3,5,7,10,14,19,25,32,41,51,63,77,92,110,130,152,177,204,234,267,303,342,384,430,479,532,589,649,714,783,856,934,1016,1103,1195,1292,1394,1501,1614,1732,1856,1986,2121,2263,2411,2565,2726,2893,3067,3248,3436,3631,3833,4043,4260,4485,4718,4958,5207,5464,5729,6003,6285,6576,6876,7185,7503,7830,8167,8513,8869,9235,9610,9996,10392,10798,11215,11642,12080,12529,12989,13460,13942,14436,14941,15458,15987,16527,17080,17645,18222,18812,19414,20029,20657,21298,21952
mov $2,$0
add $2,1
lpb $2
mov $0,0
sub $2,1
sub $0,$2
pow $0,2
mov $3,$0
add $3,14
div $3,15
add $1,$3
lpe
mov $0,$1
|
; A280512: Index sequence of the Thue-Morse sequence (A010060, using offset 1) as a reverse block-fractal sequence.
; 1,3,2,1,12,11,10,9,8,7,6,5,4,3,2,1,48,47,46,45,44,43,42,41,40,39,38,37,36,35,34,33,32,31,30,29,28,27,26,25,24,23,22,21,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,192,191,190,189,188
mov $1,1
mov $2,$0
add $2,1
lpb $0
div $0,4
mul $1,4
lpe
sub $1,$2
add $1,1
mov $0,$1
|
; ===============================================================
; Oct 2015
; ===============================================================
;
; void in_wait_key(void)
;
; Busy wait until a key is pressed.
;
; ===============================================================
SECTION code_clib
SECTION code_input
PUBLIC asm_in_wait_key
EXTERN asm_in_test_key
asm_in_wait_key:
; uses : potentially all (ix, iy saved for sdcc)
call asm_in_test_key
jr z, asm_in_wait_key
ret
|
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/globals.h"
#include "vm/instructions.h"
#include "vm/signal_handler.h"
#include "vm/simulator.h"
#if defined(HOST_OS_MACOS)
namespace dart {
uintptr_t SignalHandler::GetProgramCounter(const mcontext_t& mcontext) {
uintptr_t pc = 0;
#if defined(HOST_ARCH_IA32)
pc = static_cast<uintptr_t>(mcontext->__ss.__eip);
#elif defined(HOST_ARCH_X64)
pc = static_cast<uintptr_t>(mcontext->__ss.__rip);
#elif defined(HOST_ARCH_ARM)
pc = static_cast<uintptr_t>(mcontext->__ss.__pc);
#elif defined(HOST_ARCH_ARM64)
pc = static_cast<uintptr_t>(mcontext->__ss.__pc);
#else
#error Unsuported architecture.
#endif // HOST_ARCH_...
return pc;
}
uintptr_t SignalHandler::GetFramePointer(const mcontext_t& mcontext) {
uintptr_t fp = 0;
#if defined(HOST_ARCH_IA32)
fp = static_cast<uintptr_t>(mcontext->__ss.__ebp);
#elif defined(HOST_ARCH_X64)
fp = static_cast<uintptr_t>(mcontext->__ss.__rbp);
#elif defined(HOST_ARCH_ARM)
fp = static_cast<uintptr_t>(mcontext->__ss.__r[7]);
#elif defined(HOST_ARCH_ARM64)
fp = static_cast<uintptr_t>(mcontext->__ss.__fp);
#else
#error Unsuported architecture.
#endif // HOST_ARCH_...
return fp;
}
uintptr_t SignalHandler::GetCStackPointer(const mcontext_t& mcontext) {
uintptr_t sp = 0;
#if defined(HOST_ARCH_IA32)
sp = static_cast<uintptr_t>(mcontext->__ss.__esp);
#elif defined(HOST_ARCH_X64)
sp = static_cast<uintptr_t>(mcontext->__ss.__rsp);
#elif defined(HOST_ARCH_ARM)
sp = static_cast<uintptr_t>(mcontext->__ss.__sp);
#elif defined(HOST_ARCH_ARM64)
sp = static_cast<uintptr_t>(mcontext->__ss.__sp);
#else
UNIMPLEMENTED();
#endif // HOST_ARCH_...
return sp;
}
uintptr_t SignalHandler::GetDartStackPointer(const mcontext_t& mcontext) {
#if defined(TARGET_ARCH_ARM64) && !defined(USING_SIMULATOR)
return static_cast<uintptr_t>(mcontext->__ss.__x[SPREG]);
#else
return GetCStackPointer(mcontext);
#endif
}
uintptr_t SignalHandler::GetLinkRegister(const mcontext_t& mcontext) {
uintptr_t lr = 0;
#if defined(HOST_ARCH_IA32)
lr = 0;
#elif defined(HOST_ARCH_X64)
lr = 0;
#elif defined(HOST_ARCH_ARM)
lr = static_cast<uintptr_t>(mcontext->__ss.__lr);
#elif defined(HOST_ARCH_ARM64)
lr = static_cast<uintptr_t>(mcontext->__ss.__lr);
#else
#error Unsupported architecture.
#endif // HOST_ARCH_...
return lr;
}
void SignalHandler::InstallImpl(SignalAction action) {
struct sigaction act = {};
act.sa_handler = NULL;
act.sa_sigaction = action;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_RESTART | SA_SIGINFO;
int r = sigaction(SIGPROF, &act, NULL);
ASSERT(r == 0);
}
void SignalHandler::Remove() {
// Ignore future SIGPROF signals because by default SIGPROF will terminate
// the process and we may have some signals in flight.
struct sigaction act = {};
act.sa_handler = SIG_IGN;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
int r = sigaction(SIGPROF, &act, NULL);
ASSERT(r == 0);
}
} // namespace dart
#endif // defined(HOST_OS_MACOS)
|
; A010955: Binomial coefficient C(39,n).
; 1,39,741,9139,82251,575757,3262623,15380937,61523748,211915132,635745396,1676056044,3910797436,8122425444,15084504396,25140840660,37711260990,51021117810,62359143990,68923264410,68923264410,62359143990,51021117810,37711260990
mov $1,39
bin $1,$0
|
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/sharding_propagation.h"
#include <algorithm>
#include <list>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "absl/algorithm/container.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "absl/status/status.h"
#include "absl/strings/str_split.h"
#include "absl/types/optional.h"
#include "tensorflow/compiler/xla/service/dot_as_convolution_util.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_graph_dumper.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/hlo_sharding.h"
#include "tensorflow/compiler/xla/service/hlo_sharding_metadata.h"
#include "tensorflow/compiler/xla/service/hlo_sharding_util.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
namespace xla {
namespace {
using ComputationMap =
absl::flat_hash_map<const HloComputation*, HloInstruction*>;
// Returns true iff the specified hlo or sharding has a spatially partitioned
// sharding (tiled or replicated) what can be propagated by sharding
// propagation.
bool IsSpatiallyPartitioned(const HloSharding& sharding) {
if (sharding.IsTuple()) {
return absl::c_any_of(sharding.tuple_elements(), IsSpatiallyPartitioned);
} else {
return !sharding.IsTileMaximal() || sharding.IsReplicated();
}
}
bool IsSpatiallyPartitioned(const HloInstruction* hlo) {
return hlo->has_sharding() && IsSpatiallyPartitioned(hlo->sharding());
}
// Returns true if the lhs sharding is preferable over the rhs sharding.
// The most specific sharding is tile maximal followed by single device tile
// maximal and finally replicated. This order aims to primarily reduce memory
// usage and secondly reduce total compute.
// Note: This does NOT provide a total ordering as we can have 2 different
// sharding with same preference level.
bool IsShardingMoreSpecific(const HloSharding& lhs, const HloSharding& rhs) {
CHECK_EQ(lhs.IsTuple(), rhs.IsTuple());
if (lhs.IsTuple()) {
// For tuples we consider lhs to have a better sharding if none of the
// elements are worse and at least one element is better then in rhs
// sharding.
const auto& lhs_shardings = lhs.tuple_elements();
const auto& rhs_shardings = rhs.tuple_elements();
CHECK_EQ(lhs_shardings.size(), rhs_shardings.size());
bool is_better = false;
for (int64 i = 0; i < lhs_shardings.size(); ++i) {
if (IsShardingMoreSpecific(rhs_shardings[i], lhs_shardings[i])) {
return false;
}
if (IsShardingMoreSpecific(lhs_shardings[i], rhs_shardings[i])) {
is_better = true;
}
}
return is_better;
}
if (!rhs.IsTileMaximal()) {
return lhs.NumTiles() > rhs.NumTiles();
} else if (!rhs.IsReplicated()) {
// If we are not replicated then only tiled (not tile maximal) shardings
// can improve us.
return !lhs.IsTileMaximal();
} else {
// If we are replicated then any non-replicated sharding can improve us.
return !lhs.IsReplicated();
}
}
// Tries to refine `to_merge` by combining with `old`. Returns if the final
// `to_merge` is more specific than `old`.
bool MergeSharding(const HloSharding& old, HloSharding* to_merge,
bool may_combine_partial_sharding) {
if (old.IsTuple()) {
CHECK(to_merge->IsTuple());
bool changed = false;
for (int64 i = 0; i < old.tuple_elements().size(); ++i) {
changed |=
MergeSharding(old.tuple_elements()[i], &to_merge->tuple_elements()[i],
may_combine_partial_sharding);
}
return changed;
}
if (!may_combine_partial_sharding || !old.ReplicateOnLastTileDim() ||
!to_merge->ReplicateOnLastTileDim() ||
old.tile_assignment().num_elements() !=
to_merge->tile_assignment().num_elements()) {
return IsShardingMoreSpecific(*to_merge, old);
}
// Combine the tile dimension sizes from new and old.
int64 num_devices = old.tile_assignment().num_elements();
std::vector<int64> new_tile_dims;
bool compatible = true;
new_tile_dims.reserve(to_merge->tile_assignment().num_dimensions());
for (int64 i = 0; i < to_merge->tile_assignment().num_dimensions() - 1; ++i) {
int64 new_dim = to_merge->tile_assignment().dim(i);
int64 old_dim = old.tile_assignment().dim(i);
if (new_dim == 1) {
new_tile_dims.push_back(old_dim);
} else if (old_dim == 1) {
new_tile_dims.push_back(new_dim);
} else if (new_dim == old_dim) {
new_tile_dims.push_back(new_dim);
} else {
compatible = false;
break;
}
}
int64 replication = num_devices / Product(new_tile_dims);
if (!compatible || num_devices % Product(new_tile_dims) != 0 ||
replication >= old.tile_assignment().dimensions().back()) {
return IsShardingMoreSpecific(*to_merge, old);
}
new_tile_dims.push_back(replication);
Array<int64> new_tile(new_tile_dims);
// Maps from replication group ID to sorted members.
absl::flat_hash_map<int64, std::set<int64>> old_group_members;
absl::flat_hash_map<int64, std::set<int64>> new_group_members;
auto get_group_index = [&](absl::Span<const int64> tile_indices,
const HloSharding& sharding) {
int64 group_id = 0;
for (int64 i = 0; i < tile_indices.size() - 1; ++i) {
group_id *= to_merge->tile_assignment().dim(i);
group_id += tile_indices[i];
}
return group_id;
};
old.tile_assignment().Each(
[&](absl::Span<const int64> indices, int64 device) {
old_group_members[get_group_index(indices, old)].insert(device);
});
to_merge->tile_assignment().Each(
[&](absl::Span<const int64> indices, int64 device) {
new_group_members[get_group_index(indices, *to_merge)].insert(device);
});
// Try to find the intersection of old and new replication groups, in
// order to determine the merged tile assignment.
new_tile.Each([&](absl::Span<const int64> indices, int64* device) {
if (!compatible) {
return;
}
std::vector<int64> old_index(indices.begin(), indices.end());
std::vector<int64> new_index = old_index;
for (int64 i = 0; i < indices.size() - 1; ++i) {
if (old.tile_assignment().dim(i) == 1) {
old_index[i] = 0;
}
if (to_merge->tile_assignment().dim(i) == 1) {
new_index[i] = 0;
}
}
int64 old_group_id = get_group_index(old_index, old);
int64 new_group_id = get_group_index(new_index, *to_merge);
if (old_group_members[old_group_id].empty() ||
new_group_members[new_group_id].empty()) {
compatible = false;
return;
}
int64 smallest_old = *old_group_members[old_group_id].begin();
int64 smallest_new = *new_group_members[new_group_id].begin();
if (smallest_old < smallest_new) {
if (old_group_members[old_group_id].count(smallest_new) == 0) {
compatible = false;
return;
}
*device = smallest_new;
} else {
if (new_group_members[new_group_id].count(smallest_old) == 0) {
compatible = false;
return;
}
*device = smallest_old;
}
old_group_members[old_group_id].erase(*device);
new_group_members[new_group_id].erase(*device);
});
if (compatible) {
if (replication == 1) {
new_tile_dims.pop_back();
new_tile.Reshape(new_tile_dims);
*to_merge = HloSharding::Tile(new_tile);
} else {
*to_merge = HloSharding::PartialTile(new_tile);
}
return true;
}
return IsShardingMoreSpecific(*to_merge, old);
}
// Updates the sharding of the specified instruction with the specified sharding
// if it is better than the current one and returns true if a new sharding have
// been applied. If may_combine_partial_sharding is true, this may combine the
// new and existing sharding if they are both partial tiling partial
// replication.
bool MaybeImproveInstructionSharding(HloSharding sharding,
HloInstruction* instruction,
bool may_combine_partial_sharding) {
// We don't want to propagate tile maximal shardings.
if (!IsSpatiallyPartitioned(sharding)) {
return false;
}
// Any sharding is better then no sharding.
if (!instruction->has_sharding()) {
instruction->set_sharding(std::move(sharding));
return true;
}
int64 sharding_tiles = sharding.NumTiles();
if (MergeSharding(instruction->sharding(), &sharding,
may_combine_partial_sharding)) {
// Override existing tiled sharding only when the new sharding is compatible
// with the existing one. This avoids unexpected resharding when `sharding`
// just has more tiles than existing sharding but they are not mergeable.
if (instruction->shape().IsArray() &&
!instruction->sharding().IsTileMaximal() &&
sharding.NumTiles() == sharding_tiles) {
std::vector<int64> diff_dims;
for (int64 i = 0; i < instruction->shape().rank(); ++i) {
if (instruction->sharding().tile_assignment().dim(i) ==
sharding.tile_assignment().dim(i)) {
continue;
}
if (instruction->sharding().tile_assignment().dim(i) != 1) {
return false;
}
diff_dims.push_back(i);
}
if (hlo_sharding_util::PartiallyReplicateTiledShardingOnDims(
sharding, diff_dims) != instruction->sharding()) {
return false;
}
}
instruction->set_sharding(std::move(sharding));
return true;
}
return false;
}
// Sets the sharding for every element within a tuple to replicated (default
// sharding). This is necessary because there is no way to represent a tuple
// sharding when only some of the elements are sharded.
void SetDefaultTupleSharding(HloInstruction* instruction) {
instruction->set_sharding(
HloSharding::SingleTuple(instruction->shape(), HloSharding::Replicate()));
}
// We consider a convolution kernel to be small iff it is smaller along all
// spatial dimensions then the output of the convolution. The rational is that
// we can either shard the kernel or the output and we want to shard the larger
// one for better efficiency.
bool IsConvolutionKernelSmall(const HloInstruction* instruction) {
CHECK_EQ(instruction->opcode(), HloOpcode::kConvolution);
const HloInstruction* rhs = instruction->operand(1);
const auto& dnums = instruction->convolution_dimension_numbers();
for (int64 i = 0; i < dnums.input_spatial_dimensions().size(); ++i) {
int64 kernel_dim =
rhs->shape().dimensions(dnums.kernel_spatial_dimensions(i));
int64 output_dim =
instruction->shape().dimensions(dnums.output_spatial_dimensions(i));
if (kernel_dim >= output_dim) {
return false;
}
}
return true;
}
// Return the operand which is the most suitable for determining the sharding
// for the specified instruction or nullptr if there isn't any suitable operand.
const HloInstruction* PickRepresentativeOperand(
const HloInstruction* instruction) {
switch (instruction->opcode()) {
case HloOpcode::kMap:
case HloOpcode::kPad:
case HloOpcode::kPower:
case HloOpcode::kReverse:
case HloOpcode::kSlice:
case HloOpcode::kShiftLeft:
case HloOpcode::kShiftRightArithmetic:
case HloOpcode::kShiftRightLogical:
// For these opcodes the output sharding has to be determined by the
// sharding of the first operand but we can only determine sharding based
// on it if it already has a sharding.
if (instruction->operand(0)->has_sharding()) {
return instruction->operand(0);
}
return nullptr;
case HloOpcode::kAbs:
case HloOpcode::kAdd:
case HloOpcode::kAnd:
case HloOpcode::kAtan2:
case HloOpcode::kBitcastConvert:
case HloOpcode::kCeil:
case HloOpcode::kClamp:
case HloOpcode::kClz:
case HloOpcode::kCompare:
case HloOpcode::kComplex:
case HloOpcode::kConcatenate:
case HloOpcode::kConvert:
case HloOpcode::kCopy:
case HloOpcode::kCos:
case HloOpcode::kAllGather:
case HloOpcode::kAllReduce:
case HloOpcode::kAllToAll:
case HloOpcode::kCollectivePermute:
case HloOpcode::kDivide:
case HloOpcode::kExp:
case HloOpcode::kExpm1:
case HloOpcode::kFloor:
case HloOpcode::kImag:
case HloOpcode::kIsFinite:
case HloOpcode::kLog:
case HloOpcode::kLog1p:
case HloOpcode::kLogistic:
case HloOpcode::kMaximum:
case HloOpcode::kMinimum:
case HloOpcode::kMultiply:
case HloOpcode::kNegate:
case HloOpcode::kNot:
case HloOpcode::kOr:
case HloOpcode::kPopulationCount:
case HloOpcode::kReal:
case HloOpcode::kReducePrecision:
case HloOpcode::kRemainder:
case HloOpcode::kRoundNearestAfz:
case HloOpcode::kRsqrt:
case HloOpcode::kSelect:
case HloOpcode::kSign:
case HloOpcode::kSin:
case HloOpcode::kSort:
case HloOpcode::kSqrt:
case HloOpcode::kCbrt:
case HloOpcode::kSubtract:
case HloOpcode::kTanh:
case HloOpcode::kTupleSelect:
case HloOpcode::kWhile:
case HloOpcode::kXor: {
// For these opcodes the output sharding can be determined by any operand
// so we find the operand with the most specific sharding.
const HloInstruction* best_operand = nullptr;
for (const HloInstruction* operand : instruction->operands()) {
if (operand->has_sharding() &&
(best_operand == nullptr ||
IsShardingMoreSpecific(operand->sharding(),
best_operand->sharding()))) {
best_operand = operand;
}
}
return best_operand;
}
// There is no suitable operand for the rest of the opcodes.
case HloOpcode::kAddDependency:
case HloOpcode::kAfterAll:
case HloOpcode::kBatchNormGrad:
case HloOpcode::kBatchNormInference:
case HloOpcode::kBatchNormTraining:
case HloOpcode::kBitcast:
case HloOpcode::kBroadcast:
case HloOpcode::kCall:
case HloOpcode::kCholesky:
case HloOpcode::kCollectivePermuteDone:
case HloOpcode::kCollectivePermuteStart:
case HloOpcode::kConditional:
case HloOpcode::kConstant:
case HloOpcode::kConvolution:
case HloOpcode::kCopyDone:
case HloOpcode::kCopyStart:
case HloOpcode::kCustomCall:
case HloOpcode::kDomain:
case HloOpcode::kDot:
case HloOpcode::kDynamicSlice:
case HloOpcode::kDynamicUpdateSlice:
case HloOpcode::kDynamicReshape:
case HloOpcode::kFft:
case HloOpcode::kFusion:
case HloOpcode::kGather:
case HloOpcode::kGetTupleElement:
case HloOpcode::kInfeed:
case HloOpcode::kIota:
case HloOpcode::kOutfeed:
case HloOpcode::kParameter:
case HloOpcode::kPartitionId:
case HloOpcode::kRecv:
case HloOpcode::kRecvDone:
case HloOpcode::kReduce:
case HloOpcode::kReduceWindow:
case HloOpcode::kReplicaId:
case HloOpcode::kReshape:
case HloOpcode::kRng:
case HloOpcode::kRngGetAndUpdateState:
case HloOpcode::kRngBitGenerator:
case HloOpcode::kScatter:
case HloOpcode::kSelectAndScatter:
case HloOpcode::kSend:
case HloOpcode::kSendDone:
case HloOpcode::kTrace:
case HloOpcode::kTranspose:
case HloOpcode::kTriangularSolve:
case HloOpcode::kTuple:
case HloOpcode::kGetDimensionSize:
case HloOpcode::kSetDimensionSize:
return nullptr;
}
}
bool SupportSpatialPartitioning(const HloInstruction* instruction,
const ComputationMap& computation_map,
bool is_spmd) {
if (instruction->parent()->root_instruction() == instruction &&
computation_map.find(instruction->parent()) == computation_map.end()) {
// We don't support sharding the root instruction of a computation yet,
// unless the computation is a while body.
return false;
}
if (instruction->IsElementwise() &&
(instruction->opcode() != HloOpcode::kRng || is_spmd)) {
return true;
}
switch (instruction->opcode()) {
case HloOpcode::kBroadcast:
case HloOpcode::kConcatenate:
case HloOpcode::kConditional:
case HloOpcode::kConstant:
case HloOpcode::kConvolution:
case HloOpcode::kDot:
case HloOpcode::kDynamicSlice:
case HloOpcode::kDynamicUpdateSlice:
case HloOpcode::kGather:
case HloOpcode::kGetTupleElement:
case HloOpcode::kInfeed:
case HloOpcode::kIota:
case HloOpcode::kPad:
case HloOpcode::kReduceWindow:
case HloOpcode::kReshape:
case HloOpcode::kScatter:
case HloOpcode::kSelectAndScatter:
case HloOpcode::kSlice:
case HloOpcode::kSort:
case HloOpcode::kTranspose:
case HloOpcode::kTuple:
case HloOpcode::kWhile:
case HloOpcode::kReduce:
return true;
case HloOpcode::kAllReduce:
// Only if channel_id is not specified.
return instruction->channel_id() == absl::nullopt;
case HloOpcode::kParameter:
return computation_map.find(instruction->parent()) !=
computation_map.end();
case HloOpcode::kReverse:
return is_spmd;
default:
return false;
}
}
bool InferDotShardingFromOperands(
HloInstruction* instruction,
const dot_as_convolution_util::DotConvolutionDimsInfo& dnums,
bool may_combine_partial_sharding) {
auto from_operand = [&](int64 operand_index) {
auto operand = instruction->operand(operand_index);
const HloSharding& operand_sharding = operand->sharding();
if (operand_sharding.IsTileMaximal()) {
return operand_sharding;
}
std::vector<int64> contracting_dims;
contracting_dims.reserve(dnums.contracting_dims.size());
for (const auto& dim : dnums.contracting_dims) {
contracting_dims.push_back(operand_index == 0 ? dim.lhs : dim.rhs);
}
// It's possible that some size-1 spatial dims of convolutions are parsed as
// non-contracting dims. We might have tiled dimensions on them.
for (const auto& dim : operand_index == 0
? dnums.rhs_non_contracting_dims
: dnums.lhs_non_contracting_dims) {
int64 d = operand_index == 0 ? dim.lhs : dim.rhs;
if (d > 0) {
contracting_dims.push_back(d);
}
}
auto replicate_contracting_dims =
hlo_sharding_util::PartiallyReplicateTiledShardingOnDims(
operand_sharding, contracting_dims);
std::vector<int64> out_dims_to_op_perm(instruction->shape().rank(), -1);
std::vector<int64> op_dims_to_output_perm(operand->shape().rank(), -1);
for (const auto& dim : dnums.batch_dims) {
out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs;
op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] =
dim.output;
}
for (const auto& dim : operand_index == 0
? dnums.lhs_non_contracting_dims
: dnums.rhs_non_contracting_dims) {
out_dims_to_op_perm[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs;
op_dims_to_output_perm[operand_index == 0 ? dim.lhs : dim.rhs] =
dim.output;
}
return *hlo_sharding_util::TransposeShardingWithCollapsedDims(
replicate_contracting_dims, op_dims_to_output_perm,
out_dims_to_op_perm);
};
bool changed = false;
int64 larger_operand =
ShapeUtil::ByteSizeOf(instruction->operand(0)->shape()) >=
ShapeUtil::ByteSizeOf(instruction->operand(1)->shape())
? 0
: 1;
if (IsSpatiallyPartitioned(instruction->operand(larger_operand))) {
changed |= MaybeImproveInstructionSharding(from_operand(larger_operand),
instruction,
may_combine_partial_sharding);
}
if (IsSpatiallyPartitioned(instruction->operand(1 - larger_operand))) {
changed |= MaybeImproveInstructionSharding(from_operand(1 - larger_operand),
instruction,
may_combine_partial_sharding);
}
return changed;
}
bool InferGatherParallelShardingFromOperands(
HloInstruction* instruction,
const hlo_sharding_util::GatherParallelDims& parallel_dims,
bool may_combine_partial_sharding) {
auto from_operand = [instruction](
int64 operand_index,
absl::Span<const int64> output_aligned_parallel_dims,
absl::Span<const int64> output_parallel_dims) {
const HloInstruction* operand = instruction->operand(operand_index);
const HloSharding& operand_sharding = operand->sharding();
if (operand_sharding.IsTileMaximal()) {
return operand_sharding;
}
auto dnums = instruction->gather_dimension_numbers();
std::vector<int64> output_tile_dims(instruction->shape().rank(), 1);
std::vector<int64> index_non_parallel_dims;
index_non_parallel_dims.reserve(operand->shape().rank());
// Detect non parallel dimensions in the index.
for (int i = 0; i < operand->shape().rank(); ++i) {
if (!absl::c_linear_search(output_aligned_parallel_dims, i)) {
index_non_parallel_dims.push_back(i);
}
}
// Collect tile dimensions in the operand. The order of the parallel
// dimensions in output_aligned_parallel_dims is the same as that of the
// output
for (int i = 0; i < output_aligned_parallel_dims.size(); ++i) {
const int64 indices_idx = output_aligned_parallel_dims[i];
const int64 output_idx = output_parallel_dims[i];
output_tile_dims[output_idx] =
operand_sharding.tile_assignment().dim(indices_idx);
}
HloSharding replicate_non_parallel_dims =
hlo_sharding_util::PartiallyReplicateTiledShardingOnDims(
operand_sharding, index_non_parallel_dims);
if (replicate_non_parallel_dims.ReplicateOnLastTileDim()) {
output_tile_dims.push_back(
replicate_non_parallel_dims.tile_assignment().dimensions().back());
}
auto output_tile_assignment = replicate_non_parallel_dims.tile_assignment();
output_tile_assignment.Reshape(output_tile_dims);
return replicate_non_parallel_dims.ReplicateOnLastTileDim()
? HloSharding::PartialTile(output_tile_assignment)
: HloSharding::Tile(output_tile_assignment);
};
bool changed = false;
auto output_parallel_dims =
hlo_sharding_util::GatherParallelOutputDims(*instruction, parallel_dims);
if (IsSpatiallyPartitioned(instruction->operand(0))) {
changed |= MaybeImproveInstructionSharding(
from_operand(
0,
absl::MakeConstSpan(
hlo_sharding_util::GatherOutputAlignedOperandParallelDims(
*instruction, parallel_dims)),
absl::MakeConstSpan(output_parallel_dims)),
instruction, may_combine_partial_sharding);
}
if (IsSpatiallyPartitioned(instruction->operand(1))) {
changed |= MaybeImproveInstructionSharding(
from_operand(1,
absl::MakeConstSpan(parallel_dims.indices_parallel_dims),
absl::MakeConstSpan(output_parallel_dims)),
instruction, may_combine_partial_sharding);
}
return changed;
}
// Convolution handling for InferShardingFromOperands().
bool InferConvolutionShardingFromOperands(HloInstruction* instruction,
int64 aggressiveness,
bool may_combine_partial_sharding) {
auto get_partitions_for_dims =
[&](const HloInstruction* inst,
absl::Span<
const dot_as_convolution_util::DotConvolutionDimsInfo::DimNums>
dims,
int lhs_or_rhs) {
int64 partitions = 1;
if (!inst->has_sharding()) {
return partitions;
}
const auto& sharding = inst->sharding();
if (sharding.IsTileMaximal()) {
return partitions;
}
for (const auto& dim : dims) {
if (lhs_or_rhs == 0) {
partitions *= sharding.tile_assignment().dim(dim.lhs);
} else {
CHECK_EQ(lhs_or_rhs, 1);
partitions *= sharding.tile_assignment().dim(dim.rhs);
}
}
return partitions;
};
auto dot_dims =
dot_as_convolution_util::ParseConvolutionDimsInfo(instruction);
const int64 lhs_conv_spatial_partitions = get_partitions_for_dims(
instruction->operand(0), dot_dims.conv_spatial_dims, 0);
const int64 rhs_conv_spatial_partitions = get_partitions_for_dims(
instruction->operand(1), dot_dims.conv_spatial_dims, 1);
if (dot_dims.conv_spatial_dims.empty() ||
(lhs_conv_spatial_partitions == 1 && rhs_conv_spatial_partitions == 1 &&
instruction->batch_group_count() == 1 &&
instruction->feature_group_count() == 1)) {
return InferDotShardingFromOperands(instruction, dot_dims,
may_combine_partial_sharding);
}
const auto& dnums = instruction->convolution_dimension_numbers();
const HloInstruction* lhs = instruction->operand(0);
auto get_tiled_sharding_based_on_lhs = [&] {
CHECK(!lhs->sharding().IsTileMaximal());
std::vector<int64> output_to_lhs_indices(instruction->shape().rank());
output_to_lhs_indices[dnums.output_batch_dimension()] =
dnums.input_batch_dimension();
output_to_lhs_indices[dnums.output_feature_dimension()] =
dnums.input_feature_dimension();
for (int64 i = 0; i < dnums.input_spatial_dimensions_size(); ++i) {
output_to_lhs_indices[dnums.output_spatial_dimensions(i)] =
dnums.input_spatial_dimensions(i);
}
return hlo_sharding_util::TransposeSharding(lhs->sharding(),
output_to_lhs_indices);
};
if (!IsSpatiallyPartitioned(lhs)) {
return false;
}
if (lhs->sharding().IsReplicated()) {
return MaybeImproveInstructionSharding(
HloSharding::Replicate(), instruction, may_combine_partial_sharding);
}
if (IsConvolutionKernelSmall(instruction)) {
// If the kernel is small compared to the input then we can generate an
// output what is sharded the same way as the input.
const auto& tile_assignment = lhs->sharding().tile_assignment();
if (tile_assignment.dim(dnums.input_feature_dimension()) > 1) {
return false;
}
return MaybeImproveInstructionSharding(get_tiled_sharding_based_on_lhs(),
instruction,
may_combine_partial_sharding);
}
// If the kernel is large (e.g backward convolution) then we only support
// replicated output.
return MaybeImproveInstructionSharding(HloSharding::Replicate(), instruction,
may_combine_partial_sharding);
}
bool CanPropagateThroughAtAgressiveLevel(const HloInstruction& inst,
int64 aggressiveness) {
// At minimum agressiveness, only allow pass-through ops.
if (aggressiveness < 1 && !inst.IsElementwise() &&
inst.opcode() != HloOpcode::kTranspose &&
inst.opcode() != HloOpcode::kReshape) {
return false;
}
// Broadcast propagation should have at least aggressiveness 2.
if (aggressiveness < 2 && inst.opcode() == HloOpcode::kBroadcast) {
return false;
}
return true;
}
// Tries to update the sharding of the specified instruction based on its
// operands and returns true if the sharding of the instruction have been
// changed and false otherwise.
bool InferShardingFromOperands(HloInstruction* instruction,
const ComputationMap& computation_map,
bool is_spmd, int64 aggressiveness) {
if (!CanPropagateThroughAtAgressiveLevel(*instruction, aggressiveness)) {
return false;
}
// Do not change manual sharding.
if (instruction->has_sharding() && instruction->sharding().IsManual()) {
return false;
}
// Propagate manual sharding. Avoid tuple shaped HLOs that group independent
// together. Reduce, ReduceWindow, and Sort can be tuples but the elements
// are correlated, so we propagate manual sharding through them.
if (!instruction->has_sharding() &&
(instruction->shape().IsArray() ||
instruction->opcode() == HloOpcode::kReduce ||
instruction->opcode() == HloOpcode::kSort ||
instruction->opcode() == HloOpcode::kReduceWindow) &&
absl::c_any_of(instruction->operands(), [](const HloInstruction* op) {
return op->has_sharding() && op->sharding().IsManual();
})) {
instruction->set_sharding(HloSharding::Manual());
return true;
}
const bool may_combine_partial_sharding = is_spmd && aggressiveness > 0;
if (!SupportSpatialPartitioning(instruction, computation_map, is_spmd)) {
// If an array shaped HLO doesn't support spatial partitioning but at least
// one of its operand is replicated then we make the HLO replicated as well.
if (instruction->shape().IsTuple() || instruction->operand_count() == 0 ||
instruction == instruction->parent()->root_instruction() ||
instruction->HasSideEffect()) {
return false;
}
if (absl::c_any_of(instruction->operands(), [](const HloInstruction* op) {
return op->has_sharding() && op->sharding().IsReplicated();
})) {
return MaybeImproveInstructionSharding(
HloSharding::Replicate(), instruction, may_combine_partial_sharding);
}
return false;
}
switch (instruction->opcode()) {
case HloOpcode::kGetTupleElement: {
const HloInstruction* operand = instruction->operand(0);
if (!IsSpatiallyPartitioned(operand)) {
return false;
}
HloSharding new_sharding = operand->sharding().GetSubSharding(
operand->shape(), {instruction->tuple_index()});
return MaybeImproveInstructionSharding(
std::move(new_sharding), instruction, may_combine_partial_sharding);
}
case HloOpcode::kTuple: {
if (absl::c_none_of(instruction->operands(),
[](const HloInstruction* hlo) {
return IsSpatiallyPartitioned(hlo);
})) {
// None of the operands have a spatially partitioned sharding.
return false;
}
bool changed = false;
if (!instruction->has_sharding()) {
// Set the sharding for all elements in the tuple because it isn't
// possible to set a partial sharding.
SetDefaultTupleSharding(instruction);
changed = true;
}
// Go through each operand and if the operand has a sharding that is
// better than the current sharding for that tuple element then update
// it.
const Shape& shape = instruction->shape();
std::vector<HloSharding> sub_shardings =
instruction->sharding().tuple_elements();
int64 sub_sharding_index = 0;
for (int64 i = 0; i < ShapeUtil::TupleElementCount(shape); ++i) {
const HloInstruction* operand = instruction->operand(i);
if (operand->has_sharding()) {
if (operand->shape().IsTuple()) {
for (int64 i = 0, e = ShapeUtil::GetLeafCount(operand->shape());
i < e; ++i) {
if (IsShardingMoreSpecific(
operand->sharding().tuple_elements()[i],
sub_shardings[sub_sharding_index + i])) {
sub_shardings[sub_sharding_index + i] =
operand->sharding().tuple_elements()[i];
}
}
} else {
if (IsShardingMoreSpecific(operand->sharding(),
sub_shardings[sub_sharding_index])) {
sub_shardings[sub_sharding_index] = operand->sharding();
}
}
}
sub_sharding_index += ShapeUtil::GetLeafCount(operand->shape());
}
HloSharding new_sharding = HloSharding::Tuple(shape, sub_shardings);
if (new_sharding != instruction->sharding()) {
instruction->set_sharding(new_sharding);
return true;
}
return changed;
}
case HloOpcode::kReduce: {
// Reduce could have a tuple shape, where the first half of operands are
// the arrays to reduce, and the second half of operands are the init
// values.
bool changed = false;
for (int64 operand_id = 0; operand_id < instruction->operand_count() / 2;
++operand_id) {
const HloInstruction* operand = instruction->operand(operand_id);
if (!IsSpatiallyPartitioned(operand)) {
continue;
}
auto get_maybe_tuple_sharding = [&](HloSharding sharding) {
if (instruction->operand_count() == 2) {
return sharding;
}
std::vector<HloSharding> tuple(instruction->operand_count() / 2,
std::move(sharding));
return HloSharding::Tuple(instruction->shape(), tuple);
};
if (operand->sharding().IsReplicated() ||
(!is_spmd &&
absl::c_any_of(instruction->dimensions(), [operand](int64 dim) {
return operand->sharding().tile_assignment().dim(dim) > 1;
}))) {
// We are reducing along one of the sharded dimensions. We only
// support this in SPMD.
changed |= MaybeImproveInstructionSharding(
get_maybe_tuple_sharding(HloSharding::Replicate()), instruction,
may_combine_partial_sharding);
continue;
}
auto after_partial_replication =
operand->sharding().IsReplicated()
? operand->sharding()
: hlo_sharding_util::PartiallyReplicateTiledShardingOnDims(
operand->sharding(), instruction->dimensions());
if (after_partial_replication.IsReplicated()) {
changed |= MaybeImproveInstructionSharding(
get_maybe_tuple_sharding(HloSharding::Replicate()), instruction,
may_combine_partial_sharding);
continue;
}
// Use the same sharding for all tuple elements, because they are part
// of the same reduce instruction.
HloSharding new_sharding =
get_maybe_tuple_sharding(hlo_sharding_util::RemoveShapeDimensions(
after_partial_replication, instruction->dimensions()));
changed |= MaybeImproveInstructionSharding(
std::move(new_sharding), instruction, may_combine_partial_sharding);
}
return changed;
}
case HloOpcode::kBroadcast: {
// Make forward propagation through broadcast low priority to avoid
// resharding after broadcast.
if (aggressiveness < 3) {
return false;
}
// Do not override existing tile sharding. This is likely from users.
if (IsSpatiallyPartitioned(instruction) &&
!instruction->sharding().IsTileMaximal()) {
return false;
}
const HloInstruction* op = instruction->operand(0);
if (!IsSpatiallyPartitioned(op) || op->sharding().IsReplicated()) {
return false;
}
// The output will be tiled along the broadcasted dimension the same way
// as the input for the broadcast while the other dimensions are kept
// non-tiled.
std::vector<int64> target_tile_assignment_dimensions;
const auto& dimensions = instruction->dimensions();
for (int64 i = 0; i < instruction->shape().rank(); ++i) {
auto it = absl::c_find(dimensions, i);
if (it == dimensions.end()) {
target_tile_assignment_dimensions.push_back(1);
} else {
const int64 source_dim = std::distance(dimensions.begin(), it);
target_tile_assignment_dimensions.push_back(
op->sharding().tile_assignment().dim(source_dim));
}
}
if (op->sharding().ReplicateOnLastTileDim()) {
target_tile_assignment_dimensions.push_back(
op->sharding().tile_assignment().dimensions().back());
}
Array<int64> new_tile_assignment = op->sharding().tile_assignment();
new_tile_assignment.Reshape(target_tile_assignment_dimensions);
HloSharding new_sharding =
op->sharding().ReplicateOnLastTileDim()
? HloSharding::PartialTile(new_tile_assignment)
: HloSharding::Tile(new_tile_assignment);
return MaybeImproveInstructionSharding(
std::move(new_sharding), instruction, may_combine_partial_sharding);
}
case HloOpcode::kConvolution:
return InferConvolutionShardingFromOperands(instruction, aggressiveness,
may_combine_partial_sharding);
case HloOpcode::kTranspose: {
const HloInstruction* input = instruction->operand(0);
if (!IsSpatiallyPartitioned(input)) {
return false;
}
HloSharding sharding = hlo_sharding_util::TransposeSharding(
input->sharding(), instruction->dimensions());
return MaybeImproveInstructionSharding(std::move(sharding), instruction,
may_combine_partial_sharding);
}
case HloOpcode::kReduceWindow: {
if (instruction->shape().IsTuple()) {
// TODO (b/73062247) variadic reduce window is not yet supported here.
return false;
}
const HloInstruction* lhs = instruction->operand(0);
if (!IsSpatiallyPartitioned(lhs)) {
return false;
}
auto has_dilation = [](const WindowDimension& dimensions) {
return dimensions.base_dilation() > 1 ||
dimensions.window_dilation() > 1;
};
if (absl::c_any_of(instruction->window().dimensions(), has_dilation)) {
VLOG(2) << "Not applying sharding to reduce window because dilatation "
"isn't supported yet: "
<< instruction->ToString();
return false;
}
return MaybeImproveInstructionSharding(lhs->sharding(), instruction,
may_combine_partial_sharding);
}
case HloOpcode::kSelectAndScatter: {
// Shard according to first operand, as output keeps the same shape.
const HloInstruction* lhs = instruction->operand(0);
if (!IsSpatiallyPartitioned(lhs)) {
return false;
}
auto has_base_dilation = [](const WindowDimension& dimensions) {
return dimensions.base_dilation() > 1;
};
if (absl::c_any_of(instruction->window().dimensions(),
has_base_dilation)) {
VLOG(2) << "Not applying sharding to select-and-scatter because "
"base dilation isn't supported yet: "
<< instruction->ToString();
return false;
}
return MaybeImproveInstructionSharding(lhs->sharding(), instruction,
may_combine_partial_sharding);
}
case HloOpcode::kReshape: {
if (!IsSpatiallyPartitioned(instruction->operand(0))) {
return false;
}
absl::optional<HloSharding> new_sharding =
hlo_sharding_util::ReshapeSharding(
instruction->operand(0)->shape(), instruction->shape(),
instruction->operand(0)->sharding());
if (new_sharding.has_value()) {
return MaybeImproveInstructionSharding(std::move(*new_sharding),
instruction,
may_combine_partial_sharding);
}
return false;
}
case HloOpcode::kReverse: {
if (!IsSpatiallyPartitioned(instruction->operand(0))) {
return false;
}
return MaybeImproveInstructionSharding(
hlo_sharding_util::ReverseSharding(
instruction->operand(0)->sharding(), instruction->dimensions()),
instruction, may_combine_partial_sharding);
}
case HloOpcode::kDot: {
const auto& dnums =
dot_as_convolution_util::ParseDotGeneralFromDot(instruction);
return InferDotShardingFromOperands(instruction, dnums,
may_combine_partial_sharding);
}
case HloOpcode::kParameter: {
auto parent_it = computation_map.find(instruction->parent());
if (parent_it == computation_map.end()) {
return false;
}
const HloInstruction* parent = parent_it->second;
switch (parent->opcode()) {
case HloOpcode::kConditional: {
for (int64 i = 1; i < parent->operand_count(); ++i) {
if (parent->called_computations()[i - 1] == instruction->parent()) {
if (parent->operand(i)->has_sharding()) {
return MaybeImproveInstructionSharding(
parent->operand(i)->sharding(), instruction,
may_combine_partial_sharding);
}
return false;
}
}
return false;
}
default:
return false;
}
}
case HloOpcode::kSort: {
const HloInstruction* operand = PickRepresentativeOperand(instruction);
if (!operand || !IsSpatiallyPartitioned(operand)) {
return false;
}
if (!operand->sharding().IsTileMaximal() &&
operand->sharding().tile_assignment().dim(
instruction->dimensions(0)) != 1) {
// Doesn't support sharding the sorting dimension.
return false;
}
if (instruction->shape().IsTuple()) {
return MaybeImproveInstructionSharding(
HloSharding::SingleTuple(instruction->shape(), operand->sharding()),
instruction, may_combine_partial_sharding);
} else {
return MaybeImproveInstructionSharding(operand->sharding(), instruction,
may_combine_partial_sharding);
}
}
case HloOpcode::kDynamicSlice:
case HloOpcode::kDynamicUpdateSlice: {
auto propagate_slicing = [&]() {
const HloInstruction* operand =
instruction->opcode() == HloOpcode::kDynamicSlice
? instruction->operand(0)
: instruction->operand(1);
if (!IsSpatiallyPartitioned(operand)) {
return false;
}
if (operand->sharding().IsReplicated()) {
return MaybeImproveInstructionSharding(HloSharding::Replicate(),
instruction,
may_combine_partial_sharding);
}
const auto& tile_assignment = operand->sharding().tile_assignment();
for (int64 i = 0; i < instruction->shape().rank(); ++i) {
if (tile_assignment.dim(i) > 1 &&
instruction->shape().dimensions(i) !=
operand->shape().dimensions(i)) {
return false;
}
}
return MaybeImproveInstructionSharding(operand->sharding(), instruction,
may_combine_partial_sharding);
};
auto propagate_base = [&]() {
if (instruction->opcode() != HloOpcode::kDynamicUpdateSlice) {
return false;
}
if (!IsSpatiallyPartitioned(instruction->operand(0))) {
return false;
}
return MaybeImproveInstructionSharding(
instruction->operand(0)->sharding(), instruction,
may_combine_partial_sharding);
};
return propagate_slicing() || propagate_base();
}
case HloOpcode::kGather: {
bool changed = false;
if (is_spmd) {
auto gather_parallel_dims =
hlo_sharding_util::GetGatherBatchParallelDims(*instruction);
if (gather_parallel_dims) {
changed |= InferGatherParallelShardingFromOperands(
instruction, *gather_parallel_dims, may_combine_partial_sharding);
}
}
if (IsSpatiallyPartitioned(instruction->operand(1))) {
HloSharding new_sharding = hlo_sharding_util::GatherOutputSharding(
instruction->operand(1)->sharding(), instruction);
changed |= MaybeImproveInstructionSharding(
std::move(new_sharding), instruction, may_combine_partial_sharding);
}
if (is_spmd && IsSpatiallyPartitioned(instruction->operand(0))) {
auto maybe_from_data =
hlo_sharding_util::GatherOutputShardingFromDataOperand(
instruction->operand(0)->sharding(), *instruction);
if (maybe_from_data) {
changed |= MaybeImproveInstructionSharding(
std::move(*maybe_from_data), instruction,
may_combine_partial_sharding);
}
}
return changed;
}
case HloOpcode::kScatter: {
bool changed = false;
if (is_spmd && IsSpatiallyPartitioned(instruction->operand(0))) {
changed |= MaybeImproveInstructionSharding(
instruction->operand(0)->sharding(), instruction,
may_combine_partial_sharding);
}
if (!IsSpatiallyPartitioned(instruction->operand(1)) &&
!IsSpatiallyPartitioned(instruction->operand(2))) {
return false;
}
if (is_spmd && IsSpatiallyPartitioned(instruction->operand(2))) {
auto maybe_from_update =
hlo_sharding_util::ScatterOutputShardingFromUpdate(
instruction->operand(2)->sharding(), *instruction);
if (maybe_from_update) {
changed |= MaybeImproveInstructionSharding(
std::move(*maybe_from_update), instruction,
may_combine_partial_sharding);
}
}
changed |= MaybeImproveInstructionSharding(
HloSharding::Replicate(), instruction, may_combine_partial_sharding);
return changed;
}
case HloOpcode::kWhile: {
if (!instruction->operand(0)->has_sharding()) {
return false;
}
auto sharding = instruction->operand(0)->sharding();
if (instruction->has_sharding()) {
MergeSharding(instruction->sharding(), &sharding,
may_combine_partial_sharding);
}
return MaybeImproveInstructionSharding(std::move(sharding), instruction,
may_combine_partial_sharding);
}
default: {
if (instruction->IsElementwise() && may_combine_partial_sharding) {
bool changed = false;
for (auto operand : instruction->operands()) {
if (IsSpatiallyPartitioned(operand)) {
changed |= MaybeImproveInstructionSharding(
operand->sharding(), instruction, may_combine_partial_sharding);
}
}
return changed;
}
const HloInstruction* operand = PickRepresentativeOperand(instruction);
if (!operand || !IsSpatiallyPartitioned(operand)) {
return false;
}
return MaybeImproveInstructionSharding(operand->sharding(), instruction,
may_combine_partial_sharding);
}
}
return false;
}
HloSharding InferDotOperandSharding(
const HloInstruction* instruction,
const dot_as_convolution_util::DotConvolutionDimsInfo& dnums,
int64 operand_index, bool may_combine_partial_sharding) {
auto operand = instruction->operand(operand_index);
auto other = instruction->operand(1 - operand_index);
std::vector<int64> output_dims_to_replicate;
std::vector<int64> other_operand_dims_to_replicate;
for (const auto& dim : operand_index == 0 ? dnums.rhs_non_contracting_dims
: dnums.lhs_non_contracting_dims) {
output_dims_to_replicate.push_back(dim.output);
other_operand_dims_to_replicate.push_back(operand_index == 0 ? dim.rhs
: dim.lhs);
}
// If this dot is interpreted from a conv, then contracting dims may have
// corresponding spatial dimensions in the output, and this operand's
// non-contracting dims may have corresponding spatial dims in the other
// operand.
for (const auto& dim : dnums.contracting_dims) {
if (dim.output >= 0) {
output_dims_to_replicate.push_back(dim.output);
}
}
for (const auto& dim : operand_index == 0 ? dnums.lhs_non_contracting_dims
: dnums.rhs_non_contracting_dims) {
int64 other_dim = operand_index == 0 ? dim.rhs : dim.lhs;
if (other_dim >= 0) {
other_operand_dims_to_replicate.push_back(other_dim);
}
}
auto output_other_dims_replicated =
hlo_sharding_util::PartiallyReplicateTiledShardingOnDims(
instruction->sharding(), output_dims_to_replicate);
std::vector<int64> output_to_operand_dims(instruction->shape().rank(), -1);
std::vector<int64> operand_to_output_dims(operand->shape().rank(), -1);
for (const auto& dim : dnums.batch_dims) {
output_to_operand_dims[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs;
operand_to_output_dims[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output;
}
for (const auto& dim : operand_index == 0 ? dnums.lhs_non_contracting_dims
: dnums.rhs_non_contracting_dims) {
output_to_operand_dims[dim.output] = operand_index == 0 ? dim.lhs : dim.rhs;
operand_to_output_dims[operand_index == 0 ? dim.lhs : dim.rhs] = dim.output;
}
auto sharding = *hlo_sharding_util::TransposeShardingWithCollapsedDims(
output_other_dims_replicated, output_to_operand_dims,
operand_to_output_dims);
if (IsSpatiallyPartitioned(other)) {
auto other_operand_dims_replicated =
hlo_sharding_util::PartiallyReplicateTiledShardingOnDims(
other->sharding(), other_operand_dims_to_replicate);
std::vector<int64> other_to_operand_dims(other->shape().rank(), -1);
std::vector<int64> operand_to_other_dims(operand->shape().rank(), -1);
for (const auto& dim : dnums.batch_dims) {
other_to_operand_dims[operand_index == 0 ? dim.rhs : dim.lhs] =
operand_index == 0 ? dim.lhs : dim.rhs;
operand_to_other_dims[operand_index == 0 ? dim.lhs : dim.rhs] =
operand_index == 0 ? dim.rhs : dim.lhs;
}
for (const auto& dim : dnums.contracting_dims) {
other_to_operand_dims[operand_index == 0 ? dim.rhs : dim.lhs] =
operand_index == 0 ? dim.lhs : dim.rhs;
operand_to_other_dims[operand_index == 0 ? dim.lhs : dim.rhs] =
operand_index == 0 ? dim.rhs : dim.lhs;
}
HloSharding sharding_from_other =
*hlo_sharding_util::TransposeShardingWithCollapsedDims(
other_operand_dims_replicated, other_to_operand_dims,
operand_to_other_dims);
if (MergeSharding(sharding, &sharding_from_other,
may_combine_partial_sharding)) {
sharding = std::move(sharding_from_other);
}
}
return sharding;
}
// Return the sharding that should be propagated from user to instruction.
absl::optional<HloSharding> GetShardingFromUser(
const HloInstruction& instruction, const HloInstruction& user,
int64 aggressiveness, bool is_spmd) {
if (!CanPropagateThroughAtAgressiveLevel(user, aggressiveness)) {
return absl::nullopt;
}
if (!IsSpatiallyPartitioned(&user)) {
return absl::nullopt;
}
const bool may_combine_partial_sharding = is_spmd && aggressiveness > 0;
switch (user.opcode()) {
case HloOpcode::kBroadcast: {
if (user.sharding().IsReplicated()) {
return user.sharding();
}
std::vector<int64> dims_to_replicate;
bool needs_replication = false;
for (int64 i = 0; i < user.shape().rank(); ++i) {
if (absl::c_count(user.dimensions(), i) == 0) {
dims_to_replicate.push_back(i);
if (user.sharding().tile_assignment().dim(i) > 1) {
needs_replication = true;
}
}
}
// If not SPMD, only support when none of the partitioned dimensions in
// the broadcast output belong to new dimensions.
if (!is_spmd && needs_replication) {
return absl::nullopt;
}
return hlo_sharding_util::RemoveShapeDimensions(
hlo_sharding_util::PartiallyReplicateTiledShardingOnDims(
user.sharding(), dims_to_replicate),
dims_to_replicate);
}
case HloOpcode::kConcatenate: {
if (user.sharding().IsReplicated()) {
return user.sharding();
}
const int64 cdim = user.concatenate_dimension();
const Array<int64>& tile_assignment = user.sharding().tile_assignment();
if (tile_assignment.dim(cdim) == 1) {
// If we are concatenating along a non-sharded dimension then the
// operands should have the same sharding as the result.
return user.sharding();
}
if (is_spmd) {
// SPMD doesn't support tiling with part of the devices. Return the same
// sharding.
return user.sharding();
}
// If we are concatenating along a sharded dimension then we want the
// operands to be distributed among the devices their data is used.
int64 start_offset = 0;
for (HloInstruction* op : user.operands()) {
if (op == &instruction) {
break;
}
start_offset += op->shape().dimensions(cdim);
}
const int64 tile_shape = CeilOfRatio(user.shape().dimensions(cdim),
tile_assignment.dimensions()[cdim]);
std::vector<int64> start_indices(tile_assignment.num_dimensions());
std::vector<int64> end_indices = tile_assignment.dimensions();
start_indices[cdim] = start_offset / tile_shape;
end_indices[cdim] = CeilOfRatio(
start_offset + instruction.shape().dimensions(cdim), tile_shape);
auto new_tile_assignment =
tile_assignment.Slice(start_indices, end_indices);
if (new_tile_assignment.num_elements() == 1) {
return HloSharding::AssignDevice(*new_tile_assignment.begin());
}
return HloSharding::Tile(new_tile_assignment);
}
case HloOpcode::kConvolution: {
auto dot_dims = dot_as_convolution_util::ParseConvolutionDimsInfo(&user);
if (dot_dims.conv_spatial_dims.empty()) {
int64 op_idx = user.operand_index(&instruction);
return InferDotOperandSharding(&user, dot_dims, op_idx,
may_combine_partial_sharding);
}
return absl::nullopt;
}
case HloOpcode::kDynamicSlice:
case HloOpcode::kDynamicUpdateSlice: {
if (user.sharding().IsReplicated()) {
return user.sharding();
}
if (user.opcode() == HloOpcode::kDynamicUpdateSlice &&
&instruction == user.operand(0)) {
return user.sharding();
}
const HloInstruction* operand = user.opcode() == HloOpcode::kDynamicSlice
? user.operand(0)
: user.operand(1);
if (&instruction != operand) {
return absl::nullopt;
}
const auto& tile_assignment = user.sharding().tile_assignment();
for (int64 i = 0; i < user.shape().rank(); ++i) {
if (tile_assignment.dim(i) > 1 &&
user.shape().dimensions(i) != operand->shape().dimensions(i)) {
return absl::nullopt;
}
}
return user.sharding();
}
case HloOpcode::kReduceWindow: {
if (user.shape().IsTuple()) {
return user.sharding().GetSubSharding(
user.shape(), {user.operand_index(&instruction)});
}
if (&instruction != user.operand(0)) {
return absl::nullopt;
}
return user.sharding();
}
case HloOpcode::kReshape: {
return hlo_sharding_util::ReshapeSharding(
user.shape(), instruction.shape(), user.sharding());
}
case HloOpcode::kPad: {
if (&instruction != user.operand(0)) {
return absl::nullopt;
}
return user.sharding();
}
case HloOpcode::kSlice: {
return user.sharding();
}
case HloOpcode::kTranspose: {
// Calculate the dimension numbers for reversing the current transpose
// and then use TransposeSharding to convert the output sharding to an
// input sharding.
std::vector<int64> reverse_dimensions(user.dimensions().size());
for (int64 i = 0; i < user.dimensions().size(); ++i) {
reverse_dimensions[user.dimensions(i)] = i;
}
return hlo_sharding_util::TransposeSharding(user.sharding(),
reverse_dimensions);
}
case HloOpcode::kTuple: {
return user.sharding().GetSubSharding(user.shape(),
{user.operand_index(&instruction)});
}
case HloOpcode::kGetTupleElement: {
HloSharding new_sharding =
instruction.has_sharding()
? instruction.sharding()
: HloSharding::SingleTuple(instruction.shape(),
HloSharding::Replicate());
int64 sharding_index = 0;
for (int64 i = 0; i < instruction.shape().tuple_shapes_size(); ++i) {
if (i == user.tuple_index()) {
break;
}
if (instruction.shape().tuple_shapes(i).IsArray()) {
sharding_index += 1;
} else {
sharding_index +=
instruction.shape().tuple_shapes(i).tuple_shapes_size();
}
}
if (user.shape().IsArray()) {
new_sharding.tuple_elements()[sharding_index] = user.sharding();
}
for (int64 i = 0; i < user.sharding().tuple_elements().size(); ++i) {
new_sharding.tuple_elements()[sharding_index + i] =
user.sharding().tuple_elements()[i];
}
return new_sharding;
}
case HloOpcode::kDot: {
int64 op_idx = user.operand_index(&instruction);
auto dnums = dot_as_convolution_util::ParseDotGeneralFromDot(&user);
return InferDotOperandSharding(&user, dnums, op_idx,
may_combine_partial_sharding);
}
case HloOpcode::kReduce: {
if (instruction.shape().rank() == 0) {
return absl::nullopt;
}
auto user_sharding =
user.shape().IsTuple()
? user.sharding().GetSubSharding(
user.shape(), {user.operand_index(&instruction)})
: user.sharding();
if (user_sharding.IsTileMaximal()) {
return user_sharding;
}
std::vector<int64> target_tile_assignment_dimensions(
instruction.shape().rank() +
(user_sharding.ReplicateOnLastTileDim() ? 1 : 0));
const auto& dimensions = user.dimensions();
int64 next_output_dim = 0;
for (int64 i = 0; i < target_tile_assignment_dimensions.size(); ++i) {
if (absl::c_find(dimensions, i) == dimensions.end()) {
target_tile_assignment_dimensions[i] =
user_sharding.tile_assignment().dim(next_output_dim++);
} else {
target_tile_assignment_dimensions[i] = 1;
}
}
auto tile_assignment = user_sharding.tile_assignment();
tile_assignment.Reshape(target_tile_assignment_dimensions);
return user_sharding.ReplicateOnLastTileDim()
? HloSharding::PartialTile(tile_assignment)
: HloSharding::Tile(tile_assignment);
}
case HloOpcode::kSort: {
if (user.sharding().IsTuple()) {
return user.sharding().GetSubSharding(
user.shape(), {user.operand_index(&instruction)});
} else {
return user.sharding();
}
}
case HloOpcode::kReverse: {
return hlo_sharding_util::ReverseSharding(user.sharding(),
user.dimensions());
}
case HloOpcode::kGather: {
if (&instruction == user.operand(1)) {
return hlo_sharding_util::GatherIndexSharding(user.sharding(), &user);
}
if (is_spmd) {
return hlo_sharding_util::GatherDataOperandShardingFromOutput(
user.sharding(), user);
}
return absl::nullopt;
}
case HloOpcode::kScatter: {
if (&instruction == user.operand(0)) {
return user.sharding();
}
if (&instruction == user.operand(1)) {
auto update = user.operand(2);
if (!IsSpatiallyPartitioned(update)) {
return absl::nullopt;
}
return hlo_sharding_util::ScatterIndexSharding(update->sharding(),
&user);
}
CHECK_EQ(&instruction, user.operand(2));
auto indices = user.operand(1);
if (IsSpatiallyPartitioned(indices)) {
auto from_indices =
hlo_sharding_util::ScatterDataSharding(indices->sharding(), &user);
if (!from_indices.IsTileMaximal()) {
return from_indices;
}
}
if (is_spmd) {
return hlo_sharding_util::ScatterUpdateShardingFromOutput(
user.sharding(), user);
}
return absl::nullopt;
}
default: {
// If the user output shape is compatible with the current instruction
// shape excluding element type and the current instruction is supported
// by spatial partitioning, then the user sharding can be used for
// propagation to the current instruction.
if (ShapeUtil::CompatibleIgnoringElementType(instruction.shape(),
user.shape())) {
return user.sharding();
}
return absl::nullopt;
}
}
}
// Tries to update the sharding of the specified instruction based on its users
// and returns true if the sharding of the instruction have been changed and
// false otherwise.
bool InferShardingFromUsers(HloInstruction* instruction,
const ComputationMap& computation_map,
int64 aggressiveness, bool is_spmd) {
if (aggressiveness < 2 && instruction->opcode() == HloOpcode::kBroadcast) {
return false;
}
// Do not change manual sharding.
if (instruction->has_sharding() && instruction->sharding().IsManual()) {
return false;
}
// Propagate manual sharding.
if (!instruction->has_sharding() && instruction->shape().IsArray() &&
absl::c_any_of(instruction->users(), [](const HloInstruction* user) {
return user->has_sharding() && user->sharding().IsManual() &&
!user->IsCustomCall("SPMDFullToShardShape");
})) {
instruction->set_sharding(HloSharding::Manual());
return true;
}
if (!SupportSpatialPartitioning(instruction, computation_map, is_spmd)) {
return false;
}
bool improved_sharding = false;
const bool may_combine_partial_sharding = is_spmd && aggressiveness > 0;
for (const HloInstruction* user : instruction->users()) {
absl::optional<HloSharding> user_sharding =
GetShardingFromUser(*instruction, *user, aggressiveness, is_spmd);
if (user_sharding) {
improved_sharding |= MaybeImproveInstructionSharding(
std::move(*user_sharding), instruction, may_combine_partial_sharding);
}
}
return improved_sharding;
}
// Remove Sharding custom-call instruction by folding the sharding attribute
// to its operand. If the operand alreayd has a different sharding, insert a
// copy node for reshard.
StatusOr<bool> ProcessShardingInstruction(HloModule* module) {
bool changed = false;
for (HloComputation* computation : module->computations()) {
auto instructions = computation->MakeInstructionPostOrder();
std::reverse(instructions.begin(), instructions.end());
for (HloInstruction* instruction : instructions) {
if (instruction->opcode() != HloOpcode::kCustomCall) {
continue;
}
if (instruction->custom_call_target() != "Sharding") {
continue;
}
TF_RET_CHECK(instruction->has_sharding())
<< "Sharding instruction must have a sharding attribute";
const HloSharding& sharding = instruction->sharding();
// If the operand has a different sharding from the current sharding
// instruction, create a copy node. Otherwise, just remove the sharding
// instruction and set the operand sharding.
if (instruction->operand(0)->has_sharding() &&
instruction->operand(0)->sharding() != sharding) {
auto copy = computation->AddInstruction(
HloInstruction::CreateUnary(instruction->shape(), HloOpcode::kCopy,
instruction->mutable_operand(0)));
TF_RETURN_IF_ERROR(computation->ReplaceInstruction(instruction, copy));
copy->set_sharding(sharding);
} else {
instruction->mutable_operand(0)->set_sharding(sharding);
TF_RETURN_IF_ERROR(
instruction->ReplaceAllUsesWith(instruction->mutable_operand(0)));
TF_RETURN_IF_ERROR(computation->RemoveInstruction(instruction));
}
changed = true;
}
}
return changed;
}
// If a while contains a channel instruction on device D, check that any other
// instructions with a device assignment are on D. Further, annotate the root
// instruction of the while body to ensure that HLO partitioning will keep the
// entire while instruction on D.
Status CheckAndUpdateDeviceAssignmentsInWhileBody(
HloInstruction* while_instruction) {
auto bad_status = [](HloInstruction* instruction, int64 device,
HloInstruction* channel_instruction,
int64 correct_device) {
return FailedPrecondition(
"Instruction: %s is on device: %d, which conflicts with device: %d "
"of channel instruction: %s",
instruction->name(), device, correct_device,
channel_instruction->name());
};
CHECK_EQ(while_instruction->opcode(), HloOpcode::kWhile);
HloComputation* while_body = while_instruction->while_body();
// Maps a device number to an instruction in the while_body with that
// device assignment.
std::map<int64, HloInstruction*> devices_to_instructions;
absl::optional<int64> unique_device = absl::nullopt;
HloInstruction* channel_instruction = nullptr;
for (HloInstruction* instruction : while_body->instructions()) {
if (instruction->sharding_unique_device()) {
auto opcode = instruction->opcode();
int64 device = *instruction->sharding_unique_device();
if (unique_device.has_value()) {
if (*unique_device != device) {
return bad_status(instruction, device, channel_instruction,
*unique_device);
}
} else if (opcode == HloOpcode::kSend || opcode == HloOpcode::kRecv ||
// Cross-replica AllReduces don't have a channel_id, and we
// don't enforce any invariant about their device assignment.
(opcode == HloOpcode::kAllReduce &&
instruction->channel_id())) {
channel_instruction = instruction;
unique_device = device;
if (!devices_to_instructions.empty()) {
for (auto it = devices_to_instructions.begin();
it != devices_to_instructions.end(); ++it) {
if (*unique_device != it->first) {
return bad_status(it->second, it->first, channel_instruction,
*unique_device);
}
}
}
} else {
devices_to_instructions[device] = instruction;
}
}
}
if (unique_device.has_value()) {
auto while_device = while_instruction->sharding_unique_device();
if (while_device.has_value() && *unique_device != *while_device) {
return bad_status(while_instruction, *while_device, channel_instruction,
*unique_device);
}
auto body_root = while_body->root_instruction();
auto root_device = body_root->sharding_unique_device();
if (!root_device.has_value()) {
body_root->set_device_sharding(*unique_device);
} else if (*unique_device != *root_device) {
return bad_status(body_root, *root_device, channel_instruction,
*unique_device);
}
}
return Status::OK();
}
} // namespace
/*static*/ Status ShardingPropagation::NormalizeDomain(
const DomainMetadata::Domain& domain, const DomainMetadata* metadata) {
if (metadata != nullptr) {
TF_ASSIGN_OR_RETURN(const auto& sharding_metadata,
ShardingMetadata::ToShardingMetadata(metadata));
const auto& sharding = sharding_metadata->sharding();
if (sharding != nullptr) {
bool is_spatially_partitioned = !sharding->HasUniqueDevice();
if (sharding->IsTuple()) {
is_spatially_partitioned = absl::c_any_of(
sharding->tuple_elements(),
[](const HloSharding& s) { return !s.HasUniqueDevice(); });
}
if (is_spatially_partitioned) {
for (HloInstruction* d : domain.exit_domains) {
d->mutable_operand(0)->set_sharding(*sharding);
}
return Status::OK();
}
}
}
return ShardingMetadata::NormalizeShardingDomain(domain, metadata);
}
StatusOr<bool> ShardingPropagation::Run(HloModule* module) {
TF_ASSIGN_OR_RETURN(bool any_changed, ProcessShardingInstruction(module));
// Association of partitionable embedded computations with their parent
// instruction.
ComputationMap computation_map;
// Instructions that are related through a computation and need to share the
// same sharding.
auto get_related_instructions = [](HloInstruction* inst) {
if (inst->opcode() == HloOpcode::kWhile) {
return std::vector<HloInstruction*>{
inst, inst->while_body()->root_instruction(),
inst->while_body()->parameter_instruction(0),
inst->while_condition()->parameter_instruction(0)};
} else if (inst->opcode() == HloOpcode::kConditional) {
std::vector<HloInstruction*> comps{inst};
for (HloComputation* c : inst->called_computations()) {
comps.push_back(c->root_instruction());
}
return comps;
} else {
CHECK(false);
}
};
// If instruction is a while, or the root or a parameter of a while body,
// then propagate its sharding to the while instruction, to its body root,
// and to its condition parameter.
std::function<void(HloInstruction*, absl::flat_hash_set<HloInstruction*>*)>
maybe_computation_propagation = [&](HloInstruction* instruction,
absl::flat_hash_set<HloInstruction*>*
changed) {
auto propagate_to_instruction = [&](HloInstruction* search_inst) {
auto related_instructions = get_related_instructions(search_inst);
if (absl::c_count(related_instructions, instruction)) {
for (HloInstruction* inst : related_instructions) {
if (!inst->has_sharding() ||
inst->sharding() != instruction->sharding()) {
VLOG(2) << "Add computation sharding: " << inst->name();
inst->set_sharding(instruction->sharding());
changed->insert(inst);
maybe_computation_propagation(inst, changed);
}
}
}
};
if (instruction->opcode() == HloOpcode::kConditional ||
instruction->opcode() == HloOpcode::kWhile) {
propagate_to_instruction(instruction);
}
if (instruction->opcode() == HloOpcode::kParameter ||
instruction->parent()->root_instruction() == instruction) {
auto it = computation_map.find(instruction->parent());
if (it != computation_map.end()) {
propagate_to_instruction(it->second);
}
}
};
for (auto computation : module->computations()) {
for (auto instruction : computation->instructions()) {
if (instruction->opcode() == HloOpcode::kWhile) {
TF_RETURN_IF_ERROR(
CheckAndUpdateDeviceAssignmentsInWhileBody(instruction));
}
}
}
// Populate computation_map in order to associate while bodies to their
// while instructions.
for (auto computation : module->computations()) {
for (auto instruction : computation->instructions()) {
if (instruction->opcode() == HloOpcode::kWhile ||
instruction->opcode() == HloOpcode::kConditional) {
// Check if any of the related instructions has sharding, in which case
// propagate it to the other instructions, so they all share the same
// sharding, in case the user didn't shard all of them. We don't check
// that user shardings are consistent, because such check is already
// done by HloShardingVerifier.
const HloInstruction* sharded_inst = nullptr;
auto related_instructions = get_related_instructions(instruction);
for (auto inst : related_instructions) {
if (inst->has_sharding()) {
sharded_inst = inst;
break;
}
}
if (sharded_inst != nullptr) {
// Set the same sharding to all the other related instructions.
for (auto inst : related_instructions) {
inst->set_sharding(sharded_inst->sharding());
}
}
if (instruction->opcode() == HloOpcode::kWhile) {
computation_map[instruction->while_body()] = instruction;
} else {
for (HloComputation* c : instruction->called_computations()) {
computation_map[c] = instruction;
}
}
}
}
}
// Collect all pre-sharded instructions as we aren't allowed to modify their
// sharding.
absl::flat_hash_set<const HloInstruction*> provided_shardings;
for (const HloComputation* computation : module->computations()) {
for (const HloInstruction* inst : computation->instructions()) {
if (inst->has_sharding()) {
provided_shardings.insert(inst);
}
}
}
// Consider the root instruction of the entry module as one with provided
// sharding as its sharding have to match with the one expected by the host.
provided_shardings.insert(module->entry_computation()->root_instruction());
// Iterate to a fixpoint that is guaranteed to be reached because we only
// strictly improve the sharding of the graph and it can't be improved
// indefinitely.
int64 iterations = 0;
auto run_to_fix_point = [&](int64 aggressiveness) {
absl::flat_hash_set<const HloInstruction*> already_inferred_from_operands;
absl::flat_hash_set<const HloInstruction*> already_inferred_from_users;
bool changed_last_iter = true;
while (changed_last_iter) {
changed_last_iter = false;
int64 inferred_from_operand_counter = 0;
int64 inferred_from_user_counter = 0;
int64 instruction_counter = 0;
int64 already_sharded_counter = 0;
for (const HloComputation* computation : module->computations()) {
std::vector<HloInstruction*> instructions =
computation->MakeInstructionPostOrder();
instruction_counter += instructions.size();
for (const HloInstruction* instruction : instructions) {
already_sharded_counter += (instruction->has_sharding() ? 1 : 0);
}
auto clear_cache = [&](HloInstruction* hlo) {
for (auto operand : hlo->operands()) {
already_inferred_from_users.erase(operand);
}
for (auto user : hlo->users()) {
already_inferred_from_operands.erase(user);
}
};
// First iterate the HLO graph in post order taking shardings from
// operands.
for (HloInstruction* instruction : instructions) {
if (already_inferred_from_operands.contains(instruction) ||
provided_shardings.contains(instruction)) {
continue;
}
already_inferred_from_operands.insert(instruction);
if (InferShardingFromOperands(instruction, computation_map, is_spmd_,
aggressiveness)) {
++inferred_from_operand_counter;
any_changed = true;
VLOG(2) << "Add sharding (forward-pass): "
<< instruction->ToString();
absl::flat_hash_set<HloInstruction*> changed_in_comp_prop;
maybe_computation_propagation(instruction, &changed_in_comp_prop);
clear_cache(instruction);
for (auto hlo : changed_in_comp_prop) {
clear_cache(hlo);
}
changed_last_iter = true;
}
}
// Then iterate the HLO graph in reverse post order taking shardings
// from users.
for (auto it = instructions.rbegin(); it != instructions.rend(); ++it) {
if (already_inferred_from_users.contains(*it) ||
provided_shardings.contains(*it)) {
continue;
}
already_inferred_from_users.insert(*it);
if (InferShardingFromUsers(*it, computation_map, aggressiveness,
is_spmd_)) {
++inferred_from_user_counter;
any_changed = true;
VLOG(2) << "Add sharding (backward-pass): " << (*it)->ToString();
absl::flat_hash_set<HloInstruction*> changed_in_comp_prop;
maybe_computation_propagation(*it, &changed_in_comp_prop);
clear_cache(*it);
for (auto hlo : changed_in_comp_prop) {
clear_cache(hlo);
}
changed_last_iter = true;
}
}
}
VLOG(1) << "Sharding propagation iteration " << iterations << ";";
VLOG(1) << " total instructions: " << instruction_counter;
VLOG(1) << " instructions already sharded: " << already_sharded_counter;
VLOG(1) << " shardings inferred from operands: "
<< inferred_from_operand_counter;
VLOG(1) << " shardings inferred from users: "
<< inferred_from_user_counter;
VLOG(1) << " aggressiveness: " << aggressiveness;
++iterations;
}
};
for (int64 aggressiveness = 0; aggressiveness < 4; ++aggressiveness) {
run_to_fix_point(aggressiveness);
}
VLOG(1) << "Sharding propagation completed after " << iterations
<< " iterations";
return any_changed;
}
} // namespace xla
|
./out/forwarding.out: ファイル形式 elf32-mist32
セクション .text の逆アセンブル:
00000000 <_start>:
0: 0d 40 00 00 wl16 r0,0x0
4: 0d 60 00 0f wh16 r0,0xf
8: 1c 00 00 00 srspw r0
c: 14 30 00 1a br 74 <target>,#al
00000010 <mem_print>:
10: 0d 40 02 08 wl16 r16,0x8
14: 0d 60 02 02 wh16 r16,0x2
18: 10 a0 00 10 st32 r0,r16
1c: 14 40 03 e0 b rret,#al
00000020 <error>:
20: 0d 40 03 20 wl16 r25,0x0
24: 0d 60 03 22 wh16 r25,0x2
28: 0e c0 03 40 lil r26,0
2c: 10 a0 03 59 st32 r26,r25
30: 0d 40 03 30 wl16 r25,0x10
34: 0d 60 03 22 wh16 r25,0x2
38: 10 a0 03 79 st32 r27,r25
3c: 0d 40 03 2c wl16 r25,0xc
40: 0d 60 03 22 wh16 r25,0x2
44: 10 a0 03 99 st32 r28,r25
48: 0d 40 03 34 wl16 r25,0x14
4c: 0d 60 03 22 wh16 r25,0x2
50: 10 a0 03 b9 st32 rglobl,r25
54: 0d 40 03 38 wl16 r25,0x18
58: 0d 60 03 22 wh16 r25,0x2
5c: 10 a0 03 d9 st32 rbase,r25
00000060 <finish>:
60: 0d 40 03 24 wl16 r25,0x4
64: 0d 60 03 22 wh16 r25,0x2
68: 0e c0 03 41 lil r26,1
6c: 10 a0 03 59 st32 r26,r25
70: 14 30 00 00 br 70 <finish+0x10>,#al
00000074 <target>:
74: 0d c0 00 00 clr r0
78: 0d c0 00 20 clr r1
7c: 0d c0 00 40 clr r2
80: 0d c0 00 60 clr r3
84: 0d c0 00 80 clr r4
88: 0d c0 00 a0 clr r5
8c: 0d c0 00 c0 clr r6
90: 0d c0 00 e0 clr rtmp
94: 0d c0 01 00 clr r8
98: 0d c0 01 20 clr r9
9c: 0d c0 01 40 clr r10
a0: 0d c0 01 60 clr r11
a4: 0d c0 01 80 clr r12
a8: 0d c0 01 a0 clr r13
ac: 0d c0 01 c0 clr r14
b0: 0d c0 01 e0 clr r15
b4: 0d c0 02 00 clr r16
b8: 0d c0 02 20 clr r17
bc: 0d c0 02 40 clr r18
c0: 0d c0 02 60 clr r19
c4: 0d c0 02 80 clr r20
c8: 0d c0 02 a0 clr r21
cc: 0d c0 02 c0 clr r22
d0: 0d c0 02 e0 clr r23
d4: 0d c0 03 00 clr r24
d8: 0d c0 03 20 clr r25
dc: 0d c0 03 40 clr r26
e0: 0d c0 03 60 clr r27
e4: 0d c0 03 80 clr r28
e8: 0d c0 03 a0 clr rglobl
ec: 0d c0 03 c0 clr rbase
f0: 0d c0 03 e0 clr rret
f4: 0d c0 03 c0 clr rbase
f8: 0e c0 03 c1 lil rbase,1
fc: 20 40 00 1e move r0,rbase
100: 00 10 00 00 add r0,0
104: 00 00 00 20 add r1,r0
108: 00 00 00 41 add r2,r1
10c: 00 00 00 62 add r3,r2
110: 00 00 00 83 add r4,r3
114: 00 00 00 a4 add r5,r4
118: 00 00 00 c5 add r6,r5
11c: 00 00 00 e6 add rtmp,r6
120: 00 00 01 07 add r8,rtmp
124: 00 00 01 28 add r9,r8
128: 00 00 01 49 add r10,r9
12c: 00 00 01 6a add r11,r10
130: 00 00 01 8b add r12,r11
134: 00 00 01 ac add r13,r12
138: 00 00 01 cd add r14,r13
13c: 00 00 01 ee add r15,r14
140: 20 40 03 af move rglobl,r15
144: 20 70 03 e3 movepc rret,12
148: 00 c0 03 be cmp rglobl,rbase
14c: 14 32 ff b5 br 20 <error>,#ne
150: 00 10 03 61 add r27,1
154: 0d c0 00 00 clr r0
158: 0d c0 00 20 clr r1
15c: 0d c0 00 40 clr r2
160: 0d c0 00 60 clr r3
164: 0d c0 00 80 clr r4
168: 0d c0 00 a0 clr r5
16c: 0d c0 00 c0 clr r6
170: 0d c0 00 e0 clr rtmp
174: 0d c0 01 00 clr r8
178: 0d c0 01 20 clr r9
17c: 0d c0 01 40 clr r10
180: 0d c0 01 60 clr r11
184: 0d c0 01 80 clr r12
188: 0d c0 01 a0 clr r13
18c: 0d c0 01 c0 clr r14
190: 0d c0 01 e0 clr r15
194: 0d c0 03 c0 clr rbase
198: 0e c0 03 d0 lil rbase,16
19c: 00 10 00 01 add r0,1
1a0: 20 40 00 20 move r1,r0
1a4: 00 10 00 21 add r1,1
1a8: 20 40 00 41 move r2,r1
1ac: 00 10 00 41 add r2,1
1b0: 20 40 00 62 move r3,r2
1b4: 00 10 00 61 add r3,1
1b8: 20 40 00 83 move r4,r3
1bc: 00 10 00 81 add r4,1
1c0: 20 40 00 a4 move r5,r4
1c4: 00 10 00 a1 add r5,1
1c8: 20 40 00 c5 move r6,r5
1cc: 00 10 00 c1 add r6,1
1d0: 20 40 00 e6 move rtmp,r6
1d4: 00 10 00 e1 add rtmp,1
1d8: 20 40 01 07 move r8,rtmp
1dc: 00 10 01 01 add r8,1
1e0: 20 40 01 28 move r9,r8
1e4: 00 10 01 21 add r9,1
1e8: 20 40 01 49 move r10,r9
1ec: 00 10 01 41 add r10,1
1f0: 20 40 01 6a move r11,r10
1f4: 00 10 01 61 add r11,1
1f8: 20 40 01 8b move r12,r11
1fc: 00 10 01 81 add r12,1
200: 20 40 01 ac move r13,r12
204: 00 10 01 a1 add r13,1
208: 20 40 01 cd move r14,r13
20c: 00 10 01 c1 add r14,1
210: 20 40 01 ee move r15,r14
214: 00 10 01 e1 add r15,1
218: 20 40 03 af move rglobl,r15
21c: 20 70 03 e3 movepc rret,12
220: 00 c0 03 be cmp rglobl,rbase
224: 14 32 ff 7f br 20 <error>,#ne
228: 00 10 03 61 add r27,1
22c: 0d c0 00 00 clr r0
230: 0d c0 00 20 clr r1
234: 0d c0 00 40 clr r2
238: 0d c0 00 60 clr r3
23c: 0d c0 00 80 clr r4
240: 0d c0 00 a0 clr r5
244: 0d c0 00 c0 clr r6
248: 0d c0 00 e0 clr rtmp
24c: 0d c0 01 00 clr r8
250: 0d c0 01 20 clr r9
254: 0d c0 01 40 clr r10
258: 0d c0 01 60 clr r11
25c: 0d c0 01 80 clr r12
260: 0d c0 01 a0 clr r13
264: 0d c0 01 c0 clr r14
268: 0d c0 01 e0 clr r15
26c: 0d c0 03 60 clr r27
270: 0d c0 03 80 clr r28
274: 0e c0 03 81 lil r28,1
278: 18 00 00 00 srspr r0
27c: 20 00 00 00 nop
280: 20 00 00 00 nop
284: 20 00 00 00 nop
288: 20 00 00 00 nop
28c: 20 00 00 00 nop
290: 20 00 00 00 nop
294: 20 00 00 00 nop
298: 20 00 00 00 nop
29c: 20 40 03 c0 move rbase,r0
2a0: 00 30 03 c4 sub rbase,4
2a4: 18 00 03 a0 srspr rglobl
2a8: 00 30 03 a4 sub rglobl,4
2ac: 20 70 03 e3 movepc rret,12
2b0: 00 c0 03 be cmp rglobl,rbase
2b4: 14 32 ff 5b br 20 <error>,#ne
2b8: 00 10 03 61 add r27,1
2bc: 18 00 00 00 srspr r0
2c0: 20 40 03 c0 move rbase,r0
2c4: 20 00 00 00 nop
2c8: 20 00 00 00 nop
2cc: 20 00 00 00 nop
2d0: 20 00 00 00 nop
2d4: 20 00 00 00 nop
2d8: 20 00 00 00 nop
2dc: 20 00 00 00 nop
2e0: 20 00 00 00 nop
2e4: 1c 00 03 c0 srspw rbase
2e8: 18 00 03 c0 srspr rbase
2ec: 20 40 03 a0 move rglobl,r0
2f0: 00 30 07 a0 sub rglobl,32
2f4: 1c 00 03 a0 srspw rglobl
2f8: 18 00 03 a0 srspr rglobl
2fc: 00 10 07 a0 add rglobl,32
300: 20 70 03 e3 movepc rret,12
304: 00 c0 03 be cmp rglobl,rbase
308: 14 32 ff 46 br 20 <error>,#ne
30c: 00 10 03 61 add r27,1
310: 0d c0 00 00 clr r0
314: 0d c0 00 20 clr r1
318: 0d c0 00 40 clr r2
31c: 0d c0 00 60 clr r3
320: 0d c0 00 80 clr r4
324: 0d c0 00 a0 clr r5
328: 0d c0 00 c0 clr r6
32c: 0d c0 00 e0 clr rtmp
330: 0d c0 01 00 clr r8
334: 0d c0 01 20 clr r9
338: 0d c0 01 40 clr r10
33c: 0d c0 01 60 clr r11
340: 0d c0 01 80 clr r12
344: 0d c0 01 a0 clr r13
348: 0d c0 01 c0 clr r14
34c: 0d c0 01 e0 clr r15
350: 0d c0 03 a0 clr rglobl
354: 0d c0 03 c0 clr rbase
358: 18 00 00 00 srspr r0
35c: 20 40 00 20 move r1,r0
360: 00 30 00 30 sub r1,16
364: 1c 00 00 20 srspw r1
368: 20 00 00 00 nop
36c: 20 00 00 00 nop
370: 20 00 00 00 nop
374: 20 00 00 00 nop
378: 20 00 00 00 nop
37c: 20 00 00 00 nop
380: 20 00 00 00 nop
384: 20 00 00 00 nop
388: 18 00 03 c0 srspr rbase
38c: 1c 00 00 00 srspw r0
390: 20 00 00 00 nop
394: 20 00 00 00 nop
398: 20 00 00 00 nop
39c: 20 00 00 00 nop
3a0: 20 00 00 00 nop
3a4: 20 00 00 00 nop
3a8: 20 00 00 00 nop
3ac: 20 00 00 00 nop
3b0: 20 40 00 20 move r1,r0
3b4: 00 30 04 20 sub r1,32
3b8: 1c 00 00 20 srspw r1
3bc: 18 00 03 a0 srspr rglobl
3c0: 00 10 03 b0 add rglobl,16
3c4: 20 70 03 e3 movepc rret,12
3c8: 00 c0 03 be cmp rglobl,rbase
3cc: 14 32 ff 15 br 20 <error>,#ne
3d0: 00 10 03 61 add r27,1
3d4: 0d c0 00 00 clr r0
3d8: 0d c0 00 20 clr r1
3dc: 0d c0 00 40 clr r2
3e0: 0d c0 00 60 clr r3
3e4: 0d c0 00 80 clr r4
3e8: 0d c0 00 a0 clr r5
3ec: 0d c0 00 c0 clr r6
3f0: 0d c0 00 e0 clr rtmp
3f4: 0d c0 01 00 clr r8
3f8: 0d c0 01 20 clr r9
3fc: 0d c0 01 40 clr r10
400: 0d c0 01 60 clr r11
404: 0d c0 01 80 clr r12
408: 0d c0 01 a0 clr r13
40c: 0d c0 01 c0 clr r14
410: 0d c0 01 e0 clr r15
414: 18 00 03 c0 srspr rbase
418: 11 00 03 c0 push rbase
41c: 11 00 03 c0 push rbase
420: 11 00 03 c0 push rbase
424: 11 00 03 c0 push rbase
428: 00 30 03 d0 sub rbase,16
42c: 18 00 03 a0 srspr rglobl
430: 20 70 03 e3 movepc rret,12
434: 00 c0 03 be cmp rglobl,rbase
438: 14 32 fe fa br 20 <error>,#ne
43c: 00 10 03 61 add r27,1
440: 0d c0 00 00 clr r0
444: 0d c0 00 20 clr r1
448: 0d c0 00 40 clr r2
44c: 0d c0 00 60 clr r3
450: 0d c0 00 80 clr r4
454: 0d c0 00 a0 clr r5
458: 0d c0 00 c0 clr r6
45c: 0d c0 00 e0 clr rtmp
460: 0d c0 01 00 clr r8
464: 0d c0 01 20 clr r9
468: 0d c0 01 40 clr r10
46c: 0d c0 01 60 clr r11
470: 0d c0 01 80 clr r12
474: 0d c0 01 a0 clr r13
478: 0d c0 01 c0 clr r14
47c: 0d c0 01 e0 clr r15
480: 18 00 03 c0 srspr rbase
484: 12 00 01 e0 pop r15
488: 12 00 01 e0 pop r15
48c: 12 00 01 e0 pop r15
490: 12 00 01 e0 pop r15
494: 00 10 03 d0 add rbase,16
498: 18 00 03 a0 srspr rglobl
49c: 20 70 03 e3 movepc rret,12
4a0: 00 c0 03 be cmp rglobl,rbase
4a4: 14 32 fe df br 20 <error>,#ne
4a8: 00 10 03 61 add r27,1
4ac: 0d c0 00 00 clr r0
4b0: 0d c0 00 20 clr r1
4b4: 0d c0 00 40 clr r2
4b8: 0d c0 00 60 clr r3
4bc: 0d c0 00 80 clr r4
4c0: 0d c0 00 a0 clr r5
4c4: 0d c0 00 c0 clr r6
4c8: 0d c0 00 e0 clr rtmp
4cc: 0d c0 01 00 clr r8
4d0: 0d c0 01 20 clr r9
4d4: 0d c0 01 40 clr r10
4d8: 0d c0 01 60 clr r11
4dc: 0d c0 01 80 clr r12
4e0: 0d c0 01 a0 clr r13
4e4: 0d c0 01 c0 clr r14
4e8: 0d c0 01 e0 clr r15
4ec: 18 00 03 c0 srspr rbase
4f0: 11 00 03 c0 push rbase
4f4: 12 00 03 c0 pop rbase
4f8: 11 00 03 c0 push rbase
4fc: 12 00 03 c0 pop rbase
500: 11 00 03 c0 push rbase
504: 12 00 03 c0 pop rbase
508: 11 00 03 c0 push rbase
50c: 12 00 03 c0 pop rbase
510: 18 00 03 a0 srspr rglobl
514: 20 70 03 e3 movepc rret,12
518: 00 c0 03 be cmp rglobl,rbase
51c: 14 32 fe c1 br 20 <error>,#ne
520: 00 10 03 61 add r27,1
524: 0d c0 00 00 clr r0
528: 0d c0 00 20 clr r1
52c: 0d c0 00 40 clr r2
530: 0d c0 00 60 clr r3
534: 0d c0 00 80 clr r4
538: 0d c0 00 a0 clr r5
53c: 0d c0 00 c0 clr r6
540: 0d c0 00 e0 clr rtmp
544: 0d c0 01 00 clr r8
548: 0d c0 01 20 clr r9
54c: 0d c0 01 40 clr r10
550: 0d c0 01 60 clr r11
554: 0d c0 01 80 clr r12
558: 0d c0 01 a0 clr r13
55c: 0d c0 01 c0 clr r14
560: 0d c0 01 e0 clr r15
564: 0e c0 00 00 lil r0,0
568: 0e c0 00 21 lil r1,1
56c: 0e c0 00 42 lil r2,2
570: 0e c0 00 63 lil r3,3
574: 11 00 00 00 push r0
578: 11 00 00 20 push r1
57c: 11 00 00 40 push r2
580: 11 00 00 60 push r3
584: 20 00 00 00 nop
588: 20 00 00 00 nop
58c: 20 00 00 00 nop
590: 20 00 00 00 nop
594: 20 00 00 00 nop
598: 20 00 00 00 nop
59c: 20 00 00 00 nop
5a0: 20 00 00 00 nop
5a4: 12 00 00 80 pop r4
5a8: 20 40 03 c3 move rbase,r3
5ac: 20 40 03 a4 move rglobl,r4
5b0: 20 70 03 e3 movepc rret,12
5b4: 00 c0 03 be cmp rglobl,rbase
5b8: 14 32 fe 9a br 20 <error>,#ne
5bc: 20 00 00 00 nop
5c0: 20 00 00 00 nop
5c4: 20 00 00 00 nop
5c8: 20 00 00 00 nop
5cc: 20 00 00 00 nop
5d0: 20 00 00 00 nop
5d4: 20 00 00 00 nop
5d8: 20 00 00 00 nop
5dc: 12 00 00 80 pop r4
5e0: 20 40 03 c2 move rbase,r2
5e4: 20 40 03 a4 move rglobl,r4
5e8: 20 70 03 e3 movepc rret,12
5ec: 00 c0 03 be cmp rglobl,rbase
5f0: 14 32 fe 8c br 20 <error>,#ne
5f4: 20 00 00 00 nop
5f8: 20 00 00 00 nop
5fc: 20 00 00 00 nop
600: 20 00 00 00 nop
604: 20 00 00 00 nop
608: 20 00 00 00 nop
60c: 20 00 00 00 nop
610: 20 00 00 00 nop
614: 12 00 00 80 pop r4
618: 20 40 03 c1 move rbase,r1
61c: 20 40 03 a4 move rglobl,r4
620: 20 70 03 e3 movepc rret,12
624: 00 c0 03 be cmp rglobl,rbase
628: 14 32 fe 7e br 20 <error>,#ne
62c: 20 00 00 00 nop
630: 20 00 00 00 nop
634: 20 00 00 00 nop
638: 20 00 00 00 nop
63c: 20 00 00 00 nop
640: 20 00 00 00 nop
644: 20 00 00 00 nop
648: 20 00 00 00 nop
64c: 12 00 00 80 pop r4
650: 20 40 03 c0 move rbase,r0
654: 20 40 03 a4 move rglobl,r4
658: 20 70 03 e3 movepc rret,12
65c: 00 c0 03 be cmp rglobl,rbase
660: 14 32 fe 70 br 20 <error>,#ne
664: 00 10 03 61 add r27,1
668: 0d c0 00 00 clr r0
66c: 0d c0 00 20 clr r1
670: 0d c0 00 40 clr r2
674: 0d c0 00 60 clr r3
678: 0d c0 00 80 clr r4
67c: 0d c0 00 a0 clr r5
680: 0d c0 00 c0 clr r6
684: 0d c0 00 e0 clr rtmp
688: 0d c0 01 00 clr r8
68c: 0d c0 01 20 clr r9
690: 0d c0 01 40 clr r10
694: 0d c0 01 60 clr r11
698: 0d c0 01 80 clr r12
69c: 0d c0 01 a0 clr r13
6a0: 0d c0 01 c0 clr r14
6a4: 0d c0 01 e0 clr r15
6a8: 0e c0 00 00 lil r0,0
6ac: 0e c0 00 21 lil r1,1
6b0: 0e c0 00 42 lil r2,2
6b4: 0e c0 00 63 lil r3,3
6b8: 18 00 03 c0 srspr rbase
6bc: 20 40 03 be move rglobl,rbase
6c0: 00 30 07 c0 sub rbase,32
6c4: 1c 00 03 c0 srspw rbase
6c8: 20 00 00 00 nop
6cc: 20 00 00 00 nop
6d0: 20 00 00 00 nop
6d4: 20 00 00 00 nop
6d8: 20 00 00 00 nop
6dc: 20 00 00 00 nop
6e0: 20 00 00 00 nop
6e4: 20 00 00 00 nop
6e8: 1c 00 03 a0 srspw rglobl
6ec: 11 00 00 00 push r0
6f0: 11 00 00 20 push r1
6f4: 11 00 00 40 push r2
6f8: 11 00 00 60 push r3
6fc: 20 00 00 00 nop
700: 20 00 00 00 nop
704: 20 00 00 00 nop
708: 20 00 00 00 nop
70c: 20 00 00 00 nop
710: 20 00 00 00 nop
714: 20 00 00 00 nop
718: 20 00 00 00 nop
71c: 12 00 00 80 pop r4
720: 20 40 03 c3 move rbase,r3
724: 20 40 03 a4 move rglobl,r4
728: 20 70 03 e3 movepc rret,12
72c: 00 c0 03 be cmp rglobl,rbase
730: 14 32 fe 3c br 20 <error>,#ne
734: 20 00 00 00 nop
738: 20 00 00 00 nop
73c: 20 00 00 00 nop
740: 20 00 00 00 nop
744: 20 00 00 00 nop
748: 20 00 00 00 nop
74c: 20 00 00 00 nop
750: 20 00 00 00 nop
754: 12 00 00 80 pop r4
758: 20 40 03 c2 move rbase,r2
75c: 20 40 03 a4 move rglobl,r4
760: 20 70 03 e3 movepc rret,12
764: 00 c0 03 be cmp rglobl,rbase
768: 14 32 fe 2e br 20 <error>,#ne
76c: 20 00 00 00 nop
770: 20 00 00 00 nop
774: 20 00 00 00 nop
778: 20 00 00 00 nop
77c: 20 00 00 00 nop
780: 20 00 00 00 nop
784: 20 00 00 00 nop
788: 20 00 00 00 nop
78c: 12 00 00 80 pop r4
790: 20 40 03 c1 move rbase,r1
794: 20 40 03 a4 move rglobl,r4
798: 20 70 03 e3 movepc rret,12
79c: 00 c0 03 be cmp rglobl,rbase
7a0: 14 32 fe 20 br 20 <error>,#ne
7a4: 20 00 00 00 nop
7a8: 20 00 00 00 nop
7ac: 20 00 00 00 nop
7b0: 20 00 00 00 nop
7b4: 20 00 00 00 nop
7b8: 20 00 00 00 nop
7bc: 20 00 00 00 nop
7c0: 20 00 00 00 nop
7c4: 12 00 00 80 pop r4
7c8: 20 40 03 c0 move rbase,r0
7cc: 20 40 03 a4 move rglobl,r4
7d0: 20 70 03 e3 movepc rret,12
7d4: 00 c0 03 be cmp rglobl,rbase
7d8: 14 32 fe 12 br 20 <error>,#ne
7dc: 00 10 03 61 add r27,1
7e0: 14 30 fe 20 br 60 <finish>,#al
セクション .assert の逆アセンブル:
00020000 <CHECK_FLAG>:
20000: 00 00 00 01 add r0,r1
00020004 <CHECK_FINISH>:
20004: 00 00 00 00 add r0,r0
00020008 <CHECK_LOG>:
20008: 00 00 00 00 add r0,r0
0002000c <ERROR_TYPE>:
2000c: 00 00 00 00 add r0,r0
00020010 <ERROR_NUMBER>:
20010: 00 00 00 00 add r0,r0
00020014 <ERROR_RESULT>:
20014: 00 00 00 00 add r0,r0
00020018 <ERROR_EXPECT>:
20018: 00 00 00 00 add r0,r0
セクション .stack の逆アセンブル:
000f0000 <STACK_INDEX>:
f0000: 00 00 00 00 add r0,r0
|
; A345633: Sum of terms of odd index in the binomial decomposition of n^(n-1).
; 0,1,4,36,272,4400,51012,1188544,18640960,567108864,11225320100,421504185344,10079828372880,450353989316608,12627774819845668,654244800082329600,21046391759976988928,1240529732459024678912,45032132922921758270916,2975557672677668838178816
sub $1,$0
add $1,1
mov $2,$1
mov $1,$0
add $0,1
pow $0,$1
pow $2,$1
sub $0,$2
div $0,2
|
user/_forktest: file format elf64-littleriscv
Disassembly of section .text:
0000000000000000 <print>:
#define N 1000
void
print(const char *s)
{
0: 1101 addi sp,sp,-32
2: ec06 sd ra,24(sp)
4: e822 sd s0,16(sp)
6: e426 sd s1,8(sp)
8: 1000 addi s0,sp,32
a: 84aa mv s1,a0
write(1, s, strlen(s));
c: 00000097 auipc ra,0x0
10: 15a080e7 jalr 346(ra) # 166 <strlen>
14: 0005061b sext.w a2,a0
18: 85a6 mv a1,s1
1a: 4505 li a0,1
1c: 00000097 auipc ra,0x0
20: 38e080e7 jalr 910(ra) # 3aa <write>
}
24: 60e2 ld ra,24(sp)
26: 6442 ld s0,16(sp)
28: 64a2 ld s1,8(sp)
2a: 6105 addi sp,sp,32
2c: 8082 ret
000000000000002e <forktest>:
void
forktest(void)
{
2e: 1101 addi sp,sp,-32
30: ec06 sd ra,24(sp)
32: e822 sd s0,16(sp)
34: e426 sd s1,8(sp)
36: e04a sd s2,0(sp)
38: 1000 addi s0,sp,32
int n, pid;
print("fork test\n");
3a: 00000517 auipc a0,0x0
3e: 40e50513 addi a0,a0,1038 # 448 <set_priority+0xe>
42: 00000097 auipc ra,0x0
46: fbe080e7 jalr -66(ra) # 0 <print>
for(n=0; n<N; n++){
4a: 4481 li s1,0
4c: 3e800913 li s2,1000
pid = fork();
50: 00000097 auipc ra,0x0
54: 332080e7 jalr 818(ra) # 382 <fork>
if(pid < 0)
58: 02054763 bltz a0,86 <forktest+0x58>
break;
if(pid == 0)
5c: c10d beqz a0,7e <forktest+0x50>
for(n=0; n<N; n++){
5e: 2485 addiw s1,s1,1
60: ff2498e3 bne s1,s2,50 <forktest+0x22>
exit(0);
}
if(n == N){
print("fork claimed to work N times!\n");
64: 00000517 auipc a0,0x0
68: 3f450513 addi a0,a0,1012 # 458 <set_priority+0x1e>
6c: 00000097 auipc ra,0x0
70: f94080e7 jalr -108(ra) # 0 <print>
exit(1);
74: 4505 li a0,1
76: 00000097 auipc ra,0x0
7a: 314080e7 jalr 788(ra) # 38a <exit>
exit(0);
7e: 00000097 auipc ra,0x0
82: 30c080e7 jalr 780(ra) # 38a <exit>
if(n == N){
86: 3e800793 li a5,1000
8a: fcf48de3 beq s1,a5,64 <forktest+0x36>
}
for(; n > 0; n--){
8e: 00905b63 blez s1,a4 <forktest+0x76>
if(wait(0) < 0){
92: 4501 li a0,0
94: 00000097 auipc ra,0x0
98: 2fe080e7 jalr 766(ra) # 392 <wait>
9c: 02054a63 bltz a0,d0 <forktest+0xa2>
for(; n > 0; n--){
a0: 34fd addiw s1,s1,-1
a2: f8e5 bnez s1,92 <forktest+0x64>
print("wait stopped early\n");
exit(1);
}
}
if(wait(0) != -1){
a4: 4501 li a0,0
a6: 00000097 auipc ra,0x0
aa: 2ec080e7 jalr 748(ra) # 392 <wait>
ae: 57fd li a5,-1
b0: 02f51d63 bne a0,a5,ea <forktest+0xbc>
print("wait got too many\n");
exit(1);
}
print("fork test OK\n");
b4: 00000517 auipc a0,0x0
b8: 3f450513 addi a0,a0,1012 # 4a8 <set_priority+0x6e>
bc: 00000097 auipc ra,0x0
c0: f44080e7 jalr -188(ra) # 0 <print>
}
c4: 60e2 ld ra,24(sp)
c6: 6442 ld s0,16(sp)
c8: 64a2 ld s1,8(sp)
ca: 6902 ld s2,0(sp)
cc: 6105 addi sp,sp,32
ce: 8082 ret
print("wait stopped early\n");
d0: 00000517 auipc a0,0x0
d4: 3a850513 addi a0,a0,936 # 478 <set_priority+0x3e>
d8: 00000097 auipc ra,0x0
dc: f28080e7 jalr -216(ra) # 0 <print>
exit(1);
e0: 4505 li a0,1
e2: 00000097 auipc ra,0x0
e6: 2a8080e7 jalr 680(ra) # 38a <exit>
print("wait got too many\n");
ea: 00000517 auipc a0,0x0
ee: 3a650513 addi a0,a0,934 # 490 <set_priority+0x56>
f2: 00000097 auipc ra,0x0
f6: f0e080e7 jalr -242(ra) # 0 <print>
exit(1);
fa: 4505 li a0,1
fc: 00000097 auipc ra,0x0
100: 28e080e7 jalr 654(ra) # 38a <exit>
0000000000000104 <main>:
int
main(void)
{
104: 1141 addi sp,sp,-16
106: e406 sd ra,8(sp)
108: e022 sd s0,0(sp)
10a: 0800 addi s0,sp,16
forktest();
10c: 00000097 auipc ra,0x0
110: f22080e7 jalr -222(ra) # 2e <forktest>
exit(0);
114: 4501 li a0,0
116: 00000097 auipc ra,0x0
11a: 274080e7 jalr 628(ra) # 38a <exit>
000000000000011e <strcpy>:
#include "kernel/fcntl.h"
#include "user/user.h"
char*
strcpy(char *s, const char *t)
{
11e: 1141 addi sp,sp,-16
120: e422 sd s0,8(sp)
122: 0800 addi s0,sp,16
char *os;
os = s;
while((*s++ = *t++) != 0)
124: 87aa mv a5,a0
126: 0585 addi a1,a1,1
128: 0785 addi a5,a5,1
12a: fff5c703 lbu a4,-1(a1)
12e: fee78fa3 sb a4,-1(a5)
132: fb75 bnez a4,126 <strcpy+0x8>
;
return os;
}
134: 6422 ld s0,8(sp)
136: 0141 addi sp,sp,16
138: 8082 ret
000000000000013a <strcmp>:
int
strcmp(const char *p, const char *q)
{
13a: 1141 addi sp,sp,-16
13c: e422 sd s0,8(sp)
13e: 0800 addi s0,sp,16
while(*p && *p == *q)
140: 00054783 lbu a5,0(a0)
144: cb91 beqz a5,158 <strcmp+0x1e>
146: 0005c703 lbu a4,0(a1)
14a: 00f71763 bne a4,a5,158 <strcmp+0x1e>
p++, q++;
14e: 0505 addi a0,a0,1
150: 0585 addi a1,a1,1
while(*p && *p == *q)
152: 00054783 lbu a5,0(a0)
156: fbe5 bnez a5,146 <strcmp+0xc>
return (uchar)*p - (uchar)*q;
158: 0005c503 lbu a0,0(a1)
}
15c: 40a7853b subw a0,a5,a0
160: 6422 ld s0,8(sp)
162: 0141 addi sp,sp,16
164: 8082 ret
0000000000000166 <strlen>:
uint
strlen(const char *s)
{
166: 1141 addi sp,sp,-16
168: e422 sd s0,8(sp)
16a: 0800 addi s0,sp,16
int n;
for(n = 0; s[n]; n++)
16c: 00054783 lbu a5,0(a0)
170: cf91 beqz a5,18c <strlen+0x26>
172: 0505 addi a0,a0,1
174: 87aa mv a5,a0
176: 4685 li a3,1
178: 9e89 subw a3,a3,a0
17a: 00f6853b addw a0,a3,a5
17e: 0785 addi a5,a5,1
180: fff7c703 lbu a4,-1(a5)
184: fb7d bnez a4,17a <strlen+0x14>
;
return n;
}
186: 6422 ld s0,8(sp)
188: 0141 addi sp,sp,16
18a: 8082 ret
for(n = 0; s[n]; n++)
18c: 4501 li a0,0
18e: bfe5 j 186 <strlen+0x20>
0000000000000190 <memset>:
void*
memset(void *dst, int c, uint n)
{
190: 1141 addi sp,sp,-16
192: e422 sd s0,8(sp)
194: 0800 addi s0,sp,16
char *cdst = (char *) dst;
int i;
for(i = 0; i < n; i++){
196: ca19 beqz a2,1ac <memset+0x1c>
198: 87aa mv a5,a0
19a: 1602 slli a2,a2,0x20
19c: 9201 srli a2,a2,0x20
19e: 00a60733 add a4,a2,a0
cdst[i] = c;
1a2: 00b78023 sb a1,0(a5)
for(i = 0; i < n; i++){
1a6: 0785 addi a5,a5,1
1a8: fee79de3 bne a5,a4,1a2 <memset+0x12>
}
return dst;
}
1ac: 6422 ld s0,8(sp)
1ae: 0141 addi sp,sp,16
1b0: 8082 ret
00000000000001b2 <strchr>:
char*
strchr(const char *s, char c)
{
1b2: 1141 addi sp,sp,-16
1b4: e422 sd s0,8(sp)
1b6: 0800 addi s0,sp,16
for(; *s; s++)
1b8: 00054783 lbu a5,0(a0)
1bc: cb99 beqz a5,1d2 <strchr+0x20>
if(*s == c)
1be: 00f58763 beq a1,a5,1cc <strchr+0x1a>
for(; *s; s++)
1c2: 0505 addi a0,a0,1
1c4: 00054783 lbu a5,0(a0)
1c8: fbfd bnez a5,1be <strchr+0xc>
return (char*)s;
return 0;
1ca: 4501 li a0,0
}
1cc: 6422 ld s0,8(sp)
1ce: 0141 addi sp,sp,16
1d0: 8082 ret
return 0;
1d2: 4501 li a0,0
1d4: bfe5 j 1cc <strchr+0x1a>
00000000000001d6 <gets>:
char*
gets(char *buf, int max)
{
1d6: 711d addi sp,sp,-96
1d8: ec86 sd ra,88(sp)
1da: e8a2 sd s0,80(sp)
1dc: e4a6 sd s1,72(sp)
1de: e0ca sd s2,64(sp)
1e0: fc4e sd s3,56(sp)
1e2: f852 sd s4,48(sp)
1e4: f456 sd s5,40(sp)
1e6: f05a sd s6,32(sp)
1e8: ec5e sd s7,24(sp)
1ea: 1080 addi s0,sp,96
1ec: 8baa mv s7,a0
1ee: 8a2e mv s4,a1
int i, cc;
char c;
for(i=0; i+1 < max; ){
1f0: 892a mv s2,a0
1f2: 4481 li s1,0
cc = read(0, &c, 1);
if(cc < 1)
break;
buf[i++] = c;
if(c == '\n' || c == '\r')
1f4: 4aa9 li s5,10
1f6: 4b35 li s6,13
for(i=0; i+1 < max; ){
1f8: 89a6 mv s3,s1
1fa: 2485 addiw s1,s1,1
1fc: 0344d863 bge s1,s4,22c <gets+0x56>
cc = read(0, &c, 1);
200: 4605 li a2,1
202: faf40593 addi a1,s0,-81
206: 4501 li a0,0
208: 00000097 auipc ra,0x0
20c: 19a080e7 jalr 410(ra) # 3a2 <read>
if(cc < 1)
210: 00a05e63 blez a0,22c <gets+0x56>
buf[i++] = c;
214: faf44783 lbu a5,-81(s0)
218: 00f90023 sb a5,0(s2)
if(c == '\n' || c == '\r')
21c: 01578763 beq a5,s5,22a <gets+0x54>
220: 0905 addi s2,s2,1
222: fd679be3 bne a5,s6,1f8 <gets+0x22>
for(i=0; i+1 < max; ){
226: 89a6 mv s3,s1
228: a011 j 22c <gets+0x56>
22a: 89a6 mv s3,s1
break;
}
buf[i] = '\0';
22c: 99de add s3,s3,s7
22e: 00098023 sb zero,0(s3)
return buf;
}
232: 855e mv a0,s7
234: 60e6 ld ra,88(sp)
236: 6446 ld s0,80(sp)
238: 64a6 ld s1,72(sp)
23a: 6906 ld s2,64(sp)
23c: 79e2 ld s3,56(sp)
23e: 7a42 ld s4,48(sp)
240: 7aa2 ld s5,40(sp)
242: 7b02 ld s6,32(sp)
244: 6be2 ld s7,24(sp)
246: 6125 addi sp,sp,96
248: 8082 ret
000000000000024a <stat>:
int
stat(const char *n, struct stat *st)
{
24a: 1101 addi sp,sp,-32
24c: ec06 sd ra,24(sp)
24e: e822 sd s0,16(sp)
250: e426 sd s1,8(sp)
252: e04a sd s2,0(sp)
254: 1000 addi s0,sp,32
256: 892e mv s2,a1
int fd;
int r;
fd = open(n, O_RDONLY);
258: 4581 li a1,0
25a: 00000097 auipc ra,0x0
25e: 170080e7 jalr 368(ra) # 3ca <open>
if(fd < 0)
262: 02054563 bltz a0,28c <stat+0x42>
266: 84aa mv s1,a0
return -1;
r = fstat(fd, st);
268: 85ca mv a1,s2
26a: 00000097 auipc ra,0x0
26e: 178080e7 jalr 376(ra) # 3e2 <fstat>
272: 892a mv s2,a0
close(fd);
274: 8526 mv a0,s1
276: 00000097 auipc ra,0x0
27a: 13c080e7 jalr 316(ra) # 3b2 <close>
return r;
}
27e: 854a mv a0,s2
280: 60e2 ld ra,24(sp)
282: 6442 ld s0,16(sp)
284: 64a2 ld s1,8(sp)
286: 6902 ld s2,0(sp)
288: 6105 addi sp,sp,32
28a: 8082 ret
return -1;
28c: 597d li s2,-1
28e: bfc5 j 27e <stat+0x34>
0000000000000290 <atoi>:
int
atoi(const char *s)
{
290: 1141 addi sp,sp,-16
292: e422 sd s0,8(sp)
294: 0800 addi s0,sp,16
int n;
n = 0;
while('0' <= *s && *s <= '9')
296: 00054683 lbu a3,0(a0)
29a: fd06879b addiw a5,a3,-48
29e: 0ff7f793 zext.b a5,a5
2a2: 4625 li a2,9
2a4: 02f66863 bltu a2,a5,2d4 <atoi+0x44>
2a8: 872a mv a4,a0
n = 0;
2aa: 4501 li a0,0
n = n*10 + *s++ - '0';
2ac: 0705 addi a4,a4,1
2ae: 0025179b slliw a5,a0,0x2
2b2: 9fa9 addw a5,a5,a0
2b4: 0017979b slliw a5,a5,0x1
2b8: 9fb5 addw a5,a5,a3
2ba: fd07851b addiw a0,a5,-48
while('0' <= *s && *s <= '9')
2be: 00074683 lbu a3,0(a4)
2c2: fd06879b addiw a5,a3,-48
2c6: 0ff7f793 zext.b a5,a5
2ca: fef671e3 bgeu a2,a5,2ac <atoi+0x1c>
return n;
}
2ce: 6422 ld s0,8(sp)
2d0: 0141 addi sp,sp,16
2d2: 8082 ret
n = 0;
2d4: 4501 li a0,0
2d6: bfe5 j 2ce <atoi+0x3e>
00000000000002d8 <memmove>:
void*
memmove(void *vdst, const void *vsrc, int n)
{
2d8: 1141 addi sp,sp,-16
2da: e422 sd s0,8(sp)
2dc: 0800 addi s0,sp,16
char *dst;
const char *src;
dst = vdst;
src = vsrc;
if (src > dst) {
2de: 02b57463 bgeu a0,a1,306 <memmove+0x2e>
while(n-- > 0)
2e2: 00c05f63 blez a2,300 <memmove+0x28>
2e6: 1602 slli a2,a2,0x20
2e8: 9201 srli a2,a2,0x20
2ea: 00c507b3 add a5,a0,a2
dst = vdst;
2ee: 872a mv a4,a0
*dst++ = *src++;
2f0: 0585 addi a1,a1,1
2f2: 0705 addi a4,a4,1
2f4: fff5c683 lbu a3,-1(a1)
2f8: fed70fa3 sb a3,-1(a4)
while(n-- > 0)
2fc: fee79ae3 bne a5,a4,2f0 <memmove+0x18>
src += n;
while(n-- > 0)
*--dst = *--src;
}
return vdst;
}
300: 6422 ld s0,8(sp)
302: 0141 addi sp,sp,16
304: 8082 ret
dst += n;
306: 00c50733 add a4,a0,a2
src += n;
30a: 95b2 add a1,a1,a2
while(n-- > 0)
30c: fec05ae3 blez a2,300 <memmove+0x28>
310: fff6079b addiw a5,a2,-1
314: 1782 slli a5,a5,0x20
316: 9381 srli a5,a5,0x20
318: fff7c793 not a5,a5
31c: 97ba add a5,a5,a4
*--dst = *--src;
31e: 15fd addi a1,a1,-1
320: 177d addi a4,a4,-1
322: 0005c683 lbu a3,0(a1)
326: 00d70023 sb a3,0(a4)
while(n-- > 0)
32a: fee79ae3 bne a5,a4,31e <memmove+0x46>
32e: bfc9 j 300 <memmove+0x28>
0000000000000330 <memcmp>:
int
memcmp(const void *s1, const void *s2, uint n)
{
330: 1141 addi sp,sp,-16
332: e422 sd s0,8(sp)
334: 0800 addi s0,sp,16
const char *p1 = s1, *p2 = s2;
while (n-- > 0) {
336: ca05 beqz a2,366 <memcmp+0x36>
338: fff6069b addiw a3,a2,-1
33c: 1682 slli a3,a3,0x20
33e: 9281 srli a3,a3,0x20
340: 0685 addi a3,a3,1
342: 96aa add a3,a3,a0
if (*p1 != *p2) {
344: 00054783 lbu a5,0(a0)
348: 0005c703 lbu a4,0(a1)
34c: 00e79863 bne a5,a4,35c <memcmp+0x2c>
return *p1 - *p2;
}
p1++;
350: 0505 addi a0,a0,1
p2++;
352: 0585 addi a1,a1,1
while (n-- > 0) {
354: fed518e3 bne a0,a3,344 <memcmp+0x14>
}
return 0;
358: 4501 li a0,0
35a: a019 j 360 <memcmp+0x30>
return *p1 - *p2;
35c: 40e7853b subw a0,a5,a4
}
360: 6422 ld s0,8(sp)
362: 0141 addi sp,sp,16
364: 8082 ret
return 0;
366: 4501 li a0,0
368: bfe5 j 360 <memcmp+0x30>
000000000000036a <memcpy>:
void *
memcpy(void *dst, const void *src, uint n)
{
36a: 1141 addi sp,sp,-16
36c: e406 sd ra,8(sp)
36e: e022 sd s0,0(sp)
370: 0800 addi s0,sp,16
return memmove(dst, src, n);
372: 00000097 auipc ra,0x0
376: f66080e7 jalr -154(ra) # 2d8 <memmove>
}
37a: 60a2 ld ra,8(sp)
37c: 6402 ld s0,0(sp)
37e: 0141 addi sp,sp,16
380: 8082 ret
0000000000000382 <fork>:
# generated by usys.pl - do not edit
#include "kernel/syscall.h"
.global fork
fork:
li a7, SYS_fork
382: 4885 li a7,1
ecall
384: 00000073 ecall
ret
388: 8082 ret
000000000000038a <exit>:
.global exit
exit:
li a7, SYS_exit
38a: 4889 li a7,2
ecall
38c: 00000073 ecall
ret
390: 8082 ret
0000000000000392 <wait>:
.global wait
wait:
li a7, SYS_wait
392: 488d li a7,3
ecall
394: 00000073 ecall
ret
398: 8082 ret
000000000000039a <pipe>:
.global pipe
pipe:
li a7, SYS_pipe
39a: 4891 li a7,4
ecall
39c: 00000073 ecall
ret
3a0: 8082 ret
00000000000003a2 <read>:
.global read
read:
li a7, SYS_read
3a2: 4895 li a7,5
ecall
3a4: 00000073 ecall
ret
3a8: 8082 ret
00000000000003aa <write>:
.global write
write:
li a7, SYS_write
3aa: 48c1 li a7,16
ecall
3ac: 00000073 ecall
ret
3b0: 8082 ret
00000000000003b2 <close>:
.global close
close:
li a7, SYS_close
3b2: 48d5 li a7,21
ecall
3b4: 00000073 ecall
ret
3b8: 8082 ret
00000000000003ba <kill>:
.global kill
kill:
li a7, SYS_kill
3ba: 4899 li a7,6
ecall
3bc: 00000073 ecall
ret
3c0: 8082 ret
00000000000003c2 <exec>:
.global exec
exec:
li a7, SYS_exec
3c2: 489d li a7,7
ecall
3c4: 00000073 ecall
ret
3c8: 8082 ret
00000000000003ca <open>:
.global open
open:
li a7, SYS_open
3ca: 48bd li a7,15
ecall
3cc: 00000073 ecall
ret
3d0: 8082 ret
00000000000003d2 <mknod>:
.global mknod
mknod:
li a7, SYS_mknod
3d2: 48c5 li a7,17
ecall
3d4: 00000073 ecall
ret
3d8: 8082 ret
00000000000003da <unlink>:
.global unlink
unlink:
li a7, SYS_unlink
3da: 48c9 li a7,18
ecall
3dc: 00000073 ecall
ret
3e0: 8082 ret
00000000000003e2 <fstat>:
.global fstat
fstat:
li a7, SYS_fstat
3e2: 48a1 li a7,8
ecall
3e4: 00000073 ecall
ret
3e8: 8082 ret
00000000000003ea <link>:
.global link
link:
li a7, SYS_link
3ea: 48cd li a7,19
ecall
3ec: 00000073 ecall
ret
3f0: 8082 ret
00000000000003f2 <mkdir>:
.global mkdir
mkdir:
li a7, SYS_mkdir
3f2: 48d1 li a7,20
ecall
3f4: 00000073 ecall
ret
3f8: 8082 ret
00000000000003fa <chdir>:
.global chdir
chdir:
li a7, SYS_chdir
3fa: 48a5 li a7,9
ecall
3fc: 00000073 ecall
ret
400: 8082 ret
0000000000000402 <dup>:
.global dup
dup:
li a7, SYS_dup
402: 48a9 li a7,10
ecall
404: 00000073 ecall
ret
408: 8082 ret
000000000000040a <getpid>:
.global getpid
getpid:
li a7, SYS_getpid
40a: 48ad li a7,11
ecall
40c: 00000073 ecall
ret
410: 8082 ret
0000000000000412 <sbrk>:
.global sbrk
sbrk:
li a7, SYS_sbrk
412: 48b1 li a7,12
ecall
414: 00000073 ecall
ret
418: 8082 ret
000000000000041a <sleep>:
.global sleep
sleep:
li a7, SYS_sleep
41a: 48b5 li a7,13
ecall
41c: 00000073 ecall
ret
420: 8082 ret
0000000000000422 <uptime>:
.global uptime
uptime:
li a7, SYS_uptime
422: 48b9 li a7,14
ecall
424: 00000073 ecall
ret
428: 8082 ret
000000000000042a <waitx>:
.global waitx
waitx:
li a7, SYS_waitx
42a: 48d9 li a7,22
ecall
42c: 00000073 ecall
ret
430: 8082 ret
0000000000000432 <trace>:
.global trace
trace:
li a7, SYS_trace
432: 48e1 li a7,24
ecall
434: 00000073 ecall
ret
438: 8082 ret
000000000000043a <set_priority>:
.global set_priority
set_priority:
li a7, SYS_set_priority
43a: 48dd li a7,23
ecall
43c: 00000073 ecall
ret
440: 8082 ret
|
// Copyright (c) 2012-2017 VideoStitch SAS
// Copyright (c) 2018 stitchEm
#pragma once
#include <QWidget>
#include "ui_projectworkwidget.h"
#include "libvideostitch-gui/mainwindow/outputfilehandler.hpp"
#include "libvideostitch-gui/mainwindow/packet.hpp"
#include "libvideostitch-gui/mainwindow/frameratecompute.hpp"
#include "libvideostitch-gui/mainwindow/gpuinfoupdater.hpp"
#include "libvideostitch-base/vslog.hpp"
class AudioPlayer;
class CalibrationActionController;
class CalibrationUpdateController;
class CropInputController;
class ExposureActionController;
class OutputsController;
class OutputPluginController;
class InputPluginController;
class ProjectWorkWidget : public QWidget, public Ui::ProjectWorkWidgetClass, public GUIStateCaps {
Q_OBJECT
public:
explicit ProjectWorkWidget(QWidget* const parent = nullptr);
~ProjectWorkWidget();
void startApplication();
void openFile(QVector<int> devices, const QFileInfo& fileName, const int customWidth = 0, const int customHeight = 0);
void startNewProject(QVector<int> devices, const QString& name);
bool outputIsActivated() const;
bool algorithmIsActivated() const;
public slots:
/**
* @brief This function will synchronously close the project, delete it, ask to delete the stitcher controller
* and clear all the GUI
*/
void onCloseProject();
void saveProject();
signals:
void reqChangeState(GUIStateCaps::State s);
void reqRefresh(qint64);
void reqCreateNewProject();
void reqOpenVAHFile(QString inFile, int customWidth, int customHeight);
void reqThreadQuit();
void reqForceGPUInfoRefresh();
void reqReset();
void reqSave(const QString& file, const VideoStitch::Ptv::Value* = nullptr);
void notifyProjectClosed();
void reqReopenProject(const QString& file);
void notifyProjectOpened();
void notifyPanoResized(const unsigned customWidth, const unsigned customHeight);
void reqResetDimensions(const unsigned customWidth, const unsigned customHeight);
void notifyRemoveAudio();
void notifyAudioPlaybackActivated(bool);
// Kernel compile
void reqCancelKernelCompile();
void notifyBackendCompileProgress(const QString& message, double progress);
void notifyBackendCompileDone();
void reqDisableWindow();
void reqEnableWindow();
protected slots:
virtual void changeState(GUIStateCaps::State s) { Q_UNUSED(s) }
private:
void initializeMainTab();
void initializeStitcher();
void registerWidgetConnections(); // Register connections that are independent of the stitcher controller
void registerStitcherSignals();
void registerOutputSignals();
void registerLoggers();
void registerSignalInjections();
void registerControllers();
void registerMetaTypes();
void createStitcherController(QVector<int> devices);
void startOpenGL();
void stopOpenGL();
private slots:
void registerRenderer(std::vector<std::shared_ptr<VideoStitch::Core::PanoRenderer>>* renderers);
void setProject(ProjectDefinition* project);
void setNeedToExtract(bool newNeedToExtract);
void onPlay();
void onPause();
void onCleanStitcher();
void onStitcherErrorMessage(const VideoStitch::Status& status, bool needToExit);
void onEndOfStreamReached();
void onAudioLoadError(const QString& title, const QString& message);
void updateTopBar(mtime_t date);
/**
* @brief This slot will update the widgets enability after the activation (or deactivation) of an output or of an
* automatic algorithm.
*/
void updateEnabilityAfterActivation();
void updateClockForTab(int tab);
void updateNextFrameAction();
void onStitcherReset();
private:
LiveProjectDefinition* projectDefinition;
FramerateCompute framerateComputer;
GPUInfoUpdater gpuInfoUpdater;
OutputsController* outputsController;
CalibrationActionController* calibrationActionController;
CalibrationUpdateController* calibrationUpdateController;
ExposureActionController* exposureController;
InputPluginController* inputPluginController;
OutputPluginController* outputPluginController;
QScopedPointer<CropInputController> cropInputController;
QThread stitcherControllerThread;
StitcherController::NextFrameAction nextFrameAction;
int needToExtract = 0;
};
|
//=================================================================================================
/*!
// \file src/mathtest/operations/smatsmatsub/MZaDCb.cpp
// \brief Source file for the MZaDCb sparse matrix/sparse matrix subtraction math test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DiagonalMatrix.h>
#include <blaze/math/ZeroMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/operations/smatsmatsub/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'MZaDCb'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
using MZa = blaze::ZeroMatrix<TypeA>;
using DCb = blaze::DiagonalMatrix< blaze::CompressedMatrix<TypeB> >;
// Creator type definitions
using CMZa = blazetest::Creator<MZa>;
using CDCb = blazetest::Creator<DCb>;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
for( size_t j=0UL; j<=i; ++j ) {
RUN_SMATSMATSUB_OPERATION_TEST( CMZa( i, i ), CDCb( i, j ) );
}
}
// Running tests with large matrices
RUN_SMATSMATSUB_OPERATION_TEST( CMZa( 67UL, 67UL ), CDCb( 67UL, 13UL ) );
RUN_SMATSMATSUB_OPERATION_TEST( CMZa( 128UL, 128UL ), CDCb( 128UL, 8UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during sparse matrix/sparse matrix subtraction:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
// Original test: ./tschaefe/hw4/problem6/jal_2.asm
// Author: tschaefe
// Test source code follows
// jal test 2
// Jump instruction should cause looping to earlier portion of program, each time
// setting r7 to 0x8
lbi r1, 0xfd
addi r1, r1, 0x01
bgez r1, .done //after 3 total executions of add, go to halt
jal 0x7fa
.done:
halt
|
; Copyright (c) 2017-2021, The rav1e contributors
; Copyright (c) 2021, Nathan Egge
; All rights reserved.
;
; This source code is subject to the terms of the BSD 2 Clause License and
; the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
; was not distributed with this source code in the LICENSE file, you can
; obtain it at www.aomedia.org/license/software. If the Alliance for Open
; Media Patent License 1.0 was not distributed with this source code in the
; PATENTS file, you can obtain it at www.aomedia.org/license/patent.
%include "config.asm"
%include "ext/x86/x86inc.asm"
%if ARCH_X86_64
SECTION .text
cextern cdef_dir_8bpc_avx2
INIT_YMM avx2
cglobal cdef_dir_16bpc, 4, 4, 3, 32 + 8*8, src, ss, var, bdmax
popcnt bdmaxd, bdmaxd
movzx bdmaxq, bdmaxw
sub bdmaxq, 8
movq xm2, bdmaxq
DEFINE_ARGS src, ss, var, ss3
lea ss3q, [ssq*3]
mova xm0, [srcq + ssq*0]
mova xm1, [srcq + ssq*1]
vinserti128 m0, [srcq + ssq*2], 1
vinserti128 m1, [srcq + ss3q], 1
psraw m0, xm2
psraw m1, xm2
vpackuswb m0, m1
mova [rsp + 32 + 0*8], m0
lea srcq, [srcq + ssq*4]
mova xm0, [srcq + ssq*0]
mova xm1, [srcq + ssq*1]
vinserti128 m0, [srcq + ssq*2], 1
vinserti128 m1, [srcq + ss3q], 1
psraw m0, xm2
psraw m1, xm2
vpackuswb m0, m1
mova [rsp + 32 + 4*8], m0
lea srcq, [rsp + 32] ; WIN64 shadow space
mov ssq, 8
call mangle(private_prefix %+ _cdef_dir_8bpc %+ SUFFIX)
RET
%endif ; ARCH_X86_64
|
; A330033: a(n) = Kronecker(n, 5) * (-1)^floor(n/5).
; 0,1,-1,-1,1,0,-1,1,1,-1,0,1,-1,-1,1,0,-1,1,1,-1,0,1,-1,-1,1,0,-1,1,1,-1,0,1,-1,-1,1,0,-1,1,1,-1,0,1,-1,-1,1,0,-1,1,1,-1,0,1,-1,-1,1,0,-1,1,1,-1,0,1,-1,-1,1,0,-1,1,1,-1,0,1,-1,-1,1,0,-1
mov $2,$0
mul $0,22
mov $3,5
lpb $0
sub $0,$2
lpb $0
sub $0,5
add $3,$1
sub $1,6
sub $1,$3
lpe
lpe
div $1,11
|
;******************************************************************************
;* AAC Spectral Band Replication decoding functions
;* Copyright (C) 2012 Christophe Gisquet <christophe.gisquet@gmail.com>
;*
;* This file is part of Libav.
;*
;* Libav is free software; you can redistribute it and/or
;* modify it under the terms of the GNU Lesser General Public
;* License as published by the Free Software Foundation; either
;* version 2.1 of the License, or (at your option) any later version.
;*
;* Libav is distributed in the hope that it will be useful,
;* but WITHOUT ANY WARRANTY; without even the implied warranty of
;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
;* Lesser General Public License for more details.
;*
;* You should have received a copy of the GNU Lesser General Public
;* License along with Libav; if not, write to the Free Software
;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
;******************************************************************************
%include "x86inc.asm"
%include "x86util.asm"
;SECTION_RODATA
SECTION .text
INIT_XMM sse
cglobal sbr_sum_square, 2, 3, 6
mov r2, r1
xorps m0, m0
xorps m1, m1
sar r2, 3
jz .prepare
.loop:
movu m2, [r0 + 0]
movu m3, [r0 + 16]
movu m4, [r0 + 32]
movu m5, [r0 + 48]
mulps m2, m2
mulps m3, m3
mulps m4, m4
mulps m5, m5
addps m0, m2
addps m1, m3
addps m0, m4
addps m1, m5
add r0, 64
dec r2
jnz .loop
.prepare:
and r1, 7
sar r1, 1
jz .end
; len is a multiple of 2, thus there are at least 4 elements to process
.endloop:
movu m2, [r0]
add r0, 16
mulps m2, m2
dec r1
addps m0, m2
jnz .endloop
.end:
addps m0, m1
movhlps m2, m0
addps m0, m2
movss m1, m0
shufps m0, m0, 1
addss m0, m1
%if ARCH_X86_64 == 0
movss r0m, m0
fld dword r0m
%endif
RET
%define STEP 40*4*2
cglobal sbr_hf_g_filt, 5, 6, 5
lea r1, [r1 + 8*r4] ; offset by ixh elements into X_high
mov r5, r3
and r3, 0xFC
lea r2, [r2 + r3*4]
lea r0, [r0 + r3*8]
neg r3
jz .loop1
.loop4:
movlps m0, [r2 + 4*r3 + 0]
movlps m1, [r2 + 4*r3 + 8]
movlps m2, [r1 + 0*STEP]
movlps m3, [r1 + 2*STEP]
movhps m2, [r1 + 1*STEP]
movhps m3, [r1 + 3*STEP]
unpcklps m0, m0
unpcklps m1, m1
mulps m0, m2
mulps m1, m3
movu [r0 + 8*r3 + 0], m0
movu [r0 + 8*r3 + 16], m1
add r1, 4*STEP
add r3, 4
jnz .loop4
and r5, 3 ; number of single element loops
jz .end
.loop1: ; element 0 and 1 can be computed at the same time
movss m0, [r2]
movlps m2, [r1]
unpcklps m0, m0
mulps m2, m0
movlps [r0], m2
add r0, 8
add r2, 4
add r1, STEP
dec r5
jnz .loop1
.end:
RET
|
#include "IconCompare/IconCompare.h"
#include "uvss_label_distance/uvss_label_distance_interface.hpp"
#include "opencv_basic/opencv_match.h"
#include <math.h>
const double EPS = 1e-6;
IconCompare::IconCompare()
{
}
int IconCompare::setBenchMark(const std::map<std::string,std::string> &m_icon,const cv::Size &v_size)
{
__map_icon=m_icon;
__size_std=v_size;
return 0;
}
/// 给定图标,然后与标准图标列表中的图标一一比对,找出最相似的一个
/// 若正常则返回0
/// 输入的是图标的路径
int IconCompare::getIconMeaning(const std::string &v_path,std::string &v_mean)
{
cv::Mat v_mat=cv::imread(v_path);
return getIconMeaning(v_mat,v_mean);
}
/// 作用同上
/// 输入的是图标的数据
int IconCompare::getIconMeaning(const cv::Mat &v_mat,std::string &v_mean)
{
double min_ssd=-1;
int ret=-1;
for (auto it:__map_icon) {
cv::Mat mat_tmp=cv::imread(it.second);
cv::Mat mat_target=v_mat;
std::cout<<"mat_tmp.size:"<<mat_tmp.size<<std::endl;
std::cout<<"mat_target.size:"<<mat_target.size<<std::endl;
if (!mat_target.empty() && !mat_tmp.empty()) {
if (mat_target.size() != __size_std) {
cv::resize(mat_target,mat_target,__size_std);
}
if (mat_tmp.size() != __size_std) {
cv::resize(mat_tmp,mat_tmp,__size_std);
}
double tmpssd=opencv_match::calSSD(mat_target,mat_tmp);
if (fabs (min_ssd-(-1)) < EPS) {
min_ssd=tmpssd;
v_mean=it.first;
}
else{
if (tmpssd<min_ssd) {
tmpssd=min_ssd;
v_mean=it.first;
}
}
ret=0;
}
}
return ret;
}
|
Name: zel_pysb.asm
Type: file
Size: 126779
Last-Modified: '2016-05-13T04:25:37Z'
SHA-1: FBBE2F2F2A9D14FF52848E9F05D59B62CED8EA98
Description: null
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 The LightPayCoin developers
// Copyright (c) 2018 The e-Sport Betting Coin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcprotocol.h"
#include "clientversion.h"
#include "tinyformat.h"
#include "util.h"
#include "utilstrencodings.h"
#include "utiltime.h"
#include "version.h"
#include <stdint.h>
#include "json/json_spirit_writer_template.h"
#include <boost/algorithm/string.hpp>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/shared_ptr.hpp>
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace json_spirit;
//! Number of bytes to allocate and read at most at once in post data
const size_t POST_READ_SIZE = 256 * 1024;
/**
* HTTP protocol
*
* This ain't Apache. We're just using HTTP header for the length field
* and to be compatible with other JSON-RPC implementations.
*/
string HTTPPost(const string& strMsg, const map<string, string>& mapRequestHeaders)
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: esportbettingcoin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
<< "Connection: close\r\n"
<< "Accept: application/json\r\n";
BOOST_FOREACH (const PAIRTYPE(string, string) & item, mapRequestHeaders)
s << item.first << ": " << item.second << "\r\n";
s << "\r\n"
<< strMsg;
return s.str();
}
static string rfc1123Time()
{
return DateTimeStrFormat("%a, %d %b %Y %H:%M:%S +0000", GetTime());
}
static const char* httpStatusDescription(int nStatus)
{
switch (nStatus) {
case HTTP_OK:
return "OK";
case HTTP_BAD_REQUEST:
return "Bad Request";
case HTTP_FORBIDDEN:
return "Forbidden";
case HTTP_NOT_FOUND:
return "Not Found";
case HTTP_INTERNAL_SERVER_ERROR:
return "Internal Server Error";
default:
return "";
}
}
string HTTPError(int nStatus, bool keepalive, bool headersOnly)
{
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: esportbettingcoin-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
"\r\n"
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"\r\n"
"\"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd\">\r\n"
"<HTML>\r\n"
"<HEAD>\r\n"
"<TITLE>Error</TITLE>\r\n"
"<META HTTP-EQUIV='Content-Type' CONTENT='text/html; charset=ISO-8859-1'>\r\n"
"</HEAD>\r\n"
"<BODY><H1>401 Unauthorized.</H1></BODY>\r\n"
"</HTML>\r\n",
rfc1123Time(), FormatFullVersion());
return HTTPReply(nStatus, httpStatusDescription(nStatus), keepalive,
headersOnly, "text/plain");
}
string HTTPReplyHeader(int nStatus, bool keepalive, size_t contentLength, const char* contentType)
{
return strprintf(
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %u\r\n"
"Content-Type: %s\r\n"
"Server: esportbettingcoin-json-rpc/%s\r\n"
"\r\n",
nStatus,
httpStatusDescription(nStatus),
rfc1123Time(),
keepalive ? "keep-alive" : "close",
contentLength,
contentType,
FormatFullVersion());
}
string HTTPReply(int nStatus, const string& strMsg, bool keepalive, bool headersOnly, const char* contentType)
{
if (headersOnly) {
return HTTPReplyHeader(nStatus, keepalive, 0, contentType);
} else {
return HTTPReplyHeader(nStatus, keepalive, strMsg.size(), contentType) + strMsg;
}
}
bool ReadHTTPRequestLine(std::basic_istream<char>& stream, int& proto, string& http_method, string& http_uri)
{
string str;
getline(stream, str);
// HTTP request line is space-delimited
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return false;
// HTTP methods permitted: GET, POST
http_method = vWords[0];
if (http_method != "GET" && http_method != "POST")
return false;
// HTTP URI must be an absolute path, relative to current host
http_uri = vWords[1];
if (http_uri.size() == 0 || http_uri[0] != '/')
return false;
// parse proto, if present
string strProto = "";
if (vWords.size() > 2)
strProto = vWords[2];
proto = 0;
const char* ver = strstr(strProto.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver + 7);
return true;
}
int ReadHTTPStatus(std::basic_istream<char>& stream, int& proto)
{
string str;
getline(stream, str);
//LogPrintf("ReadHTTPStatus - getline string: %s\n",str.c_str());
vector<string> vWords;
boost::split(vWords, str, boost::is_any_of(" "));
if (vWords.size() < 2)
return HTTP_INTERNAL_SERVER_ERROR;
proto = 0;
const char* ver = strstr(str.c_str(), "HTTP/1.");
if (ver != NULL)
proto = atoi(ver + 7);
return atoi(vWords[1].c_str());
}
int ReadHTTPHeaders(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet)
{
int nLen = 0;
while (true) {
string str;
std::getline(stream, str);
if (str.empty() || str == "\r")
break;
string::size_type nColon = str.find(":");
if (nColon != string::npos) {
string strHeader = str.substr(0, nColon);
boost::trim(strHeader);
boost::to_lower(strHeader);
string strValue = str.substr(nColon + 1);
boost::trim(strValue);
mapHeadersRet[strHeader] = strValue;
if (strHeader == "content-length")
nLen = atoi(strValue.c_str());
}
}
return nLen;
}
int ReadHTTPMessage(std::basic_istream<char>& stream, map<string, string>& mapHeadersRet, string& strMessageRet, int nProto, size_t max_size)
{
mapHeadersRet.clear();
strMessageRet = "";
// Read header
int nLen = ReadHTTPHeaders(stream, mapHeadersRet);
if (nLen < 0 || (size_t)nLen > max_size)
return HTTP_INTERNAL_SERVER_ERROR;
// Read message
if (nLen > 0) {
vector<char> vch;
size_t ptr = 0;
while (ptr < (size_t)nLen) {
size_t bytes_to_read = std::min((size_t)nLen - ptr, POST_READ_SIZE);
vch.resize(ptr + bytes_to_read);
stream.read(&vch[ptr], bytes_to_read);
if (!stream) // Connection lost while reading
return HTTP_INTERNAL_SERVER_ERROR;
ptr += bytes_to_read;
}
strMessageRet = string(vch.begin(), vch.end());
}
string sConHdr = mapHeadersRet["connection"];
if ((sConHdr != "close") && (sConHdr != "keep-alive")) {
if (nProto >= 1)
mapHeadersRet["connection"] = "keep-alive";
else
mapHeadersRet["connection"] = "close";
}
return HTTP_OK;
}
/**
* JSON-RPC protocol. e-Sport Betting Coin speaks version 1.0 for maximum compatibility,
* but uses JSON-RPC 1.1/2.0 standards for parts of the 1.0 standard that were
* unspecified (HTTP errors and contents of 'error').
*
* 1.0 spec: http://json-rpc.org/wiki/specification
* 1.2 spec: http://jsonrpc.org/historical/json-rpc-over-http.html
* http://www.codeproject.com/KB/recipes/JSON_Spirit.aspx
*/
string JSONRPCRequest(const string& strMethod, const Array& params, const Value& id)
{
Object request;
request.push_back(Pair("method", strMethod));
request.push_back(Pair("params", params));
request.push_back(Pair("id", id));
return write_string(Value(request), false) + "\n";
}
Object JSONRPCReplyObj(const Value& result, const Value& error, const Value& id)
{
Object reply;
if (error.type() != null_type)
reply.push_back(Pair("result", Value::null));
else
reply.push_back(Pair("result", result));
reply.push_back(Pair("error", error));
reply.push_back(Pair("id", id));
return reply;
}
string JSONRPCReply(const Value& result, const Value& error, const Value& id)
{
Object reply = JSONRPCReplyObj(result, error, id);
return write_string(Value(reply), false) + "\n";
}
Object JSONRPCError(int code, const string& message)
{
Object error;
error.push_back(Pair("code", code));
error.push_back(Pair("message", message));
return error;
}
|
; A172193: 5*n^2+31*n+1.
; 1,37,83,139,205,281,367,463,569,685,811,947,1093,1249,1415,1591,1777,1973,2179,2395,2621,2857,3103,3359,3625,3901,4187,4483,4789,5105,5431,5767,6113,6469,6835,7211,7597,7993,8399,8815,9241,9677,10123,10579,11045,11521,12007,12503,13009,13525,14051,14587,15133,15689,16255,16831,17417,18013,18619,19235,19861,20497,21143,21799,22465,23141,23827,24523,25229,25945,26671,27407,28153,28909,29675,30451,31237,32033,32839,33655,34481,35317,36163,37019,37885,38761,39647,40543,41449,42365,43291,44227,45173
add $0,3
mov $1,$0
mul $0,5
add $0,1
mul $0,$1
sub $0,47
|
; A059015: Total number of 0's in binary expansions of 0, ..., n.
; 1,1,2,2,4,5,6,6,9,11,13,14,16,17,18,18,22,25,28,30,33,35,37,38,41,43,45,46,48,49,50,50,55,59,63,66,70,73,76,78,82,85,88,90,93,95,97,98,102,105,108,110,113,115,117,118,121,123,125,126,128,129,130,130,136,141,146,150,155,159,163,166,171,175,179,182,186,189,192,194,199,203,207,210,214,217,220,222,226,229,232,234,237,239,241,242,247,251,255,258
lpb $0
mov $2,$0
sub $0,1
seq $2,80791 ; Number of nonleading 0's in binary expansion of n.
add $1,$2
lpe
add $1,1
mov $0,$1
|
; A034724: a(n) = n-th sextic factorial number divided by 4.
; 1,10,160,3520,98560,3351040,134041600,6165913600,320627507200,18596395417600,1190169306726400,83311851470848000,6331700711784448000,519199458366324736000,45689552336236576768000,4294817919606238216192000,429481791960623821619200000,45525069947826125091635200000,5098807834156526010263142400000,601659324430470069211050803200000,74605756229378288582170299596800000
mov $1,1
mov $2,4
lpb $0
sub $0,1
add $2,6
mul $1,$2
lpe
mov $0,$1
|
dnl X86 MMX mpn_sec_tabselect.
dnl Contributed to the GNU project by Torbjörn Granlund.
dnl Copyright 2011-2013 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of either:
dnl
dnl * the GNU Lesser General Public License as published by the Free
dnl Software Foundation; either version 3 of the License, or (at your
dnl option) any later version.
dnl
dnl or
dnl
dnl * the GNU General Public License as published by the Free Software
dnl Foundation; either version 2 of the License, or (at your option) any
dnl later version.
dnl
dnl or both in parallel, as here.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
dnl for more details.
dnl
dnl You should have received copies of the GNU General Public License and the
dnl GNU Lesser General Public License along with the GNU MP Library. If not,
dnl see https://www.gnu.org/licenses/.
include(`../config.m4')
C cycles/limb cycles/limb
C ali,evn n unal,evn n
C P5
C P6 model 0-8,10-12
C P6 model 9 (Banias)
C P6 model 13 (Dothan) 1.33 1.87
C P4 model 0 (Willamette)
C P4 model 1 (?)
C P4 model 2 (Northwood) 2.1 2.63
C P4 model 3 (Prescott)
C P4 model 4 (Nocona) 1.7 2.57
C Intel Atom 1.85 2.7
C AMD K6
C AMD K7 1.33 1.33
C AMD K8
C AMD K10
define(`rp', `%edi')
define(`tp', `%esi')
define(`n', `%edx')
define(`nents', `%ecx')
define(`which', `')
define(`i', `%ebp')
define(`j', `%ebx')
ASM_START()
TEXT
ALIGN(16)
PROLOGUE(mpn_sec_tabselect)
push %ebx
push %esi
push %edi
push %ebp
mov 20(%esp), rp
mov 24(%esp), tp
mov 28(%esp), n
mov 32(%esp), nents
movd 36(%esp), %mm6
punpckldq %mm6, %mm6 C 2 copies of `which'
mov $1, %ebx
movd %ebx, %mm7
punpckldq %mm7, %mm7 C 2 copies of 1
mov n, j
add $-4, j
js L(outer_end)
L(outer_top):
mov nents, i
mov tp, %eax
pxor %mm1, %mm1
pxor %mm4, %mm4
pxor %mm5, %mm5
ALIGN(16)
L(top): movq %mm6, %mm0
pcmpeqd %mm1, %mm0
paddd %mm7, %mm1
movq (tp), %mm2
movq 8(tp), %mm3
pand %mm0, %mm2
pand %mm0, %mm3
por %mm2, %mm4
por %mm3, %mm5
lea (tp,n,4), tp
add $-1, i
jne L(top)
movq %mm4, (rp)
movq %mm5, 8(rp)
lea 16(%eax), tp
lea 16(rp), rp
add $-4, j
jns L(outer_top)
L(outer_end):
test $2, %dl
jz L(b0x)
L(b1x): mov nents, i
mov tp, %eax
pxor %mm1, %mm1
pxor %mm4, %mm4
ALIGN(16)
L(tp2): movq %mm6, %mm0
pcmpeqd %mm1, %mm0
paddd %mm7, %mm1
movq (tp), %mm2
pand %mm0, %mm2
por %mm2, %mm4
lea (tp,n,4), tp
add $-1, i
jne L(tp2)
movq %mm4, (rp)
lea 8(%eax), tp
lea 8(rp), rp
L(b0x): test $1, %dl
jz L(b00)
L(b01): mov nents, i
pxor %mm1, %mm1
pxor %mm4, %mm4
ALIGN(16)
L(tp1): movq %mm6, %mm0
pcmpeqd %mm1, %mm0
paddd %mm7, %mm1
movd (tp), %mm2
pand %mm0, %mm2
por %mm2, %mm4
lea (tp,n,4), tp
add $-1, i
jne L(tp1)
movd %mm4, (rp)
L(b00): pop %ebp
pop %edi
pop %esi
pop %ebx
emms
ret
EPILOGUE()
|
global find_word
extern string_equals
section .text
; Params:
; rdi - pointer to null-terminated key string
; rsi - pointer to the last word in dictionary
; Out:
; rax - if not found ? 0 : list element ptr
find_word:
cmp rsi, 0
je .not_found
add rsi, 8
push rdi
push rsi
call string_equals
pop rsi
pop rdi
test rax, rax
jnz .get_element_ptr; 1 - equals, 0 - not
mov rsi, [rsi - 8]
jmp find_word
.get_element_ptr:
sub rsi, 8
mov rax, rsi
ret
.not_found:
mov rax, 0
ret
|
// Tests break statement in a simple loop
// Commodore 64 PRG executable file
.file [name="loop-break-nested.prg", type="prg", segments="Program"]
.segmentdef Program [segments="Basic, Code, Data"]
.segmentdef Basic [start=$0801]
.segmentdef Code [start=$80d]
.segmentdef Data [startAfter="Code"]
.segment Basic
:BasicUpstart(main)
.segment Code
main: {
.label line = 2
lda #<$400
sta.z line
lda #>$400
sta.z line+1
__b1:
// for(byte* line = (char*)$400; line<$400+40*25;line+=40 )
lda.z line+1
cmp #>$400+$28*$19
bcc !+
bne __breturn
lda.z line
cmp #<$400+$28*$19
bcs __breturn
!:
// if(*line=='a')
ldy #0
lda (line),y
cmp #'a'
bne __b2
__breturn:
// }
rts
__b2:
ldy #0
__b3:
// if(line[i]=='a')
lda #'a'
cmp (line),y
beq __b5
// line[i] = 'a'
sta (line),y
// for( byte i: 0..39)
iny
cpy #$28
bne __b3
__b5:
// line+=40
lda #$28
clc
adc.z line
sta.z line
bcc !+
inc.z line+1
!:
jmp __b1
}
|
db VULPIX ; 037
db 38, 41, 40, 65, 50, 65
; hp atk def spd sat sdf
db FIRE, FIRE ; type
db 190 ; catch rate
db 63 ; base exp
db BURNT_BERRY, BURNT_BERRY ; items
db GENDER_F75 ; gender ratio
db 100 ; unknown 1
db 20 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/vulpix/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_MEDIUM_FAST ; growth rate
dn EGG_GROUND, EGG_GROUND ; egg groups
; tm/hm learnset
tmhm HEADBUTT, CURSE, TOXIC, HIDDEN_POWER, SUNNY_DAY, SNORE, PROTECT, ENDURE, FRUSTRATION, IRON_TAIL, RETURN, DIG, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, FIRE_BLAST, SWIFT, REST, ATTRACT, FLAMETHROWER
; end
|
; --COPYRIGHT--,BSD_EX
; Copyright (c) 2012, Texas Instruments Incorporated
; 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 Texas Instruments Incorporated 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.
;
; ******************************************************************************
;
; MSP430 CODE EXAMPLE DISCLAIMER
;
; MSP430 code examples are self-contained low-level programs that typically
; demonstrate a single peripheral function or device feature in a highly
; concise manner. For this the code may rely on the device's power-on default
; register values and settings such as the clock configuration and care must
; be taken when combining code from several examples to avoid potential side
; effects. Also see www.ti.com/grace for a GUI- and www.ti.com/msp430ware
; for an API functional library-approach to peripheral configuration.
;
; --/COPYRIGHT--
;*******************************************************************************
; MSP430G2xx3 Demo - Timer_A, PWM TA1, Up Mode, DCO SMCLK
;
; Description: This program generates one PWM output on P1.2 using
; Timer_A configured for up mode. The value in CCR0, 512-1, defines the PWM
; period and the value in CCR1 the PWM duty cycles.
; A 75% duty cycle is on P1.2.
; ACLK = n/a, SMCLK = MCLK = TACLK = default DCO
;
; MSP430G2xx3
; -----------------
; /|\| XIN|-
; | | |
; --|RST XOUT|-
; | |
; | P1.2/TA1|--> CCR1 - 75% PWM
;
; D. Dang
; Texas Instruments Inc.
; December 2010
; Built with Code Composer Essentials Version: 4.2.0
;*******************************************************************************
.cdecls C,LIST, "msp430.h"
;------------------------------------------------------------------------------
.text ; Progam Start
;------------------------------------------------------------------------------
RESET mov.w #0280h,SP ; Initialize stackpointer
StopWDT mov.w #WDTPW+WDTHOLD,&WDTCTL ; Stop WDT
SetupP1 bis.b #00Ch,&P1DIR ; P1.2 and P1.3 output
bis.b #00Ch,&P1SEL ; P1.2 and P1.3 TA1/2 otions
SetupC0 mov.w #512-1,&CCR0 ; PWM Period
SetupC1 mov.w #OUTMOD_7,&CCTL1 ; CCR1 reset/set
mov.w #384,&CCR1 ; CCR1 PWM Duty Cycle
SetupTA mov.w #TASSEL_2+MC_1,&TACTL ; SMCLK, upmode
;
Mainloop bis.w #CPUOFF,SR ; CPU off
nop ; Required only for debugger
;
;------------------------------------------------------------------------------
; Interrupt Vectors
;------------------------------------------------------------------------------
.sect ".reset" ; MSP430 RESET Vector
.short RESET ;
.end
|
; A070396: a(n) = 6^n mod 23.
; 1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3,18,16,4,1,6,13,9,8,2,12,3
mov $1,1
mov $2,$0
lpb $2,1
mul $1,6
mod $1,23
sub $2,1
lpe
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r8
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_A_ht+0x15437, %r11
nop
xor %r8, %r8
vmovups (%r11), %ymm3
vextracti128 $0, %ymm3, %xmm3
vpextrq $0, %xmm3, %rcx
nop
nop
nop
sub $51158, %r8
lea addresses_normal_ht+0x14c37, %rsi
lea addresses_WC_ht+0x106c7, %rdi
nop
nop
cmp %rdx, %rdx
mov $127, %rcx
rep movsw
nop
nop
nop
nop
nop
add %rdi, %rdi
lea addresses_A_ht+0x114b7, %rsi
lea addresses_A_ht+0x1ea37, %rdi
nop
nop
nop
and %r8, %r8
mov $59, %rcx
rep movsl
xor %rdi, %rdi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r8
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r14
push %r15
push %rbp
push %rbx
push %rdx
push %rsi
// Store
lea addresses_RW+0xaae7, %rbp
and %r12, %r12
movb $0x51, (%rbp)
sub %rbx, %rbx
// Store
lea addresses_US+0x290f, %rsi
nop
nop
nop
nop
and %rbx, %rbx
mov $0x5152535455565758, %r14
movq %r14, (%rsi)
nop
nop
nop
xor %r12, %r12
// Store
lea addresses_A+0x12aa9, %rdx
nop
nop
xor $47698, %r15
mov $0x5152535455565758, %rbx
movq %rbx, %xmm1
vmovups %ymm1, (%rdx)
cmp $16076, %r14
// Load
lea addresses_RW+0x17a37, %rbp
nop
nop
nop
nop
nop
sub %rdx, %rdx
mov (%rbp), %r12d
nop
nop
nop
nop
cmp %rsi, %rsi
// Store
lea addresses_A+0xce07, %r15
nop
nop
cmp $54123, %rsi
movb $0x51, (%r15)
nop
nop
nop
nop
add %rbp, %rbp
// Faulty Load
lea addresses_WT+0x16c37, %rbx
and $51378, %rdx
vmovups (%rbx), %ymm1
vextracti128 $0, %ymm1, %xmm1
vpextrq $0, %xmm1, %r15
lea oracles, %rdx
and $0xff, %r15
shlq $12, %r15
mov (%rdx,%r15,1), %r15
pop %rsi
pop %rdx
pop %rbx
pop %rbp
pop %r15
pop %r14
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0, 'same': False, 'type': 'addresses_WT'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 2, 'same': False, 'type': 'addresses_RW'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 1, 'same': False, 'type': 'addresses_US'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 1, 'same': False, 'type': 'addresses_A'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': True, 'size': 4, 'congruent': 8, 'same': False, 'type': 'addresses_RW'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': False, 'type': 'addresses_A'}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 0, 'same': True, 'type': 'addresses_WT'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 11, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 11, 'same': False, 'type': 'addresses_normal_ht'}, 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'REPM'}
{'src': {'congruent': 6, 'same': False, 'type': 'addresses_A_ht'}, 'dst': {'congruent': 9, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM'}
{'39': 21829}
39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39
*/
|
; 04.2004 aralbrec
PUBLIC ba_Malloc
EXTERN _ba_qtbl
; Returns block of memory from the indicated queue.
;
; enter: HL = queue number
; exit : HL = address of memory block (0 = fail)
; Carry = success
; uses : AF,BC,DE,HL
.ba_Malloc
add hl,hl
ld de,_ba_qtbl
add hl,de
ld e,(hl)
inc hl
ld d,(hl)
ex de,hl
ld a,h
or l
ret z
inc hl
ldd
ld a,(hl)
ld (de),a
scf
ret
|
; A307513: Beatty sequence for 1/log(2).
; 1,2,4,5,7,8,10,11,12,14,15,17,18,20,21,23,24,25,27,28,30,31,33,34,36,37,38,40,41,43,44,46,47,49,50,51,53,54,56,57,59,60,62,63,64,66,67,69,70,72,73,75,76,77,79,80,82,83,85,86,88,89,90,92,93,95,96,98,99,100,102,103,105,106,108,109,111,112,113,115
mov $2,$0
add $2,1
mov $7,$0
lpb $2,1
mov $0,$7
sub $2,1
sub $0,$2
mov $3,$0
mov $5,2
lpb $5,1
mov $0,$3
sub $5,1
add $0,$5
mov $6,$5
mov $8,$0
mul $8,576
div $8,61
lpb $6,1
mov $4,$8
sub $6,1
lpe
lpe
lpb $3,1
mov $3,0
sub $4,$8
lpe
mov $8,$4
sub $8,8
add $1,$8
lpe
|
.data
mgs0: .asciiz "Fin del programa \n"
_I: .word 0
_X: .word 0
.text
.globl main
main:
li $t0, 1
sw $t0, _I
li $t0, 4
sw $t0, _X
_etiq0:
lw $t0, _I
li $t1, 6
ble $t0, $t1, _etiq3
li $t0, 0
b _etiq4
_etiq3:
li $t0, 1
_etiq4:
lw $t1, _X
li $t2, 4
beq $t1, $t2, _etiq5
li $t1, 0
b _etiq6
_etiq5:
li $t1, 1
_etiq6:
and $t2, $t0, $t1
beq $t2, 1, _etiq1
b _etiq2
_etiq1:
li $v0, 1
lw $a0, _I
syscall
lw $t0, _I
add $t1, $t0, 1
sw $t1, _I
b _etiq0
_etiq2:
li $t1, 4
add $t0, $t1, 4
sw $t0, _X
li $v0, 4
la $a0, mgs0
syscall
|
; A010157: Continued fraction for sqrt(79).
; 8,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1,7,1,16,1
pow $0,2
add $0,3
div $0,2
mul $0,7
lpb $0
sub $0,1
mod $0,8
bin $0,2
lpe
add $0,4
mov $1,$0
sub $1,3
|
; A298025: Partial sums of A298024.
; 1,5,15,29,47,71,99,131,169,211,257,309,365,425,491,561,635,715,799,887,981,1079,1181,1289,1401,1517,1639,1765,1895,2031,2171,2315,2465,2619,2777,2941,3109,3281,3459,3641,3827,4019,4215,4415,4621,4831,5045,5265,5489,5717,5951,6189,6431,6679,6931,7187,7449,7715,7985,8261,8541,8825,9115,9409,9707,10011,10319,10631,10949,11271,11597,11929,12265,12605,12951,13301,13655,14015,14379,14747,15121,15499,15881,16269,16661,17057,17459,17865,18275,18691,19111,19535,19965,20399,20837,21281,21729,22181,22639
add $0,1
bin $0,2
mul $0,14
div $0,3
add $0,1
|
; A104769: G.f. -x/(1+x-x^3).
; Submitted by Jon Maiga
; 0,-1,1,-1,0,1,-2,2,-1,-1,3,-4,3,0,-4,7,-7,3,4,-11,14,-10,-1,15,-25,24,-9,-16,40,-49,33,7,-56,89,-82,26,63,-145,171,-108,-37,208,-316,279,-71,-245,524,-595,350,174,-769,1119,-945,176,943,-1888,2064,-1121,-767,2831,-3952,3185,-354,-3598,6783,-7137,3539,3244,-10381,13920,-10676,295,13625,-24301,24596,-10971,-13330,37926,-48897,35567,2359,-51256,86823,-84464,33208,53615,-138079,171287,-117672,-20407,191694,-309366,288959,-97265,-212101,501060,-598325,386224,114836,-713161
mov $2,1
lpb $0
sub $0,1
div $3,-1
mov $4,$1
mov $1,$3
sub $3,$2
mov $2,$4
lpe
mov $0,$3
|
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int n, cnt = 0;
vector<int> in, cbt;
void inOrder(int index) {
if (index >= n) return;
inOrder(2 * index + 1);
cbt[index] = in[cnt++];
inOrder(2 * index + 2);
}
int main() {
cin >> n;
in.resize(n), cbt.resize(n);
for (int i = 0; i < n; i++) scanf("%d", &in[i]);
sort(in.begin(), in.end());
inOrder(0);
for (int i = 0; i < n; i++) {
if (i != 0) printf(" ");
printf("%d", cbt[i]);
}
return 0;
}
|
; A161532: a(n) = 2n^2 + 8n + 1.
; 1,11,25,43,65,91,121,155,193,235,281,331,385,443,505,571,641,715,793,875,961,1051,1145,1243,1345,1451,1561,1675,1793,1915,2041,2171,2305,2443,2585,2731,2881,3035,3193,3355,3521,3691,3865,4043,4225,4411,4601,4795,4993,5195,5401,5611,5825,6043,6265,6491,6721,6955,7193,7435,7681,7931,8185,8443,8705,8971,9241,9515,9793,10075,10361,10651,10945,11243,11545,11851,12161,12475,12793,13115,13441,13771,14105,14443,14785,15131,15481,15835,16193,16555,16921,17291,17665,18043,18425,18811,19201,19595,19993,20395
add $0,2
pow $0,2
mul $0,2
sub $0,7
|
//
// detail/win_iocp_io_service.hpp
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
// Copyright (c) 2003-2011 Christopher M. Kohlhoff (chris at kohlhoff dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef BOOST_ASIO_DETAIL_WIN_IOCP_IO_SERVICE_HPP
#define BOOST_ASIO_DETAIL_WIN_IOCP_IO_SERVICE_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include <boost/asio/detail/config.hpp>
#if defined(BOOST_ASIO_HAS_IOCP)
#include <boost/limits.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/detail/mutex.hpp>
#include <boost/asio/detail/op_queue.hpp>
#include <boost/asio/detail/scoped_ptr.hpp>
#include <boost/asio/detail/socket_types.hpp>
#include <boost/asio/detail/timer_op.hpp>
#include <boost/asio/detail/timer_queue_base.hpp>
#include <boost/asio/detail/timer_queue_fwd.hpp>
#include <boost/asio/detail/timer_queue_set.hpp>
#include <boost/asio/detail/win_iocp_io_service_fwd.hpp>
#include <boost/asio/detail/win_iocp_operation.hpp>
#include <boost/asio/detail/thread.hpp>
#include <boost/asio/detail/push_options.hpp>
namespace riakboost{} namespace boost = riakboost; namespace riakboost{
namespace asio {
namespace detail {
class timer_op;
class win_iocp_io_service
: public riakboost::asio::detail::service_base<win_iocp_io_service>
{
public:
// Constructor.
BOOST_ASIO_DECL win_iocp_io_service(riakboost::asio::io_service& io_service);
BOOST_ASIO_DECL void init(size_t concurrency_hint);
// Destroy all user-defined handler objects owned by the service.
BOOST_ASIO_DECL void shutdown_service();
// Initialise the task. Nothing to do here.
void init_task()
{
}
// Register a handle with the IO completion port.
BOOST_ASIO_DECL riakboost::system::error_code register_handle(
HANDLE handle, riakboost::system::error_code& ec);
// Run the event loop until stopped or no more work.
BOOST_ASIO_DECL size_t run(riakboost::system::error_code& ec);
// Run until stopped or one operation is performed.
BOOST_ASIO_DECL size_t run_one(riakboost::system::error_code& ec);
// Poll for operations without blocking.
BOOST_ASIO_DECL size_t poll(riakboost::system::error_code& ec);
// Poll for one operation without blocking.
BOOST_ASIO_DECL size_t poll_one(riakboost::system::error_code& ec);
// Stop the event processing loop.
BOOST_ASIO_DECL void stop();
// Determine whether the io_service is stopped.
bool stopped() const
{
return ::InterlockedExchangeAdd(&stopped_, 0) != 0;
}
// Reset in preparation for a subsequent run invocation.
void reset()
{
::InterlockedExchange(&stopped_, 0);
}
// Notify that some work has started.
void work_started()
{
::InterlockedIncrement(&outstanding_work_);
}
// Notify that some work has finished.
void work_finished()
{
if (::InterlockedDecrement(&outstanding_work_) == 0)
stop();
}
// Request invocation of the given handler.
template <typename Handler>
void dispatch(Handler handler);
// Request invocation of the given handler and return immediately.
template <typename Handler>
void post(Handler handler);
// Request invocation of the given operation and return immediately. Assumes
// that work_started() has not yet been called for the operation.
void post_immediate_completion(win_iocp_operation* op)
{
work_started();
post_deferred_completion(op);
}
// Request invocation of the given operation and return immediately. Assumes
// that work_started() was previously called for the operation.
BOOST_ASIO_DECL void post_deferred_completion(win_iocp_operation* op);
// Request invocation of the given operation and return immediately. Assumes
// that work_started() was previously called for the operations.
BOOST_ASIO_DECL void post_deferred_completions(
op_queue<win_iocp_operation>& ops);
// Process unfinished operations as part of a shutdown_service operation.
// Assumes that work_started() was previously called for the operations.
BOOST_ASIO_DECL void abandon_operations(op_queue<operation>& ops);
// Called after starting an overlapped I/O operation that did not complete
// immediately. The caller must have already called work_started() prior to
// starting the operation.
BOOST_ASIO_DECL void on_pending(win_iocp_operation* op);
// Called after starting an overlapped I/O operation that completed
// immediately. The caller must have already called work_started() prior to
// starting the operation.
BOOST_ASIO_DECL void on_completion(win_iocp_operation* op,
DWORD last_error = 0, DWORD bytes_transferred = 0);
// Called after starting an overlapped I/O operation that completed
// immediately. The caller must have already called work_started() prior to
// starting the operation.
BOOST_ASIO_DECL void on_completion(win_iocp_operation* op,
const riakboost::system::error_code& ec, DWORD bytes_transferred = 0);
// Add a new timer queue to the service.
template <typename Time_Traits>
void add_timer_queue(timer_queue<Time_Traits>& timer_queue);
// Remove a timer queue from the service.
template <typename Time_Traits>
void remove_timer_queue(timer_queue<Time_Traits>& timer_queue);
// Schedule a new operation in the given timer queue to expire at the
// specified absolute time.
template <typename Time_Traits>
void schedule_timer(timer_queue<Time_Traits>& queue,
const typename Time_Traits::time_type& time,
typename timer_queue<Time_Traits>::per_timer_data& timer, timer_op* op);
// Cancel the timer associated with the given token. Returns the number of
// handlers that have been posted or dispatched.
template <typename Time_Traits>
std::size_t cancel_timer(timer_queue<Time_Traits>& queue,
typename timer_queue<Time_Traits>::per_timer_data& timer,
std::size_t max_cancelled = (std::numeric_limits<std::size_t>::max)());
private:
#if defined(WINVER) && (WINVER < 0x0500)
typedef DWORD dword_ptr_t;
typedef ULONG ulong_ptr_t;
#else // defined(WINVER) && (WINVER < 0x0500)
typedef DWORD_PTR dword_ptr_t;
typedef ULONG_PTR ulong_ptr_t;
#endif // defined(WINVER) && (WINVER < 0x0500)
// Dequeues at most one operation from the I/O completion port, and then
// executes it. Returns the number of operations that were dequeued (i.e.
// either 0 or 1).
BOOST_ASIO_DECL size_t do_one(bool block, riakboost::system::error_code& ec);
// Helper function to add a new timer queue.
BOOST_ASIO_DECL void do_add_timer_queue(timer_queue_base& queue);
// Helper function to remove a timer queue.
BOOST_ASIO_DECL void do_remove_timer_queue(timer_queue_base& queue);
// Called to recalculate and update the timeout.
BOOST_ASIO_DECL void update_timeout();
// Helper class to call work_finished() on block exit.
struct work_finished_on_block_exit;
// Helper class for managing a HANDLE.
struct auto_handle
{
HANDLE handle;
auto_handle() : handle(0) {}
~auto_handle() { if (handle) ::CloseHandle(handle); }
};
// The IO completion port used for queueing operations.
auto_handle iocp_;
// The count of unfinished work.
long outstanding_work_;
// Flag to indicate whether the event loop has been stopped.
mutable long stopped_;
// Flag to indicate whether the service has been shut down.
long shutdown_;
enum
{
// Timeout to use with GetQueuedCompletionStatus. Some versions of windows
// have a "bug" where a call to GetQueuedCompletionStatus can appear stuck
// even though there are events waiting on the queue. Using a timeout helps
// to work around the issue.
gqcs_timeout = 500,
// Maximum waitable timer timeout, in milliseconds.
max_timeout_msec = 5 * 60 * 1000,
// Maximum waitable timer timeout, in microseconds.
max_timeout_usec = max_timeout_msec * 1000,
// Completion key value used to wake up a thread to dispatch timers or
// completed operations.
wake_for_dispatch = 1,
// Completion key value to indicate that an operation has posted with the
// original last_error and bytes_transferred values stored in the fields of
// the OVERLAPPED structure.
overlapped_contains_result = 2
};
// Function object for processing timeouts in a background thread.
struct timer_thread_function;
friend struct timer_thread_function;
// Background thread used for processing timeouts.
scoped_ptr<thread> timer_thread_;
// A waitable timer object used for waiting for timeouts.
auto_handle waitable_timer_;
// Non-zero if timers or completed operations need to be dispatched.
long dispatch_required_;
// Mutex for protecting access to the timer queues and completed operations.
mutex dispatch_mutex_;
// The timer queues.
timer_queue_set timer_queues_;
// The operations that are ready to dispatch.
op_queue<win_iocp_operation> completed_ops_;
};
} // namespace detail
} // namespace asio
} // namespace riakboost
#include <boost/asio/detail/pop_options.hpp>
#include <boost/asio/detail/impl/win_iocp_io_service.hpp>
#if defined(BOOST_ASIO_HEADER_ONLY)
# include <boost/asio/detail/impl/win_iocp_io_service.ipp>
#endif // defined(BOOST_ASIO_HEADER_ONLY)
#endif // defined(BOOST_ASIO_HAS_IOCP)
#endif // BOOST_ASIO_DETAIL_WIN_IOCP_IO_SERVICE_HPP
|
; A170077: Number of reduced words of length n in Coxeter group on 20 generators S_i with relations (S_i)^2 = (S_i S_j)^37 = I.
; 1,20,380,7220,137180,2606420,49521980,940917620,17877434780,339671260820,6453753955580,122621325156020,2329805177964380,44266298381323220,841059669245141180,15980133715657682420
add $0,1
mov $3,1
lpb $0
sub $0,1
add $2,$3
div $3,$2
mul $2,19
lpe
mov $0,$2
div $0,19
|
// Copyright (C) 2013 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "storage_test_runner.h"
#include <libaddressinput/callback.h>
#include <gtest/gtest.h>
namespace i18n {
namespace addressinput {
StorageTestRunner::StorageTestRunner(Storage* storage)
: storage_(storage),
success_(false),
key_(),
data_() {}
void StorageTestRunner::RunAllTests() {
EXPECT_NO_FATAL_FAILURE(GetWithoutPutReturnsEmptyData());
EXPECT_NO_FATAL_FAILURE(GetReturnsWhatWasPut());
EXPECT_NO_FATAL_FAILURE(SecondPutOverwritesData());
}
void StorageTestRunner::ClearValues() {
success_ = false;
key_.clear();
data_.clear();
}
scoped_ptr<Storage::Callback> StorageTestRunner::BuildCallback() {
return ::i18n::addressinput::BuildCallback(
this, &StorageTestRunner::OnDataReady);
}
void StorageTestRunner::OnDataReady(bool success,
const std::string& key,
const std::string& data) {
success_ = success;
key_ = key;
data_ = data;
}
void StorageTestRunner::GetWithoutPutReturnsEmptyData() {
ClearValues();
storage_->Get("key", BuildCallback());
EXPECT_FALSE(success_);
EXPECT_EQ("key", key_);
EXPECT_TRUE(data_.empty());
}
void StorageTestRunner::GetReturnsWhatWasPut() {
ClearValues();
storage_->Put("key", make_scoped_ptr(new std::string("value")));
storage_->Get("key", BuildCallback());
EXPECT_TRUE(success_);
EXPECT_EQ("key", key_);
EXPECT_EQ("value", data_);
}
void StorageTestRunner::SecondPutOverwritesData() {
ClearValues();
storage_->Put("key", make_scoped_ptr(new std::string("bad-value")));
storage_->Put("key", make_scoped_ptr(new std::string("good-value")));
storage_->Get("key", BuildCallback());
EXPECT_TRUE(success_);
EXPECT_EQ("key", key_);
EXPECT_EQ("good-value", data_);
}
} // addressinput
} // i18n
|
/*
Qt4xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 4
Copyright (C) 2021 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
*/
/*
DO NOT EDIT THIS FILE - the content was created using a source code generator
*/
#include "QDragSlots.h"
QDragSlots::QDragSlots( QObject * parent ) : QObject( parent )
{
}
QDragSlots::~QDragSlots()
{
}
void QDragSlots::actionChanged( Qt::DropAction action )
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "actionChanged(Qt::DropAction)" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QDRAG" );
PHB_ITEM pAction = hb_itemPutNI( NULL, static_cast< int >( action ) );
hb_vmEvalBlockV( cb, 2, pSender, pAction );
hb_itemRelease( pSender );
hb_itemRelease( pAction );
}
}
void QDragSlots::targetChanged( QWidget * newTarget )
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "targetChanged(QWidget*)" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QDRAG" );
PHB_ITEM pNewTarget = Qt4xHb::Signals_return_qobject( newTarget, "QWIDGET" );
hb_vmEvalBlockV( cb, 2, pSender, pNewTarget );
hb_itemRelease( pSender );
hb_itemRelease( pNewTarget );
}
}
void QDragSlots_connect_signal( const QString & signal, const QString & slot )
{
QDrag * obj = qobject_cast< QDrag * >( Qt4xHb::getQObjectPointerFromSelfItem() );
if( obj )
{
QDragSlots * s = QCoreApplication::instance()->findChild<QDragSlots *>();
if( s == NULL )
{
s = new QDragSlots();
s->moveToThread( QCoreApplication::instance()->thread() );
s->setParent( QCoreApplication::instance() );
}
hb_retl( Qt4xHb::Signals_connection_disconnection( s, signal, slot ) );
}
else
{
hb_retl( false );
}
}
|
//=====================================================================//
/*! @file
@brief OpenGL モーション・オブジェクト・クラス
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2017 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/glfw3_app/blob/master/LICENSE
*/
//=====================================================================//
#include "gl_fw/glmobj.hpp"
#include "gl_fw/glutils.hpp"
#include "img_io/img_utils.hpp"
#include <boost/format.hpp>
#include <iostream>
using namespace std;
using namespace vtx;
namespace gl {
using namespace img;
//-----------------------------------------------------------------//
/*!
@brief 初期化
@param[in] pgw テクスチャーページの最大横サイズ
@param[in] pgh テクスチャーページの最大高さサイズ
@param[in] internalFormat OpenGL の内部画像形式
@param[in] mp ミップマップの場合「true」
@param[in] im 初期化イメージ
*/
//-----------------------------------------------------------------//
void texture_mem::initialize(int pgw, int pgh, GLint internalFormat, bool mp, const img_rgba8& im)
{
// 16 ピクセル毎のブロック管理
int ww = pgw / 16;
if(pgw & 15) ++ww;
int hh = pgh / 16;
if(pgh & 15) ++hh;
block_w_ = ww;
block_h_ = hh;
block_num_ = ww * hh;
tex_map_.resize(block_num_ >> 5);
for(int i = 0; i < (block_num_ >> 5); ++i) tex_map_[i] = 0;
glGenTextures(1, &id_);
glBindTexture(GL_TEXTURE_2D, id_);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
if(im.get_size().x != pgw || im.get_size().y != pgh) {
img_rgba8 dst;
dst.create(vtx::spos(pgw, pgh), true);
dst.fill(rgba8(0, 0, 0, 0));
dst.copy(vtx::spos(0), im, vtx::srect(vtx::spos(0), im.get_size()));
glTexImage2D(GL_TEXTURE_2D, 0,
internalFormat, pgw, pgh, 0, GL_RGBA, GL_UNSIGNED_BYTE, dst());
} else {
glTexImage2D(GL_TEXTURE_2D, 0,
internalFormat, pgw, pgh, 0, GL_RGBA, GL_UNSIGNED_BYTE, im());
}
#if 0
if(mp) {
for(int i = 1; i < g_mipmap_level_max; ++i) {
pgw /= 2;
pgh /= 2;
glTexImage2D(GL_TEXTURE_2D, i, internalFormat, pgw, pgh, 0, GL_RGBA, GL_UNSIGNED_BYTE, im());
}
}
#endif
}
//-----------------------------------------------------------------//
/*!
@brief テクスチャー・エリアの割り当て
@param[in] x アロケートの位置 X を受け取るリファレンス
@param[in] y アロケートの位置 Y を受け取るリファレンス
@param[in] w アロケートする幅
@param[in] h アロケートする高さ
return 失敗したら「false」が返る
*/
//-----------------------------------------------------------------//
bool texture_mem::allocate(short& x, short& y, short w, short h)
{
if(block_num_ <= 0) return false;
int w_num = w >> 4;
if(w & 15) w_num++;
int h_num = h >> 4;
if(h & 15) h_num++;
if(w_num > block_w_ || h_num > block_h_) return false;
for(int i = 0; i < (block_h_ - h_num + 1); ++i) {
for(int j = 0; j < (block_w_ - w_num + 1); ++j) {
if(scan(j, w_num, i, h_num)) {
x = j << 4;
y = i << 4;
block_num_ -= w_num * h_num;
fill(j, w_num, i, h_num);
return true;
}
}
}
return false;
}
//-----------------------------------------------------------------//
/*!
@brief 廃棄
*/
//-----------------------------------------------------------------//
void texture_mem::destroy()
{
std::vector<unsigned int>().swap(tex_map_);
}
//-----------------------------------------------------------------//
/*!
@brief テクスチャーページの利用状態をダンプ(デバッグ確認用)
@param[in] ost ファイル・ストリーム
*/
//-----------------------------------------------------------------//
void texture_mem::dump(std::ostream& ost)
{
for(int j = 0; j < 16; ++j) {
unsigned short bits = 1;
for(int i = 0; i < 16; ++i) {
char c;
if(tex_map_[j] & bits) c = '*';
else c = ' ';
ost << boost::format("%c") % c;
i <<= 1;
}
ost << std::endl;
}
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief テクスチャー小片のアロケート
@param[in] mems テクスチャー管理(vector)
@param[in] mo モーションオブジェクト情報
@return 管理領域があれば「true」
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
bool mobj::allocate_texture(texture_mems& mems, obj* mo)
{
for(unsigned int i = 0; i < mems.size(); ++i) {
if(mems[i].allocate(mo->tx, mo->ty, mo->tw, mo->th)) {
mo->id = mems[i].get_id();
return true;
}
}
return false;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief テクスチャー小片を新規に追加
@param[in] mems テクスチャー管理(vector)
@param[in] mo モーションオブジェクト情報
@param[in] im 初期化画像
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
void mobj::add_texture_page(texture_mems& mems, obj* mo, const img_rgba8& im)
{
texture_mem mem;
mem.initialize(tex_page_w_, tex_page_h_, internal_format_, mo->mp, im);
mem.allocate(mo->tx, mo->ty, mo->tw, mo->th);
mems.push_back(mem);
mo->id = mem.get_id();
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief テクスチャー小片を全廃棄
@param[in] mems テクスチャー管理(vector)
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
void mobj::destroy_texture_page(texture_mems& mems)
{
BOOST_FOREACH(texture_mem& txm, mems) {
GLuint id = txm.get_id();
glDeleteTextures(1, &id);
}
texture_mems().swap(mems);
}
//-----------------------------------------------------------------//
/*!
@brief 初期化
@param[in] pgw テクスチャーページの最大横サイズ
@param[in] pgh テクスチャーページの最大高さサイズ
*/
//-----------------------------------------------------------------//
void mobj::initialize(int pgw, int pgh)
{
// 0 番ハンドルは使わないので無効とする。
objs_.clear();
objs_.push_back(0);
texture_pages_.clear();
tex_page_w_ = pgw;
tex_page_h_ = pgh;
}
//-----------------------------------------------------------------//
/*!
@brief モーションオブジェクトの大きさを得る
@param[in] h ハンドル
@return サイズ
*/
//-----------------------------------------------------------------//
const vtx::spos& mobj::get_size(handle h) const
{
if(h > 0 && h < objs_.size()) {
return objs_[h]->size;
} else {
static vtx::spos zero_(0);
return zero_;
}
}
//-----------------------------------------------------------------//
/*!
@brief モーションオブジェクトとして登録する。
@param[in] imf 登録画像
@param[in] mipmap ミっプマップの場合は「true」
@return ハンドルを返す
*/
//-----------------------------------------------------------------//
mobj::handle mobj::install(const img::i_img* imf, bool mipmap)
{
mipmap = false;
obj* root = 0;
obj* lk = 0;
int sox = 0;
int soy = 0;
const vtx::spos& isz = imf->get_size();
if(isz.x > tex_page_w_) sox = 2;
if(isz.y > tex_page_h_) soy = 2;
int hh = isz.y;
short oy = 0;
while(hh > 0) {
short ox = 0;
int ww = isz.x;
while(ww > 0) {
obj* mo = new obj;
mo->nx = 0;
mo->ny = 0;
if(lk) lk->link = mo;
mo->size = isz; // 元の画像サイズ
mo->mp = mipmap;
mo->ex = false;
int txw;
if(ww > tex_page_w_) {
mo->tw = tex_page_w_ - sox;
txw = tex_page_w_;
} else {
mo->tw = ww;
txw = ww;
}
mo->dw = mo->tw;
int txh;
if(hh > tex_page_h_) {
mo->th = tex_page_h_ - soy;
txh = tex_page_h_;
} else {
mo->th = hh;
txh = hh;
}
mo->dh = mo->th;
// positive offset
mo->oxp = ox;
mo->oyp = oy;
// negative offset
mo->oxn = isz.x - (ox + mo->dw);
mo->oyn = isz.y - (oy + mo->dh);
// テクスチャー領域のアロケート
{
img_rgba8 im;
im.create(vtx::spos(txw, txh), true);
copy_to_rgba8(imf, vtx::srect(ox, oy, txw, txh), im, vtx::spos(0, 0));
bool f = false;
if(sox == 0 && soy == 0) {
f = allocate_texture(texture_mems_, mo);
}
if(!f) {
add_texture_page(texture_mems_, mo, im);
} else {
glBindTexture(GL_TEXTURE_2D, mo->id);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glTexSubImage2D(GL_TEXTURE_2D, 0,
mo->tx, mo->ty, txw, txh, GL_RGBA, GL_UNSIGNED_BYTE,
im());
}
if(mipmap) {
int ofsx = mo->tx;
int ofsy = mo->ty;
/// img_rgba8 tmp;
for(int i = 1; i < mipmap_level_max_; ++i) {
ofsx /= 2;
ofsy /= 2;
txw /= 2;
txh /= 2;
/// scale_50percent(imf, tmp);
/// glTexSubImage2D(GL_TEXTURE_2D, i, ofsx, ofsy, txw, txh, GL_RGBA, GL_UNSIGNED_BYTE, im);
}
}
}
if(root == 0) root = mo;
ww -= mo->tw;
ox += mo->tw;
lk = mo;
}
hh -= lk->th;
oy += lk->th;
}
handle h = objs_.size();
objs_.push_back(root);
return h;
}
//-----------------------------------------------------------------//
/*!
@brief モーションオブジェクトとして拡張登録する。
@param[in] imf 登録最小画像(グリッド・サイズの3倍)
@param[in] size 実際の拡張サイズ
@param[in] grid グリッド・サイズ(指定しないと16ピクセル)
@return ハンドルを返す
*/
//-----------------------------------------------------------------//
mobj::handle mobj::install(const img::i_img* imf, const vtx::spos& size, const vtx::spos& grid)
{
const vtx::spos& isz = imf->get_size();
// 基本テクスチャーサイズを超える場合はエラーとする。
if(isz.x > tex_page_w_ || isz.y > tex_page_h_) return 0;
int jn;
if(size.y < (grid.y * 3)) {
jn = 1;
} else if(isz.y >= (grid.y * 3)) {
jn = 3;
} else {
return 0;
}
int in;
if(size.x < (grid.x * 3)) {
in = 1;
} else if(isz.x >= (grid.x * 3)) {
in = 3;
} else {
return 0;
}
obj* root = 0;
obj* lk = 0;
short oy = 0;
for(int j = 0; j < jn; ++j) {
short ox = 0;
for(int i = 0; i < in; ++i) {
obj* mo = new obj;
mo->nx = in;
mo->ny = jn;
if(lk) lk->link = mo;
mo->size = size; // 元の画像サイズ
mo->mp = false;
mo->ex = true;
if(in == 1) {
mo->dw = size.x;
} else if(i != 1) {
mo->dw = grid.x;
} else {
mo->dw = size.x - grid.x * 2;
}
if(jn == 1) {
mo->dh = size.y;
} else if(j != 1) {
mo->dh = grid.y;
} else {
mo->dh = size.y - grid.y * 2;
}
// positive offset
mo->oxp = ox;
mo->oyp = oy;
// negative offset
mo->oxn = size.x - (ox + mo->dw);
mo->oyn = size.y - (oy + mo->dh);
// テクスチャー領域のアロケート
{
img_rgba8 im;
im.create(vtx::spos(mo->dw + 2, mo->dh + 2), true);
im.fill(rgba8(0));
static const short sofs[3] = { 0, -1, -1 };
static const short cpyw[3] = { 1, 2, 1 };
static const short dofs[3] = { 1, 0, 0 };
copy_to_rgba8(imf, vtx::srect(ox + sofs[i], oy + sofs[j],
mo->dw + cpyw[i], mo->dh + cpyw[j]), im, vtx::spos(dofs[i], dofs[j]));
mo->tw = im.get_size().x;
mo->th = im.get_size().y;
bool f = allocate_texture(texture_mems_, mo);
if(!f) {
add_texture_page(texture_mems_, mo, im);
} else {
glBindTexture(GL_TEXTURE_2D, mo->id);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glTexSubImage2D(GL_TEXTURE_2D, 0,
mo->tx, mo->ty, im.get_size().x, im.get_size().y,
GL_RGBA, GL_UNSIGNED_BYTE, im());
}
}
mo->tx += 1;
mo->ty += 1;
mo->tw -= 2;
mo->th -= 2;
if(root == 0) root = mo;
ox += mo->dw;
lk = mo;
}
oy += lk->dh;
}
handle h = objs_.size();
objs_.push_back(root);
return h;
}
//-----------------------------------------------------------------//
/*!
@brief テクスチャーを登録する。
@param[in] imf イメージインターフェース
@return テクスチャー・ハンドルを返す
*/
//-----------------------------------------------------------------//
GLuint mobj::install_texture(const img::i_img* imf)
{
if(imf == 0) return 0;
GLuint id = 0;
int level = 0;
const vtx::spos& size = imf->get_size();
if(imf->get_type() == IMG::FULL8) {
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glTexImage2D(GL_TEXTURE_2D, level, internal_format_,
size.x, size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, (*imf)());
} else if(imf->get_type() == IMG::INDEXED8) {
glGenTextures(1, &id);
glBindTexture(GL_TEXTURE_2D, id);
img_rgba8 im;
im.create(size, true);
copy_to_rgba8(imf, im, vtx::spos(0));
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glTexImage2D(GL_TEXTURE_2D, level, internal_format_,
size.x, size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE, im());
} else {
std::cout << boost::format("Install Texture No Type: %d") % static_cast<int>(imf->get_type()) << std::endl;
}
texture_pages_.push_back(id);
return id;
}
//-----------------------------------------------------------------//
/*!
@brief テクスチャーを登録する。
@param[in] ptr 圧縮テクスチャーのポインター
@param[in] size 圧縮テクスチャーのサイズ
@param[in] type 圧縮タイプ
@param[in] w 横幅
@param[in] h 高さ
@return テクスチャー・ハンドルを返す
*/
//-----------------------------------------------------------------//
GLuint mobj::install_compressed_texture(const void* ptr, size_t size, int type, int w, int h)
{
GLuint id;
::glGenTextures(1, &id);
::glBindTexture(GL_TEXTURE_2D, id);
::glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
#ifdef IPHONE_IPAD
::glCompressedTexImage2D(GL_TEXTURE_2D, level, type, w, h, 0, size, ptr);
#endif
texture_pages_.push_back(id);
return id;
}
//-----------------------------------------------------------------//
/*!
@brief 画像をモーションオブジェクトとして登録する。
@param[in] root モーションオブジェクト設定情報
@return ハンドルを返す
*/
//-----------------------------------------------------------------//
mobj::handle mobj::install_direct(const obj& root)
{
obj* top = new obj;
*top = root;
obj* p = top;
while(p->link) {
obj* tmp = new obj;
tmp = p->link;
p->link = tmp;
p = tmp;
}
handle h = objs_.size();
objs_.push_back(top);
return h;
}
//-----------------------------------------------------------------//
/*!
@brief モーション・オブジェクト描画前設定(テクスチャースケールのみ)
*/
//-----------------------------------------------------------------//
void mobj::setup_matrix()
{
glMatrixMode(GL_TEXTURE);
glLoadIdentity();
float u = static_cast<float>(tex_page_w_);
float v = static_cast<float>(tex_page_h_);
glScalef(1.0f / u, 1.0f / v, 1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
//-----------------------------------------------------------------//
/*!
@brief モーション・オブジェクト描画用マトリックスの設定
@param[in] x 開始位置 X
@param[in] y 開始位置 Y
@param[in] w 横幅の指定
@param[in] h 高さの指定
@param[in] zn Z (手前)
@param[in] zf Z (奥)
*/
//-----------------------------------------------------------------//
void mobj::setup_matrix(int x, int y, int w, int h, float zn, float zf)
{
setup_matrix();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrthof(static_cast<float>(x), static_cast<float>(w),
static_cast<float>(h), static_cast<float>(y), zn, zf);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
//-----------------------------------------------------------------//
/*!
@brief モーションオブジェクトのイメージを更新
@param[in] h ハンドル
@param[in] src ソース、イメージインターフェース
@param[in] dst ディスとネーションのオフセット
*/
//-----------------------------------------------------------------//
void mobj::copy_image(handle h, const img::i_img* src, const vtx::spos& dst)
{
const i_img* imif = src;
// RGBA8 以外の画像タイプなら、一旦 RGBA8 形式で画像を作成。
img_rgba8 tmp;
if(src->get_type() != IMG::FULL8) {
tmp.create(src->get_size(), true);
copy_to_rgba8(src, tmp);
imif = &tmp;
}
const obj* m = objs_[h];
while(m != 0) {
glBindTexture(GL_TEXTURE_2D, m->id);
int level = 0;
// if(mop->link == 0 && mop->w >= imif->get_width() && mop->h >= imif->get_height()) {
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glTexSubImage2D(GL_TEXTURE_2D, level, m->tx + dst.x, m->ty + dst.y,
imif->get_size().x, imif->get_size().y,
GL_RGBA, GL_UNSIGNED_BYTE, (*imif)());
// }
m = m->link;
}
glFlush();
}
static void tex_para_(bool linear)
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
if(linear) {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
} else {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
}
//-----------------------------------------------------------------//
/*!
@brief モーション・オブジェクトを描画する。
@param[in] h ハンドル
@param[in] atr アトリビュート
@param[in] pos 描画位置
@param[in] linear 「true」ならリニアフィルター
*/
//-----------------------------------------------------------------//
void mobj::draw(handle h, attribute::type atr, const vtx::spos& pos, bool linear)
{
if(h == 0 || h >= objs_.size()) return;
bool hf = false;
bool vf = false;
if(atr != attribute::normal) {
if(atr == attribute::h_flip) hf = true;
else if(atr == attribute::v_flip) vf = true;
else if(atr == attribute::hv_flip) hf = vf = true;
}
const obj* m = objs_[h];
do {
short xp;
if(hf) {
xp = pos.x + m->oxn;
} else {
xp = pos.x + m->oxp;
}
short yp;
if(vf) {
yp = pos.y + m->oyn;
} else {
yp = pos.y + m->oyp;
}
spos vlist[4];
spos tlist[4];
switch(atr) {
case attribute::h_flip:
tlist[0].set(m->tx + m->tw, m->ty);
vlist[0].set( xp, yp);
tlist[1].set(m->tx + m->tw, m->ty + m->th);
vlist[1].set( xp, yp + m->dh);
tlist[3].set(m->tx, m->ty + m->th);
vlist[3].set( xp + m->dw, yp + m->dh);
tlist[2].set(m->tx, m->ty);
vlist[2].set( xp + m->dw, yp);
break;
case attribute::v_flip:
tlist[0].set(m->tx, m->ty + m->th);
vlist[0].set( xp, yp);
tlist[1].set(m->tx, m->ty);
vlist[1].set( xp, yp + m->dh);
tlist[3].set(m->tx + m->tw, m->ty);
vlist[3].set( xp + m->dw, yp + m->dh);
tlist[2].set(m->tx + m->tw, m->ty + m->th);
vlist[2].set( xp + m->dw, yp);
break;
case attribute::hv_flip:
tlist[0].set(m->tx + m->tw, m->ty + m->th);
vlist[0].set( xp, yp);
tlist[1].set(m->tx + m->tw, m->ty);
vlist[1].set( xp, yp + m->dh);
tlist[3].set(m->tx, m->ty);
vlist[3].set( xp + m->dw, yp + m->dh);
tlist[2].set(m->tx, m->ty + m->th);
vlist[2].set( xp + m->dw, yp);
break;
case attribute::normal:
default:
tlist[0].set(m->tx, m->ty);
vlist[0].set(xp, yp);
tlist[1].set(m->tx, m->ty + m->th);
vlist[1].set(xp, yp + m->dh);
tlist[3].set(m->tx + m->tw, m->ty + m->th);
vlist[3].set( xp + m->dw, yp + m->dh);
tlist[2].set(m->tx + m->tw, m->ty);
vlist[2].set( xp + m->dw, yp);
break;
}
glBindTexture(GL_TEXTURE_2D, m->id);
tex_para_(linear);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glTexCoordPointer(2, GL_SHORT, 0, &tlist[0]);
glVertexPointer(2, GL_SHORT, 0, &vlist[0]);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
m = m->link;
} while(m != 0) ;
}
//-----------------------------------------------------------------//
/*!
@brief モーション・オブジェクトの描画
@param[in] h ハンドル
@param[in] atr アトリビュート
@param[in] pos 描画位置
@param[in] ofs オフセット
@param[in] wh 描画幅、高さ
@param[in] linear 「true」ならリニアフィルター
*/
//-----------------------------------------------------------------//
void mobj::draw_sub(handle h, attribute::type atr, const vtx::spos& pos, const vtx::spos& ofs, const vtx::spos& wh, bool linear)
{
if(h == 0 || h >= objs_.size()) return;
const obj* m = objs_[h];
do {
short xp = m->oxp;
short yp = m->oyp;
short w = m->dw;
short h = m->dh;
short tx = m->tx;
short ty = m->ty;
short dx;
if(ofs.x >= xp) dx = ofs.x - xp + wh.x;
else dx = xp - ofs.x + wh.x;
short dy;
if(ofs.y >= yp) dy = ofs.y - yp + wh.y;
else dy = yp - ofs.y + wh.y;
if(dx < (w + wh.x) && dy < (h + wh.y)) {
if(ofs.x >= xp) {
w -= ofs.x - xp;
if(w > wh.x) w = wh.x;
tx += ofs.x - xp;
xp += ofs.x - xp;
} else {
w = ofs.x - xp + wh.x;
}
if(ofs.y >= yp) {
h -= ofs.y - yp;
if(h > wh.y) h = wh.y;
ty += ofs.y - yp;
yp += ofs.y - yp;
} else {
h = ofs.y - yp + wh.y;
}
xp += pos.x;
yp += pos.y;
::glBindTexture(GL_TEXTURE_2D, m->id);
tex_para_(linear);
spos vlist[4];
spos tlist[4];
switch(atr) {
case attribute::h_flip:
tlist[0].set(tx + w, ty);
vlist[0].set(xp, yp);
tlist[1].set(tx + w, ty + h);
vlist[1].set(xp, yp + h);
tlist[3].set(tx, ty + h);
vlist[3].set(xp + w, yp + h);
tlist[2].set(tx, ty);
vlist[2].set(xp + w, yp);
break;
case attribute::v_flip:
tlist[0].set(tx, ty + h);
vlist[0].set(xp, yp);
tlist[1].set(tx, ty);
vlist[1].set(xp, yp + h);
tlist[3].set(tx + w, ty);
vlist[3].set(xp + w, yp + h);
tlist[2].set(tx + w, ty + h);
vlist[2].set(xp + w, yp);
break;
case attribute::hv_flip:
tlist[0].set(tx + w, ty + h);
vlist[0].set(xp, yp);
tlist[1].set(tx + w, ty);
vlist[1].set(xp, yp + h);
tlist[3].set(tx, ty);
vlist[3].set(xp + w, yp + h);
tlist[2].set(tx, ty + h);
vlist[2].set(xp + w, yp);
break;
case attribute::normal:
default:
tlist[0].set(tx, ty);
vlist[0].set(xp, yp);
tlist[1].set(tx, ty + h);
vlist[1].set(xp, yp + h);
tlist[3].set(tx + w, ty + h);
vlist[3].set(xp + w, yp + h);
tlist[2].set(tx + w, ty);
vlist[2].set(xp + w, yp);
break;
}
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnableClientState(GL_VERTEX_ARRAY);
glTexCoordPointer(2, GL_SHORT, 0, &tlist[0]);
glVertexPointer(2, GL_SHORT, 0, &vlist[0]);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
}
m = m->link;
} while(m != 0) ;
}
//-----------------------------------------------------------------//
/*!
@brief モーション・オブジェクト列の描画
@param[in] hs ハンドルのポインター
@param[in] atr アトリビュート
@param[in] pos 描画位置
@param[in] linear 「true」ならリニア
*/
//-----------------------------------------------------------------//
void mobj::draws(const handle* hs, attribute::type atr, const vtx::spos& pos, bool linear)
{
handle h;
vtx::spos p = pos;
while((h = *hs++) != 0) {
draw(h, atr, p, linear);
const vtx::spos& size = get_size(h);
p.x += size.x + space_;
}
}
//-----------------------------------------------------------------//
/*!
@brief 拡張登録されたモーションオブジェクトのリサイズ
@param[in] h ハンドル
@param[in] size 新しいサイズ
@return エラーなら「false」
*/
//-----------------------------------------------------------------//
bool mobj::resize(handle h, const vtx::spos& size)
{
if(h == 0 && h >= objs_.size()) {
return false;
}
obj* m = objs_[h];
if(!m->ex) return false;
if(m->nx == 0 || m->ny == 0) return false;
// if(m->ww == size.x && m->hh == size.y) return true;
vtx::spos grid(m->tw, m->th);
int nx = m->nx;
int ny = m->ny;
for(int j = 0; j < ny; ++j) {
for(int i = 0; i < nx; ++i) {
if(nx == 1) {
m->oxp = 0;
m->dw = size.x;
} else if(i == 0) {
m->oxp = 0;
m->dw = grid.x;
} else if(i == 1) {
m->oxp = grid.x;
m->dw = size.x - grid.x * 2;
} else {
m->oxp = size.x - grid.x;
m->dw = grid.x;
}
m->oxn = size.x - (m->oxp + m->dw);
m->size.x = size.x;
if(ny == 1) {
m->oyp = 0;
m->dh = size.y;
} else if(j == 0) {
m->oyp = 0;
m->dh = grid.y;
} else if(j == 1) {
m->oyp = grid.y;
m->dh = size.y - grid.y * 2;
} else {
m->oyp = size.y - grid.y;
m->dh = grid.y;
}
m->oyn = size.y - (m->oyp + m->dh);
m->size.y = size.y;
m = m->link;
}
}
return true;
}
//-----------------------------------------------------------------//
/*!
@brief 廃棄
*/
//-----------------------------------------------------------------//
void mobj::destroy()
{
for(objs_it it = objs_.begin(); it != objs_.end(); ++it) {
obj* o = *it;
while(o != 0) {
obj* tmp = o;
o = tmp->link;
delete tmp;
}
}
objs().swap(objs_);
destroy_texture_page(texture_mems_);
texture_mems().swap(texture_mems_);
if(!texture_pages_.empty()) {
::glDeleteTextures(texture_pages_.size(), &texture_pages_[0]);
}
}
}
/* ----- End Of File "glmobj.cpp" ----- */
|
<% from pwnlib.shellcraft import mips %>
<%docstring>Execute /bin/sh</%docstring>
${mips.execve('//bin/sh', ['sh'], {})}
|
#ifndef BSL_OVERRIDES_STD
#define BSL_OVERRIDES_STD
#endif
#include <strstream>
#ifndef std
# error std was expected to be a macro
#endif
int main() { return 0; }
// ----------------------------------------------------------------------------
// Copyright (C) 2013 Bloomberg L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
|
; A213432: 2^(n-3)*binomial(n,4).
; 0,0,0,0,2,20,120,560,2240,8064,26880,84480,253440,732160,2050048,5591040,14909440,38993920,100270080,254017536,635043840,1568931840,3835166720,9285140480,22284337152,53057945600,125409689600,294440140800,687026995200,1593902628864,3678236835840,8446321623040,19305877995520,43937515438080,99591701659648
mov $1,2
pow $1,$0
bin $0,4
mul $1,$0
div $1,16
mul $1,2
mov $0,$1
|
PAGE 60,132;
TITLE EDLIN
;/*
; * Microsoft Confidential
; * Copyright (C) Microsoft Corporation 1991
; * All Rights Reserved.
; */
;======================= START OF SPECIFICATIONS =========================
;
; MODULE NAME: EDLIN.SAL
;
; DESCRIPTIVE NAME: LINE TEXT EDITOR
;
; FUNCTION: EDLIN IS A SIMPLE, LINE ORIENTED TEXT EDITOR. IT PROVIDES
; USERS OF DOS THE ABILITY TO CREATE AND EDIT TEXT FILES.
;
; ENTRY POINT: EDLIN
;
; INPUT: DOS COMMAND LINE
; EDLIN COMMANDS
; TEXT
;
; EXIT NORMAL: NA
;
; EXIT ERROR: NA
;
; INTERNAL REFERENCES:
;
; EXTERNAL REFERENCES:
;
; ROUTINE: EDLCMD1 - CONTAINS ROUTINES CALLED BY EDLIN
; EDLCMD1 - CONTAINS ROUTINES CALLED BY EDLIN
; EDLMES - CONTAINS ROUTINES CALLED BY EDLIN
;
; LINK EDLIN+EDLCMD1+EDLCMD2+EDLMES+EDLPARSE
;
; REVISION HISTORY:
;
; AN000 VERSION 4.00 - REVISIONS MADE RELATE TO THE FOLLOWING:
;
; - IMPLEMENT SYSPARSE
; - IMPLEMENT MESSAGE RETRIEVER
; - IMPLEMENT DBCS ENABLING
; - ENHANCED VIDEO SUPPORT
; - EXTENDED OPENS
; - SCROLLING ERROR
;
; COPYRIGHT: "MS DOS EDLIN UTILITY"
; "VERSION 4.00 (C) COPYRIGHT 1988 Microsoft"
; "LICENSED MATERIAL - PROPERTY OF Microsoft"
;
;
; MICROSOFT REVISION HISTORY:
; ;
; V1.02 ;
; ;
; V2.00 9/13/82 M.A.U ;
; ;
; 2/23/82 Rev. 13 N. P ;
; Changed to 2.0 system calls. ;
; Added an error message for READ-ONLY files ;
; ;
; 11/7/83 Rev. 14 N. P ;
; Changed to .EXE format and added Printf ;
; ;
; V2.50 11/15/83 Rev. 1 M.A. U ;
; Official dos 2.50 version. Some random bug ;
; fixes and message changes. ;
; ;
; 11/30/83 Rev. 2 MZ ;
; Close input file before rename. ;
; Jmp to replace after line edit ;
; ;
; 02/01/84 Rev. 3 M.A. U ;
; Now it is called 3.00 dos. Repaired problem ;
; with using printf and having %'s as data. ;
; ;
; 02/15/84 MZ make out of space a fatal error with output;
; ;
; 03/28/84 MZ fixes bogus (totally) code in MOVE/COPY ;
; ;
; 04/02/84 MZ fixes DELETE and changes MOVE/COPY/EDIT ;
; ;
; V3.20 08/29/86 Rev. 1 S.M. G ;
; ;
; 08/29/86 M001 MSKK TAR 593, TAB MOVEMENT ;
; ;
; 08/29/86 M002 MSKK TAR 157, BLKMOVE 1,1,1m, 1,3,1m ;
; ;
; 08/29/86 M003 MSKK TAR 476, EDLCMD2,MAKECAPS,kana char ;
; ;
; 08/29/86 M004 MSKK TAR 191, Append load size ;
; ;
; 08/29/86 M005 IBMJ TAR Transfer Load command ;
; ;
; 04/17/90 c-PaulB ;
; Added /? switch to display options ;
; Files changed: edlin.asm, edlparse.asm, edlmes.asm, ;
; edlin.skl. ;
; ;
;======================= END OF SPECIFICATIONS =========================== ;
include version.inc
include intnat.inc
include syscall.inc
include edlequ.asm
SUBTTL Contants and Data areas
PAGE
extrn parser_command:near ;an000;SYSPARSE
CODE SEGMENT PUBLIC
CODE ENDS
CONST SEGMENT PUBLIC WORD
CONST ENDS
cstack segment stack
cstack ends
DATA SEGMENT PUBLIC WORD
DATA ENDS
DG GROUP CODE,CONST,cstack,DATA
CONST SEGMENT PUBLIC WORD
public bak,$$$file,delflg,loadmod,txt1,txt2
EXTRN BADDRV:abs,NDNAME:abs
EXTRN opt_err_ptr:word,NOBAK:abs,BADCOM:abs
EXTRN NEWFIL:abs,DEST:abs,MRGERR:abs
EXTRN NODIR:abs,FILENM_ptr:word,ro_err:abs
EXTRN bcreat:abs,msg_too_many:abs,msg_lf:abs
EXTRN prompt:abs,MemFul_Ptr:word,simple_msg:word
extrn dsp_options:abs
extrn dsp_help:abs,num_help_msgs:abs
BAK DB ".BAK",0
$$$FILE DB ".$$$",0
fourth db 0 ;fourth parameter flag
loadmod db 0 ;Load mode flag, 0 = ^Z marks the
; end of a file, 1 = viceversa.
optchar db "-"
TXT1 DB 0,80H DUP (?)
TXT2 DB 0,80H DUP (?)
DELFLG DB 0
fNew DB 0 ; old file
HAVEOF DB 0
CONST ENDS
cstack segment stack
db stksiz dup (?)
cstack ends
DATA SEGMENT PUBLIC WORD
extrn arg_buf_ptr:word ;an000;
extrn line_num_buf_ptr:word ;an000;
public path_name,ext_ptr,start,line_num,line_flag
public arg_buf,wrt_handle,temp_path
public current,pointer,qflg,editbuf,amnt_req,fname_len,delflg,lastlin
public olddat,oldlen,newlen,srchflg,srchmod
public comline,lstfnd,numpos,lstnum,last_mem,srchcnt
public rd_handle,haveof,ending,three4th,one4th
public lc_adj ;an000;page length adj. factor
public lc_flag ;an000;display cont. flag
public pg_count ;an000;lines left on screen
public Disp_Len ;an000;display length
public Disp_Width ;an000;display width
public continue ;an000;boolean T/F
public temp_path ;an000;pointer to filespec buf
Video_Buffer label word ;an000;buffer for video attr
db 0 ;an000;dms;
db 0 ;an000;dms;
dw 14 ;an000;dms;
dw 0 ;an000;dms;
db ? ;an000;dms;
db 0 ;an000;dms;
dw ? ;an000;dms;# of colors
dw ? ;an000;dms;# of pixels in width
dw ? ;an000;dms;# of pixels in len.
dw ? ;an000;dms;# of chars in width
dw ? ;an000;dms;# of chars in length
video_org db ? ;an000;original video mode on
; entry to EDLIN.
lc_adj db ? ;an000;page length adj. factor
lc_flag db ? ;an000;display cont. flag
pg_count db ? ;an000;lines left on screen
Disp_Len db ? ;an000;display length
Disp_Width db ? ;an000;display width
continue db ? ;an000;boolean T/F
;-----------------------------------------------------------------------;
; This is a table that is sequentially filled via GetNum. Any additions to it
; must be placed in the correct position. Currently Param4 is known to be a
; count and thus is treated specially.
public param1,param2,Param3,param4,ParamCt
PARAM1 DW ?
PARAM2 DW ?
PARAM3 DW ?
PARAM4 DW ?
ParamCt DW ? ; count of passed parameters
ifdef DBCS ; Used in TESTKANJ:
LBTbl dd ? ; long pointer to lead byte table
endif ; in the dos (from syscall 63H)
;-----------------------------------------------------------------------;
PUBLIC PTR_1, PTR_2, PTR_3, OLDLEN, NEWLEN, LSTFND, LSTNUM, NUMPOS, SRCHCNT
PUBLIC CURRENT, POINTER, ONE4TH, THREE4TH, LAST_MEM, ENDTXT, COPYSIZ
PUBLIC COMLINE, LASTLIN, COMBUF, EDITBUF, EOL, QFLG, ENDING, SRCHFLG
PUBLIC PATH_NAME, FNAME_LEN, RD_HANDLE, TEMP_PATH, WRT_HANDLE, EXT_PTR
PUBLIC MRG_PATH_NAME, MRG_HANDLE, amnt_req, olddat, srchmod, MOVFLG, org_ds
ifdef DBCS
public lbtbl
endif
;
; These comprise the known state of the internal buffer. All editing
; functions must preserve these values.
;
CURRENT DW ? ; the 1-based index of the current line
POINTER DW ? ; pointer to the current line
ENDTXT DW ? ; pointer to end of buffer. (at ^Z)
LAST_MEM DW ? ; offset of last byte of memory
;
; The label Start is the beginning of the in-core buffer.
;
;
; Internal temporary pointers
;
PTR_1 DW ?
PTR_2 DW ?
PTR_3 DW ?
QFLG DB ? ; TRUE => query for replacement
OLDLEN DW ?
NEWLEN DW ?
LSTFND DW ?
LSTNUM DW ?
NUMPOS DW ?
SRCHCNT DW ?
ONE4TH DW ?
THREE4TH DW ?
COPYSIZ DW ? ; total length to copy
COPYLEN DW ? ; single copy length
COMLINE DW ?
LASTLIN DW ?
COMBUF DB 82H DUP (?)
EDITBUF DB 258 DUP (?)
EOL DB ?
ENDING DB ?
SRCHFLG DB ?
PATH_NAME DB 128 DUP(0)
FNAME_LEN DW ?
RD_HANDLE DW ?
TEMP_PATH DB 128 DUP(?)
WRT_HANDLE DW ?
EXT_PTR DW ?
MRG_PATH_NAME DB 128 DUP(?)
MRG_HANDLE DW ?
amnt_req dw ? ; amount of bytes requested to read
olddat db ? ; Used in replace and search, replace
; by old data flag (1=yes)
srchmod db ? ; Search mode: 1=from current+1 to
; end of buffer, 0=from beg. of
; buffer to the end (old way).
MOVFLG DB ?
org_ds dw ? ;Orginal ds points to header block
arg_buf db 258 dup (?)
EA_Flag db False ;an000; dms;set to false
EA_Buffer_Size dw ? ;an000; dms;EA buffer's size
EA_Parm_List label word ;an000; dms;EA parms
dd dg:Start ;an000; dms;ptr to EA's
dw 0001h ;an000; dms;additional parms
db 06h ;an000; dms;
dw 0002h ;an000; dms;iomode
line_num dw ?
line_flag db ?,0
EVEN ;align on word boundaries
;
; Byte before start of data buffer must be < 40H !!!!!!
;
dw 0 ;we scan backwards looking for
;a character which can't be part
;of a two-byte seqence. This
;double byte sequence will cause the back
;scan to stop here.
START LABEL WORD
DATA ENDS
CODE SEGMENT PUBLIC
ASSUME CS:DG,DS:NOTHING,ES:NOTHING,SS:CStack
extrn pre_load_message:near ;an000;message loader
extrn disp_fatal:near ;an000;fatal message
extrn printf:near ;an000;new PRINTF routine
extrn findlin:near,shownum:near,loadbuf:near,crlf:near,lf:near
extrn abortcom:near,delbak:near,unquote:near,kill_bl:near
extrn make_caps:near,dispone:near,display:near,query:near
extrn quit:near,make_cntrl:near,scanln:near,scaneof:near
extrn fndfirst:near,fndnext:near,replace:near,memerr:near
extrn xerror:near
extrn zerror:near
extrn bad_read:near,append:near
extrn nocom:near,pager:near,list:near,search_from_curr:near
extrn replac_from_curr:near,ewrite:near,wrt:near,delete:near
extrn filespec:byte ;an000;parser's filespec
extrn parse_switch_b:byte ;an000;result of switch scan
extrn parse_switch_?:byte ; result of switch scan
public std_printf,command,chkrange,comerr
public display_message
; exit from EDLIN
IFDEF DBCS
extrn testkanj:near
ENDIF
EDLIN:
JMP SHORT SIMPED
std_printf proc near ;ac000;convert to proc
push dx
call printf
pop dx ;an000;balance the push
ret
std_printf endp ;ac000;end proc
Break <Dispatch Table>
;-----------------------------------------------------------------------;
; Careful changing the order of the next two tables. They are linked and
; changes should be be to both.
COMTAB DB 13,";ACDEILMPQRSTW"
NUMCOM EQU $-COMTAB
TABLE DW BLANKLINE ; Blank line
DW NOCOM ; ;
DW APPEND ; A(ppend)
DW COPY ; C(opy)
DW DELETE ; D(elete)
DW ENDED ; E(xit)
DW INSERT ; I(nsert)
DW LIST ; L(ist)
DW MOVE ; M(ove)
DW PAGER ; P(age)
DW QUIT ; Q(uit)
dw replac_from_curr ; R(eplace)
dw search_from_curr ; S(earch)
DW MERGE ; T(merge)
DW EWRITE ; W(rite)
Break <Initialization Code>
NONAME:
mov ax,NDNAME
jmp zerror
SIMPED:
mov org_ds,DS
push ax ;ac000;save for drive compare
push cs ;an000;exchange cs/es
pop es ;an000;
push cs ;an000;exchange cs/ds
pop ds ;an000;
assume ds:dg,es:dg ;an000;establish addressibility
MOV dg:ENDING,0
mov sp,stack
call EDLIN_DISP_GET ;an000;get current video
; mode & set it to
; text
;=========================================================================
; invoke PRE_LOAD_MESSAGE here. If the messages were not loaded we will
; exit with an appropriate error message.
;
; Date : 6/14/87
;=========================================================================
call PRE_LOAD_MESSAGE ;an000;invoke SYSLOADMSG
; $if c ;an000;if the load was unsuccessful
JNC $$IF1
mov ah,exit ;an000;exit EDLIN. PRE_LOAD_MESSAGE
; has said why we are exiting
mov al,00h ;an000
int 21h ;an000;exit
; $endif ;an000;
$$IF1:
VERS_OK:
;----- Check for valid drive specifier --------------------------------;
pop ax
OR AL,AL
JZ get_switch_char
mov ax,BADDRV
jmp zerror
get_switch_char:
MOV AX,(CHAR_OPER SHL 8) ;GET SWITCH CHARACTER
INT 21H
CMP DL,"/"
JNZ CMD_LINE ;IF NOT / , THEN NOT PC
MOV OPTCHAR,"/" ;IN PC, OPTION CHAR = /
IFDEF DBCS
push ds ; SAVE! all regs destroyed on this
push es
push si ; call !!
mov ax,(ECS_call shl 8) or 00h ; get kanji lead tbl
int 21h
assume ds:nothing
assume es:nothing
mov word ptr [LBTbl],si
mov word ptr [LBTbl+2],ds
pop si
pop es
pop ds
assume ds:dg
assume es:dg
ENDIF
CMD_LINE:
push cs
pop es
ASSUME ES:DG
;----- Process any options ------------------------------------------;
;=========================================================================
; The system parser, called through PARSER_COMMAND, parses external
; command lines. In the case of EDLIN we are looking for two parameters
; on the command line.
;
; Parameter 1 - Filespec (REQUIRED)
; Parameter 2 - \B switch (OPTIONAL)
;
; PARSER_COMMAND - exit_normal : ffffh
; exit_error : not = ffffh
;=========================================================================
call PARSER_COMMAND ;an000;invoke sysparse
; DMS:6/11/87
; Check for /? switch.
; If so, display the options
; and exit.
;
; This is done first so that if the user typed
; /? along with unknown commands, they can get
; a coherent message without being over-errored.
;
; 4/17/90 c-PaulB
cmp [parse_switch_?], true ; is the /? switch on?
jne CheckOptionsDone ; skip the rest of this if not
mov ax,dsp_options
call display_message
mov al, 0 ; get an okay exit code
mov ah, exit ; and
int 21h ; bail out.
CheckOptionsDone:
cmp ax,nrm_parse_exit ;an000;was it a good parse
; $if z ;an000;it was a good parse
JNZ $$IF3
call EDLIN_COMMAND ;an000;interface results
; into EDLIN
; $else ;an000;
JMP SHORT $$EN3
$$IF3:
cmp ax,too_many ;an000;too many operands
; $if z ;an000;we have too many
JNZ $$IF5
jmp short badopt ;an000;say why and exit
; $endif
$$IF5:
cmp ax,op_missing ;an000;required parm missing
; $if z ;an000;missing parm
JNZ $$IF7
ifdef DBCS
jmp noname ;an000;say why and exit
else
jmp short noname ;an000;say why and exit
endif
; $endif ;an000;
$$IF7:
cmp ax,sw_missing ;an000;is it an invalid switch
; $if z ;an000;invalid switch
JNZ $$IF9
jmp short badopt ;an000;say why and exit
; $endif ;an000;
$$IF9:
; $endif ;an000;
$$EN3:
;=========================================================================
;======================= begin .BAK check ================================
; Check for .BAK extension on the filename
push ds ;an000;save reg.
push cs ;an000;set up addressibility
pop ds ;an000;
assume ds:dg ;an000;
push ax ;an000;save reg.
mov ax,offset dg:path_name ;an000;point to path_name
add ax,[fname_len] ;an000;calculate end of path_name
mov si,ax ;an000;point to end of path_name
pop ax ;an000;restore reg.
MOV CX,4 ;compare 4 bytes
SUB SI,4 ;Point 4th to last char
MOV DI,OFFSET DG:BAK ;Point to string ".BAK"
REPE CMPSB ;Compare the two strings
pop ds
ASSUME DS:NOTHING
JNZ NOTBAK
JMP HAVBAK
;======================= end .BAK check ==================================
;======================= begin NOTBAK ====================================
; we have a file without a .BAK extension, try to open it
NOTBAK:
push ds
push cs
pop ds
ASSUME DS:DG
;=========================================================================
; implement EXTENDED OPEN
;=========================================================================
push es ;an000;save reg.
mov bx,RW ;an000;open for read/write
mov cx,ATTR ;an000;file attributes
mov dx,RW_FLAG ;an000;action to take on open
mov di,0ffffh ;an000;nul parm list
call EXT_OPEN1 ;an000;open for R/W;DMS:6/10/87
pop es ;an000;restore reg.
;=========================================================================
pop ds
ASSUME DS:NOTHING
JC CHK_OPEN_ERR ;an open error occurred
MOV RD_HANDLE,AX ;Save the handle
Jmp HavFil ;work with the opened file
;======================= end NOTBAK ======================================
Badopt:
MOV DX,OFFSET DG:OPT_ERR_ptr;Bad option specified
JMP XERROR
;=========================================================================
;
; The open of the file failed. We need to figure out why and report the
; correct message. The circumstances we can handle are:
;
; open returns pathnotfound => bad drive or file name
; open returns toomanyopenfiles => too many open files
; open returns access denied =>
; chmod indicates read-only => cannot edit read only file
; else => file creation error
; open returns filenotfound =>
; creat ok => close, delete, new file
; creat fails => file creation error
; else => file cre
;
CHK_OPEN_ERR:
cmp ax,error_path_not_found
jz BadDriveError
cmp ax,error_too_many_open_files
jz TooManyError
cmp ax,error_access_denied
jnz CheckFNF
push ds
push cs
pop ds
assume ds:dg
mov ax,(chmod shl 8)
MOV DX,OFFSET DG:PATH_NAME
int 21h
jc FileCreationError
test cx,attr_read_only
jz FileCreationError
jmp short ReadOnlyError
CheckFNF:
cmp ax,error_file_not_found
jnz FileCreationError
;
; Try to create the file to see if it is OK.
;
push ds
push cs
pop ds
assume ds:dg
;=========================================================================
; implement EXTENDED OPEN
;=========================================================================
mov bx,RW ;an000;open for read/write
mov cx,ATTR ;an000;file attributes
mov dx,CREAT_FLAG ;an000;action to take on open
mov di,0ffffh ;an000;null parm list
call EXT_OPEN1 ;an000;create file;DMS:6/10/87
;=========================================================================
pop ds
assume ds:nothing
jc CreateCheck
mov bx,ax
mov ah,close
int 21h
push ds
push cs
pop ds
assume ds:dg
mov ah,unlink
MOV DX,OFFSET DG:PATH_NAME
int 21h
pop ds
assume ds:nothing
jc FileCreationError ; This should NEVER be taken!!!
MOV HAVEOF,0FFH ; Flag from a system 1.xx call
MOV fNew,-1
JMP short HAVFIL
CreateCheck:
cmp ax,error_access_denied
jnz BadDriveError
DiskFull:
mov ax,NODIR
jmp zerror
FileCreationError:
mov ax,bcreat
jmp zerror
ReadOnlyError:
mov ax,RO_ERR
jmp zerror
BadDriveError:
mov ax,BADDRV
jmp zerror
TooManyError:
mov ax,msg_too_many
jmp zerror
CREAT_ERR:
CMP DELFLG,0
JNZ DiskFull
push cs
pop ds
CALL DELBAK
JMP short MAKFIL
HAVBAK:
mov ax,NOBAK
jmp zerror
HAVFIL:
push cs
pop ds
ASSUME DS:DG
CMP fNew,0
JZ MakeBak
mov ax,newfil
call display_message
MakeBak:
MOV SI,OFFSET DG:PATH_NAME
MOV CX,[FNAME_LEN]
PUSH CX
MOV DI,OFFSET DG:TEMP_PATH
REP MOVSB
DEC DI
MOV DX,DI
POP CX
MOV AL,"."
STD
REPNE SCASB
JZ FOUND_EXT
MOV DI,DX ;Point to last char in filename
FOUND_EXT:
CLD
INC DI
MOV [EXT_PTR],DI
MOV SI,OFFSET DG:$$$FILE
MOV CX,5
REP MOVSB
;Create .$$$ file to make sure directory has room
MAKFIL:
;=========================================================================
; implement EXTENDED OPEN
;=========================================================================
mov bx,RW ;an000;open for read/write
mov cx,ATTR ;an000;file attributes
mov dx,Creat_Open_Flag ;an000;action to take on open
cmp EA_Flag,True ;an000;EA_Buffer used?
; $if e ;an000;yes
JNE $$IF12
mov di,offset dg:EA_Parm_List ;an000; point to buffer
; $else ;an000;
JMP SHORT $$EN12
$$IF12:
mov di,0ffffh ;an000;nul parm list
; $endif ;an000;
$$EN12:
call EXT_OPEN2 ;an000;create file;DMS:6/10/87
;=========================================================================
JC CREAT_ERR
MOV [WRT_HANDLE],AX
;
; We determine the size of the available memory. Use the word in the PDB at
; [2] to determine the number of paragraphs. Then truncate this to 64K at
; most.
;
push ds ;save ds for size calc
mov ds,[org_ds]
MOV CX,DS:[2]
MOV DI,CS
SUB CX,DI
CMP CX,1000h
JBE GotSize
MOV CX,0FFFh
GotSize:
SHL CX,1
SHL CX,1
SHL CX,1
SHL CX,1
pop ds ;restore ds after size calc
DEC CX
MOV [LAST_MEM],CX
MOV DI,OFFSET DG:START
TEST fNew,-1
JNZ SAVEND
SUB CX,OFFSET DG:START ;Available memory
SHR CX,1 ;1/2 of available memory
MOV AX,CX
SHR CX,1 ;1/4 of available memory
MOV [ONE4TH],CX ;Save amount of 1/4 full
ADD CX,AX ;3/4 of available memory
MOV DX,CX
ADD DX,OFFSET DG:START
MOV [THREE4TH],DX ;Save pointer to 3/4 full
MOV DX,OFFSET DG:START
SAVEND:
CLD
MOV BYTE PTR [DI],1AH
MOV [ENDTXT],DI
MOV BYTE PTR [COMBUF],128
MOV BYTE PTR [EDITBUF],255
MOV BYTE PTR [EOL],10
MOV [POINTER],OFFSET DG:START
MOV [CURRENT],1
MOV ParamCt,1
MOV [PARAM1],0 ;M004 Leave room in memory, was -1
TEST fNew,-1
JNZ COMMAND
;
; The above setting of PARAM1 to -1 causes this call to APPEND to try to read
; in as many lines that will fit, BUT.... What we are doing is simulating
; the user issuing an APPEND command, and if the user asks for more lines
; than we get then an "Insufficient memory" error occurs. In this case we
; DO NOT want this error, we just want as many lines as possible read in.
; The twiddle of ENDING suppresses the memory error
;
MOV BYTE PTR [ENDING],1 ;Suppress memory errors
CALL APPEND
MOV ENDING,0 ; restore correct initial value
Break <Main command loop>
;
; Main read/parse/execute loop. We reset the stack all the time as there
; are routines that JMP back here. Don't blame me; Tim Paterson write this.
;
COMMAND:
push cs ;an000;set up addressibility
pop ds ;an000;
push cs ;an000;
pop es ;an000;
assume ds:dg,es:dg ;an000;
MOV SP, STACK
MOV AX,(SET_INTERRUPT_VECTOR SHL 8) OR 23H
MOV DX,OFFSET DG:ABORTCOM
INT 21H
mov ax,prompt
call display_message
MOV DX,OFFSET DG:COMBUF
MOV AH,STD_CON_STRING_INPUT
INT 21H
MOV [COMLINE],OFFSET DG:COMBUF + 2
mov ax,msg_lf
call display_message
PARSE:
MOV [PARAM2],0
MOV [PARAM3],0
MOV [PARAM4],0
mov [fourth],0 ;reset the fourth parameter flag
MOV QFLG,0
MOV SI,[COMLINE]
MOV BP,OFFSET DG:PARAM1
XOR DI,DI
CHKLP:
CALL GETNUM
;
; AL has first char after arg
;
MOV ds:[BP+DI],DX
ADD DI,2
MOV ParamCt,DI ; set up count of parameters
SHR ParamCt,1 ; convert to index (1-based)
CALL SKIP1 ; skip to next parameter
CMP AL,"," ; is there a comma?
jnz NOT_COMMA ; if not, then done with arguments
cmp di,8 ; **** maximum size of PARAM array!
jb CHKLP ; continue scanning if <4 PARAMS
jmp short COMERR
NOT_COMMA:
DEC SI ; point at char next
CALL Kill_BL ; skip all blanks
CMP AL,"?" ; is there a ?
JNZ DISPATCH ; no, got command letter
MOV QFLG,-1 ; signal query
CALL Kill_BL
DISPATCH:
CMP AL,5FH
JBE UPCASE
cmp al,"z"
ja upcase
AND AL,5FH
UPCASE:
MOV DI,OFFSET DG:COMTAB
mov cx,NUMCOM
REPNE SCASB
JNZ COMERR
SUB DI,1+OFFSET DG:COMTAB ; convert to index
MOV BX,DI
MOV AX,[PARAM2]
OR AX,AX
JZ PARMOK
CMP AX,[PARAM1]
JB COMERR ; Param. 2 must be >= param 1
PARMOK:
MOV [COMLINE],SI
SHL BX,1
CALL [BX+TABLE]
COMOVER:
MOV SI,[COMLINE]
CALL Kill_BL
CMP AL,0DH
JZ COMMANDJ
CMP AL,1AH
JZ DELIM
CMP AL,";"
JNZ NODELIM
DELIM:
INC SI
NODELIM:
DEC SI
MOV [COMLINE],SI
JMP PARSE
COMMANDJ:
JMP COMMAND
SKIP1:
DEC SI
CALL Kill_BL
ret1: return
Break <Range Checking and argument parsing>
;
; People call here. we need to reset the stack.
; Inputs: BX has param1
; Outputs: Returns if BX <= Param2
;
CHKRANGE:
CMP [PARAM2],0
retz
CMP BX,[PARAM2]
JBE RET1
POP DX ; clean up return address
COMERR:
mov ax,BADCOM
zcomerr1:
call display_message
jmp command
COMERR1:
call std_printf
JMP COMMAND
;
; GetNum parses off 1 argument from the command line. Argument forms are:
; nnn a number < 65536
; +nnn current line + number
; -nnn current line - number
; . current line
; # lastline + 1
;
;
GETNUM:
CALL Kill_BL
cmp di,6 ;Is this the fourth parameter?
jne sk1
mov [fourth],1 ;yes, set the flag
sk1:
CMP AL,"."
JZ CURLIN
CMP AL,"#"
JZ MAXLIN
CMP AL,"+"
JZ FORLIN
CMP AL,"-"
JZ BACKLIN
MOV DX,0
MOV CL,0 ;Flag no parameter seen yet
NUMLP:
CMP AL,"0"
JB NUMCHK
CMP AL,"9"
JA NUMCHK
CMP DX,6553 ;Max line/10
JAE COMERR ;Ten times this is too big
MOV CL,1 ;Parameter digit has been found
SUB AL,"0"
MOV BX,DX
SHL DX,1
SHL DX,1
ADD DX,BX
SHL DX,1
CBW
ADD DX,AX
LODSB
JMP SHORT NUMLP
NUMCHK:
CMP CL,0
retz
OR DX,DX
JZ COMERR ;Don't allow zero as a parameter
return
CURLIN:
cmp [fourth],1 ;the fourth parameter?
je comerra ;yes, an error
MOV DX,[CURRENT]
LODSB
return
MAXLIN:
cmp [fourth],1 ;the fourth parameter?
je comerra ;yes, an error
MOV DX,1
MOV AL,0Ah
PUSH DI
MOV DI,OFFSET DG:START
MOV CX,EndTxt
SUB CX,DI
MLoop:
JCXZ MDone
REPNZ SCASB
JNZ MDone
INC DX
JMP MLoop
MDone:
POP DI
LODSB
return
FORLIN:
cmp [fourth],1 ;the fourth parameter?
je comerra ;yes, an error
CALL GETNUM
ADD DX,[CURRENT]
return
BACKLIN:
cmp [fourth],1 ;the fourth parameter?
je comerra ;yes, an error
CALL GETNUM
MOV BX,[CURRENT]
SUB BX,DX
JA OkLin ; if negative or zero
MOV BX,1 ; use first line
OkLin:
MOV DX,BX
return
comerra:
jmp comerr
ERRORJ:
JMP COMERR
ERROR1J:
JMP zcomerr1
BLANKLINE:
cmp QFLG,0
jnz SHOWHELP ; if ? at front of blank line, do HELP
jmp NOCOM ; ignore blank line otherwise
SHOWHELP:
dec [COMLINE] ; point back to <cr>
mov cx,num_help_msgs-1
mov ax,dsp_help
SHOWHELP1:
call display_message
inc ax
loop SHOWHELP1
; fall into display_message for last message and return
;=========================================================================
; display_message : Displays a simple common message through the
; ; message retriever, using a common parameter
; ; block.
; Inputs : ax = message number to display
;
;=========================================================================
display_message proc near
mov dg:[simple_msg],ax
mov dx,offset dg:simple_msg
jmp printf ; display it
display_message endp
Break <Move and Copy commands>
PUBLIC MOVE
MOVE:
CMP ParamCt,3
JNZ ERRORJ
MOV BYTE PTR [MOVFLG],1
JMP SHORT BLKMOVE
PUBLIC COPY
COPY:
CMP ParamCt,3
JB ERRORJ
MOV BYTE PTR [MOVFLG],0
;
; We are to move/copy a number of lines from one range to another.
;
; Memory looks like this:
;
; START: line 1
; ...
; pointer-> line n Current has n in it
; ...
; line m
; endtxt-> ^Z
;
; The algoritm is:
;
; Bounds check on args.
; set ptr1 and ptr2 to range before move
; set copysiz to number to move
; open up copysize * count for destination
; if destination is before ptr1 then
; add copysize * count to both ptrs
; while count > 0 do
; move from ptr1 to destination for copysize bytes
; count --
; if moving then
; move from ptr2 through end to ptr1
; set endtxt to last byte moved.
; set current, pointer to original destination
;
BLKMOVE:
;
; Make sure that all correct arguments are specified.
;
MOV BX,[PARAM3] ; get destination of move/copy
OR BX,BX ; must be specified (non-0)
mov ax,DEST
JZ ERROR1J ; is 0 => error
;
; get arg 1 (defaulting if necessary) and range check it.
;
MOV BX,[PARAM1] ; get first argument
OR BX,BX ; do we default it?
JNZ NXTARG ; no, assume it is OK.
MOV BX,[CURRENT] ; Defaults to the current line
CALL CHKRANGE ; Make sure it is good.
MOV [PARAM1],BX ; set it
NXTARG:
CALL FINDLIN ; find first argument line
JNZ ErrorJ ; line not found
MOV [PTR_1],DI
;
; get arg 2 (defaulting if necessary) and range check it.
;
MOV BX,[PARAM2] ; Get the second parameter
OR BX,BX ; do we default it too?
JNZ HAVARGS ; Nope.
MOV BX,[CURRENT] ; Defaults to the current line
MOV [PARAM2],BX ; Stash it away
HAVARGS:
CALL FindLin
JNZ ErrorJ ; line not found
MOV BX,Param2
INC BX ;Get pointer to line Param2+1
CALL FINDLIN
MOV [PTR_2],DI ;Save it
;
; We now have true line number arguments and pointers to the relevant places.
; ptr_1 points to beginning of region and ptr_2 points to first byte beyond
; that region.
;
; Check args for correct ordering of first two arguments
;
mov dx,[param1]
cmp dx,[param2]
jbe havargs1 ; first must be <= second
jmp comerr
havargs1:
;
; make sure that the third argument is not contained in the first range
;
MOV DX,[PARAM3]
CMP DX,[PARAM1] ; third must be <= first or
JBE NOERROR
CMP DX,[PARAM2]
JA NoError ; third must be > last
JMP ComErr
NOERROR:
;
; Determine number to move
;
MOV CX,Ptr_2
SUB CX,Ptr_1 ; Calculate number of bytes to copy
MOV CopySiz,CX
MOV CopyLen,CX ; Save for individual move.
MOV AX,[PARAM4] ; Was count defaulted?
OR AX,AX
JZ SizeOk ; yes, CX has correct value
MUL [COPYSIZ] ; convert to true size
MOV CX,AX ; move to count register
OR DX,DX ; overflow?
JZ SizeOK ; no
JMP MEMERR ; yes, bomb.
SizeOK:
MOV [COPYSIZ],CX
;
; Check to see that we have room to grow by copysiz
;
MOV AX,[ENDTXT] ; get pointer to last byte
MOV DI,[LAST_MEM] ; get offset of last location in memory
SUB DI,AX ; remainder of space
CMP DI,CX ; is there at least copysiz room?
JAE HAV_ROOM ; yes
JMP MEMERR
HAV_ROOM:
;
; Find destination of move/copy
;
MOV BX,[PARAM3]
CALL FINDLIN
MOV [PTR_3],DI
;
; open up copysiz bytes of space at destination
;
; move (p3, p3+copysiz, endtxt-p3);
;
MOV SI,EndTxt ; get source pointer to end
MOV CX,SI
SUB CX,DI ; number of bytes from here to end
INC CX ; remember ^Z at end
MOV DI,SI ; destination starts at end
ADD DI,[COPYSIZ] ; plus size we are opening
MOV [ENDTXT],DI ; new end point
STD ; go backwards
REP MOVSB ; and store everything
CLD ; go forward
;
; relocate ptr_1 and ptr_2 if we moved them
;
MOV BX,Ptr_3
CMP BX,Ptr_1 ; was dest before source?
JA NoReloc ; no, above. no relocation
MOV BX,CopySiz
ADD Ptr_1,BX
ADD Ptr_2,BX ; relocate pointers
NoReloc:
;
; Now we copy for count times copylen bytes from ptr_1 to ptr_3
;
; move (ptr_1, ptr_3, copylen);
;
MOV BX,Param4 ; count (0 and 1 are both 1)
MOV DI,Ptr_3 ; destination
CopyText:
MOV CX,CopyLen ; number to move
MOV SI,Ptr_1 ; start point
REP MOVSB ; move the bytes
SUB BX,1 ; exhaust count?
JG CopyText ; no, go for more
;
; If we are moving
;
CMP BYTE PTR MovFlg,0
JZ CopyDone
;
; Delete the source text between ptr_1 and ptr_2
;
; move (ptr_2, ptr_1, endtxt-ptr_2);
;
MOV DI,Ptr_1 ; destination
MOV SI,Ptr_2 ; source
MOV CX,EndTxt ; pointer to end
SUB CX,SI ; number of bytes to move
CLD ; forwards
REP MOVSB
MOV BYTE PTR ES:[DI],1Ah ; remember ^Z terminate
MOV EndTxt,DI ; new end of file
;
; May need to relocate current line (parameter 3).
;
MOV BX,Param3 ; get new current line
CMP BX,Param1 ; do we need to relocate
JBE CopyDone ; no, current line is before removed M002
ADD BX,Param1 ; add in first
SUB BX,Param2 ; current += first-last - 1;
DEC BX
MOV Param3,BX
CopyDone:
;
; we are done. Make current line the destination
;
MOV BX,Param3 ; set parameter 3 to be current
CALL FINDLIN
MOV [POINTER],DI
MOV [CURRENT],BX
return
Break <MoveFile - open up a hole in the internal file>
;
; MoveFile moves the text in the buffer to create a hole
;
; Inputs: DX is spot in buffer for destination
; DI is spot in buffer for source
MOVEFILE:
MOV CX,[ENDTXT] ;Get End-of-text marker
MOV SI,CX
SUB CX,DI ;Calculate number of bytes to copy
INC CX ; remember ^Z
MOV DI,DX
STD
REP MOVSB ;Copy CX bytes
XCHG SI,DI
CLD
INC DI
MOV BP,SI
SETPTS:
MOV [POINTER],DI ;Current line is first free loc
MOV [CURRENT],BX ; in the file
MOV [ENDTXT],BP ;End-of-text is last free loc before
return
NAMERR:
cmp ax,error_file_not_found
jne otherMergeErr
MOV DX,OFFSET DG:FILENM_ptr
JMP COMERR1
otherMergeErr:
mov ax,BADDRV
jmp zcomerr1
PUBLIC MERGE
MERGE:
CMP ParamCt,1
JZ MergeOK
JMP Comerr
MergeOK:
CALL KILL_BL
DEC SI
MOV DI,OFFSET DG:MRG_PATH_NAME
XOR CX,CX
CLD
MRG1:
LODSB
CMP AL," "
JE MRG2
CMP AL,9
JE MRG2
CMP AL,CR
JE MRG2
CMP AL,";"
JE MRG2
STOSB
JMP SHORT MRG1
MRG2:
MOV BYTE PTR[DI],0
DEC SI
MOV [COMLINE],SI
;=========================================================================
; implement EXTENDED OPEN
;=========================================================================
push es ;an000;save reg.
mov bx,ext_read ;an000;open for read
mov cx,ATTR ;an000;file attributes
mov dx,OPEN_FLAG ;an000;action to take on open
mov di,0ffffh ;an000;null parm list
call EXT_OPEN3 ;an000;create file;DMS:6/10/87
pop es ;an000;restore reg.
;=========================================================================
JC NAMERR
MOV [MRG_HANDLE],AX
MOV AX,(SET_INTERRUPT_VECTOR SHL 8) OR 23H
MOV DX,OFFSET DG:ABORTMERGE
INT 21H
MOV BX,[PARAM1]
OR BX,BX
JNZ MRG
MOV BX,[CURRENT]
CALL CHKRANGE
MRG:
CALL FINDLIN
MOV BX,DX
MOV DX,[LAST_MEM]
CALL MOVEFILE
MOV DX,[POINTER]
MOV CX,[ENDTXT]
SUB CX,[POINTER]
PUSH CX
MOV BX,[MRG_HANDLE]
MOV AH,READ
INT 21H
POP DX
MOV CX,AX
CMP DX,CX
JA FILEMRG ; M005
mov ax,mrgerr
call display_message
MOV CX,[POINTER]
JMP SHORT RESTORE_Z
FILEMRG:
ADD CX,[POINTER]
MOV SI,CX
dec si
LODSB
CMP AL,1AH
JNZ RESTORE_Z
dec cx
RESTORE_Z:
MOV DI,CX
MOV SI,[ENDTXT]
INC SI
MOV CX,[LAST_MEM]
SUB CX,SI
inc cx ; remember ^Z
REP MOVSB
dec di ; unremember ^Z
MOV [ENDTXT],DI
MOV BX,[MRG_HANDLE]
MOV AH,CLOSE
INT 21H
return
PUBLIC INSERT
INSERT:
CMP ParamCt,1
JBE OKIns
JMP ComErr
OKIns:
MOV AX,(SET_INTERRUPT_VECTOR SHL 8) OR 23H ;Set vector 23H
MOV DX,OFFSET DG:ABORTINS
INT 21H
MOV BX,[PARAM1]
OR BX,BX
JNZ INS
MOV BX,[CURRENT]
CALL CHKRANGE
INS:
CALL FINDLIN
MOV BX,DX
MOV DX,[LAST_MEM]
CALL MOVEFILE
INLP:
CALL SETPTS ;Update the pointers into file
CALL SHOWNUM
MOV DX,OFFSET DG:EDITBUF
MOV AH,STD_CON_STRING_INPUT
INT 21H
CALL LF
MOV SI,2 + OFFSET DG:EDITBUF
CMP BYTE PTR [SI],1AH
JZ ENDINS
;-----------------------------------------------------------------------
call unquote ;scan for quote chars if any
;-----------------------------------------------------------------------
MOV CL,[SI-1]
MOV CH,0
MOV DX,DI
INC CX
ADD DX,CX
JC MEMERRJ1
JZ MEMERRJ1
CMP DX,BP
JB MEMOK
MEMERRJ1:
CALL END_INS
JMP MEMERR
MEMOK:
REP MOVSB
MOV AL,10
STOSB
INC BX
JMP SHORT INLP
ABORTMERGE:
MOV DX,OFFSET DG:START
MOV AH,SET_DMA
INT 21H
ABORTINS:
MOV AX,CS ;Restore segment registers
MOV DS,AX
MOV ES,AX
MOV AX,CSTACK
MOV SS,AX
MOV SP,STACK
STI
CALL CRLF
CALL ENDINS
JMP COMOVER
ENDINS:
CALL END_INS
return
END_INS:
MOV BP,[ENDTXT]
MOV DI,[POINTER]
MOV SI,BP
INC SI
MOV CX,[LAST_MEM]
SUB CX,BP
REP MOVSB
DEC DI
MOV [ENDTXT],DI
MOV AX,(SET_INTERRUPT_VECTOR SHL 8) OR 23H
MOV DX,OFFSET DG:ABORTCOM
INT 21H
return
FILLBUF:
MOV [PARAM1],-1 ;Read in max. no of lines
MOV ParamCt,1
CALL APPEND
MOV Param1,0
PUBLIC ENDED
ENDED:
;Write text out to .$$$ file
CMP ParamCt,1
JZ ENDED1
CERR: JMP ComErr
Ended1:
CMP Param1,0
JNZ Cerr
MOV BYTE PTR [ENDING],1 ;Suppress memory errors
MOV BX,-1 ;Write max. no of lines
CALL WRT
TEST BYTE PTR [HAVEOF],-1
JZ FILLBUF
MOV DX,[ENDTXT]
MOV CX,1
MOV BX,[WRT_HANDLE]
MOV AH,WRITE
INT 21H ;Write end-of-file byte
;Close input file ; MZ 11/30
; MZ 11/30
MOV BX,[RD_HANDLE] ; MZ 11/30
MOV AH,CLOSE ; MZ 11/30
INT 21H ; MZ 11/30
;Close .$$$ file
MOV BX,[WRT_HANDLE]
MOV AH,CLOSE
INT 21H
;Rename original file .BAK
MOV DI,[EXT_PTR]
MOV SI,OFFSET DG:BAK
MOVSW
MOVSW
MOVSB
MOV DX,OFFSET DG:PATH_NAME
MOV DI,OFFSET DG:TEMP_PATH
MOV AH,RENAME
INT 21H
MOV DI,[EXT_PTR]
MOV SI,OFFSET DG:$$$FILE
MOVSW
MOVSW
MOVSB
;Rename .$$$ file to original name
MOV DX,OFFSET DG:TEMP_PATH
MOV DI,OFFSET DG:PATH_NAME
MOV AH,RENAME
INT 21H
; mode
mov ah,exit
xor al,al
int 21h
;=========================================================================
; EDLIN_DISP_GET: This routine will give us the attributes of the
; current display, which are to be used to restore the screen
; back to its original state on exit from EDLIN. We also
; set the screen to a text mode here with an 80 X 25 color
; format.
;
; Inputs : VIDEO_GET - 0fH (get current video mode)
; VIDEO_SET - 00h (set video mode)
; VIDEO_TEXT- 03h (80 X 25 color mode)
;
; Outputs : VIDEO_ORG - Original video attributes on entry to EDLIN
;
;=========================================================================
EDLIN_DISP_GET proc near ;an000;video attributes
push ax ;an000;save affected regs.
push bx ;an000;
push cx ;an000;
push dx ;an000;
push si ;an000;
push ds ;an000;
push cs ;an000;exchange cs/ds
pop ds ;an000;
mov ax,440Ch ;an000;generic ioctl
mov bx,Std_Out ;an000;Console
mov cx,(Display_Attr shl 8) or Get_Display ;an000;get display
mov dx,offset dg:Video_Buffer ;an000;buffer for video attr.
int 21h ;an000;
; $if nc ;an000;function returned a
JC $$IF15
; buffer
mov si,dx ;an000;get pointer
mov ax,word ptr dg:[si].Display_Length_Char ;an000;get video len.
dec ax ;an000;allow room for message
mov dg:Disp_Len,al ;an000;put it into var.
mov ax,word ptr dg:[si].Display_Width_Char ;an000;get video width
mov dg:Disp_Width,al ;an000;put it into var.
; $else ;an000;function failed use
JMP SHORT $$EN15
$$IF15:
; default values
mov al,Def_Disp_Len ;an000;get default length
dec al ;an000;leave room for messages
mov dg:Disp_Len,al ;an000;use default length
mov dg:Disp_Width,Def_Disp_Width;an000;use default width
; $endif ;an000;
$$EN15:
pop ds ;an000;restore affected regs.
pop si ;an000;
pop dx ;an000;
pop cx ;an000;
pop bx ;an000;
pop ax ;an000;
ret ;an000;return to caller
EDLIN_DISP_GET endp ;an000;end proc.
;=========================================================================
; EXT_OPEN1 : This routine opens a file for read/write access. If the file
; if not present for opening the open will fail and return with a
; carry set.
;
; Inputs : BX - Open mode
; CX - File attributes
; DX - Open action
;
; Outputs: CY - If error
;
; Date : 6/10/87
;=========================================================================
EXT_OPEN1 proc near ;an000;open for R/W
assume ds:dg
push ds ;an000;save regs
push si ;an000;
mov ah,ExtOpen ;an000;extended open
mov al,0 ;an000;reserved by system
mov si,offset dg:path_name ;an000;point to PATH_NAME
int 21h ;an000;invoke function
pop si ;an000;restore regs
pop ds ;an000;
ret ;an000;return to caller
EXT_OPEN1 endp ;an000;end proc.
;=========================================================================
; EXT_OPEN2 : This routine will attempt to create a file for read/write
; access. If the files exists the create will fail and return
; with the carry set.
;
; Inputs : BX - Open mode
; CX - File attributes
; DX - Open action
;
; Outputs: CY - If error
;
; Date : 6/10/87
;=========================================================================
EXT_OPEN2 proc near ;an000;create a file
assume ds:dg
push ds ;an000;save regs
push si ;an000;
mov ah,ExtOpen ;an000;extended open
mov al,0 ;an000;reserved by system
mov si,offset dg:temp_path ;an000;point to TEMP_PATH
int 21h ;an000;invoke function
pop si ;an000;restore regs
pop ds ;an000;
ret ;an000;return to caller
EXT_OPEN2 endp ;an000;end proc.
;=========================================================================
; EXT_OPEN3 : This routine will attempt to create a file for read
; access. If the files exists the create will fail and return
; with the carry set.
;
; Inputs : BX - Open mode
; CX - File attributes
; DX - Open action
;
; Outputs: CY - If error
;
; Date : 6/10/87
;=========================================================================
EXT_OPEN3 proc near ;an000;create a file
assume ds:dg
push ds ;an000;save regs
push si ;an000;
mov ah,ExtOpen ;an000;extended open
mov al,0 ;an000;reserved by system
mov si,offset dg:mrg_path_name ;an000;point to mrg_path_name
int 21h ;an000;invoke function
pop si ;an000;restore regs
pop ds ;an000;
ret ;an000;return to caller
EXT_OPEN3 endp ;an000;end proc.
;=========================================================================
; EDLIN_COMMAND : This routine provides an interface between the new
; parser and the existing logic of EDLIN. We will be
; interfacing the parser with three existing variables.
;
; Inputs : FILESPEC - Filespec entered by the user and passed by
; the parser.
;
; PARSE_SWITCH_B - Contains the result of the parse for the
; /B switch. This is passed by the parser.
;
; Outputs: PATH_NAME - Filespec
; LOADMOD - Flag for /B switch
; FNAME_LEN - Length of filespec
;
; Date : 6/11/87
;=========================================================================
EDLIN_COMMAND proc near ;an000;interface parser
push ax ;an000;save regs.
push cx ;an000;
push di ;an000
push si ;an000;
mov si,offset dg:filespec ;an000;get its offset
mov di,offset dg:path_name ;an000;get its offset
mov cx,00h ;an000;cx will count filespec
; length
cmp parse_switch_b,true ;an000;do we have /B switch
; $if z ;an000;we have the switch
JNZ $$IF18
mov [LOADMOD],01h ;an000;signal switch found
; $endif ;an000
$$IF18:
; $do ;an000;while we have filespec
$$DO20:
lodsb ;an000;move byte to al
cmp al,nul ;an000;see if we are at
; the end of the
; filespec
; $leave e ;an000;exit while loop
JE $$EN20
stosb ;an000;move byte to path_name
inc cx ;an000;increment the length
; of the filespec
; $enddo ;an000;end do while
JMP SHORT $$DO20
$$EN20:
mov [FNAME_LEN],cx ;an000;save filespec's length
pop si ;an000; restore regs
pop di ;an000;
pop cx ;an000;
pop ax ;an000;
ret ;an000;return to caller
EDLIN_COMMAND endp ;an000;end proc
;=========================================================================
; Calc_Memory_Avail : This routine will calculate the memory
; available for use by EDLIN.
;
; Inputs : ORG_DS - DS of PSP
;
; Outputs : DX - paras available
;=========================================================================
Calc_Memory_Avail proc near ;an000; dms;
push ds ;save ds for size calc
push cx ;an000; dms;
push di ;an000; dms;
mov ds,cs:[org_ds]
MOV CX,DS:[2]
MOV DI,CS
SUB CX,DI
mov dx,cx ;an000; dms;put paras in DX
pop di ;an000; dms;
pop cx ;an000; dms;
pop ds ;an000; dms;
ret ;an000; dms;
Calc_Memory_Avail endp ;an000; dms;
;=========================================================================
; EA_Fail_Exit : This routine tells the user that there was
; Insufficient memory and exits EDLIN.
;
; Inputs : MemFul_Ptr - "Insufficient memory"
;
; Outputs : message
;=========================================================================
EA_Fail_Exit proc near ;an000; dms;
mov dx,offset dg:MemFul_Ptr ;an000; dms;"Insufficient
push cs ;an000; dms;xchange ds/cs
pop ds ;an000; dms;
; memory"
call Std_Printf ;an000; dms;print message
mov ah,exit ;an000; dms;exit
xor al,al ;an000; dms;clear al
int 21h ;an000; dms;
ret ;an000; dms;
EA_Fail_Exit endp ;an000; dms;
CODE ENDS
END EDLIN
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %rbp
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WT_ht+0x12e81, %rcx
add $50788, %r11
mov $0x6162636465666768, %rdi
movq %rdi, %xmm2
movups %xmm2, (%rcx)
nop
nop
nop
nop
and $47867, %r11
lea addresses_normal_ht+0x2f63, %rsi
nop
nop
nop
nop
nop
xor %rbx, %rbx
movb $0x61, (%rsi)
nop
and $12185, %rbx
lea addresses_UC_ht+0xb8f, %rdx
nop
nop
nop
nop
dec %rbp
mov (%rdx), %esi
nop
nop
nop
xor $28423, %r11
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r15
push %r9
push %rax
push %rbp
// Store
mov $0x3ed01c0000000755, %r10
nop
sub $27007, %r12
mov $0x5152535455565758, %rbp
movq %rbp, (%r10)
nop
nop
nop
dec %rbp
// Faulty Load
lea addresses_WC+0x18b35, %rbp
nop
xor $64637, %r9
mov (%rbp), %r15d
lea oracles, %rbp
and $0xff, %r15
shlq $12, %r15
mov (%rbp,%r15,1), %r15
pop %rbp
pop %rax
pop %r9
pop %r15
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_WC', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_NC', 'same': False, 'AVXalign': False, 'congruent': 5}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_WC', 'same': True, 'AVXalign': False, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'size': 1, 'NT': True, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 1}}
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_UC_ht', 'same': True, 'AVXalign': True, 'congruent': 1}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
.data
textA: .asciiz "+ Nhap so a = "
textB: .asciiz "+ Nhap so b = "
soA: .float 0
soB: .float 0
kq1: .asciiz " \n+ Ket qua : \n\t a + b = "
kq2: .asciiz " \n\t a - b = "
.text
#Nhap so thu nhat
la $a0,textA
li $v0,4
syscall
li $v0,6
syscall
swc1 $f0,soA
#Nhap so thu 2
la $a0,textB
li $v0,4
syscall
li $v0,6
syscall
swc1 $f0,soB
#Chuyen du lieu sang ma nhi phan
lw $a1,soA
lw $a2,soB
#Tach cac truong cua ma nhi phan 32 bit
srl $t1,$a1,31 #truong sign cua so A = $t1
srl $t2,$a2,31 #truong sign cua so B = $t2
move $t8,$t1
move $t9,$t2
sll $t3,$a1,1 #Tim truong Exponent cua so A
srl $t3,$t3,24
subi $t3,$t3,127#Exponent A = t3
sll $t4,$a2,1 #Tim truong Exponent cua so B
srl $t4,$t4,24
subi $t4,$t4,127#Exponent B = t4
sll $t5,$a1,9 #Tim truong fraction cua so A
srl $t5,$t5,9
ori $t5,$t5,0x00800000# t5 = 1bit + fraction A
sll $t6,$a2,9 #Tim truong fraction cua so B
srl $t6,$t6,9
ori $t6,$t6,0x00800000# t6 = 1bit + fraction B
###### BUOC 1: So sanh cac truong va chon dau cho phep (+) va (-)
slt $s0,$t3,$t4 #So sanh Exponent A va Exponent B
beq $s0,1,A_N_B# A<B
j A_LB_B# A >= B
A_LB_B: bne $t3,$t4,A_L_B# A > B
slt $s0,$t5,$t6 #So sanh fraction A va fraction B
beq $s0,1,A_N_B # A < B
beq $t5,$t6,SSExp # A == B
j A_L_B #A>B
A_L_B: addi $s6,$t1,0 #s6 = bit dau cua phep +
addi $s7,$t1,0 #s7 = bit dau cua phep -
j ThucThi
A_N_B:
addi $s6,$t2,0
xor $s7,$t2,1
j ThucThi
SSExp: beq $t3,-127,man0
beq $t1,$t2,A_B_B #So sanh Sign A va sign B
addi $s6,$0,0 #A = - B
addi $s7,$t1,0
j ThucThi
A_B_B: addi $s6,$t1,1
xor $s7,$0,0
j ThucThi
man0: beq $t5,0x00800000,result0 #Truong hop 2 so deu bang 0
###### BUOC 2: Thuc hien phep (+),(-) tren truong Exponent, fraction cua so A va B
ThucThi:
slt $s1,$t3,$t4 #So sanh Exponent A va Exponent B
beq $s1,0,NoSwap
#Doi cho Sign giua A va B
move $s0,$t3
move $t3,$t4
move $t4,$s0
#Doi cho Exponent giua A va B
move $s0,$t5
move $t5,$t6
move $t6,$s0
#Doi cho fraction giua A va B
move $s0,$t1
move $t1,$t2
move $t2,$s0
NoSwap:
sub $s1,$t3,$t4
move $t4,$t3 # copy t3 vao t4 de tinh toan cho phep "-"
dich: addi $s0,$0,0 # t2 la bo dem so mu
loop: slt $s2,$s0,$s1
beq $s2,0,Add
srl $t6,$t6,1 # Dich sang phai truong Fraction cua so B (EA-EB) bit
addi $s0,$s0,1
j loop
#Thuc hien phep + truong fraction giua so A va V
Add: add $s3,$t5,$t6
addi $s0,$0,0x01000000
LoopB1: slt $s5,$s3,$s0 # so sanh s3 co lon hon 23 bit khong ?
beq $s5,1,Sub
srl $s3,$s3,1 # Neu co thi Dich truong Fraction sang phai 1bit
addi $t3,$t3,1 # Neu co thi Tang truong Exponent them 1
j LoopB1
#Thuc hien phep - truong fraction giua so A va V
Sub: beq $s1,0,A_BF_B # Fraction A = Fraction B
A_K_B: sub $s4,$t5,$t6
abs $s4,$s4
addi $s0,$0,0x007fffff
LoopB2: slt $s5,$s0,$s4 #So sanh s5 co nho hon 23 bit khong ?
beq $s5,1,IEEE
sll $s4,$s4,1 # Neu co thi Dich truong Fraction sang trai 1bit
subi $t4,$t4,1 # Neu co thi giam truong Exponent bot 1
j LoopB2
A_BF_B: bne $t5,$t6,A_K_B
addi $s4,$0,-1 # Exponent A = Exponent B => Ket qua phep (-) = 0
###### BUOC 3: Chuan hoa cac truong fraction v� exponent cua ket qua phep (+),(-)
IEEE:
# Ket qua cua phep (+)
sll $s6,$s6,31 # Chuyen bit Sign cua phep (+) vao dung vi tri
addi $s1,$t3,127 # s1 la 8-bit E
sll $s1,$s1,23 # chuyen bit E vao dung vi tri
sll $s3,$s3,9
srl $s3,$s3,9 # loai bo so 1 ==> s3 la truong fraction cua phep (+)
or $s2,$s1,$s3 # dua truong exponent va fraction vao ket qua phep (+)
# Ket qua cua phep (-)
sll $s7,$s7,31 # Chuyen bit Sign cua phep (-) vao dung vi tri
beq $s4,-1,Bang0 # Neu s4 = -1, tra ket qua phep (-) = 0
addi $s1,$t4,127 # s1 la 8-bit E
sll $s1,$s1,23 # -chuyen bit E vao dung vi tri
sll $s4,$s4,9
srl $s4,$s4,9 # loai bo so 1 ==> s3 la truong fraction cua phep (-)
or $s4,$s1,$s4 # dua truong exponent va fraction vao ket qua phep (-)
j Sign
Bang0: addi $s4,$0,0 # tra ket qua phep (-) = 0
##### Luu truong Sign va chon ket qua cua phep (+) va (-)
Sign: beq $t8,$t9,A_cd_B
j A_kd_B
A_cd_B: # A va B cung dau
or $v0,$s6,$s2 # |a+b| = |a| + |b|
or $v1,$s7,$s4 # |a-b| = ||a| - |b||
j trans # A va B khac dau
A_kd_B: or $v0,$s6,$s4 # |a+b| = ||a| - |b||
or $v1,$s7,$s2 # |a-b| = |a| + |b|
j trans
result0:# truong hop hai so deu bang 0
li $v0,0
li $v1,0
trans:
mtc1 $v0,$f1 # v0 la gia tri phep + theo chuan IEEE 754
mtc1 $v1,$f2 # v1 la gia tri phep - theo chuan IEEE 754
###### xuat kq ra man hinh
#In ket qua phep (+)
li $v0,4
la $a0,kq1
syscall
mov.s $f12,$f1
li $v0,2
syscall
#In ket qua phep (-)
li $v0,4
la $a0,kq2
syscall
mov.s $f12,$f2
li $v0,2
syscall
mfc1 $v0,$f1
li $v0,10 #Ket thuc chuong trinh
syscall
|
user/_strace: file format elf64-littleriscv
Disassembly of section .text:
0000000000000000 <main>:
#include "user/user.h"
//user program for strace
int
main(int argc, char *argv[])
{
0: 7179 addi sp,sp,-48
2: f406 sd ra,40(sp)
4: f022 sd s0,32(sp)
6: ec26 sd s1,24(sp)
8: e84a sd s2,16(sp)
a: e44e sd s3,8(sp)
c: 1800 addi s0,sp,48
int mask;
if (argc <= 2)
e: 4789 li a5,2
10: 02a7c063 blt a5,a0,30 <main+0x30>
{
fprintf(2, "Invalid syntax\n");
14: 00001597 auipc a1,0x1
18: 84c58593 addi a1,a1,-1972 # 860 <malloc+0xea>
1c: 4509 li a0,2
1e: 00000097 auipc ra,0x0
22: 66c080e7 jalr 1644(ra) # 68a <fprintf>
exit(1);
26: 4505 li a0,1
28: 00000097 auipc ra,0x0
2c: 300080e7 jalr 768(ra) # 328 <exit>
30: 84aa mv s1,a0
32: 892e mv s2,a1
}
mask = atoi(argv[1]);
34: 6588 ld a0,8(a1)
36: 00000097 auipc ra,0x0
3a: 1f2080e7 jalr 498(ra) # 228 <atoi>
trace(mask);
3e: 00000097 auipc ra,0x0
42: 38a080e7 jalr 906(ra) # 3c8 <trace>
// Executing the command which we have to trace until it exits
char *execargs[argc - 1];
46: fff4879b addiw a5,s1,-1
4a: 078e slli a5,a5,0x3
4c: 07bd addi a5,a5,15
4e: 9bc1 andi a5,a5,-16
50: 40f10133 sub sp,sp,a5
54: 898a mv s3,sp
for (int i = 0; i < argc - 2; i++)
56: ffe4859b addiw a1,s1,-2
5a: 01090793 addi a5,s2,16
5e: 874e mv a4,s3
60: ffd4869b addiw a3,s1,-3
64: 1682 slli a3,a3,0x20
66: 9281 srli a3,a3,0x20
68: 068e slli a3,a3,0x3
6a: 0961 addi s2,s2,24
6c: 96ca add a3,a3,s2
{
execargs[i] = argv[i + 2];
6e: 6390 ld a2,0(a5)
70: e310 sd a2,0(a4)
for (int i = 0; i < argc - 2; i++)
72: 07a1 addi a5,a5,8
74: 0721 addi a4,a4,8
76: fed79ce3 bne a5,a3,6e <main+0x6e>
}
execargs[argc - 2] = 0;
7a: 00359793 slli a5,a1,0x3
7e: 97ce add a5,a5,s3
80: 0007b023 sd zero,0(a5)
exec(execargs[0], execargs);
84: 85ce mv a1,s3
86: 0009b503 ld a0,0(s3)
8a: 00000097 auipc ra,0x0
8e: 2d6080e7 jalr 726(ra) # 360 <exec>
fprintf(2, "exec of %s failed\n", execargs[0]);
92: 0009b603 ld a2,0(s3)
96: 00000597 auipc a1,0x0
9a: 7da58593 addi a1,a1,2010 # 870 <malloc+0xfa>
9e: 4509 li a0,2
a0: 00000097 auipc ra,0x0
a4: 5ea080e7 jalr 1514(ra) # 68a <fprintf>
exit(0);
a8: 4501 li a0,0
aa: 00000097 auipc ra,0x0
ae: 27e080e7 jalr 638(ra) # 328 <exit>
00000000000000b2 <strcpy>:
#include "kernel/fcntl.h"
#include "user/user.h"
char*
strcpy(char *s, const char *t)
{
b2: 1141 addi sp,sp,-16
b4: e422 sd s0,8(sp)
b6: 0800 addi s0,sp,16
char *os;
os = s;
while((*s++ = *t++) != 0)
b8: 87aa mv a5,a0
ba: 0585 addi a1,a1,1
bc: 0785 addi a5,a5,1
be: fff5c703 lbu a4,-1(a1)
c2: fee78fa3 sb a4,-1(a5)
c6: fb75 bnez a4,ba <strcpy+0x8>
;
return os;
}
c8: 6422 ld s0,8(sp)
ca: 0141 addi sp,sp,16
cc: 8082 ret
00000000000000ce <strcmp>:
int
strcmp(const char *p, const char *q)
{
ce: 1141 addi sp,sp,-16
d0: e422 sd s0,8(sp)
d2: 0800 addi s0,sp,16
while(*p && *p == *q)
d4: 00054783 lbu a5,0(a0)
d8: cb91 beqz a5,ec <strcmp+0x1e>
da: 0005c703 lbu a4,0(a1)
de: 00f71763 bne a4,a5,ec <strcmp+0x1e>
p++, q++;
e2: 0505 addi a0,a0,1
e4: 0585 addi a1,a1,1
while(*p && *p == *q)
e6: 00054783 lbu a5,0(a0)
ea: fbe5 bnez a5,da <strcmp+0xc>
return (uchar)*p - (uchar)*q;
ec: 0005c503 lbu a0,0(a1)
}
f0: 40a7853b subw a0,a5,a0
f4: 6422 ld s0,8(sp)
f6: 0141 addi sp,sp,16
f8: 8082 ret
00000000000000fa <strlen>:
uint
strlen(const char *s)
{
fa: 1141 addi sp,sp,-16
fc: e422 sd s0,8(sp)
fe: 0800 addi s0,sp,16
int n;
for(n = 0; s[n]; n++)
100: 00054783 lbu a5,0(a0)
104: cf91 beqz a5,120 <strlen+0x26>
106: 0505 addi a0,a0,1
108: 87aa mv a5,a0
10a: 4685 li a3,1
10c: 9e89 subw a3,a3,a0
10e: 00f6853b addw a0,a3,a5
112: 0785 addi a5,a5,1
114: fff7c703 lbu a4,-1(a5)
118: fb7d bnez a4,10e <strlen+0x14>
;
return n;
}
11a: 6422 ld s0,8(sp)
11c: 0141 addi sp,sp,16
11e: 8082 ret
for(n = 0; s[n]; n++)
120: 4501 li a0,0
122: bfe5 j 11a <strlen+0x20>
0000000000000124 <memset>:
void*
memset(void *dst, int c, uint n)
{
124: 1141 addi sp,sp,-16
126: e422 sd s0,8(sp)
128: 0800 addi s0,sp,16
char *cdst = (char *) dst;
int i;
for(i = 0; i < n; i++){
12a: ce09 beqz a2,144 <memset+0x20>
12c: 87aa mv a5,a0
12e: fff6071b addiw a4,a2,-1
132: 1702 slli a4,a4,0x20
134: 9301 srli a4,a4,0x20
136: 0705 addi a4,a4,1
138: 972a add a4,a4,a0
cdst[i] = c;
13a: 00b78023 sb a1,0(a5)
for(i = 0; i < n; i++){
13e: 0785 addi a5,a5,1
140: fee79de3 bne a5,a4,13a <memset+0x16>
}
return dst;
}
144: 6422 ld s0,8(sp)
146: 0141 addi sp,sp,16
148: 8082 ret
000000000000014a <strchr>:
char*
strchr(const char *s, char c)
{
14a: 1141 addi sp,sp,-16
14c: e422 sd s0,8(sp)
14e: 0800 addi s0,sp,16
for(; *s; s++)
150: 00054783 lbu a5,0(a0)
154: cb99 beqz a5,16a <strchr+0x20>
if(*s == c)
156: 00f58763 beq a1,a5,164 <strchr+0x1a>
for(; *s; s++)
15a: 0505 addi a0,a0,1
15c: 00054783 lbu a5,0(a0)
160: fbfd bnez a5,156 <strchr+0xc>
return (char*)s;
return 0;
162: 4501 li a0,0
}
164: 6422 ld s0,8(sp)
166: 0141 addi sp,sp,16
168: 8082 ret
return 0;
16a: 4501 li a0,0
16c: bfe5 j 164 <strchr+0x1a>
000000000000016e <gets>:
char*
gets(char *buf, int max)
{
16e: 711d addi sp,sp,-96
170: ec86 sd ra,88(sp)
172: e8a2 sd s0,80(sp)
174: e4a6 sd s1,72(sp)
176: e0ca sd s2,64(sp)
178: fc4e sd s3,56(sp)
17a: f852 sd s4,48(sp)
17c: f456 sd s5,40(sp)
17e: f05a sd s6,32(sp)
180: ec5e sd s7,24(sp)
182: 1080 addi s0,sp,96
184: 8baa mv s7,a0
186: 8a2e mv s4,a1
int i, cc;
char c;
for(i=0; i+1 < max; ){
188: 892a mv s2,a0
18a: 4481 li s1,0
cc = read(0, &c, 1);
if(cc < 1)
break;
buf[i++] = c;
if(c == '\n' || c == '\r')
18c: 4aa9 li s5,10
18e: 4b35 li s6,13
for(i=0; i+1 < max; ){
190: 89a6 mv s3,s1
192: 2485 addiw s1,s1,1
194: 0344d863 bge s1,s4,1c4 <gets+0x56>
cc = read(0, &c, 1);
198: 4605 li a2,1
19a: faf40593 addi a1,s0,-81
19e: 4501 li a0,0
1a0: 00000097 auipc ra,0x0
1a4: 1a0080e7 jalr 416(ra) # 340 <read>
if(cc < 1)
1a8: 00a05e63 blez a0,1c4 <gets+0x56>
buf[i++] = c;
1ac: faf44783 lbu a5,-81(s0)
1b0: 00f90023 sb a5,0(s2)
if(c == '\n' || c == '\r')
1b4: 01578763 beq a5,s5,1c2 <gets+0x54>
1b8: 0905 addi s2,s2,1
1ba: fd679be3 bne a5,s6,190 <gets+0x22>
for(i=0; i+1 < max; ){
1be: 89a6 mv s3,s1
1c0: a011 j 1c4 <gets+0x56>
1c2: 89a6 mv s3,s1
break;
}
buf[i] = '\0';
1c4: 99de add s3,s3,s7
1c6: 00098023 sb zero,0(s3)
return buf;
}
1ca: 855e mv a0,s7
1cc: 60e6 ld ra,88(sp)
1ce: 6446 ld s0,80(sp)
1d0: 64a6 ld s1,72(sp)
1d2: 6906 ld s2,64(sp)
1d4: 79e2 ld s3,56(sp)
1d6: 7a42 ld s4,48(sp)
1d8: 7aa2 ld s5,40(sp)
1da: 7b02 ld s6,32(sp)
1dc: 6be2 ld s7,24(sp)
1de: 6125 addi sp,sp,96
1e0: 8082 ret
00000000000001e2 <stat>:
int
stat(const char *n, struct stat *st)
{
1e2: 1101 addi sp,sp,-32
1e4: ec06 sd ra,24(sp)
1e6: e822 sd s0,16(sp)
1e8: e426 sd s1,8(sp)
1ea: e04a sd s2,0(sp)
1ec: 1000 addi s0,sp,32
1ee: 892e mv s2,a1
int fd;
int r;
fd = open(n, O_RDONLY);
1f0: 4581 li a1,0
1f2: 00000097 auipc ra,0x0
1f6: 176080e7 jalr 374(ra) # 368 <open>
if(fd < 0)
1fa: 02054563 bltz a0,224 <stat+0x42>
1fe: 84aa mv s1,a0
return -1;
r = fstat(fd, st);
200: 85ca mv a1,s2
202: 00000097 auipc ra,0x0
206: 17e080e7 jalr 382(ra) # 380 <fstat>
20a: 892a mv s2,a0
close(fd);
20c: 8526 mv a0,s1
20e: 00000097 auipc ra,0x0
212: 142080e7 jalr 322(ra) # 350 <close>
return r;
}
216: 854a mv a0,s2
218: 60e2 ld ra,24(sp)
21a: 6442 ld s0,16(sp)
21c: 64a2 ld s1,8(sp)
21e: 6902 ld s2,0(sp)
220: 6105 addi sp,sp,32
222: 8082 ret
return -1;
224: 597d li s2,-1
226: bfc5 j 216 <stat+0x34>
0000000000000228 <atoi>:
int
atoi(const char *s)
{
228: 1141 addi sp,sp,-16
22a: e422 sd s0,8(sp)
22c: 0800 addi s0,sp,16
int n;
n = 0;
while('0' <= *s && *s <= '9')
22e: 00054603 lbu a2,0(a0)
232: fd06079b addiw a5,a2,-48
236: 0ff7f793 andi a5,a5,255
23a: 4725 li a4,9
23c: 02f76963 bltu a4,a5,26e <atoi+0x46>
240: 86aa mv a3,a0
n = 0;
242: 4501 li a0,0
while('0' <= *s && *s <= '9')
244: 45a5 li a1,9
n = n*10 + *s++ - '0';
246: 0685 addi a3,a3,1
248: 0025179b slliw a5,a0,0x2
24c: 9fa9 addw a5,a5,a0
24e: 0017979b slliw a5,a5,0x1
252: 9fb1 addw a5,a5,a2
254: fd07851b addiw a0,a5,-48
while('0' <= *s && *s <= '9')
258: 0006c603 lbu a2,0(a3)
25c: fd06071b addiw a4,a2,-48
260: 0ff77713 andi a4,a4,255
264: fee5f1e3 bgeu a1,a4,246 <atoi+0x1e>
return n;
}
268: 6422 ld s0,8(sp)
26a: 0141 addi sp,sp,16
26c: 8082 ret
n = 0;
26e: 4501 li a0,0
270: bfe5 j 268 <atoi+0x40>
0000000000000272 <memmove>:
void*
memmove(void *vdst, const void *vsrc, int n)
{
272: 1141 addi sp,sp,-16
274: e422 sd s0,8(sp)
276: 0800 addi s0,sp,16
char *dst;
const char *src;
dst = vdst;
src = vsrc;
if (src > dst) {
278: 02b57663 bgeu a0,a1,2a4 <memmove+0x32>
while(n-- > 0)
27c: 02c05163 blez a2,29e <memmove+0x2c>
280: fff6079b addiw a5,a2,-1
284: 1782 slli a5,a5,0x20
286: 9381 srli a5,a5,0x20
288: 0785 addi a5,a5,1
28a: 97aa add a5,a5,a0
dst = vdst;
28c: 872a mv a4,a0
*dst++ = *src++;
28e: 0585 addi a1,a1,1
290: 0705 addi a4,a4,1
292: fff5c683 lbu a3,-1(a1)
296: fed70fa3 sb a3,-1(a4)
while(n-- > 0)
29a: fee79ae3 bne a5,a4,28e <memmove+0x1c>
src += n;
while(n-- > 0)
*--dst = *--src;
}
return vdst;
}
29e: 6422 ld s0,8(sp)
2a0: 0141 addi sp,sp,16
2a2: 8082 ret
dst += n;
2a4: 00c50733 add a4,a0,a2
src += n;
2a8: 95b2 add a1,a1,a2
while(n-- > 0)
2aa: fec05ae3 blez a2,29e <memmove+0x2c>
2ae: fff6079b addiw a5,a2,-1
2b2: 1782 slli a5,a5,0x20
2b4: 9381 srli a5,a5,0x20
2b6: fff7c793 not a5,a5
2ba: 97ba add a5,a5,a4
*--dst = *--src;
2bc: 15fd addi a1,a1,-1
2be: 177d addi a4,a4,-1
2c0: 0005c683 lbu a3,0(a1)
2c4: 00d70023 sb a3,0(a4)
while(n-- > 0)
2c8: fee79ae3 bne a5,a4,2bc <memmove+0x4a>
2cc: bfc9 j 29e <memmove+0x2c>
00000000000002ce <memcmp>:
int
memcmp(const void *s1, const void *s2, uint n)
{
2ce: 1141 addi sp,sp,-16
2d0: e422 sd s0,8(sp)
2d2: 0800 addi s0,sp,16
const char *p1 = s1, *p2 = s2;
while (n-- > 0) {
2d4: ca05 beqz a2,304 <memcmp+0x36>
2d6: fff6069b addiw a3,a2,-1
2da: 1682 slli a3,a3,0x20
2dc: 9281 srli a3,a3,0x20
2de: 0685 addi a3,a3,1
2e0: 96aa add a3,a3,a0
if (*p1 != *p2) {
2e2: 00054783 lbu a5,0(a0)
2e6: 0005c703 lbu a4,0(a1)
2ea: 00e79863 bne a5,a4,2fa <memcmp+0x2c>
return *p1 - *p2;
}
p1++;
2ee: 0505 addi a0,a0,1
p2++;
2f0: 0585 addi a1,a1,1
while (n-- > 0) {
2f2: fed518e3 bne a0,a3,2e2 <memcmp+0x14>
}
return 0;
2f6: 4501 li a0,0
2f8: a019 j 2fe <memcmp+0x30>
return *p1 - *p2;
2fa: 40e7853b subw a0,a5,a4
}
2fe: 6422 ld s0,8(sp)
300: 0141 addi sp,sp,16
302: 8082 ret
return 0;
304: 4501 li a0,0
306: bfe5 j 2fe <memcmp+0x30>
0000000000000308 <memcpy>:
void *
memcpy(void *dst, const void *src, uint n)
{
308: 1141 addi sp,sp,-16
30a: e406 sd ra,8(sp)
30c: e022 sd s0,0(sp)
30e: 0800 addi s0,sp,16
return memmove(dst, src, n);
310: 00000097 auipc ra,0x0
314: f62080e7 jalr -158(ra) # 272 <memmove>
}
318: 60a2 ld ra,8(sp)
31a: 6402 ld s0,0(sp)
31c: 0141 addi sp,sp,16
31e: 8082 ret
0000000000000320 <fork>:
# generated by usys.pl - do not edit
#include "kernel/syscall.h"
.global fork
fork:
li a7, SYS_fork
320: 4885 li a7,1
ecall
322: 00000073 ecall
ret
326: 8082 ret
0000000000000328 <exit>:
.global exit
exit:
li a7, SYS_exit
328: 4889 li a7,2
ecall
32a: 00000073 ecall
ret
32e: 8082 ret
0000000000000330 <wait>:
.global wait
wait:
li a7, SYS_wait
330: 488d li a7,3
ecall
332: 00000073 ecall
ret
336: 8082 ret
0000000000000338 <pipe>:
.global pipe
pipe:
li a7, SYS_pipe
338: 4891 li a7,4
ecall
33a: 00000073 ecall
ret
33e: 8082 ret
0000000000000340 <read>:
.global read
read:
li a7, SYS_read
340: 4895 li a7,5
ecall
342: 00000073 ecall
ret
346: 8082 ret
0000000000000348 <write>:
.global write
write:
li a7, SYS_write
348: 48c1 li a7,16
ecall
34a: 00000073 ecall
ret
34e: 8082 ret
0000000000000350 <close>:
.global close
close:
li a7, SYS_close
350: 48d5 li a7,21
ecall
352: 00000073 ecall
ret
356: 8082 ret
0000000000000358 <kill>:
.global kill
kill:
li a7, SYS_kill
358: 4899 li a7,6
ecall
35a: 00000073 ecall
ret
35e: 8082 ret
0000000000000360 <exec>:
.global exec
exec:
li a7, SYS_exec
360: 489d li a7,7
ecall
362: 00000073 ecall
ret
366: 8082 ret
0000000000000368 <open>:
.global open
open:
li a7, SYS_open
368: 48bd li a7,15
ecall
36a: 00000073 ecall
ret
36e: 8082 ret
0000000000000370 <mknod>:
.global mknod
mknod:
li a7, SYS_mknod
370: 48c5 li a7,17
ecall
372: 00000073 ecall
ret
376: 8082 ret
0000000000000378 <unlink>:
.global unlink
unlink:
li a7, SYS_unlink
378: 48c9 li a7,18
ecall
37a: 00000073 ecall
ret
37e: 8082 ret
0000000000000380 <fstat>:
.global fstat
fstat:
li a7, SYS_fstat
380: 48a1 li a7,8
ecall
382: 00000073 ecall
ret
386: 8082 ret
0000000000000388 <link>:
.global link
link:
li a7, SYS_link
388: 48cd li a7,19
ecall
38a: 00000073 ecall
ret
38e: 8082 ret
0000000000000390 <mkdir>:
.global mkdir
mkdir:
li a7, SYS_mkdir
390: 48d1 li a7,20
ecall
392: 00000073 ecall
ret
396: 8082 ret
0000000000000398 <chdir>:
.global chdir
chdir:
li a7, SYS_chdir
398: 48a5 li a7,9
ecall
39a: 00000073 ecall
ret
39e: 8082 ret
00000000000003a0 <dup>:
.global dup
dup:
li a7, SYS_dup
3a0: 48a9 li a7,10
ecall
3a2: 00000073 ecall
ret
3a6: 8082 ret
00000000000003a8 <getpid>:
.global getpid
getpid:
li a7, SYS_getpid
3a8: 48ad li a7,11
ecall
3aa: 00000073 ecall
ret
3ae: 8082 ret
00000000000003b0 <sbrk>:
.global sbrk
sbrk:
li a7, SYS_sbrk
3b0: 48b1 li a7,12
ecall
3b2: 00000073 ecall
ret
3b6: 8082 ret
00000000000003b8 <sleep>:
.global sleep
sleep:
li a7, SYS_sleep
3b8: 48b5 li a7,13
ecall
3ba: 00000073 ecall
ret
3be: 8082 ret
00000000000003c0 <uptime>:
.global uptime
uptime:
li a7, SYS_uptime
3c0: 48b9 li a7,14
ecall
3c2: 00000073 ecall
ret
3c6: 8082 ret
00000000000003c8 <trace>:
.global trace
trace:
li a7, SYS_trace
3c8: 48d9 li a7,22
ecall
3ca: 00000073 ecall
ret
3ce: 8082 ret
00000000000003d0 <waitx>:
.global waitx
waitx:
li a7, SYS_waitx
3d0: 48dd li a7,23
ecall
3d2: 00000073 ecall
ret
3d6: 8082 ret
00000000000003d8 <set_priority>:
.global set_priority
set_priority:
li a7, SYS_set_priority
3d8: 48e1 li a7,24
ecall
3da: 00000073 ecall
ret
3de: 8082 ret
00000000000003e0 <putc>:
static char digits[] = "0123456789ABCDEF";
static void
putc(int fd, char c)
{
3e0: 1101 addi sp,sp,-32
3e2: ec06 sd ra,24(sp)
3e4: e822 sd s0,16(sp)
3e6: 1000 addi s0,sp,32
3e8: feb407a3 sb a1,-17(s0)
write(fd, &c, 1);
3ec: 4605 li a2,1
3ee: fef40593 addi a1,s0,-17
3f2: 00000097 auipc ra,0x0
3f6: f56080e7 jalr -170(ra) # 348 <write>
}
3fa: 60e2 ld ra,24(sp)
3fc: 6442 ld s0,16(sp)
3fe: 6105 addi sp,sp,32
400: 8082 ret
0000000000000402 <printint>:
static void
printint(int fd, int xx, int base, int sgn)
{
402: 7139 addi sp,sp,-64
404: fc06 sd ra,56(sp)
406: f822 sd s0,48(sp)
408: f426 sd s1,40(sp)
40a: f04a sd s2,32(sp)
40c: ec4e sd s3,24(sp)
40e: 0080 addi s0,sp,64
410: 84aa mv s1,a0
char buf[16];
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
412: c299 beqz a3,418 <printint+0x16>
414: 0805c863 bltz a1,4a4 <printint+0xa2>
neg = 1;
x = -xx;
} else {
x = xx;
418: 2581 sext.w a1,a1
neg = 0;
41a: 4881 li a7,0
41c: fc040693 addi a3,s0,-64
}
i = 0;
420: 4701 li a4,0
do{
buf[i++] = digits[x % base];
422: 2601 sext.w a2,a2
424: 00000517 auipc a0,0x0
428: 46c50513 addi a0,a0,1132 # 890 <digits>
42c: 883a mv a6,a4
42e: 2705 addiw a4,a4,1
430: 02c5f7bb remuw a5,a1,a2
434: 1782 slli a5,a5,0x20
436: 9381 srli a5,a5,0x20
438: 97aa add a5,a5,a0
43a: 0007c783 lbu a5,0(a5)
43e: 00f68023 sb a5,0(a3)
}while((x /= base) != 0);
442: 0005879b sext.w a5,a1
446: 02c5d5bb divuw a1,a1,a2
44a: 0685 addi a3,a3,1
44c: fec7f0e3 bgeu a5,a2,42c <printint+0x2a>
if(neg)
450: 00088b63 beqz a7,466 <printint+0x64>
buf[i++] = '-';
454: fd040793 addi a5,s0,-48
458: 973e add a4,a4,a5
45a: 02d00793 li a5,45
45e: fef70823 sb a5,-16(a4)
462: 0028071b addiw a4,a6,2
while(--i >= 0)
466: 02e05863 blez a4,496 <printint+0x94>
46a: fc040793 addi a5,s0,-64
46e: 00e78933 add s2,a5,a4
472: fff78993 addi s3,a5,-1
476: 99ba add s3,s3,a4
478: 377d addiw a4,a4,-1
47a: 1702 slli a4,a4,0x20
47c: 9301 srli a4,a4,0x20
47e: 40e989b3 sub s3,s3,a4
putc(fd, buf[i]);
482: fff94583 lbu a1,-1(s2)
486: 8526 mv a0,s1
488: 00000097 auipc ra,0x0
48c: f58080e7 jalr -168(ra) # 3e0 <putc>
while(--i >= 0)
490: 197d addi s2,s2,-1
492: ff3918e3 bne s2,s3,482 <printint+0x80>
}
496: 70e2 ld ra,56(sp)
498: 7442 ld s0,48(sp)
49a: 74a2 ld s1,40(sp)
49c: 7902 ld s2,32(sp)
49e: 69e2 ld s3,24(sp)
4a0: 6121 addi sp,sp,64
4a2: 8082 ret
x = -xx;
4a4: 40b005bb negw a1,a1
neg = 1;
4a8: 4885 li a7,1
x = -xx;
4aa: bf8d j 41c <printint+0x1a>
00000000000004ac <vprintf>:
}
// Print to the given fd. Only understands %d, %x, %p, %s.
void
vprintf(int fd, const char *fmt, va_list ap)
{
4ac: 7119 addi sp,sp,-128
4ae: fc86 sd ra,120(sp)
4b0: f8a2 sd s0,112(sp)
4b2: f4a6 sd s1,104(sp)
4b4: f0ca sd s2,96(sp)
4b6: ecce sd s3,88(sp)
4b8: e8d2 sd s4,80(sp)
4ba: e4d6 sd s5,72(sp)
4bc: e0da sd s6,64(sp)
4be: fc5e sd s7,56(sp)
4c0: f862 sd s8,48(sp)
4c2: f466 sd s9,40(sp)
4c4: f06a sd s10,32(sp)
4c6: ec6e sd s11,24(sp)
4c8: 0100 addi s0,sp,128
char *s;
int c, i, state;
state = 0;
for(i = 0; fmt[i]; i++){
4ca: 0005c903 lbu s2,0(a1)
4ce: 18090f63 beqz s2,66c <vprintf+0x1c0>
4d2: 8aaa mv s5,a0
4d4: 8b32 mv s6,a2
4d6: 00158493 addi s1,a1,1
state = 0;
4da: 4981 li s3,0
if(c == '%'){
state = '%';
} else {
putc(fd, c);
}
} else if(state == '%'){
4dc: 02500a13 li s4,37
if(c == 'd'){
4e0: 06400c13 li s8,100
printint(fd, va_arg(ap, int), 10, 1);
} else if(c == 'l') {
4e4: 06c00c93 li s9,108
printint(fd, va_arg(ap, uint64), 10, 0);
} else if(c == 'x') {
4e8: 07800d13 li s10,120
printint(fd, va_arg(ap, int), 16, 0);
} else if(c == 'p') {
4ec: 07000d93 li s11,112
putc(fd, digits[x >> (sizeof(uint64) * 8 - 4)]);
4f0: 00000b97 auipc s7,0x0
4f4: 3a0b8b93 addi s7,s7,928 # 890 <digits>
4f8: a839 j 516 <vprintf+0x6a>
putc(fd, c);
4fa: 85ca mv a1,s2
4fc: 8556 mv a0,s5
4fe: 00000097 auipc ra,0x0
502: ee2080e7 jalr -286(ra) # 3e0 <putc>
506: a019 j 50c <vprintf+0x60>
} else if(state == '%'){
508: 01498f63 beq s3,s4,526 <vprintf+0x7a>
for(i = 0; fmt[i]; i++){
50c: 0485 addi s1,s1,1
50e: fff4c903 lbu s2,-1(s1)
512: 14090d63 beqz s2,66c <vprintf+0x1c0>
c = fmt[i] & 0xff;
516: 0009079b sext.w a5,s2
if(state == 0){
51a: fe0997e3 bnez s3,508 <vprintf+0x5c>
if(c == '%'){
51e: fd479ee3 bne a5,s4,4fa <vprintf+0x4e>
state = '%';
522: 89be mv s3,a5
524: b7e5 j 50c <vprintf+0x60>
if(c == 'd'){
526: 05878063 beq a5,s8,566 <vprintf+0xba>
} else if(c == 'l') {
52a: 05978c63 beq a5,s9,582 <vprintf+0xd6>
} else if(c == 'x') {
52e: 07a78863 beq a5,s10,59e <vprintf+0xf2>
} else if(c == 'p') {
532: 09b78463 beq a5,s11,5ba <vprintf+0x10e>
printptr(fd, va_arg(ap, uint64));
} else if(c == 's'){
536: 07300713 li a4,115
53a: 0ce78663 beq a5,a4,606 <vprintf+0x15a>
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
53e: 06300713 li a4,99
542: 0ee78e63 beq a5,a4,63e <vprintf+0x192>
putc(fd, va_arg(ap, uint));
} else if(c == '%'){
546: 11478863 beq a5,s4,656 <vprintf+0x1aa>
putc(fd, c);
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
54a: 85d2 mv a1,s4
54c: 8556 mv a0,s5
54e: 00000097 auipc ra,0x0
552: e92080e7 jalr -366(ra) # 3e0 <putc>
putc(fd, c);
556: 85ca mv a1,s2
558: 8556 mv a0,s5
55a: 00000097 auipc ra,0x0
55e: e86080e7 jalr -378(ra) # 3e0 <putc>
}
state = 0;
562: 4981 li s3,0
564: b765 j 50c <vprintf+0x60>
printint(fd, va_arg(ap, int), 10, 1);
566: 008b0913 addi s2,s6,8
56a: 4685 li a3,1
56c: 4629 li a2,10
56e: 000b2583 lw a1,0(s6)
572: 8556 mv a0,s5
574: 00000097 auipc ra,0x0
578: e8e080e7 jalr -370(ra) # 402 <printint>
57c: 8b4a mv s6,s2
state = 0;
57e: 4981 li s3,0
580: b771 j 50c <vprintf+0x60>
printint(fd, va_arg(ap, uint64), 10, 0);
582: 008b0913 addi s2,s6,8
586: 4681 li a3,0
588: 4629 li a2,10
58a: 000b2583 lw a1,0(s6)
58e: 8556 mv a0,s5
590: 00000097 auipc ra,0x0
594: e72080e7 jalr -398(ra) # 402 <printint>
598: 8b4a mv s6,s2
state = 0;
59a: 4981 li s3,0
59c: bf85 j 50c <vprintf+0x60>
printint(fd, va_arg(ap, int), 16, 0);
59e: 008b0913 addi s2,s6,8
5a2: 4681 li a3,0
5a4: 4641 li a2,16
5a6: 000b2583 lw a1,0(s6)
5aa: 8556 mv a0,s5
5ac: 00000097 auipc ra,0x0
5b0: e56080e7 jalr -426(ra) # 402 <printint>
5b4: 8b4a mv s6,s2
state = 0;
5b6: 4981 li s3,0
5b8: bf91 j 50c <vprintf+0x60>
printptr(fd, va_arg(ap, uint64));
5ba: 008b0793 addi a5,s6,8
5be: f8f43423 sd a5,-120(s0)
5c2: 000b3983 ld s3,0(s6)
putc(fd, '0');
5c6: 03000593 li a1,48
5ca: 8556 mv a0,s5
5cc: 00000097 auipc ra,0x0
5d0: e14080e7 jalr -492(ra) # 3e0 <putc>
putc(fd, 'x');
5d4: 85ea mv a1,s10
5d6: 8556 mv a0,s5
5d8: 00000097 auipc ra,0x0
5dc: e08080e7 jalr -504(ra) # 3e0 <putc>
5e0: 4941 li s2,16
putc(fd, digits[x >> (sizeof(uint64) * 8 - 4)]);
5e2: 03c9d793 srli a5,s3,0x3c
5e6: 97de add a5,a5,s7
5e8: 0007c583 lbu a1,0(a5)
5ec: 8556 mv a0,s5
5ee: 00000097 auipc ra,0x0
5f2: df2080e7 jalr -526(ra) # 3e0 <putc>
for (i = 0; i < (sizeof(uint64) * 2); i++, x <<= 4)
5f6: 0992 slli s3,s3,0x4
5f8: 397d addiw s2,s2,-1
5fa: fe0914e3 bnez s2,5e2 <vprintf+0x136>
printptr(fd, va_arg(ap, uint64));
5fe: f8843b03 ld s6,-120(s0)
state = 0;
602: 4981 li s3,0
604: b721 j 50c <vprintf+0x60>
s = va_arg(ap, char*);
606: 008b0993 addi s3,s6,8
60a: 000b3903 ld s2,0(s6)
if(s == 0)
60e: 02090163 beqz s2,630 <vprintf+0x184>
while(*s != 0){
612: 00094583 lbu a1,0(s2)
616: c9a1 beqz a1,666 <vprintf+0x1ba>
putc(fd, *s);
618: 8556 mv a0,s5
61a: 00000097 auipc ra,0x0
61e: dc6080e7 jalr -570(ra) # 3e0 <putc>
s++;
622: 0905 addi s2,s2,1
while(*s != 0){
624: 00094583 lbu a1,0(s2)
628: f9e5 bnez a1,618 <vprintf+0x16c>
s = va_arg(ap, char*);
62a: 8b4e mv s6,s3
state = 0;
62c: 4981 li s3,0
62e: bdf9 j 50c <vprintf+0x60>
s = "(null)";
630: 00000917 auipc s2,0x0
634: 25890913 addi s2,s2,600 # 888 <malloc+0x112>
while(*s != 0){
638: 02800593 li a1,40
63c: bff1 j 618 <vprintf+0x16c>
putc(fd, va_arg(ap, uint));
63e: 008b0913 addi s2,s6,8
642: 000b4583 lbu a1,0(s6)
646: 8556 mv a0,s5
648: 00000097 auipc ra,0x0
64c: d98080e7 jalr -616(ra) # 3e0 <putc>
650: 8b4a mv s6,s2
state = 0;
652: 4981 li s3,0
654: bd65 j 50c <vprintf+0x60>
putc(fd, c);
656: 85d2 mv a1,s4
658: 8556 mv a0,s5
65a: 00000097 auipc ra,0x0
65e: d86080e7 jalr -634(ra) # 3e0 <putc>
state = 0;
662: 4981 li s3,0
664: b565 j 50c <vprintf+0x60>
s = va_arg(ap, char*);
666: 8b4e mv s6,s3
state = 0;
668: 4981 li s3,0
66a: b54d j 50c <vprintf+0x60>
}
}
}
66c: 70e6 ld ra,120(sp)
66e: 7446 ld s0,112(sp)
670: 74a6 ld s1,104(sp)
672: 7906 ld s2,96(sp)
674: 69e6 ld s3,88(sp)
676: 6a46 ld s4,80(sp)
678: 6aa6 ld s5,72(sp)
67a: 6b06 ld s6,64(sp)
67c: 7be2 ld s7,56(sp)
67e: 7c42 ld s8,48(sp)
680: 7ca2 ld s9,40(sp)
682: 7d02 ld s10,32(sp)
684: 6de2 ld s11,24(sp)
686: 6109 addi sp,sp,128
688: 8082 ret
000000000000068a <fprintf>:
void
fprintf(int fd, const char *fmt, ...)
{
68a: 715d addi sp,sp,-80
68c: ec06 sd ra,24(sp)
68e: e822 sd s0,16(sp)
690: 1000 addi s0,sp,32
692: e010 sd a2,0(s0)
694: e414 sd a3,8(s0)
696: e818 sd a4,16(s0)
698: ec1c sd a5,24(s0)
69a: 03043023 sd a6,32(s0)
69e: 03143423 sd a7,40(s0)
va_list ap;
va_start(ap, fmt);
6a2: fe843423 sd s0,-24(s0)
vprintf(fd, fmt, ap);
6a6: 8622 mv a2,s0
6a8: 00000097 auipc ra,0x0
6ac: e04080e7 jalr -508(ra) # 4ac <vprintf>
}
6b0: 60e2 ld ra,24(sp)
6b2: 6442 ld s0,16(sp)
6b4: 6161 addi sp,sp,80
6b6: 8082 ret
00000000000006b8 <printf>:
void
printf(const char *fmt, ...)
{
6b8: 711d addi sp,sp,-96
6ba: ec06 sd ra,24(sp)
6bc: e822 sd s0,16(sp)
6be: 1000 addi s0,sp,32
6c0: e40c sd a1,8(s0)
6c2: e810 sd a2,16(s0)
6c4: ec14 sd a3,24(s0)
6c6: f018 sd a4,32(s0)
6c8: f41c sd a5,40(s0)
6ca: 03043823 sd a6,48(s0)
6ce: 03143c23 sd a7,56(s0)
va_list ap;
va_start(ap, fmt);
6d2: 00840613 addi a2,s0,8
6d6: fec43423 sd a2,-24(s0)
vprintf(1, fmt, ap);
6da: 85aa mv a1,a0
6dc: 4505 li a0,1
6de: 00000097 auipc ra,0x0
6e2: dce080e7 jalr -562(ra) # 4ac <vprintf>
}
6e6: 60e2 ld ra,24(sp)
6e8: 6442 ld s0,16(sp)
6ea: 6125 addi sp,sp,96
6ec: 8082 ret
00000000000006ee <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
6ee: 1141 addi sp,sp,-16
6f0: e422 sd s0,8(sp)
6f2: 0800 addi s0,sp,16
Header *bp, *p;
bp = (Header*)ap - 1;
6f4: ff050693 addi a3,a0,-16
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
6f8: 00000797 auipc a5,0x0
6fc: 1b07b783 ld a5,432(a5) # 8a8 <freep>
700: a805 j 730 <free+0x42>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
break;
if(bp + bp->s.size == p->s.ptr){
bp->s.size += p->s.ptr->s.size;
702: 4618 lw a4,8(a2)
704: 9db9 addw a1,a1,a4
706: feb52c23 sw a1,-8(a0)
bp->s.ptr = p->s.ptr->s.ptr;
70a: 6398 ld a4,0(a5)
70c: 6318 ld a4,0(a4)
70e: fee53823 sd a4,-16(a0)
712: a091 j 756 <free+0x68>
} else
bp->s.ptr = p->s.ptr;
if(p + p->s.size == bp){
p->s.size += bp->s.size;
714: ff852703 lw a4,-8(a0)
718: 9e39 addw a2,a2,a4
71a: c790 sw a2,8(a5)
p->s.ptr = bp->s.ptr;
71c: ff053703 ld a4,-16(a0)
720: e398 sd a4,0(a5)
722: a099 j 768 <free+0x7a>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
724: 6398 ld a4,0(a5)
726: 00e7e463 bltu a5,a4,72e <free+0x40>
72a: 00e6ea63 bltu a3,a4,73e <free+0x50>
{
72e: 87ba mv a5,a4
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
730: fed7fae3 bgeu a5,a3,724 <free+0x36>
734: 6398 ld a4,0(a5)
736: 00e6e463 bltu a3,a4,73e <free+0x50>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
73a: fee7eae3 bltu a5,a4,72e <free+0x40>
if(bp + bp->s.size == p->s.ptr){
73e: ff852583 lw a1,-8(a0)
742: 6390 ld a2,0(a5)
744: 02059713 slli a4,a1,0x20
748: 9301 srli a4,a4,0x20
74a: 0712 slli a4,a4,0x4
74c: 9736 add a4,a4,a3
74e: fae60ae3 beq a2,a4,702 <free+0x14>
bp->s.ptr = p->s.ptr;
752: fec53823 sd a2,-16(a0)
if(p + p->s.size == bp){
756: 4790 lw a2,8(a5)
758: 02061713 slli a4,a2,0x20
75c: 9301 srli a4,a4,0x20
75e: 0712 slli a4,a4,0x4
760: 973e add a4,a4,a5
762: fae689e3 beq a3,a4,714 <free+0x26>
} else
p->s.ptr = bp;
766: e394 sd a3,0(a5)
freep = p;
768: 00000717 auipc a4,0x0
76c: 14f73023 sd a5,320(a4) # 8a8 <freep>
}
770: 6422 ld s0,8(sp)
772: 0141 addi sp,sp,16
774: 8082 ret
0000000000000776 <malloc>:
return freep;
}
void*
malloc(uint nbytes)
{
776: 7139 addi sp,sp,-64
778: fc06 sd ra,56(sp)
77a: f822 sd s0,48(sp)
77c: f426 sd s1,40(sp)
77e: f04a sd s2,32(sp)
780: ec4e sd s3,24(sp)
782: e852 sd s4,16(sp)
784: e456 sd s5,8(sp)
786: e05a sd s6,0(sp)
788: 0080 addi s0,sp,64
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
78a: 02051493 slli s1,a0,0x20
78e: 9081 srli s1,s1,0x20
790: 04bd addi s1,s1,15
792: 8091 srli s1,s1,0x4
794: 0014899b addiw s3,s1,1
798: 0485 addi s1,s1,1
if((prevp = freep) == 0){
79a: 00000517 auipc a0,0x0
79e: 10e53503 ld a0,270(a0) # 8a8 <freep>
7a2: c515 beqz a0,7ce <malloc+0x58>
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
7a4: 611c ld a5,0(a0)
if(p->s.size >= nunits){
7a6: 4798 lw a4,8(a5)
7a8: 02977f63 bgeu a4,s1,7e6 <malloc+0x70>
7ac: 8a4e mv s4,s3
7ae: 0009871b sext.w a4,s3
7b2: 6685 lui a3,0x1
7b4: 00d77363 bgeu a4,a3,7ba <malloc+0x44>
7b8: 6a05 lui s4,0x1
7ba: 000a0b1b sext.w s6,s4
p = sbrk(nu * sizeof(Header));
7be: 004a1a1b slliw s4,s4,0x4
p->s.size = nunits;
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
7c2: 00000917 auipc s2,0x0
7c6: 0e690913 addi s2,s2,230 # 8a8 <freep>
if(p == (char*)-1)
7ca: 5afd li s5,-1
7cc: a88d j 83e <malloc+0xc8>
base.s.ptr = freep = prevp = &base;
7ce: 00000797 auipc a5,0x0
7d2: 0e278793 addi a5,a5,226 # 8b0 <base>
7d6: 00000717 auipc a4,0x0
7da: 0cf73923 sd a5,210(a4) # 8a8 <freep>
7de: e39c sd a5,0(a5)
base.s.size = 0;
7e0: 0007a423 sw zero,8(a5)
if(p->s.size >= nunits){
7e4: b7e1 j 7ac <malloc+0x36>
if(p->s.size == nunits)
7e6: 02e48b63 beq s1,a4,81c <malloc+0xa6>
p->s.size -= nunits;
7ea: 4137073b subw a4,a4,s3
7ee: c798 sw a4,8(a5)
p += p->s.size;
7f0: 1702 slli a4,a4,0x20
7f2: 9301 srli a4,a4,0x20
7f4: 0712 slli a4,a4,0x4
7f6: 97ba add a5,a5,a4
p->s.size = nunits;
7f8: 0137a423 sw s3,8(a5)
freep = prevp;
7fc: 00000717 auipc a4,0x0
800: 0aa73623 sd a0,172(a4) # 8a8 <freep>
return (void*)(p + 1);
804: 01078513 addi a0,a5,16
if((p = morecore(nunits)) == 0)
return 0;
}
}
808: 70e2 ld ra,56(sp)
80a: 7442 ld s0,48(sp)
80c: 74a2 ld s1,40(sp)
80e: 7902 ld s2,32(sp)
810: 69e2 ld s3,24(sp)
812: 6a42 ld s4,16(sp)
814: 6aa2 ld s5,8(sp)
816: 6b02 ld s6,0(sp)
818: 6121 addi sp,sp,64
81a: 8082 ret
prevp->s.ptr = p->s.ptr;
81c: 6398 ld a4,0(a5)
81e: e118 sd a4,0(a0)
820: bff1 j 7fc <malloc+0x86>
hp->s.size = nu;
822: 01652423 sw s6,8(a0)
free((void*)(hp + 1));
826: 0541 addi a0,a0,16
828: 00000097 auipc ra,0x0
82c: ec6080e7 jalr -314(ra) # 6ee <free>
return freep;
830: 00093503 ld a0,0(s2)
if((p = morecore(nunits)) == 0)
834: d971 beqz a0,808 <malloc+0x92>
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
836: 611c ld a5,0(a0)
if(p->s.size >= nunits){
838: 4798 lw a4,8(a5)
83a: fa9776e3 bgeu a4,s1,7e6 <malloc+0x70>
if(p == freep)
83e: 00093703 ld a4,0(s2)
842: 853e mv a0,a5
844: fef719e3 bne a4,a5,836 <malloc+0xc0>
p = sbrk(nu * sizeof(Header));
848: 8552 mv a0,s4
84a: 00000097 auipc ra,0x0
84e: b66080e7 jalr -1178(ra) # 3b0 <sbrk>
if(p == (char*)-1)
852: fd5518e3 bne a0,s5,822 <malloc+0xac>
return 0;
856: 4501 li a0,0
858: bf45 j 808 <malloc+0x92>
|
;/*
; * FreeRTOS Kernel V10.0.1
; * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
; *
; * Permission is hereby granted, free of charge, to any person obtaining a copy of
; * this software and associated documentation files (the "Software"), to deal in
; * the Software without restriction, including without limitation the rights to
; * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
; * the Software, and to permit persons to whom the Software is furnished to do so,
; * subject to the following conditions:
; *
; * The above copyright notice and this permission notice shall be included in all
; * copies or substantial portions of the Software.
; *
; * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
; * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
; * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
; * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
; * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
; * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
; *
; * http://www.FreeRTOS.org
; * http://aws.amazon.com/freertos
; *
; * 1 tab == 4 spaces!
; */
.extern pxCurrentTCB
.extern vTaskSwitchContext
.extern ulMaxSyscallInterruptPriorityConst
.global _vector_14
.global _lc_ref__vector_pp_14
.global SVC_Handler
.global vPortStartFirstTask
.global vPortEnableVFP
.global ulPortSetInterruptMask
.global vPortClearInterruptMask
;-----------------------------------------------------------
.section .text
.thumb
.align 4
_vector_14: .type func
mrs r0, psp
isb
;Get the location of the current TCB.
ldr.w r3, =pxCurrentTCB
ldr r2, [r3]
;Is the task using the FPU context? If so, push high vfp registers.
tst r14, #0x10
it eq
vstmdbeq r0!, {s16-s31}
;Save the core registers.
stmdb r0!, {r4-r11, r14}
;Save the new top of stack into the first member of the TCB.
str r0, [r2]
stmdb sp!, {r0, r3}
ldr.w r0, =ulMaxSyscallInterruptPriorityConst
ldr r0, [r0]
msr basepri, r0
bl vTaskSwitchContext
mov r0, #0
msr basepri, r0
ldmia sp!, {r0, r3}
;The first item in pxCurrentTCB is the task top of stack.
ldr r1, [r3]
ldr r0, [r1]
;Pop the core registers.
ldmia r0!, {r4-r11, r14}
;Is the task using the FPU context? If so, pop the high vfp registers too.
tst r14, #0x10
it eq
vldmiaeq r0!, {s16-s31}
msr psp, r0
isb
bx r14
.size _vector_14, $-_vector_14
.endsec
;-----------------------------------------------------------
; This function is an XMC4000 silicon errata workaround. It will get used when
; the SILICON_BUG_PMC_CM_001 linker macro is defined.
.section .text
.thumb
.align 4
_lc_ref__vector_pp_14: .type func
mrs r0, psp
isb
;Get the location of the current TCB.
ldr.w r3, =pxCurrentTCB
ldr r2, [r3]
;Is the task using the FPU context? If so, push high vfp registers.
tst r14, #0x10
it eq
vstmdbeq r0!, {s16-s31}
;Save the core registers.
stmdb r0!, {r4-r11, r14}
;Save the new top of stack into the first member of the TCB.
str r0, [r2]
stmdb sp!, {r3}
ldr.w r0, =ulMaxSyscallInterruptPriorityConst
ldr r0, [r0]
msr basepri, r0
bl vTaskSwitchContext
mov r0, #0
msr basepri, r0
ldmia sp!, {r3}
;The first item in pxCurrentTCB is the task top of stack.
ldr r1, [r3]
ldr r0, [r1]
;Pop the core registers.
ldmia r0!, {r4-r11, r14}
;Is the task using the FPU context? If so, pop the high vfp registers too.
tst r14, #0x10
it eq
vldmiaeq r0!, {s16-s31}
msr psp, r0
isb
push { lr }
pop { pc } ; XMC4000 specific errata workaround. Do not used "bx lr" here.
.size _lc_ref__vector_pp_14, $-_lc_ref__vector_pp_14
.endsec
;-----------------------------------------------------------
.section .text
.thumb
.align 4
SVC_Handler: .type func
;Get the location of the current TCB.
ldr.w r3, =pxCurrentTCB
ldr r1, [r3]
ldr r0, [r1]
;Pop the core registers.
ldmia r0!, {r4-r11, r14}
msr psp, r0
isb
mov r0, #0
msr basepri, r0
bx r14
.size SVC_Handler, $-SVC_Handler
.endsec
;-----------------------------------------------------------
.section .text
.thumb
.align 4
vPortStartFirstTask .type func
;Use the NVIC offset register to locate the stack.
ldr.w r0, =0xE000ED08
ldr r0, [r0]
ldr r0, [r0]
;Set the msp back to the start of the stack.
msr msp, r0
;Call SVC to start the first task.
cpsie i
cpsie f
dsb
isb
svc 0
.size vPortStartFirstTask, $-vPortStartFirstTask
.endsec
;-----------------------------------------------------------
.section .text
.thumb
.align 4
vPortEnableVFP .type func
;The FPU enable bits are in the CPACR.
ldr.w r0, =0xE000ED88
ldr r1, [r0]
;Enable CP10 and CP11 coprocessors, then save back.
orr r1, r1, #( 0xf << 20 )
str r1, [r0]
bx r14
.size vPortEnableVFP, $-vPortEnableVFP
.endsec
;-----------------------------------------------------------
.section .text
.thumb
.align 4
ulPortSetInterruptMask:
mrs r0, basepri
ldr.w r1, =ulMaxSyscallInterruptPriorityConst
ldr r1, [r1]
msr basepri, r1
bx r14
.size ulPortSetInterruptMask, $-ulPortSetInterruptMask
.endsec
;-----------------------------------------------------------
.section .text
.thumb
.align 4
vPortClearInterruptMask:
msr basepri, r0
bx r14
.size vPortClearInterruptMask, $-vPortClearInterruptMask
.endsec
;-----------------------------------------------------------
.end
|
db 0 ; species ID placeholder
db 65, 105, 60, 95, 60, 70
; hp atk def spd sat sdf
db FIGHTING, FIGHTING ; type
db 75 ; catch rate
db 149 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_F0 ; gender ratio
db 100 ; unknown 1
db 20 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/primeape/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_MEDIUM_FAST ; growth rate
dn EGG_GROUND, EGG_GROUND ; egg groups
; tm/hm learnset
tmhm DYNAMICPUNCH, HEADBUTT, CURSE, TOXIC, ROCK_SMASH, PSYCH_UP, HIDDEN_POWER, SUNNY_DAY, SNORE, HYPER_BEAM, PROTECT, ENDURE, FRUSTRATION, IRON_TAIL, THUNDER, RETURN, DIG, MUD_SLAP, DOUBLE_TEAM, ICE_PUNCH, SWAGGER, SLEEP_TALK, SWIFT, DEFENSE_CURL, THUNDERPUNCH, DETECT, REST, ATTRACT, THIEF, FIRE_PUNCH, STRENGTH, THUNDERBOLT
; end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.