Защита информации в системах дистанционного обучения с монопольным доступом (pril 1)

Посмотреть архив целиком

168




Часть исходных текстов вспомогательного характера опущена. В качестве примера можно привести класс com_ptr, представляющий вспомогательный класс для более удобной работы с COM интерфейсом. Также полностью опущены исходные тектсыт свободно распрострняемой библиотеки ZLIB 1.1.2.


Файл blocks.h.


#ifndef __BLOCKS_H__

#define __BLOCKS_H__


#ifndef CALC_ARRAY_SIZE

#define CALC_ARRAY_SIZE(arr) ((int) (sizeof arr / sizeof arr[0]))

#endif


#define BLOCK_START(num) const static int block_##num [] = {

#define BLOCK_END(num) }; const size_t sizeBlock_##num = CALC_ARRAY_SIZE(block_##num);


#define BLOCKS_START(num) const static int * const blocks_##num [] = {

#define BLOCKS_END(num) }; const size_t sizeBlocksArray_##num = CALC_ARRAY_SIZE(blocks_##num);

#define BLOCK(num) static_cast(block_##num),


#define BLOCKS_SIZE_START(num) const static unsigned sizeBlocks_##num [] = {

#define BLOCK_SIZE(num) sizeBlock_##num,

#define BLOCKS_SIZE_END(num) };


// Абстрактный алгоритм

// [ADDR(REG|VAR) <= VAR]

// [COUNT(REG|VAR) <= VAR]

// {[R(REG|VAR) <= VAR]} * i(1; n)

// label:

// {

// TEMP <= [ADDR]

// TEMP = TEMP opearation R[i]

// [ADDR] <= TEMP

// ADDR++

// COUNT--

// } * i(1; n)

// if (COUNT!=0)

// GOTO label

// TrstDate

// EXIT


//-----------------------------------------------------------------------------

// Блок N0. (x1)

// Служит для инициализации указателя нулем.

// ES_VARIABLE_0 - ячейка которая может быть занята под указатель.

// ES_REG_0 - регистр который может быть занят под указатель.

BLOCK_START(00_00)

EO_MOV, EOP_VAR, ES_VARIABLE_0, EOP_CONST, 0

BLOCK_END(00_00)


BLOCK_START(00_01)

EO_MOV, EOP_REG, ES_REG_0, EOP_CONST, 0

BLOCK_END(00_01)


BLOCK_START(00_02)

EO_PUSH, EOP_CONST, 0,

ES_RANDOM_NOP,

ES_RANDOM_NOP,

EO_POP, EOP_REG, ES_REG_0

BLOCK_END(00_02)


BLOCK_START(00_03)

EO_PUSH, EOP_CONST, ES_RANDOM_CONST,

ES_RANDOM_NOP,

EO_POP, EOP_REG, ES_REG_0,

EO_SUB, EOP_REG, ES_REG_0, EOP_REG, ES_REG_0

BLOCK_END(00_03)


BLOCK_START(00_04)

EO_MOV, EOP_VAR, ES_VARIABLE_0, EOP_CONST, 1,

EO_DEC, EOP_VAR, ES_VARIABLE_0,

EO_CMP, EOP_VAR, ES_VARIABLE_0, EOP_CONST, 0,

EO_JNZ, EOP_CONST, ES_RANDOM_CONST

BLOCK_END(00_04)


BLOCK_START(00_05)

EO_XOR, EOP_REG, ES_REG_0, EOP_REG, ES_REG_0

BLOCK_END(00_05)


BLOCK_START(00_06)

EO_XOR, EOP_VAR, ES_VARIABLE_0, EOP_VAR, ES_VARIABLE_0

BLOCK_END(00_06)


BLOCKS_START(00)

BLOCK(00_00)

BLOCK(00_01)

BLOCK(00_02)

BLOCK(00_03)

BLOCK(00_04)

BLOCK(00_05)

BLOCK(00_06)

BLOCKS_END(00)


BLOCKS_SIZE_START(00)

BLOCK_SIZE(00_00)

BLOCK_SIZE(00_01)

BLOCK_SIZE(00_02)

BLOCK_SIZE(00_03)

BLOCK_SIZE(00_04)

BLOCK_SIZE(00_05)

BLOCK_SIZE(00_06)

BLOCKS_SIZE_END(00)

//-----------------------------------------------------------------------------



//-----------------------------------------------------------------------------

// Блок N1. (x1)

// Служит для инициализации счетчика нужным значением.

// ES_VARIABLE_0 - ячейка которая может быть занята под значение.

// ES_REG_0 - регистр который может быть занят под значение.

// ES_VARIABLE_1 - Отсюда необхлдимо взять размер

BLOCK_START(01_00)

EO_MOV, EOP_VAR, ES_VARIABLE_0, EOP_VAR, ES_VARIABLE_1

BLOCK_END(01_00)


BLOCK_START(01_01)

EO_MOV, EOP_REG, ES_REG_0, EOP_VAR, ES_VARIABLE_1

BLOCK_END(01_01)


BLOCK_START(01_02)

EO_PUSH, EOP_VAR, ES_VARIABLE_1,

ES_RANDOM_NOP,

ES_RANDOM_NOP,

EO_POP, EOP_REG, ES_REG_0

BLOCK_END(01_02)


BLOCK_START(01_03)

EO_PUSH, EOP_VAR, ES_VARIABLE_1,

EO_MOV, EOP_REG, ES_REG_0, EOP_RAND,

EO_POP, EOP_REG, ES_REG_0

BLOCK_END(01_03)


BLOCK_START(01_04)

EO_XCHG, EOP_VAR, ES_VARIABLE_0, EOP_VAR, ES_VARIABLE_1

BLOCK_END(01_04)


BLOCK_START(01_05)

EO_XCHG, EOP_REG, ES_REG_0, EOP_VAR, ES_VARIABLE_1

BLOCK_END(01_05)


BLOCKS_START(01)

BLOCK(01_00)

BLOCK(01_01)

BLOCK(01_02)

BLOCK(01_03)

BLOCK(01_04)

BLOCK(01_05)

BLOCKS_END(01)


BLOCKS_SIZE_START(01)

BLOCK_SIZE(01_00)

BLOCK_SIZE(01_01)

BLOCK_SIZE(01_02)

BLOCK_SIZE(01_03)

BLOCK_SIZE(01_04)

BLOCK_SIZE(01_05)

BLOCKS_SIZE_END(01)

//-----------------------------------------------------------------------------



//-----------------------------------------------------------------------------

// Блок N2. (xN)

// Служит для инициализации модификатора нужным значением.

// ES_VARIABLE_0 - ячейка которая может быть занята под значение.

// ES_REG_0 - регистр который может быть занят под значение.

// ES_VARIABLE_1 - ячейка, где может храниться модификатор

// ES_COSNT_0 - здесь может храниться модификатор

BLOCK_START(02_00)

EO_MOV, EOP_VAR, ES_VARIABLE_0, EOP_VAR, ES_VARIABLE_1

BLOCK_END(02_00)


BLOCK_START(02_01)

EO_MOV, EOP_REG, ES_REG_0, EOP_VAR, ES_VARIABLE_1

BLOCK_END(02_01)


BLOCK_START(02_02)

EO_MOV, EOP_VAR, ES_VARIABLE_0, EOP_CONST, ES_CONST_0

BLOCK_END(02_02)


BLOCK_START(02_03)

EO_MOV, EOP_REG, ES_REG_0, EOP_CONST, ES_CONST_0

BLOCK_END(02_03)


BLOCK_START(02_04)

EO_XCHG, EOP_VAR, ES_VARIABLE_0, EOP_VAR, ES_VARIABLE_1

BLOCK_END(02_04)


BLOCK_START(02_05)

EO_XCHG, EOP_REG, ES_REG_0, EOP_VAR, ES_VARIABLE_1

BLOCK_END(02_05)


BLOCK_START(02_06)

EO_PUSH, EOP_CONST, ES_CONST_0,

ES_RANDOM_NOP,

ES_RANDOM_NOP,

EO_POP, EOP_REG, ES_REG_0

BLOCK_END(02_06)


BLOCK_START(02_07)

EO_MOV, EOP_VAR, ES_VARIABLE_0, EOP_CONST, 0,

EO_ADD, EOP_VAR, ES_VARIABLE_0, EOP_VAR, ES_VARIABLE_1

BLOCK_END(02_07)


BLOCKS_START(02)

BLOCK(02_00)

BLOCK(02_01)

BLOCK(02_02)

BLOCK(02_03)

BLOCK(02_04)

BLOCK(02_05)

BLOCK(02_06)

BLOCK(02_07)

BLOCKS_END(02)


BLOCKS_SIZE_START(02)

BLOCK_SIZE(02_00)

BLOCK_SIZE(02_01)

BLOCK_SIZE(02_02)

BLOCK_SIZE(02_03)

BLOCK_SIZE(02_04)

BLOCK_SIZE(02_05)

BLOCK_SIZE(02_06)

BLOCK_SIZE(02_07)

BLOCKS_SIZE_END(02)

//-----------------------------------------------------------------------------



//-----------------------------------------------------------------------------

// Блок N3. (xN)

// Служит для преобразования одной ячейки памяти.

// ES_VARIABLE_0 - \ указатель на ячейку памяти

// ES_REG_0 - /

// ES_VARIABLE_1 - \ модификатор

// ES_REG_1 - /

// ES_VARIABLE_2 - \ счетчик

// ES_REG_2 - /

// ES_SPECIFIC_0 - сюда подставить операцию

//. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .



const static int block_03_operation_AB[] =

{

EO_XOR, EO_ADD, EO_SUB

};


const static int block_03_operation_BA[] =

{

EO_XOR, EO_SUB, EO_ADD

};


BLOCK_START(03_00)

ES_SPECIFIC_0, EOP_REF_REG, ES_REG_0, EOP_REG, ES_REG_1

BLOCK_END(03_00)


BLOCK_START(03_01)

ES_SPECIFIC_0, EOP_REF_VAR, ES_VARIABLE_0, EOP_REG, ES_REG_1

BLOCK_END(03_01)


BLOCK_START(03_02)

ES_SPECIFIC_0, EOP_REF_REG, ES_REG_0, EOP_REG, ES_REG_2

BLOCK_END(03_02)


BLOCK_START(03_03)

ES_SPECIFIC_0, EOP_REF_VAR, ES_VARIABLE_0, EOP_REG, ES_REG_2

BLOCK_END(03_03)


BLOCK_START(03_04)

ES_SPECIFIC_0, EOP_REF_REG, ES_REG_0, EOP_VAR, ES_VARIABLE_1

BLOCK_END(03_04)


BLOCK_START(03_05)

ES_SPECIFIC_0, EOP_REF_VAR, ES_VARIABLE_0, EOP_VAR, ES_VARIABLE_1

BLOCK_END(03_05)


BLOCK_START(03_06)

ES_SPECIFIC_0, EOP_REF_REG, ES_REG_0, EOP_VAR, ES_VARIABLE_2

BLOCK_END(03_06)


BLOCK_START(03_07)

ES_SPECIFIC_0, EOP_REF_VAR, ES_VARIABLE_0, EOP_VAR, ES_VARIABLE_2

BLOCK_END(03_07)


BLOCKS_START(03)

BLOCK(03_00)

BLOCK(03_01)

BLOCK(03_02)

BLOCK(03_03)

BLOCK(03_04)

BLOCK(03_05)

BLOCK(03_06)

BLOCK(03_07)

BLOCKS_END(03)


BLOCKS_SIZE_START(03)

BLOCK_SIZE(03_00)

BLOCK_SIZE(03_01)

BLOCK_SIZE(03_02)

BLOCK_SIZE(03_03)

BLOCK_SIZE(03_04)

BLOCK_SIZE(03_05)

BLOCK_SIZE(03_06)

BLOCK_SIZE(03_07)

BLOCKS_SIZE_END(03)

//-----------------------------------------------------------------------------


//-----------------------------------------------------------------------------

// Блок N4. (x1)

// Служит для увеличения значения указателя.

// ES_VARIABLE_0 - ячейка которая может быть занята под указатель.

// ES_REG_0 - регистр который может быть занят под указатель.

BLOCK_START(04_00)

EO_ADD, EOP_VAR, ES_VARIABLE_0, EOP_CONST, 1

BLOCK_END(04_00)


BLOCK_START(04_01)

EO_INC, EOP_VAR, ES_VARIABLE_0

BLOCK_END(04_01)


BLOCK_START(04_02)

EO_INC, EOP_REG, ES_REG_0

BLOCK_END(04_02)


BLOCK_START(04_03)

EO_SUB, EOP_VAR, ES_VARIABLE_0, EOP_CONST, -1

BLOCK_END(04_03)


BLOCK_START(04_04)

EO_SUB, EOP_REG, ES_REG_0, EOP_CONST, -1

BLOCK_END(04_04)


BLOCK_START(04_05)

EO_NEG, EOP_REG, ES_REG_0,

ES_RANDOM_NOP,

ES_RANDOM_NOP,

EO_DEC, EOP_REG, ES_REG_0,

EO_NEG, EOP_REG, ES_REG_0

BLOCK_END(04_05)


BLOCKS_START(04)

BLOCK(04_00)

BLOCK(04_01)

BLOCK(04_02)

BLOCK(04_03)

BLOCK(04_04)

BLOCK(04_05)

BLOCKS_END(04)


BLOCKS_SIZE_START(04)

BLOCK_SIZE(04_00)

BLOCK_SIZE(04_01)

BLOCK_SIZE(04_02)

BLOCK_SIZE(04_03)

BLOCK_SIZE(04_04)

BLOCK_SIZE(04_05)

BLOCKS_SIZE_END(04)

//-----------------------------------------------------------------------------


//-----------------------------------------------------------------------------

// Блок N5. (x1)

// Служит для организации цикла.

// ES_VARIABLE_0 - ячейка которая может быть занята под счетчик.

// ES_REG_0 - регистр который может быть занят под счетчик.

// ES_ADDRESS_0 - куда осуществить переход для повтора цикла.


BLOCK_START(05_00)

EO_DEC, EOP_VAR, ES_VARIABLE_0,

EO_CMP, EOP_VAR, ES_VARIABLE_0, EOP_CONST, 0,

EO_JNZ, EOP_CONST, ES_ADDRESS_0

BLOCK_END(05_00)


BLOCK_START(05_01)

EO_DEC, EOP_REG, ES_REG_0,

EO_CMP, EOP_REG, ES_REG_0, EOP_CONST, 0,

EO_JNZ, EOP_CONST, ES_ADDRESS_0

BLOCK_END(05_01)


BLOCKS_START(05)

BLOCK(05_00)

BLOCK(05_01)

BLOCKS_END(05)


BLOCKS_SIZE_START(05)

BLOCK_SIZE(05_00)

BLOCK_SIZE(05_01)

BLOCKS_SIZE_END(05)

//-----------------------------------------------------------------------------


//-----------------------------------------------------------------------------

// Блок N6. (x1)

// Служит для проверки временных ограничений. (может отсутсвовать)

// ES_CONST_0 - константа которая может содержать дату для контроля.

// ES_VARIABLE_0 - ячейка которая может содержать дату для контроля.


BLOCK_START(06_00)

EO_TEST_TIME_0, EOP_CONST, ES_CONST_0

BLOCK_END(06_00)


BLOCK_START(06_01)

EO_TEST_TIME_1, EOP_CONST, ES_CONST_0

BLOCK_END(06_01)


BLOCK_START(06_02)

EO_TEST_TIME_0, EOP_VAR, ES_VARIABLE_0

BLOCK_END(06_02)


BLOCK_START(06_03)

EO_TEST_TIME_1, EOP_VAR, ES_VARIABLE_0

BLOCK_END(06_03)


BLOCKS_START(06)

BLOCK(06_00)

BLOCK(06_01)

BLOCK(06_02)

BLOCK(06_03)

BLOCKS_END(06)


BLOCKS_SIZE_START(06)

BLOCK_SIZE(06_00)

BLOCK_SIZE(06_01)

BLOCK_SIZE(06_02)

BLOCK_SIZE(06_03)

BLOCKS_SIZE_END(06)



//-----------------------------------------------------------------------------

// Блок N7. (x1)

// Служит для завершения.


BLOCK_START(07_00)

EO_EXIT_0

BLOCK_END(07_00)


BLOCK_START(07_01)

EO_EXIT_1

BLOCK_END(07_01)


BLOCK_START(07_02)

EO_EXIT_2,

EO_NOP_0,

EO_JMP, EOP_CONST, 0

BLOCK_END(07_02)


BLOCKS_START(07)

BLOCK(07_00)

BLOCK(07_01)

BLOCK(07_02)

BLOCKS_END(07)


BLOCKS_SIZE_START(07)

BLOCK_SIZE(07_00)

BLOCK_SIZE(07_01)

BLOCK_SIZE(07_02)

BLOCKS_SIZE_END(07)


//-----------------------------------------------------------------------------

// Блок NOP.

BLOCK_START(nop_00)

EO_XCHG, EOP_REG, ES_RANDOM_REG, EOP_VAR, ES_RANDOM_VAR,

BLOCK_END(nop_00)


BLOCK_START(nop_01)

EO_ADD, EOP_REG, ES_RANDOM_REG, EOP_REG, ES_RANDOM_USE_REG,

BLOCK_END(nop_01)


BLOCK_START(nop_02)

EO_NOP_0

BLOCK_END(nop_02)


BLOCK_START(nop_03)

EO_NOP_1

BLOCK_END(nop_03)


BLOCK_START(nop_04)

EO_NOP_2

BLOCK_END(nop_04)


BLOCK_START(nop_05)

EO_NOP_3

BLOCK_END(nop_05)


BLOCK_START(nop_06)

EO_MOV, EOP_REG, ES_RANDOM_REG, EOP_RAND

BLOCK_END(nop_06)


BLOCKS_START(Nops)

BLOCK(nop_00)

BLOCK(nop_01)

BLOCK(nop_02)

BLOCK(nop_03)

BLOCK(nop_04)

BLOCK(nop_05)

BLOCK(nop_06)

BLOCKS_END(Nops)


BLOCKS_SIZE_START(Nops)

BLOCK_SIZE(nop_00)

BLOCK_SIZE(nop_01)

BLOCK_SIZE(nop_02)

BLOCK_SIZE(nop_03)

BLOCK_SIZE(nop_04)

BLOCK_SIZE(nop_05)

BLOCK_SIZE(nop_06)

BLOCKS_SIZE_END(Nops)

//-----------------------------------------------------------------------------


#endif // __BLOCKS_H__



Файл p_enums.h.


#ifndef __P_ENUMS_H__

#define __P_ENUMS_H__


#ifndef CALC_ARRAY_SIZE

#define CALC_ARRAY_SIZE(arr) ((int) (sizeof arr / sizeof arr[0]))

#endif


enum E_OPERATION // Инструкции

{

EO_ERROR = -1, // Недопустимая инструкция

EO_EXIT_0, EO_EXIT_1, EO_EXIT_2, // Конец рабоботы

EO_NOP_0, EO_NOP_1, EO_NOP_2, EO_NOP_3, // Пустые команды

EO_TEST_TIME_0, EO_TEST_TIME_1, // Контроль времени

EO_MOV, EO_XCHG, // Пересылка данных

EO_PUSH, EO_POP, // Работа со стеком

EO_XOR, EO_AND, EO_OR, EO_NOT, // Логические операции

EO_ADD, EO_SUB, EO_MUL, EO_DIV, EO_NEG, // Арифметические операции

EO_INC, EO_DEC,

EO_TEST, EO_CMP, // Операции сравнения

// (влияют на флаги)

EO_JMP, EO_CALL, EO_RET, // Операторы безусловного перехода

EO_JZ, EO_JNZ, EO_JA, EO_JNA, // Условные переходы

};


#define LAST_DEFINED_NOP EO_NOP_3

#define LAST_OPERATION EO_JNA


enum E_FLAGS // Флаги

{

EF_ZERO = 1, // Ноль

EF_ABOVE = 2, // Больше

};


enum E_OPERAND

{ // Операндом является:

EOP_REG = 0, // Регистр

EOP_REF_REG, // Память по адресу в регистре

EOP_VAR, // Переменная

EOP_REF_VAR, // Память по адресу в переменная

EOP_CONST, // Константное значение

EOP_RAND // Случайное число

};


enum E_SUBSTITUTION // Подстановки

{

// НЕ зАБЫВАТЬ подправить ArraySubstitution

ES_RANDOM_NOP = 0x0A0FF00, // Сюда можно подставить любой NOP-блок

ES_RANDOM_CONST = 0x0A0FF01, // Сюда можно подставит любое число

ES_RANDOM_REG = 0x0A0FF02, // Сюда можно подставить любой незанятый

// регистр

ES_RANDOM_VAR = 0x0A0FF03, // Сюда можно подставить любую незанятую

// переменную

ES_RANDOM_USE_REG = 0x0A0FF04, // Сюда можно подставить любой незанятый

// или занятый регистр

ES_RANDOM_USE_VAR = 0x0A0FF05, // Сюда можно подставить любую незанятую

// или занятую переменную

ES_VARIABLE_0 = 0x0B0FF02, // Сюда подставляются данные, актуальные

ES_VARIABLE_1 = 0x0B0FF03, // для данного блока

ES_VARIABLE_2 = 0x0B0FF04,

ES_REG_0 = 0x0C0FF05,

ES_REG_1 = 0x0C0FF06,

ES_REG_2 = 0x0C0FF07,

ES_ADDRESS_0 = 0x0D0AA08,

ES_ADDRESS_1 = 0x0D0AA09,

ES_CONST_0 = 0x0E0AA0A,

ES_CONST_1 = 0x0E0AA0B,

ES_SPECIFIC_0 = 0x0E0BB0C,

ES_SPECIFIC_1 = 0x0E0BB0D

};


static const E_SUBSTITUTION AllSubstitution[] =

{ ES_RANDOM_NOP, ES_RANDOM_CONST, ES_RANDOM_REG, ES_RANDOM_VAR,

ES_RANDOM_USE_REG, ES_RANDOM_USE_VAR,

ES_VARIABLE_0, ES_VARIABLE_1, ES_VARIABLE_2,

ES_REG_0, ES_REG_1, ES_REG_2,

ES_ADDRESS_0, ES_ADDRESS_1,

ES_CONST_0, ES_CONST_1,

ES_SPECIFIC_0, ES_SPECIFIC_1

};

unsigned AllSubstitutionSize = CALC_ARRAY_SIZE(AllSubstitution);


#endif // __P_ENUMS_H__



Файл pdebug.h.


#ifndef __PDEBUG_H__

#define __PDEBUG_H__


#ifdef _DEBUG

#define WRITE_LOG

#endif


#ifdef WRITE_LOG

void WriteToLog(LPCTSTR str, bool newLine = true);

void WriteToLog(int num, bool newLine = true);

#else

inline void WriteToLog(LPCTSTR, bool = true) { }

inline void WriteToLog(int, bool = true) { }

#endif


#endif //__PDEBUG_H__



Файл pdebug.cpp.


#include "stdafx.h"

#include

#include "pdebug.h"

#include "ckg_str.h"


#ifdef WRITE_LOG

static FILE *logFile = NULL;

void WriteToLog(LPCTSTR str, bool newLine)

{

if (!logFile)

{

logFile = _tfopen(_T("uniprot.log"), _T("wb"));

_ASSERT(logFile);

}

fwrite(str, sizeof(TCHAR), _tcslen(str), logFile);

if (newLine)

{

static LPCTSTR endStr = _T("\r\n");

fwrite(endStr, sizeof(TCHAR), _tcslen(endStr), logFile);

}

fflush(logFile);

}

void WriteToLog(int num, bool newLine)

{

CkgString str;

str.Format(_T("%d "), num);

WriteToLog(str, newLine);

}

#endif



Файл polymorphism.h.


#ifndef __POLYMORPHISM_H__

#define __POLYMORPHISM_H__


// Чему должны быть кранты размеры данных.

#define ROUND_SATA_SIZE 64


// Минимально допустимый год.

// (Вычитется в GetCurrentDayNum)

#define MIN_YEAR 1970 // бездумно не трогать.

// (подумать над DataToDay())


void CryptData (BYTE &dataArray, size_t size, BYTE &algorithmDataArray,

size_t algorithmDataSize);


void DecryptData(BYTE &dataArray, size_t size, BYTE &algorithmDataArray,

size_t algorithmDataSize);


void CryptData (BYTE &dataArray, size_t size, const TCHAR &fileName);


void DecryptData(BYTE &dataArray, size_t size, const TCHAR &fileName);


unsigned GetCurrentDayNum();


void GenerateAlgorithm(pure_c_ptr &algorithmCrypt, size_t &sizeCrypt,

pure_c_ptr &algorithmDecrypt, size_t &sizeDecrypt,

unsigned deltaTimeCrypt = 0,

unsigned deltaTimeDecrypt = 0);


void GenerateAlgorithm(const TCHAR &algorithmCryptFileName,

const TCHAR &algorithmDecryptFileName,

unsigned deltaTimeCrypt = 0,

unsigned deltaTimeDecrypt = 0);


int CoolRand();

int CoolRand(unsigned limit);


#endif // __POLYMORPHISM_H__



Файл polymorphism.cpp.


#include "stdafx.h"

#include

#include

#include

#include "resource.h"

#include "cpp_ptr.h"

#include "c_ptr.h"

#include "ckg_str.h"

#include "ckg_error.h"

#include "ckg_alloc.h"

#include "ckg_array.h"

#include "polymorphism.h"

#include "p_enums.h"

#include "blocks.h"

#include "pdebug.h"


// Количество переменных для виртуальной машины.

// В отличии от виртуальных регистров, переменные

// явдяются инициализированными до начала работы.

const unsigned variablesNum = 20;


// Количество виртуальных регистров

const unsigned registersNum = 10;


const BYTE idSupportAlgorithm = 1; // Идентификатор блока с алгоритмом

const BYTE idCryptAlgorithm = 0; // Алгоритм для шифрования

const BYTE idDecryptAlgorithm = 1; // Алгоритм для расшифрования


const unsigned maxUseTime = INT_MAX; // Ограничение по максимальному

// времени использования (дней).


typedef CkgSimpleContainerArray Block;


struct AlgorithmDataStruct

{

BYTE idSupportAlgorithm;

BYTE idType;

size_t sizeAll;

int variables[variablesNum];

unsigned numVarForSetSize; // В переменную с этим номером занести

// размер данных

};


const unsigned minSizeAlgorithm = 160; // Придельные размеры алгоритма.

const unsigned maxSizeAlgorithm = 200; //

const unsigned minNumTransformation = 2; // Придельное количество

const unsigned maxNumTransformation = 5; // трансформаций.

const unsigned numBlocks = 8; // Количество блоков.

const unsigned numBlocksBeforeLoop = 3; // Количество блоков до метки

// Loop.

const unsigned dataSizeSmoothing = ROUND_SATA_SIZE;

// Чему должны быть кранты

// размеры данных


struct AlgorithmParameters

{

unsigned sizeAlgorithm; // Размер алгоритма

unsigned numTransformation; // Количество блоков для преобразования

bool addressIsReg; // Адрес в регистре или переменной

unsigned addressNumber; // Номер переменной или регистра где

// будет храниться адрес.

bool modificatoryIsReg[maxNumTransformation];

// Модификатор регистр / переменная.

unsigned modificatorsNumbers[maxNumTransformation];

// Номера регистров/переменных для

// модификаторов.

unsigned counterIsReg; // Счетчик в регистре или переменной.

unsigned counterNumber; // Номер переменной или регистра где

// будет храниться счетчик.

unsigned initCounterNumber; // Какую переменную использовать для

// инициализации счетчика

unsigned totalNumTrueBlocks; // Сколько всего блоков должно получиться

// (без учета nops)


bool usedRegisters[registersNum]; // Занятые регистры.

bool usedVariables[variablesNum]; // Занятые перемненные.

};


//-----------------------------------------------------------------------------

#ifdef _DEBUG

void DebugTestBlock(int a)

{

unsigned sizeArrayAllSubstitution = CALC_ARRAY_SIZE(AllSubstitution);


_ASSERT(a != EO_ERROR);

for (unsigned i = 0; i < sizeArrayAllSubstitution; i++)

_ASSERT(AllSubstitution[i] != a);


}

#define DEBUG_TEST_BLOCK(a) DebugTestBlock(a)

#else

#define DEBUG_TEST_BLOCK(a)

#endif // _DEBUG

//-----------------------------------------------------------------------------

int TestRegNum(int reg)

{

if (reg < 0 || reg >= registersNum)

CkgExcept(_T("error register number"));

return reg;

}

//-----------------------------------------------------------------------------

int TestVarNum(int var)

{

if (var < 0 || var >= variablesNum)

CkgExcept(_T("error variables number"));

return var;

}

//-----------------------------------------------------------------------------

void SkepValue(const int *&p)

{

E_OPERAND operand = static_cast(*p++);

switch (operand)

{

case EOP_REG:

case EOP_REF_REG:

case EOP_VAR:

case EOP_REF_VAR:

case EOP_CONST: *p++; return;

case EOP_RAND: return;

default: CkgExcept(_T("error operand type"));

}

}

//-----------------------------------------------------------------------------

int GetValue(const int *&p, int &variables, int ®isters, const int &data)

{

E_OPERAND operand = static_cast(*p++);

int reg, var;

switch (operand)

{

case EOP_REG: reg = TestRegNum(*p++);

WriteToLog(_T("REG_"), false);

WriteToLog(reg, false);

return (®isters)[reg];

case EOP_REF_REG: {

reg = TestRegNum(*p++);

int n = (®isters)[reg];

WriteToLog(_T("REF_REG_"), false);

WriteToLog(reg, false);

return (&data)[n];

}

case EOP_VAR: var = TestVarNum(*p++);

WriteToLog(_T("VAR_"), false);

WriteToLog(var, false);

return (&variables)[var];

case EOP_REF_VAR: {

var = TestVarNum(*p++);

int n = (&variables)[var];

WriteToLog(_T("REF_VAR_"), false);

WriteToLog(var, false);

return (&data)[n];

}

case EOP_CONST: WriteToLog(_T("CONST "), false);

return *p++;

case EOP_RAND: WriteToLog(_T("RAND "), false);

return CoolRand();

default: CkgExcept(_T("error operand type"));

}

return 0; // anti warning

}

//-----------------------------------------------------------------------------

void SetValue(const int *&p, int &variables, int ®isters, int &data,

int value)

{

E_OPERAND operand = static_cast(*p++);

int reg, var;

switch (operand)

{

case EOP_REG: reg = TestRegNum(*p++);

(®isters)[reg] = value;

WriteToLog(_T("REG_"), false);

WriteToLog(reg, false);

break;

case EOP_REF_REG: {

reg = TestRegNum(*p++);

int n = (®isters)[reg];

(&data)[n] = value;

WriteToLog(_T("REF_REG_"), false);

WriteToLog(reg, false);

break;

}

case EOP_VAR: var = TestVarNum(*p++);

(&variables)[var] = value;

WriteToLog(_T("VAR_"), false);

WriteToLog(var, false);

break;

case EOP_REF_VAR: {

var = TestVarNum(*p++);

int n = (&variables)[var];

(&data)[n] = value;

WriteToLog(_T("REF_VAR_"), false);

WriteToLog(var, false);

break;

}

default: CkgExcept(_T("error operand type"));

}

}

//-----------------------------------------------------------------------------

void TranslateOperations(const int &operations, const int &variables,

BYTE &memory)

{

const int *p = &operations;

cpp_arr_ptr vars(new int[variablesNum]);

TestPtr(vars);

cpp_arr_ptr regs(new int[registersNum]);

TestPtr(regs);

memcpy(vars.ptr(), &variables, variablesNum * sizeof(int));

memset(regs.ptr(), 0, registersNum * sizeof(int));

int *data = reinterpret_cast(&memory);

CkgSimpleContainerArray stack;

unsigned flags = 0;


WriteToLog(_T("\r\n=== Start TranslateOperations ===\r\n"));


E_OPERATION operation;

for (;;)

{

if (*p == EO_ERROR)

CkgExcept(IDS_PL_ERROR_INSTRUCTION_IN_ALG_0);

if (*p < 0 || *p > LAST_OPERATION)

CkgExcept(IDS_PL_ERROR_INSTRUCTION_IN_ALG);

operation = static_cast(*p++);

switch (operation)

{

case EO_EXIT_0: WriteToLog(_T("exit")); return;

case EO_EXIT_1: WriteToLog(_T("exit")); return;

case EO_EXIT_2: WriteToLog(_T("exit")); return;

case EO_NOP_0: break;

case EO_NOP_1: break;

case EO_NOP_2: break;

case EO_NOP_3: break;

case EO_MOV: {

WriteToLog(_T("mov "), false);

const int *oldP = p;

SkepValue(p);

int value = GetValue(p, *vars, *regs, *data);

WriteToLog(_T(" ==> "), false);

SetValue(oldP, *vars, *regs, *data, value);

WriteToLog(_T(""));

break;

}

case EO_XCHG: {

const int *oldP = p;

WriteToLog(_T("xchg "), false);

int value1 = GetValue(p, *vars, *regs, *data);

int value2 = GetValue(p, *vars, *regs, *data);

p = oldP;

WriteToLog(_T(" <==> "), false);

SetValue(p, *vars, *regs, *data, value2);

SetValue(p, *vars, *regs, *data, value1);

WriteToLog(_T(""));

break;

}

case EO_PUSH: {

WriteToLog(_T("push "), false);

int value = GetValue(p, *vars, *regs, *data);

WriteToLog(_T(""));

stack.Add(value);

break;

}

case EO_POP: {

WriteToLog(_T("pop "), false);

int value = stack.Remove(stack.GetSize() - 1);

SetValue(p, *vars, *regs, *data, value);

WriteToLog(_T(""));

break;

}

case EO_XOR:

case EO_AND:

case EO_OR:

case EO_ADD:

case EO_SUB:

case EO_MUL:

case EO_DIV:

{

const int *oldP = p;

#ifdef WRITE_LOG

if (operation == EO_XOR)

WriteToLog(_T("xor "), false);

else if (operation == EO_AND)

WriteToLog(_T("and "), false);

else if (operation == EO_OR)

WriteToLog(_T("or "), false);

else if (operation == EO_ADD)

WriteToLog(_T("add "), false);

else if (operation == EO_SUB)

WriteToLog(_T("sub "), false);

else if (operation == EO_MUL)

WriteToLog(_T("mul "), false);

else if (operation == EO_DIV)

WriteToLog(_T("div "), false);

#endif

int value1 = GetValue(p, *vars, *regs, *data);

int value2 = GetValue(p, *vars, *regs, *data);

WriteToLog(_T(" ==> "), false);

int result = 0; // anti warning

if (operation == EO_XOR)

result = value1 ^ value2;

else if (operation == EO_AND)

result = value1 & value2;

else if (operation == EO_OR)

result = value1 | value2;

else if (operation == EO_ADD)

result = value1 + value2;

else if (operation == EO_SUB)

result = value1 - value2;

else if (operation == EO_MUL)

result = value1 * value2;

else if (operation == EO_DIV)

result = value1 / value2;

else

CkgExcept();

SetValue(oldP, *vars, *regs, *data, result);

WriteToLog(_T(""));

break;

}

case EO_NOT:

case EO_NEG:

case EO_INC:

case EO_DEC:

{

const int *oldP = p;

#ifdef WRITE_LOG

if (operation == EO_NOT)

WriteToLog(_T("not "), false);

else if (operation == EO_NEG)

WriteToLog(_T("neg "), false);

else if (operation == EO_INC)

WriteToLog(_T("inc "), false);

else if (operation == EO_DEC)

WriteToLog(_T("dec "), false);

#endif

int value = GetValue(p, *vars, *regs, *data);

if (operation == EO_NOT)

value = 0 ^ value;

else if (operation == EO_NEG)

value = -value;

else if (operation == EO_INC)

value++;

else if (operation == EO_DEC)

value--;

else

CkgExcept();

WriteToLog(" ==> ", false);

SetValue(oldP, *vars, *regs, *data, value);

WriteToLog("");

break;

}

case EO_CMP:

case EO_TEST:

{

#ifdef WRITE_LOG

if (operation == EO_CMP)

WriteToLog(_T("cmp "), false);

else if (operation == EO_TEST)

WriteToLog(_T("test "), false);

#endif

int value1 = GetValue(p, *vars, *regs, *data);

int value2 = GetValue(p, *vars, *regs, *data);

WriteToLog("");

flags = 0;

if (operation == EO_CMP)

{

flags = ((value1 == value2) * EF_ZERO) |

((value1 < value2) * EF_ABOVE);

}

else if (operation == EO_TEST)

{

flags = (((value1 & value2) == 0) * EF_ZERO);

}

else

CkgExcept();

break;

}

case EO_JMP: {

WriteToLog(_T("jmp "), false);

int addr = GetValue(p, *vars, *regs, *data);

WriteToLog("\r\n");

p = (&operations) + addr;

break;

}

case EO_CALL: {

WriteToLog(_T("call "), false);

int addr = GetValue(p, *vars, *regs, *data);

WriteToLog("\r\n");

stack.Add(p - (&operations));

p = (&operations) + addr;

break;

}

case EO_RET: {

WriteToLog(_T("ret\r\n"));

int addr = stack.Remove(stack.GetSize() - 1);

p = (&operations) + addr;

break;

}

case EO_JZ:

case EO_JNZ:

case EO_JA:

case EO_JNA:

{

#ifdef WRITE_LOG

if (operation == EO_JZ)

WriteToLog(_T("jz "), false);

if (operation == EO_JNZ)

WriteToLog(_T("jnz "), false);

if (operation == EO_JA)

WriteToLog(_T("ja "), false);

if (operation == EO_JNA)

WriteToLog(_T("jna "), false);

#endif

int addr = GetValue(p, *vars, *regs, *data);

WriteToLog("\r\n");

if (operation == EO_JZ && !(flags & EF_ZERO))

break;

else if (operation == EO_JNZ && (flags & EF_ZERO))

break;

else if (operation == EO_JA && !(flags & EF_ABOVE))

break;

else if (operation == EO_JNA && (flags & EF_ABOVE))

break;

p = (&operations) + addr;

break;

}

case EO_TEST_TIME_0:

{

WriteToLog(_T("test_time0 "), false);

int day = abs(GetValue(p, *vars, *regs, *data));

WriteToLog("");

if (static_cast(GetCurrentDayNum()) > day)

{

WriteToLog("ERROR TIME (except)");

data[0] ^= 0x00030001;

break;

}

WriteToLog("OK TIME (continue)");

break;

}

case EO_TEST_TIME_1:

{

WriteToLog(_T("test_time1 "), false);

int dayTmp = GetValue(p, *vars, *regs, *data);

WriteToLog("");

unsigned day = static_cast(abs(dayTmp));

if (GetCurrentDayNum() <= day)

{

WriteToLog("OK TIME (continue)");

break;

}

WriteToLog("ERROR TIME (except)");

GetValue(p, *vars, *regs, *data);

GetValue(p, *vars, *regs, *data);

SetValue(p, *vars, *regs, *data, 0);

p = (&operations) - dayTmp;

break;

}

}

}

}

//-----------------------------------------------------------------------------

void CryptDecryptData(BYTE &dataArray, size_t size, BYTE &algorithmDataArray,

size_t algorithmDataSize, bool crypt)

{

_ASSERT(dataSizeSmoothing >= sizeof(int) * maxNumTransformation);

if (!size || !algorithmDataSize || size % dataSizeSmoothing != 0)

CkgExcept(ERROR_INVALID_ARGUMENT);

AlgorithmDataStruct &alg = reinterpret_cast

(algorithmDataArray);

if (alg.idSupportAlgorithm != idSupportAlgorithm ||

(crypt && alg.idType != idCryptAlgorithm) ||

(!crypt && alg.idType != idDecryptAlgorithm))

CkgExcept(_T("unsupported crypt algorithm type"));

if (alg.sizeAll != algorithmDataSize)

CkgExcept(_T("error crypt algorithm size"));

alg.variables[alg.numVarForSetSize] = size / sizeof(int);


BYTE *p = &algorithmDataArray;

p += sizeof AlgorithmDataStruct;

// _ASSERT(DWORD(p) & 0x03 == 0x0);

_ASSERT(DWORD(p) % sizeof(int) == 0x0);

TranslateOperations(*reinterpret_cast(p), *alg.variables,

dataArray);

}

//-----------------------------------------------------------------------------

void CryptData(BYTE &dataArray, size_t size, BYTE &algorithmDataArray,

size_t algorithmDataSize)

{

CryptDecryptData(dataArray, size, algorithmDataArray,

algorithmDataSize, true);

}

//-----------------------------------------------------------------------------

void DecryptData(BYTE &dataArray, size_t size, BYTE &algorithmDataArray,

size_t algorithmDataSize)

{

CryptDecryptData(dataArray, size, algorithmDataArray,

algorithmDataSize, false);

}

//-----------------------------------------------------------------------------

void CryptDecryptData(BYTE &dataArray, size_t size, const TCHAR &fileName,

bool crypt)

{

FILE *f = _tfopen(&fileName, _T("rb"));

if (!f)

CkgExcept(ERROR_OPEN_FILE);

try

{

if (fseek(f, 0, SEEK_END))

CkgExcept(ERROR_READ_FILE);

long algorithmDataSize = ftell(f);

cpp_arr_ptr algorithmDataArray(new BYTE[algorithmDataSize]);

TestPtr(algorithmDataArray);

if (fseek(f, 0, SEEK_SET))

CkgExcept(ERROR_READ_FILE);

if (fread(algorithmDataArray, sizeof(BYTE), algorithmDataSize, f) !=

static_cast(algorithmDataSize))

CkgExcept(ERROR_READ_FILE);

if (fclose(f))

CkgExcept(ERROR_CLOSE_FILE);

f = 0;

CryptDecryptData(dataArray, size, *algorithmDataArray,

algorithmDataSize, crypt);

}

catch (...)

{

if (f)

fclose(f);

throw;

}

}

//-----------------------------------------------------------------------------

void CryptData(BYTE &dataArray, size_t size, const TCHAR &fileName)

{

CryptDecryptData(dataArray, size, fileName, true);

}

//-----------------------------------------------------------------------------

void DecryptData(BYTE &dataArray, size_t size, const TCHAR &fileName)

{

CryptDecryptData(dataArray, size, fileName, false);

}

//-----------------------------------------------------------------------------

unsigned GetRandomNonUsedRegister(const AlgorithmParameters ¶meters)

{

unsigned i;

unsigned numberNonUsedRegisters = 0;

for (i = 0; i < registersNum; i++)

numberNonUsedRegisters += !parameters.usedRegisters[i];

if (!numberNonUsedRegisters)

CkgExcept();

unsigned randomNum = CoolRand(numberNonUsedRegisters) + 1;

for (i = 0; i < registersNum; i++)

{

randomNum -= !parameters.usedRegisters[i];

if (!randomNum)

break;

}

_ASSERT(!randomNum && !parameters.usedRegisters[i]);

return i;

}

//-----------------------------------------------------------------------------

unsigned GetRandomNonUsedVariable(const AlgorithmParameters ¶meters)

{

unsigned i;

unsigned numberNonUsedVariables = 0;

for (i = 0; i < variablesNum; i++)

numberNonUsedVariables += !parameters.usedVariables[i];

if (!numberNonUsedVariables)

CkgExcept();

unsigned randomNum = CoolRand(numberNonUsedVariables) + 1;

for (i = 0; i < variablesNum; i++)

{

randomNum -= !parameters.usedVariables[i];

if (!randomNum)

break;

}

_ASSERT(!randomNum && !parameters.usedVariables[i]);

return i;

}

//-----------------------------------------------------------------------------

unsigned ReserveRandomNonUsedRegister(AlgorithmParameters ¶meters)

{

unsigned num = GetRandomNonUsedRegister(parameters);

parameters.usedRegisters[num] = true;

return num;

}

//-----------------------------------------------------------------------------

unsigned ReserveRandomNonUsedVariables(AlgorithmParameters ¶meters)

{

unsigned num = GetRandomNonUsedVariable(parameters);

parameters.usedVariables[num] = true;

return num;

}

//-----------------------------------------------------------------------------

void RandomInitAlgorithmParameters(AlgorithmParameters ¶meters,

unsigned numTransformation)

{

unsigned i;

for (i = 0; i < registersNum; i++)

parameters.usedRegisters[i] = false;

for (i = 0; i < variablesNum; i++)

parameters.usedVariables[i] = false;


parameters.sizeAlgorithm =

CoolRand(maxSizeAlgorithm - minSizeAlgorithm) + minSizeAlgorithm;

parameters.numTransformation = numTransformation;


parameters.addressIsReg = CoolRand(2) == 1;

if (parameters.addressIsReg)

parameters.addressNumber = ReserveRandomNonUsedRegister(parameters);

else

parameters.addressNumber = ReserveRandomNonUsedVariables(parameters);

for (i = 0; i < parameters.numTransformation; i++)

{

bool isReg = CoolRand(2) == 1;

parameters.modificatoryIsReg[i] = isReg;

if (isReg)

parameters.modificatorsNumbers[i] = ReserveRandomNonUsedRegister(parameters);

else

parameters.modificatorsNumbers[i] = ReserveRandomNonUsedVariables(parameters);

}


parameters.counterIsReg = CoolRand(2);

if (parameters.counterIsReg)

parameters.counterNumber = ReserveRandomNonUsedRegister(parameters);

else

parameters.counterNumber = ReserveRandomNonUsedVariables(parameters);


parameters.initCounterNumber = ReserveRandomNonUsedVariables(parameters);


parameters.totalNumTrueBlocks =

numBlocks + parameters.numTransformation * 2 - 2;

}

//-----------------------------------------------------------------------------

void RandomInitAlgorithmParameters(AlgorithmParameters (¶meters)[2])

{

SYSTEMTIME lpSystemTime;

GetSystemTime(&lpSystemTime);

srand(unsigned(lpSystemTime.wSecond) * 1000 + lpSystemTime.wMilliseconds);


unsigned numTransformation = (maxNumTransformation > minNumTransformation) ?

CoolRand(maxNumTransformation - minNumTransformation) + minNumTransformation :

1;

RandomInitAlgorithmParameters(parameters[0], numTransformation);

RandomInitAlgorithmParameters(parameters[1], numTransformation);

}

//-----------------------------------------------------------------------------

bool SearchSubstitution(const Block &block, unsigned &position)

{

unsigned blockSize = block.GetSize();

_ASSERT(position <= blockSize);

for (; position < blockSize; position++)

{

int a = block[position];

for (unsigned i = 0; i < AllSubstitutionSize; i++)

if (AllSubstitution[i] == a)

return true;

}

return false;

}

//-----------------------------------------------------------------------------

struct SAppropriate

{

bool testSize;

unsigned maxSize;

bool testContain;

const int *shouldContain;

unsigned numShouldContain;

bool testNotContain;

unsigned numNotShouldContain;

const int *notShouldContain;

SAppropriate() : testSize(false), maxSize(0),

testContain(false), shouldContain(NULL), numShouldContain(0),

testNotContain(false), notShouldContain(NULL), numNotShouldContain(0)

{ }

~SAppropriate() { }

};

//-----------------------------------------------------------------------------

bool Search(const int &block, unsigned blockSize, int needFind)

{

_ASSERT(blockSize);

unsigned j;

for (j = 0; j < blockSize; j++)

if ((&block)[j] == needFind)

break;

return !(j == blockSize);

}

//-----------------------------------------------------------------------------

bool SearchRandomAppropriateBlock(unsigned numberBlockForTest,

const unsigned &blocksSize,

const int * const &addrBlocks,

const SAppropriate &appropriate,

unsigned &retAppropriateBlock)

{

_ASSERT(numberBlockForTest);

CkgSimpleContainerArray convenianceSample;


for (unsigned i = 0; i < numberBlockForTest; i++)

{

unsigned blockSize = (&blocksSize)[i];

_ASSERT(blockSize);

if (appropriate.testSize && blockSize > appropriate.maxSize)

continue;

const int *block = (&addrBlocks)[i];

_ASSERT(block);

if (appropriate.testContain)

{

_ASSERT(appropriate.shouldContain && appropriate.numShouldContain);

bool found = true;

for (unsigned j = 0; j < appropriate.numShouldContain && found; j++)

{

int needFind = appropriate.shouldContain[j];

found = Search(*block, blockSize, needFind);

}

if (!found)

continue;

}

if (appropriate.testNotContain)

{

_ASSERT(appropriate.notShouldContain && appropriate.numNotShouldContain);

bool found = false;

for (unsigned j = 0; j < appropriate.numNotShouldContain && !found; j++)

{

int needFind = appropriate.notShouldContain[j];

found = Search(*block, blockSize, needFind);

}

if (found)

continue;

}

convenianceSample.Add(i);

}

unsigned numConvenianceSample = convenianceSample.GetSize();

if (!numConvenianceSample)

return false;

unsigned select = numConvenianceSample > 1 ?

CoolRand(numConvenianceSample) :

0;

retAppropriateBlock = convenianceSample[select];

return true;

}

//-----------------------------------------------------------------------------

bool ReplacemenRandomEntity(int &entity, const AlgorithmParameters ¶meters)

{

switch (entity)

{

case ES_RANDOM_NOP: {

unsigned NumNops = LAST_DEFINED_NOP - EO_NOP_0;

entity = CoolRand(NumNops);

entity += EO_NOP_0;

_ASSERT(entity >= EO_NOP_0 && entity <= LAST_DEFINED_NOP);

break;

}

case ES_RANDOM_CONST: entity = CoolRand(); break;

case ES_RANDOM_REG: entity = GetRandomNonUsedRegister(parameters); break;

case ES_RANDOM_VAR: entity = GetRandomNonUsedVariable(parameters); break;

case ES_RANDOM_USE_REG: entity = CoolRand(registersNum); break;

case ES_RANDOM_USE_VAR: entity = CoolRand(variablesNum); break;

default: return false;

}

return true;

}

//-----------------------------------------------------------------------------

void CreateNopBlock(Block &block, AlgorithmParameters ¶meters, cpp_arr_ptr &,

unsigned maxSize)

{

_ASSERT(block.IsEmpty());

if (!maxSize)

CkgExcept();


SAppropriate appropriate;

appropriate.testSize = true;

appropriate.maxSize = maxSize;


unsigned index;

if (!SearchRandomAppropriateBlock(sizeBlocksArray_Nops, *sizeBlocks_Nops,

*blocks_Nops, appropriate, index))

CkgExcept();


for (unsigned i = 0; i < sizeBlocks_Nops[index]; i++)

block.Add(blocks_Nops[index][i]);


unsigned position = 0;

while (SearchSubstitution(block, position))

{

if (!ReplacemenRandomEntity(block.GetRef(position), parameters))

CkgExcept();

DEBUG_TEST_BLOCK(block.Get(position));

position++;

}

}

//-----------------------------------------------------------------------------

void CreateBlock0_(Block &block, AlgorithmParameters ¶meters, cpp_arr_ptr &)

{

_ASSERT(block.IsEmpty());

SAppropriate appropriate;

appropriate.testContain = true;

appropriate.numShouldContain = 1;

int whatSearch = parameters.addressIsReg ? ES_REG_0 : ES_VARIABLE_0;

appropriate.shouldContain = &whatSearch;


unsigned index;

if (!SearchRandomAppropriateBlock(sizeBlocksArray_00, *sizeBlocks_00,

*blocks_00, appropriate, index))

CkgExcept();


for (unsigned i = 0; i < sizeBlocks_00[index]; i++)

block.Add(blocks_00[index][i]);


unsigned position = 0;

while (SearchSubstitution(block, position))

{

if (!ReplacemenRandomEntity(block.GetRef(position), parameters))

{

int newValue = EO_ERROR;

int b = block[position];

switch (b)

{

case ES_REG_0: _ASSERT(parameters.addressIsReg);

newValue = parameters.addressNumber;

break;

case ES_VARIABLE_0: _ASSERT(!parameters.addressIsReg);

newValue = parameters.addressNumber;

break;

default: CkgExcept();

}

block.GetRef(position) = newValue;

}

DEBUG_TEST_BLOCK(block.Get(position));

position++;

}

}

//-----------------------------------------------------------------------------

void CreateBlock0(Block block[], AlgorithmParameters parameters[], cpp_arr_ptr vars[])

{

CreateBlock0_(block[0], parameters[0], vars[0]);

CreateBlock0_(block[1], parameters[1], vars[1]);

}

//-----------------------------------------------------------------------------

void CreateBlock1_(Block &block, AlgorithmParameters ¶meters, cpp_arr_ptr &)

{

_ASSERT(block.IsEmpty());

SAppropriate appropriate;

appropriate.testContain = true;

appropriate.numShouldContain = 1;

int whatSearch = parameters.counterIsReg ? ES_REG_0 : ES_VARIABLE_0;

appropriate.shouldContain = &whatSearch;


unsigned index;

if (!SearchRandomAppropriateBlock(sizeBlocksArray_01, *sizeBlocks_01,

*blocks_01, appropriate, index))

CkgExcept();


for (unsigned i = 0; i < sizeBlocks_01[index]; i++)

block.Add(blocks_01[index][i]);


unsigned position = 0;

while (SearchSubstitution(block, position))

{

if (!ReplacemenRandomEntity(block.GetRef(position), parameters))

{

int newValue = EO_ERROR;

int b = block[position];

switch (b)

{

case ES_REG_0: _ASSERT(parameters.counterIsReg);

newValue = parameters.counterNumber;

break;

case ES_VARIABLE_0: _ASSERT(!parameters.counterIsReg);

newValue = parameters.counterNumber;

break;

case ES_VARIABLE_1: newValue =

parameters.initCounterNumber;

break;

default: CkgExcept();

}

block.GetRef(position) = newValue;

}

DEBUG_TEST_BLOCK(block.Get(position));

position++;

}

}

//-----------------------------------------------------------------------------

void CreateBlock1(Block block[], AlgorithmParameters parameters[],

cpp_arr_ptr vars[])

{

CreateBlock1_(block[0], parameters[0], vars[0]);

CreateBlock1_(block[1], parameters[1], vars[1]);

}

//-----------------------------------------------------------------------------

void CreateBlock2_(Block &block, AlgorithmParameters ¶meters,

cpp_arr_ptr &vars, unsigned n, int randValue)

{

_ASSERT(n < maxNumTransformation);


SAppropriate appropriate;

appropriate.testContain = true;

appropriate.numShouldContain = 1;

int whatSearch = parameters.modificatoryIsReg[n] ? ES_REG_0 : ES_VARIABLE_0;

appropriate.shouldContain = &whatSearch;


unsigned index;

if (!SearchRandomAppropriateBlock(sizeBlocksArray_02, *sizeBlocks_02,

*blocks_02, appropriate, index))

CkgExcept();


for (unsigned i = 0; i < sizeBlocks_02[index]; i++)

block.Add(blocks_02[index][i]);


unsigned position = 0;

while (SearchSubstitution(block, position))

{

if (!ReplacemenRandomEntity(block.GetRef(position), parameters))

{

int newValue = EO_ERROR;

int b = block[position];

switch (b)

{

case ES_REG_0: _ASSERT(parameters.modificatoryIsReg[n]);

newValue = parameters.modificatorsNumbers[n];

break;

case ES_VARIABLE_0: _ASSERT(!parameters.modificatoryIsReg[n]);

newValue = parameters.modificatorsNumbers[n];

break;

case ES_VARIABLE_1: {

unsigned varNum =

ReserveRandomNonUsedVariables(parameters);

vars[varNum] = randValue;

newValue = static_cast(varNum);

break;

}

case ES_CONST_0: newValue = randValue;

break;

default: CkgExcept();

}

block.GetRef(position) = newValue;

}

DEBUG_TEST_BLOCK(block.Get(position));

position++;

}

}

//-----------------------------------------------------------------------------

void CreateBlock2(Block block[], AlgorithmParameters parameters[],

cpp_arr_ptr vars[], unsigned n)

{

int randValue = CoolRand();

CreateBlock2_(block[0], parameters[0], vars[0], n, randValue);

CreateBlock2_(block[1], parameters[1], vars[1], n, randValue);

}

//-----------------------------------------------------------------------------

void CalcBlocksSize(Block (*blocks)[2], unsigned num, unsigned &size1, unsigned &size2)

{

_ASSERT(num);

unsigned i;

size1 = 0;

for (i = 0; i < num; i++)

size1 += blocks[i][0].GetSize();

size2 = 0;

for (i = 0; i < num; i++)

size2 += blocks[i][1].GetSize();

}

//-----------------------------------------------------------------------------

void CreateLoopAddres_(unsigned num, const AlgorithmParameters ¶meters,

unsigned sizeBeforeLoop,

unsigned &addr)

{

const double dispersion = 0.1;

const double k = (static_cast(CoolRand()) / INT_MAX) * dispersion;

_ASSERT(fabs(k) <= dispersion);

const double allSize = parameters.sizeAlgorithm;

const double sizeInBlocks = num;

const double allSizeInBlocks = parameters.totalNumTrueBlocks;

double randAddr = sizeInBlocks * allSize / allSizeInBlocks;

_ASSERT(static_cast(randAddr) > sizeBeforeLoop);

randAddr += randAddr * k;

addr = static_cast(randAddr);

_ASSERT(addr >= sizeBeforeLoop);

if (addr < sizeBeforeLoop)

CkgExcept();


Случайные файлы

Файл
56018.rtf
29870-1.rtf
101011.rtf
58017.rtf
8219.rtf