text stringlengths 1 1.05M |
|---|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) Geoworks 1994. All rights reserved.
GEOWORKS CONFIDENTIAL
PROJECT: Pasta
MODULE: Fax
FILE: faxprintStartPage.asm
AUTHOR: Jacob Gabrielson, Apr 7, 1993
ROUTINES:
Name Description
---- -----------
INT PrintStartPage do stuff appropriate at the start of a page
INT FaxprintCreateNewPage Makes a new page in the fax file
INT FaxprintAddHeader Makes a swath using the Bitmap routines and
appends that to the fax file
REVISION HISTORY:
Name Date Description
---- ---- -----------
jag 4/ 7/93 Initial revision
AC 9/ 8/93 Changed for Faxprint
jimw 4/12/95 Updated for multi-page cover pages
DESCRIPTION:
$Id: faxprintStartPage.asm,v 1.1 97/04/18 11:53:06 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PrintStartPage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: do stuff appropriate at the start of a page
CALLED BY: DriverStrategy
PASS: bp = PState segment
RETURN: carry set on error
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
jag 4/ 7/93 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PrintStartPage proc far
uses ax, bx, cx, di
.enter
;
; Make sure there's enough disk space available.
;
call FaxprintResetDiskSpace
jc done ; jump if not enough space
;
; Start cursor out at top, left position (in PState)
;
call PrintHomeCursor
;
; Allocate a page to the fax file. NOTE! If this is the cover page,
; then the new page will be prepended to the list of existing pages!
;
call FaxprintCreateNewPage ; bx.di = HugeArray handle
; es = dgroup
;
; Add the TTL to the top of the page.
;
EC < call ECCheckDGroupES >
; reset number of lines so far
clr ax, \
es:[twoDCompressedLines], \
es:[lowestNonBlankLine]
call FaxprintAddHeader ; carry set accordingly
EC < call ECCheckDGroupES >
done:
.leave
ret
PrintStartPage endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FaxprintCreateNewPage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Makes a new page in the fax file. If the cover page is
currently being printed, the new page will be prepended before
any existing pages. Unless of course, if the cover page is
a header. Then, by gosh, we need to replace some of an
exisiting page.
Or if this is the page that will BE replaced,
then we need to say so, so that PrintSwath can ensure
that the lines that will be replaced are encoded 1-d
and NOT 2-d. 2-d and replacement just don't work well
together because decompression of one scanline is
dependent on the previous one (which could have been
replaced with something different).
CALLED BY: PrintStartPage
PASS: nothing
RETURN: bx = VM file handle of the fax
di = VM block handle of HugeArray bitmap
bp = Pstate segment
es = dgroup
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
AC 9/13/93 Initial version
jimw 4/12/95 Added multiple-page cover page support
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
FaxprintCreateNewPage proc near
uses ax, cx, dx, ds
.enter
;
; Clear out significant bit flags and other set up.
;
mov bx, handle dgroup
call MemDerefES ; es <- dgroup
inc es:[faxPageCount] ;1s based
andnf es:[faxFileFlags], not (mask FFF_DONE_REPLACING or \
mask FFF_PRE_REPLACE_PAGE or \
mask FFF_REPLACE_WITH_COVER_PAGE)
mov ax, FAP_ADD_CREATE
;
; Assume we'll prepend. Later code decrements the page to
; insert/append (cx). That's why we add one here.
;
mov cx, FAX_PAGE_LAST +1
mov bx, es:[outputVMFileHan]
;
; If we're NOT printing the cover page, then we need to check for
; pre-replacement status.
;
mov ds, bp ; ds <- PState segment
test ({FaxFileHeader}ds:[PS_jobParams].JP_printerData).\
FFH_flags, mask FFF_PRINTING_COVER_PAGE
LONG jz replacementCheck
;
; Get the 1s based page number.
;
mov cx, es:[faxPageCount]
Assert ae, cx, 1
;
; If we're not doing the header thing, then just insert the page.
; cx has the 1-based position to insert.
;
test ({FaxFileHeader}ds:[PS_jobParams].JP_printerData).\
FFH_flags, mask FFF_COVER_PAGE_IS_HEADER
jz insertPage
;
; Ok, so we are doing the header thing. If this page = cpPageCount
; then we have to do the replacement biz. Otherwise, just insert
; as usual.
;
Assert le, cx, ({FaxFileHeader}ds:[PS_jobParams].JP_printerData).FFH_cpPageCount
cmp cx, ({FaxFileHeader}ds:[PS_jobParams].JP_printerData).\
FFH_cpPageCount
jne insertPage
;
; This cover page page will be put on top of an existing page.
; Say so with a flag, and get the page in question.
;
BitSet es:[faxFileFlags], FFF_REPLACE_WITH_COVER_PAGE
dec cx ;zero-based, you know
call FaxFileGetPage ;ax <- page handle
mov dx, ax ;dx <- page handle
jmp saveInfo
replacementCheck:
;
; We need to know whether this body page will be partially replaced
; by the cover page. We know this is true if: 1) we're here in the
; code 2) the page number is the same as the last cp page number,
; and 3) the cover page is a header.
;
mov dx, es:[faxPageCount]
cmp dx, ({FaxFileHeader}ds:[PS_jobParams].JP_printerData).\
FFH_cpPageCount
jne insertPage
test {word} es:[faxFileFlags], mask FFF_COVER_PAGE_IS_HEADER
jz insertPage
BitSet es:[faxFileFlags], FFF_PRE_REPLACE_PAGE
insertPage:
dec cx ;page count - 1 = insertion point
call FaxFileInsertPage
saveInfo:
;
; Save the handle so we can manipulate it later.
; Zero out the absoluteCurrentLine here, too.
;
clr es:[absoluteCurrentLine]
mov es:[outputHugeArrayHan], dx
mov di, dx
.leave
ret
FaxprintCreateNewPage endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FaxprintAddHeader
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Makes a swath using the Bitmap routines and appends that
to the fax file
CALLED BY: PrintStartPage
PASS: bx = Fax file handle
di = VM block handle of the new page
bp = PState
es = dgroup
RETURN: carry set if error
clear if all's well
DESTROYED: ax
PSEUDO CODE/STRATEGY:
REVISION HISTORY:
Name Date Description
---- ---- -----------
AC 10/15/93 Initial version
jdashe 11/17/94 Tiramisu-ized
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
FaxprintAddHeader proc near
uses bx, cx, dx, si, di, bp, es, ds
.enter
EC < call ECCheckDGroupES >
;
; Create a bitmap to make the swath that we'll prepend.
;
mov ds, bp ; ds:0 <- PState
mov si, offset PS_jobParams ; ds:si <- JobParams
clr dh
mov dl, ds:[PS_mode] ; dx <- vertical rez.
mov ax, es:[faxPageCount] ; ax <- current pge
call FaxfileCreateTTL ; ax <- VM block
; di <- gstate handle
mov cx, ax ; cx <- vm block handle
mov dx, bx ; dx <- file handle
call PrintSwath ; error ? (carry)
;
; Kill the window, gstate, & bitmap data, as they are no
; longer needed.
;
pushf ; save carry
mov ax, BMD_KILL_DATA
call GrDestroyBitmap
popf ; restore carry
.leave
ret
FaxprintAddHeader endp
|
#include "VHud.h"
#include "TextNew.h"
#include "Utility.h"
#include "MenuNew.h"
#include "CText.h"
#include "CFileMgr.h"
using namespace plugin;
CTextNew TextNew;
static LateStaticInit InstallHooks([]() {
TextNew.ReadLanguagesFromFile();
CdeclEvent<AddressList<0x6A03E3, H_CALL>, PRIORITY_AFTER, ArgPickNone, void(const char*)> OnTextLoad;
OnTextLoad += [] {
TextNew.Load();
};
auto openFile = [](const char* a, const char* b) {
char file[32];
sprintf(file, "%s.gxt", TextNew.TextSwitch.text[MenuNew.TempSettings.language].gxt);
if (!FileCheck(file)) {
sprintf(file, "%s.gxt", "AMERICAN.GXT");
}
return CFileMgr::OpenFile(file, b);
};
patch::RedirectJump(0x6A0228, (int(__cdecl*)(const char*, const char*))openFile);
patch::RedirectJump(0x69FD5A, (int(__cdecl*)(const char*, const char*))openFile);
});
void CTextNew::ReadLanguagesFromFile() {
std::ifstream file(PLUGIN_PATH("VHud\\data\\languages.dat"));
if (file.is_open()) {
int id = 0;
for (std::string line; getline(file, line);) {
char name[64];
char gxt[64];
char ini[64];
if (!line[0] || line[0] == '\t' || line[0] == ' ' || line[0] == '#' || line[0] == '[')
continue;
sscanf(line.c_str(), "%s %s %s", &name, &ini, &gxt);
strcpy(TextSwitch.text[id].name, name);
strcpy(TextSwitch.text[id].ini, ini);
strcpy(TextSwitch.text[id].gxt, gxt);
TextSwitch.count = id;
id++;
}
file.close();
}
}
void CTextNew::Load() {
std::ifstream file;
char textFile[512];
char* filePtr;
sprintf(textFile, "VHud\\text\\%s.ini", TextNew.TextSwitch.text[MenuNew.TempSettings.language].ini);
if (!FileCheck(PLUGIN_PATH(textFile)))
filePtr = "VHud\\text\\english.ini";
else
filePtr = textFile;
for (int i = 0; i < 512; i++) {
strcpy(TextList[i].text, "\0");
}
file.open(PLUGIN_PATH(filePtr));
if (file.is_open()) {
int id = 0;
for (std::string line; getline(file, line);) {
char str[16];
char* text;
int r, g, b, a;
if (!line[0] || line[0] == '#' || line[0] == '[' || line[0] == ';')
continue;
text = new char[16000];
sscanf(line.c_str(), "%s = %[^\n]", &str, text);
strcpy(TextList[id].str, str);
strcpy(TextList[id].text, text);
id++;
delete[] text;
}
file.close();
}
}
CTextRead CTextNew::GetText(int s) {
return TextList[s];
}
CTextRead CTextNew::GetText(const char* str) {
CTextRead result = CTextRead(str);
if (*str == '\0')
return result;
for (int i = 0; i < 512; i++) {
if (TextList[i].str[0] == str[0]
&& TextList[i].str[1] == str[1]
&& TextList[i].str[2] == str[2]
&& TextList[i].str[3] == str[3]
&& !faststrcmp(str, TextList[i].str, 4)) {
result = GetText(i);
break;
}
}
return result;
}
char CTextNew::GetUpperCase(char c) {
if (c >= 'a' && c <= 'z') {
c = c - ('a' - 'A');
}
return c;
}
void CTextNew::UpperCase(char* s) {
while (*s) {
*s = GetUpperCase(*s);
s++;
}
}
|
;;#############################################################################
;;! \file source/CFFT32_mag.asm
;;!
;;! \brief Magnitude function for the complex FFT
;;!
;;! \date Nov 2, 2010
;;!
;;
;; Group: C2000
;; Target Family: C28x
;;
;;#############################################################################
;;$TI Release: C28x Fixed Point DSP Library v1.20.00.00 $
;;$Release Date: Thu Oct 18 15:57:22 CDT 2018 $
;;$Copyright: Copyright (C) 2014-2018 Texas Instruments Incorporated -
;; http://www.ti.com/ ALL RIGHTS RESERVED $
;;#############################################################################
;;
;;
;;*****************************************************************************
;; includes
;;*****************************************************************************
;;
;;*****************************************************************************
;; globals
;;*****************************************************************************
; Module definition for external reference
.def _CFFT32_mag
;; Module Structure
;; typedef struct { <--------- XAR4
;; int32_t *ipcbptr; /* +0 Pointer to input buffer */
;; int32_t *tfptr /* +2 Pointer to twiddle factors */
;; int16_t size; /* +4 Size of the FFT */
;; int16_t nrstage; /* +5 Number of FFT stages (log2(size)) */
;; int16_t *magptr; /* +6 Pointer to the magnitude buffer */
;; int16_t *winptr; /* +8 Pointer to the sampling window */
;; int16_t peakmag; /* +10 Peak magnitude value */
;; int16_t peakfrq; /* +11 Peak Frequency */
;; int16_t ratio; /* +12 Twiddles Skip factor */
;; void (*init)(void); /* +14 Pointer to the initialization () */
;; void (*izero)(void *); /* +16 Pointer to the zero-out imaginary () */
;; void (*calc)(void *); /* +18 Pointer to the calculation () */
;; void (*mag)(void *); /* +20 Pointer to the magnitude () */
;; void (*win)(void *); /* +22 Pointer to the windowing () */
;;}CFFT32;
;;=============================================================================
;; Routine Type : C Callable
;; Description :
;; void CFFT32_mag(CFFT32_Handle)
;; This function computes the magnitude square of complex FFT outputs. Allows in-place
;; and off-place storage of the magnitude square results.
;;
_CFFT32_mag:
SETC SXM
MOVL XAR7,*XAR4 ; XAR5=ipcbptr
MOVL XAR6,*+XAR4[6] ; XAR6=magptr
MOVZ AR0,*+XAR4[4] ; AR7=size
SUBB XAR0,#1 ; AR0=size-1
MAG_LP:
ZAPA ; ACC=0, P=0
QMACL P,*XAR7,*XAR7++ ; Q15*Q15=Q30
QMACL P,*XAR7,*XAR7++ ; Q15*Q15+Q30=Q30
ADDL ACC,P
MOVL *XAR6++,ACC ; Store in Q30
BANZ MAG_LP,AR0--
; Find maximum magnitude
ADDB XAR4,#4 ; XAR4->size
MOVB ACC,#0
MOVL *+XAR4[6],ACC ; peakmag=0
MOVZ AR0,*XAR4 ; AR0=size
MOVL XAR5,*+XAR4[2] ; XAR5=magptr
MOV ACC,#0
SUBB XAR0,#1 ; AR0=size-1
;Find the maximum value among the FFT Magnitudes
RPT AR0
|| MAXL ACC,*XAR5++
MOVL *+XAR4[6],ACC ; update peak magnitude
MOVB XAR7,#0 ; XAR7=0
MOVL XAR5,*+XAR4[2] ; XAR5=magptr
;Find the spectral bin corresponding to maximum magnitude.
NEXT_BIN:
MAXL ACC,*XAR5++
NOP *XAR7++
SBF NEXT_BIN,NEQ
NOP *--XAR7
ADDB XAR4,#8 ; XAR4->peakfrq
MOV *XAR4,AR7 ; update peak magnitude
LRETR
;;#############################################################################
;; End of File
;;#############################################################################
|
.global s_prepare_buffers
s_prepare_buffers:
push %r15
push %r8
push %r9
push %rax
push %rcx
push %rdi
push %rsi
lea addresses_UC_ht+0xbf9b, %r15
nop
nop
dec %rsi
movb (%r15), %r9b
nop
nop
and %rax, %rax
lea addresses_D_ht+0x153b8, %rsi
lea addresses_A_ht+0xba98, %rdi
nop
nop
nop
nop
nop
sub $43565, %rax
mov $51, %rcx
rep movsl
nop
nop
nop
nop
add %rax, %rax
lea addresses_WT_ht+0x105c6, %rsi
cmp %r8, %r8
and $0xffffffffffffffc0, %rsi
vmovaps (%rsi), %ymm0
vextracti128 $1, %ymm0, %xmm0
vpextrq $0, %xmm0, %rdi
nop
nop
nop
cmp %rsi, %rsi
lea addresses_WC_ht+0x8698, %rsi
lea addresses_WT_ht+0x5ebc, %rdi
cmp $46543, %r8
mov $48, %rcx
rep movsb
nop
nop
cmp $25858, %rsi
lea addresses_UC_ht+0x6c0a, %rsi
nop
nop
nop
nop
lfence
mov (%rsi), %di
nop
nop
nop
nop
nop
dec %rsi
lea addresses_WC_ht+0x3298, %rsi
nop
nop
nop
nop
sub $36162, %r9
mov (%rsi), %rdi
nop
nop
nop
and %r15, %r15
lea addresses_A_ht+0xf7d8, %rdi
nop
nop
nop
nop
inc %rax
mov (%rdi), %r8d
nop
nop
nop
nop
add %rax, %rax
pop %rsi
pop %rdi
pop %rcx
pop %rax
pop %r9
pop %r8
pop %r15
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %r15
push %r9
push %rbp
push %rbx
push %rdx
// Faulty Load
lea addresses_RW+0x6298, %rdx
nop
nop
sub $61582, %r13
movups (%rdx), %xmm3
vpextrq $1, %xmm3, %r9
lea oracles, %rdx
and $0xff, %r9
shlq $12, %r9
mov (%rdx,%r9,1), %r9
pop %rdx
pop %rbx
pop %rbp
pop %r9
pop %r15
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0, 'same': False, 'type': 'addresses_RW'}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0, 'same': True, 'type': 'addresses_RW'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 4, 'same': True, 'type': 'addresses_D_ht'}, 'dst': {'congruent': 6, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM'}
{'src': {'NT': False, 'AVXalign': True, 'size': 32, 'congruent': 1, 'same': True, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 10, 'same': False, 'type': 'addresses_WC_ht'}, 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'}
{'src': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 1, 'same': True, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'}
{'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 11, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'}
{'src': {'NT': False, 'AVXalign': True, 'size': 4, 'congruent': 6, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'}
{'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
*/
|
; A003269: a(n) = a(n-1) + a(n-4) with a(0) = 0, a(1) = a(2) = a(3) = 1.
; Submitted by Christian Krause
; 0,1,1,1,1,2,3,4,5,7,10,14,19,26,36,50,69,95,131,181,250,345,476,657,907,1252,1728,2385,3292,4544,6272,8657,11949,16493,22765,31422,43371,59864,82629,114051,157422,217286,299915,413966,571388,788674,1088589,1502555,2073943,2862617,3951206,5453761,7527704,10390321,14341527,19795288,27322992,37713313,52054840,71850128,99173120,136886433,188941273,260791401,359964521,496850954,685792227,946583628,1306548149,1803399103,2489191330,3435774958,4742323107,6545722210,9034913540,12470688498,17213011605
lpb $0
sub $0,1
add $4,$1
add $1,$3
add $5,$2
mov $2,$3
sub $5,$3
mov $3,$5
add $4,1
sub $1,$4
add $2,$4
lpe
mov $0,$2
|
; A309075: Total number of black cells after n iterations of Langton's ant with two ants on the grid placed side-by-side on neighboring squares and initially looking in the same direction.
; 0,2,2,4,6,6,8,8,8,6,6,4,2,2,0,2,2,4,6,6,8,8,8,6,6,4,2,2,0,2,2,4,6,6,8,8,8,6,6,4,2,2,0,2,2,4,6,6,8,8,8,6,6,4,2,2,0,2,2,4,6,6,8,8,8,6,6,4,2,2,0,2,2,4,6,6,8,8,8,6,6,4,2,2,0,2,2
seq $0,279313 ; Period 14 zigzag sequence: repeat [0,1,2,3,4,5,6,7,6,5,4,3,2,1].
mov $1,$0
seq $1,259626 ; List of numbers L and L + 1, where L = A000032, the Lucas numbers, sorted into increasing order and duplicates removed.
div $1,3
sub $0,$1
mul $0,2
|
#include "JanusContext.h"
#include "Function.h"
#include "Executable.h"
#include "Arch.h"
#include "Analysis.h"
#include "ControlFlow.h"
#include "SSA.h"
#include "AST.h"
#include <iostream>
#include <sstream>
#include <string>
#include <queue>
#include <algorithm>
using namespace std;
using namespace janus;
Function::Function(JanusContext *gc,FuncID fid, const Symbol &symbol, uint32_t size)
:context(gc),fid(fid),size(size)
{
startAddress = symbol.startAddr;
endAddress = startAddress + size;
int offset = startAddress - (symbol.section->startAddr);
contents = symbol.section->contents + offset;
name = symbol.name;
replace(name.begin(),name.end(), '.', '_'); // replace all '.' to '_'
if(symbol.type == SYM_FUNC)
isExecutable = true;
else isExecutable = false;
domTree = NULL;
entry = NULL;
translated = false;
hasIndirectStackAccesses = false;
available = true;
isExternal = false;
implicitStack = false;
liveRegIn = NULL;
liveRegOut = NULL;
}
Function::~Function()
{
/* Now we free all the instructions */
for (auto &instr: minstrs) {
if (instr.operands)
free(instr.operands);
if (instr.name)
free(instr.name);
}
if (domTree)
delete domTree;
}
/* retrieve further information from instructions */
void
Function::translate()
{
if (translated) return;
if (!entry) {
available = false;
return;
}
translated = true;
GASSERT(entry, "CFG not found in "<<name<<endl);
/* Scan the code to retrieve stack information
* this has to be done at first */
analyseStack(this);
/* Scan for memory accesses */
scanMemoryAccess(this);
/* For other mode, memory accesses are enough,
* Only paralleliser and analysis mode needs to go further */
if (context->mode != JPARALLEL &&
context->mode != JPROF &&
context->mode != JANALYSIS &&
context->mode != JVECTOR &&
context->mode != JOPT)
return;
/* Construct the abstract syntax tree of the function */
buildASTGraph(this);
/* Perform variable analaysis */
variableAnalysis(this);
/* Peform liveness analysis */
livenessAnalysis(this);
}
static void
assign_loop_blocks(Loop *loop) {
BasicBlock *entry = loop->parent->entry;
for (auto bid: loop->body) {
entry[bid].parentLoop = loop;
}
//then call subloops
for (auto subLoop: loop->subLoops)
assign_loop_blocks(subLoop);
}
void
Function::analyseLoopRelations()
{
//get loop array
Loop *loopArray = context->loops.data();
//step 1 we simply use a O(n^2) comparison
for (auto loopID: loops) {
for (auto loopID2 : loops) {
if (loopID != loopID2) {
//if loop 2 start block is in the loop 1's body
if (loopArray[loopID-1].contains(loopArray[loopID2-1].start->bid)) {
//then loop 2 is descendant of loop 1
loopArray[loopID-1].descendants.insert(loopArray + loopID2-1);
//loop 1 is ancestor of loop 2
loopArray[loopID2-1].ancestors.insert(loopArray + loopID-1);
}
}
}
}
//step 2 assign immediate parent and children
map<LoopID,int> levels;
int undecided = 0;
for (auto loopID: loops) {
Loop &loop = loopArray[loopID-1];
//starts with loops with 0 ancestors
if (loop.ancestors.size()==0) {
loop.level = 0;
levels[loopID] = 0;
}
else {
levels[loopID] = -1;
undecided++;
}
}
//if all loops are level 0, simply return
if (!undecided) goto assign_blocks;
//if all are undecided, it is a recursive loop
if (undecided == loops.size()) return;
//step 3 recursively calculates the levels for each loop
bool converge;
do {
converge = true;
for (auto loopID: loops) {
Loop &loop = loopArray[loopID-1];
if (loop.ancestors.size()==0) continue;
bool allVisited = true;
LoopID maxLoopID = 0;
int maxLevel = -1;
for (auto anc: loop.ancestors) {
if (levels[anc->id] == -1) {
allVisited = false;
break;
}
if (maxLevel < levels[anc->id]) {
maxLevel = levels[anc->id];
maxLoopID = anc->id;
}
}
//if all visited, this loop is the immediate children of the deepest loop.
if (allVisited) {
loopArray[maxLoopID-1].subLoops.insert(loopArray+loopID-1);
loopArray[loopID-1].parentLoop = loopArray+maxLoopID-1;
levels[loopID] = levels[maxLoopID] + 1;
loopArray[loopID-1].level = levels[loopID];
} else {
converge = false;
}
}
} while(!converge);
assign_blocks:
//assign basic block to inner most loops
for (auto loopID: loops) {
assign_loop_blocks(loopArray + loopID -1);
}
}
void
Function::print(void *outputStream)
{
ostream &os = *(ostream *)outputStream;
os << fid<<" "<<name <<": 0x"<<hex<<startAddress<<"-0x"<<endAddress<<" size "<<dec<<size<<endl;
}
void
Function::visualize(void *outputStream)
{
ostream &os = *(ostream *)outputStream;
//if block size less than 4, there is no need to draw it since it is too simple
if(size<=2) return;
os<<dec;
os << "digraph "<<name<<"CFG {"<<endl;
os << "label=\""<<name<<"_"<<dec<<fid+1<<"_CFG\";"<<endl;
for (auto &bb:blocks) {
//name of the basic block
os << "\tBB"<<dec<<bb.bid<<" ";
//append attributes
os <<"[";
//os <<"label=<"<< bb.dot_print()<<">";
os <<"label=\"BB"<<dec<<bb.bid<<" 0x"<<hex<<bb.instrs->pc<<"\\l";
bb.printDot(outputStream);
os <<"\"";
os<<",shape=box"<<"];";
os <<endl;
}
//print all the edges
os<<dec;
for (auto &bb:blocks) {
if(bb.succ1)
os << "\tBB"<<bb.bid<<" -> BB"<<bb.succ1->bid<<";"<<endl;
if(bb.succ2)
os << "\tBB"<<bb.bid<<" -> BB"<<bb.succ2->bid<<";"<<endl;
}
os << "} "<<endl;
//cfg tree
os << "digraph "<<name<<"CFG_TREE {"<<endl;
os << "label=\""<<name<<"_"<<dec<<fid+1<<"_CFG_Simplify\";"<<endl;
for (auto &bb:blocks) {
//name of the basic block
os << "\tBB"<<dec<<bb.bid<<" ";
//append attributes
os <<"[";
//os <<"label=<"<< bb.dot_print()<<">";
os <<"label=\"BB"<<dec<<bb.bid<<"\"";
os<<",shape=box"<<"];";
os <<endl;
}
//print the dom edge
os<<dec;
for (auto &bb:blocks) {
if(bb.succ1)
os << "\tBB"<<bb.bid<<" -> BB"<<bb.succ1->bid<<";"<<endl;
if(bb.succ2)
os << "\tBB"<<bb.bid<<" -> BB"<<bb.succ2->bid<<";"<<endl;
}
os << "} "<<endl;
//dominator tree
os << "digraph "<<name<<"DOM_TREE {"<<endl;
os << "label=\""<<name<<"_"<<dec<<fid+1<<"_Dom_Tree\";"<<endl;
for (auto &bb:blocks) {
//name of the basic block
os << "\tBB"<<dec<<bb.bid<<" ";
//append attributes
os <<"[";
//os <<"label=<"<< bb.dot_print()<<">";
os <<"label=\"BB"<<dec<<bb.bid<<"\"";
os<<",shape=box"<<"];";
os <<endl;
}
//print the dom edge
os<<dec;
for (auto &bb:blocks) {
if(bb.idom && bb.idom->bid != bb.bid)
os << "\tBB"<<bb.idom->bid<<" -> BB"<<bb.bid<<";"<<endl;
}
os << "} "<<endl;
//post dominator tree
os << "digraph "<<name<<"POST_DOM_TREE {"<<endl;
os << "label=\""<<name<<"_"<<dec<<fid+1<<"_Post_Dom_Tree\";"<<endl;
for (auto &bb:blocks) {
//name of the basic block
os << "\tBB"<<dec<<bb.bid<<" ";
//append attributes
os <<"[";
//os <<"label=<"<< bb.dot_print()<<">";
os <<"label=\"BB"<<dec<<bb.bid<<"\"";
os<<",shape=box"<<"];";
os <<endl;
}
//print the dom edge
os<<dec;
for (auto &bb:blocks) {
if(bb.ipdom)
os << "\tBB"<<bb.ipdom->bid<<" -> BB"<<bb.bid<<";"<<endl;
}
os << "} "<<endl;
}
bool
Function::needSync()
{
/* For the moment we only check the name
* Check the relocation pattern in the future */
if (name.find("@plt") != string::npos) {
if (name.find("sqrt") != string::npos)
return false;
if (name.find("exp") != string::npos)
return false;
if (name.find("sincos") != string::npos)
return false;
if (name.find("atan") != string::npos)
return false;
return true;
}
return false;
}
|
;*****************************************************************************
;* predict-a.asm: x86 intra prediction
;*****************************************************************************
;* Copyright (C) 2005-2020 x264 project
;*
;* Authors: Loren Merritt <lorenm@u.washington.edu>
;* Holger Lubitz <holger@lubitz.org>
;* Fiona Glaser <fiona@x264.com>
;* Henrik Gramner <henrik@gramner.com>
;*
;* This program is free software; you can redistribute it and/or modify
;* it under the terms of the GNU General Public License as published by
;* the Free Software Foundation; either version 2 of the License, or
;* (at your option) any later version.
;*
;* 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
;* GNU General Public License for more details.
;*
;* You should have received a copy of the GNU General Public License
;* along with this program; if not, write to the Free Software
;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA.
;*
;* This program is also available under a commercial proprietary license.
;* For more information, contact us at licensing@x264.com.
;*****************************************************************************
%include "x86inc.asm"
%include "x86util.asm"
SECTION_RODATA 32
pw_43210123: times 2 dw -3, -2, -1, 0, 1, 2, 3, 4
pw_m3: times 16 dw -3
pw_m7: times 16 dw -7
pb_00s_ff: times 8 db 0
pb_0s_ff: times 7 db 0
db 0xff
shuf_fixtr: db 0, 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7
shuf_nop: db 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
shuf_hu: db 7,6,5,4,3,2,1,0,0,0,0,0,0,0,0,0
shuf_vr: db 2,4,6,8,9,10,11,12,13,14,15,0,1,3,5,7
pw_reverse: db 14,15,12,13,10,11,8,9,6,7,4,5,2,3,0,1
SECTION .text
cextern pb_0
cextern pb_1
cextern pb_3
cextern pw_1
cextern pw_2
cextern pw_4
cextern pw_8
cextern pw_16
cextern pw_00ff
cextern pw_pixel_max
cextern pw_0to15
%macro STORE8 1
mova [r0+0*FDEC_STRIDEB], %1
mova [r0+1*FDEC_STRIDEB], %1
add r0, 4*FDEC_STRIDEB
mova [r0-2*FDEC_STRIDEB], %1
mova [r0-1*FDEC_STRIDEB], %1
mova [r0+0*FDEC_STRIDEB], %1
mova [r0+1*FDEC_STRIDEB], %1
mova [r0+2*FDEC_STRIDEB], %1
mova [r0+3*FDEC_STRIDEB], %1
%endmacro
%macro STORE16 1-4
%if %0 > 1
mov r1d, 2*%0
.loop:
mova [r0+0*FDEC_STRIDEB+0*mmsize], %1
mova [r0+0*FDEC_STRIDEB+1*mmsize], %2
mova [r0+1*FDEC_STRIDEB+0*mmsize], %1
mova [r0+1*FDEC_STRIDEB+1*mmsize], %2
%ifidn %0, 4
mova [r0+0*FDEC_STRIDEB+2*mmsize], %3
mova [r0+0*FDEC_STRIDEB+3*mmsize], %4
mova [r0+1*FDEC_STRIDEB+2*mmsize], %3
mova [r0+1*FDEC_STRIDEB+3*mmsize], %4
add r0, 2*FDEC_STRIDEB
%else ; %0 == 2
add r0, 4*FDEC_STRIDEB
mova [r0-2*FDEC_STRIDEB+0*mmsize], %1
mova [r0-2*FDEC_STRIDEB+1*mmsize], %2
mova [r0-1*FDEC_STRIDEB+0*mmsize], %1
mova [r0-1*FDEC_STRIDEB+1*mmsize], %2
%endif
dec r1d
jg .loop
%else ; %0 == 1
STORE8 %1
%if HIGH_BIT_DEPTH ; Different code paths to reduce code size
add r0, 6*FDEC_STRIDEB
mova [r0-2*FDEC_STRIDEB], %1
mova [r0-1*FDEC_STRIDEB], %1
mova [r0+0*FDEC_STRIDEB], %1
mova [r0+1*FDEC_STRIDEB], %1
add r0, 4*FDEC_STRIDEB
mova [r0-2*FDEC_STRIDEB], %1
mova [r0-1*FDEC_STRIDEB], %1
mova [r0+0*FDEC_STRIDEB], %1
mova [r0+1*FDEC_STRIDEB], %1
%else
add r0, 8*FDEC_STRIDE
mova [r0-4*FDEC_STRIDE], %1
mova [r0-3*FDEC_STRIDE], %1
mova [r0-2*FDEC_STRIDE], %1
mova [r0-1*FDEC_STRIDE], %1
mova [r0+0*FDEC_STRIDE], %1
mova [r0+1*FDEC_STRIDE], %1
mova [r0+2*FDEC_STRIDE], %1
mova [r0+3*FDEC_STRIDE], %1
%endif ; HIGH_BIT_DEPTH
%endif
%endmacro
%macro PRED_H_LOAD 2 ; reg, offset
%if cpuflag(avx2)
vpbroadcastpix %1, [r0+(%2)*FDEC_STRIDEB-SIZEOF_PIXEL]
%elif HIGH_BIT_DEPTH
movd %1, [r0+(%2)*FDEC_STRIDEB-4]
SPLATW %1, %1, 1
%else
SPLATB_LOAD %1, r0+(%2)*FDEC_STRIDE-1, m2
%endif
%endmacro
%macro PRED_H_STORE 3 ; reg, offset, width
%assign %%w %3*SIZEOF_PIXEL
%if %%w == 8
movq [r0+(%2)*FDEC_STRIDEB], %1
%else
%assign %%i 0
%rep %%w/mmsize
mova [r0+(%2)*FDEC_STRIDEB+%%i], %1
%assign %%i %%i+mmsize
%endrep
%endif
%endmacro
%macro PRED_H_4ROWS 2 ; width, inc_ptr
PRED_H_LOAD m0, 0
PRED_H_LOAD m1, 1
PRED_H_STORE m0, 0, %1
PRED_H_STORE m1, 1, %1
PRED_H_LOAD m0, 2
%if %2
add r0, 4*FDEC_STRIDEB
%endif
PRED_H_LOAD m1, 3-4*%2
PRED_H_STORE m0, 2-4*%2, %1
PRED_H_STORE m1, 3-4*%2, %1
%endmacro
; dest, left, right, src, tmp
; output: %1 = (t[n-1] + t[n]*2 + t[n+1] + 2) >> 2
%macro PRED8x8_LOWPASS 4-5
%if HIGH_BIT_DEPTH
paddw %2, %3
psrlw %2, 1
pavgw %1, %4, %2
%else
mova %5, %2
pavgb %2, %3
pxor %3, %5
pand %3, [pb_1]
psubusb %2, %3
pavgb %1, %4, %2
%endif
%endmacro
;-----------------------------------------------------------------------------
; void predict_4x4_h( pixel *src )
;-----------------------------------------------------------------------------
%if HIGH_BIT_DEPTH
INIT_XMM avx2
cglobal predict_4x4_h, 1,1
PRED_H_4ROWS 4, 0
RET
%endif
;-----------------------------------------------------------------------------
; void predict_4x4_ddl( pixel *src )
;-----------------------------------------------------------------------------
%macro PREDICT_4x4_DDL 0
cglobal predict_4x4_ddl, 1,1
movu m1, [r0-FDEC_STRIDEB]
PSLLPIX m2, m1, 1
mova m0, m1
%if HIGH_BIT_DEPTH
PSRLPIX m1, m1, 1
pshufhw m1, m1, q2210
%else
pxor m1, m2
PSRLPIX m1, m1, 1
pxor m1, m0
%endif
PRED8x8_LOWPASS m0, m2, m1, m0, m3
%assign Y 0
%rep 4
PSRLPIX m0, m0, 1
movh [r0+Y*FDEC_STRIDEB], m0
%assign Y (Y+1)
%endrep
RET
%endmacro
%if HIGH_BIT_DEPTH
INIT_XMM sse2
PREDICT_4x4_DDL
INIT_XMM avx
PREDICT_4x4_DDL
INIT_MMX mmx2
cglobal predict_4x4_ddl, 1,2
movu m1, [r0-FDEC_STRIDEB+4]
PRED8x8_LOWPASS m0, m1, [r0-FDEC_STRIDEB+0], [r0-FDEC_STRIDEB+2]
mova m3, [r0-FDEC_STRIDEB+8]
mova [r0+0*FDEC_STRIDEB], m0
pshufw m4, m3, q3321
PRED8x8_LOWPASS m2, m4, [r0-FDEC_STRIDEB+6], m3
mova [r0+3*FDEC_STRIDEB], m2
pshufw m1, m0, q0021
punpckldq m1, m2
mova [r0+1*FDEC_STRIDEB], m1
psllq m0, 16
PALIGNR m2, m0, 6, m0
mova [r0+2*FDEC_STRIDEB], m2
RET
%else ; !HIGH_BIT_DEPTH
INIT_MMX mmx2
PREDICT_4x4_DDL
%endif
;-----------------------------------------------------------------------------
; void predict_4x4_vr( pixel *src )
;-----------------------------------------------------------------------------
%if HIGH_BIT_DEPTH == 0
INIT_MMX ssse3
cglobal predict_4x4_vr, 1,1
movd m1, [r0-1*FDEC_STRIDEB] ; ........t3t2t1t0
mova m4, m1
palignr m1, [r0-1*FDEC_STRIDEB-8], 7 ; ......t3t2t1t0lt
pavgb m4, m1
palignr m1, [r0+0*FDEC_STRIDEB-8], 7 ; ....t3t2t1t0ltl0
mova m0, m1
palignr m1, [r0+1*FDEC_STRIDEB-8], 7 ; ..t3t2t1t0ltl0l1
mova m2, m1
palignr m1, [r0+2*FDEC_STRIDEB-8], 7 ; t3t2t1t0ltl0l1l2
PRED8x8_LOWPASS m2, m0, m1, m2, m3
pshufw m0, m2, 0
psrlq m2, 16
movd [r0+0*FDEC_STRIDEB], m4
palignr m4, m0, 7
movd [r0+1*FDEC_STRIDEB], m2
psllq m0, 8
movd [r0+2*FDEC_STRIDEB], m4
palignr m2, m0, 7
movd [r0+3*FDEC_STRIDEB], m2
RET
%endif ; !HIGH_BIT_DEPTH
;-----------------------------------------------------------------------------
; void predict_4x4_ddr( pixel *src )
;-----------------------------------------------------------------------------
%macro PREDICT_4x4 4
cglobal predict_4x4_ddr, 1,1
%if HIGH_BIT_DEPTH
movu m2, [r0-1*FDEC_STRIDEB-8]
pinsrw m2, [r0+0*FDEC_STRIDEB-2], 2
pinsrw m2, [r0+1*FDEC_STRIDEB-2], 1
pinsrw m2, [r0+2*FDEC_STRIDEB-2], 0
movhps m3, [r0+3*FDEC_STRIDEB-8]
%else ; !HIGH_BIT_DEPTH
movd m0, [r0+2*FDEC_STRIDEB-4]
movd m1, [r0+0*FDEC_STRIDEB-4]
punpcklbw m0, [r0+1*FDEC_STRIDEB-4]
punpcklbw m1, [r0-1*FDEC_STRIDEB-4]
punpckhwd m0, m1
movd m2, [r0-1*FDEC_STRIDEB]
%if cpuflag(ssse3)
palignr m2, m0, 4
%else
psllq m2, 32
punpckhdq m0, m2
SWAP 2, 0
%endif
movd m3, [r0+3*FDEC_STRIDEB-4]
psllq m3, 32
%endif ; !HIGH_BIT_DEPTH
PSRLPIX m1, m2, 1
mova m0, m2
PALIGNR m2, m3, 7*SIZEOF_PIXEL, m3
PRED8x8_LOWPASS m0, m2, m1, m0, m3
%assign Y 3
movh [r0+Y*FDEC_STRIDEB], m0
%rep 3
%assign Y (Y-1)
PSRLPIX m0, m0, 1
movh [r0+Y*FDEC_STRIDEB], m0
%endrep
RET
;-----------------------------------------------------------------------------
; void predict_4x4_vr( pixel *src )
;-----------------------------------------------------------------------------
cglobal predict_4x4_vr, 1,1
%if HIGH_BIT_DEPTH
movu m1, [r0-1*FDEC_STRIDEB-8]
pinsrw m1, [r0+0*FDEC_STRIDEB-2], 2
pinsrw m1, [r0+1*FDEC_STRIDEB-2], 1
pinsrw m1, [r0+2*FDEC_STRIDEB-2], 0
%else ; !HIGH_BIT_DEPTH
movd m0, [r0+2*FDEC_STRIDEB-4]
movd m1, [r0+0*FDEC_STRIDEB-4]
punpcklbw m0, [r0+1*FDEC_STRIDEB-4]
punpcklbw m1, [r0-1*FDEC_STRIDEB-4]
punpckhwd m0, m1
movd m1, [r0-1*FDEC_STRIDEB]
%if cpuflag(ssse3)
palignr m1, m0, 4
%else
psllq m1, 32
punpckhdq m0, m1
SWAP 1, 0
%endif
%endif ; !HIGH_BIT_DEPTH
PSRLPIX m2, m1, 1
PSRLPIX m0, m1, 2
pavg%1 m4, m1, m2
PSRLPIX m4, m4, 3
PRED8x8_LOWPASS m2, m0, m1, m2, m3
PSLLPIX m0, m2, 6
PSRLPIX m2, m2, 2
movh [r0+0*FDEC_STRIDEB], m4
PALIGNR m4, m0, 7*SIZEOF_PIXEL, m3
movh [r0+1*FDEC_STRIDEB], m2
PSLLPIX m0, m0, 1
movh [r0+2*FDEC_STRIDEB], m4
PALIGNR m2, m0, 7*SIZEOF_PIXEL, m0
movh [r0+3*FDEC_STRIDEB], m2
RET
;-----------------------------------------------------------------------------
; void predict_4x4_hd( pixel *src )
;-----------------------------------------------------------------------------
cglobal predict_4x4_hd, 1,1
%if HIGH_BIT_DEPTH
movu m1, [r0-1*FDEC_STRIDEB-8]
PSLLPIX m1, m1, 1
pinsrw m1, [r0+0*FDEC_STRIDEB-2], 3
pinsrw m1, [r0+1*FDEC_STRIDEB-2], 2
pinsrw m1, [r0+2*FDEC_STRIDEB-2], 1
pinsrw m1, [r0+3*FDEC_STRIDEB-2], 0
%else
movd m0, [r0-1*FDEC_STRIDEB-4] ; lt ..
punpckldq m0, [r0-1*FDEC_STRIDEB] ; t3 t2 t1 t0 lt .. .. ..
PSLLPIX m0, m0, 1 ; t2 t1 t0 lt .. .. .. ..
movd m1, [r0+3*FDEC_STRIDEB-4] ; l3
punpcklbw m1, [r0+2*FDEC_STRIDEB-4] ; l2 l3
movd m2, [r0+1*FDEC_STRIDEB-4] ; l1
punpcklbw m2, [r0+0*FDEC_STRIDEB-4] ; l0 l1
punpckh%3 m1, m2 ; l0 l1 l2 l3
punpckh%4 m1, m0 ; t2 t1 t0 lt l0 l1 l2 l3
%endif
PSRLPIX m2, m1, 1 ; .. t2 t1 t0 lt l0 l1 l2
PSRLPIX m0, m1, 2 ; .. .. t2 t1 t0 lt l0 l1
pavg%1 m5, m1, m2
PRED8x8_LOWPASS m3, m1, m0, m2, m4
punpckl%2 m5, m3
PSRLPIX m3, m3, 4
PALIGNR m3, m5, 6*SIZEOF_PIXEL, m4
%assign Y 3
movh [r0+Y*FDEC_STRIDEB], m5
%rep 2
%assign Y (Y-1)
PSRLPIX m5, m5, 2
movh [r0+Y*FDEC_STRIDEB], m5
%endrep
movh [r0+0*FDEC_STRIDEB], m3
RET
%endmacro ; PREDICT_4x4
;-----------------------------------------------------------------------------
; void predict_4x4_ddr( pixel *src )
;-----------------------------------------------------------------------------
%if HIGH_BIT_DEPTH
INIT_MMX mmx2
cglobal predict_4x4_ddr, 1,1
mova m0, [r0+1*FDEC_STRIDEB-8]
punpckhwd m0, [r0+0*FDEC_STRIDEB-8]
mova m3, [r0+3*FDEC_STRIDEB-8]
punpckhwd m3, [r0+2*FDEC_STRIDEB-8]
punpckhdq m3, m0
pshufw m0, m3, q3321
pinsrw m0, [r0-1*FDEC_STRIDEB-2], 3
pshufw m1, m0, q3321
PRED8x8_LOWPASS m0, m1, m3, m0
movq [r0+3*FDEC_STRIDEB], m0
movq m2, [r0-1*FDEC_STRIDEB-0]
pshufw m4, m2, q2100
pinsrw m4, [r0-1*FDEC_STRIDEB-2], 0
movq m1, m4
PALIGNR m4, m3, 6, m3
PRED8x8_LOWPASS m1, m4, m2, m1
movq [r0+0*FDEC_STRIDEB], m1
pshufw m2, m0, q3321
punpckldq m2, m1
psllq m0, 16
PALIGNR m1, m0, 6, m0
movq [r0+1*FDEC_STRIDEB], m1
movq [r0+2*FDEC_STRIDEB], m2
movd [r0+3*FDEC_STRIDEB+4], m1
RET
;-----------------------------------------------------------------------------
; void predict_4x4_hd( pixel *src )
;-----------------------------------------------------------------------------
cglobal predict_4x4_hd, 1,1
mova m0, [r0+1*FDEC_STRIDEB-8]
punpckhwd m0, [r0+0*FDEC_STRIDEB-8]
mova m1, [r0+3*FDEC_STRIDEB-8]
punpckhwd m1, [r0+2*FDEC_STRIDEB-8]
punpckhdq m1, m0
mova m0, m1
movu m3, [r0-1*FDEC_STRIDEB-2]
pshufw m4, m1, q0032
mova m7, m3
punpckldq m4, m3
PALIGNR m3, m1, 2, m2
PRED8x8_LOWPASS m2, m4, m1, m3
pavgw m0, m3
punpcklwd m5, m0, m2
punpckhwd m4, m0, m2
mova [r0+3*FDEC_STRIDEB], m5
mova [r0+1*FDEC_STRIDEB], m4
psrlq m5, 32
punpckldq m5, m4
mova [r0+2*FDEC_STRIDEB], m5
pshufw m4, m7, q2100
mova m6, [r0-1*FDEC_STRIDEB+0]
pinsrw m4, [r0+0*FDEC_STRIDEB-2], 0
PRED8x8_LOWPASS m3, m4, m6, m7
PALIGNR m3, m0, 6, m0
mova [r0+0*FDEC_STRIDEB], m3
RET
INIT_XMM sse2
PREDICT_4x4 w, wd, dq, qdq
INIT_XMM ssse3
PREDICT_4x4 w, wd, dq, qdq
INIT_XMM avx
PREDICT_4x4 w, wd, dq, qdq
%else ; !HIGH_BIT_DEPTH
INIT_MMX mmx2
PREDICT_4x4 b, bw, wd, dq
INIT_MMX ssse3
%define predict_4x4_vr_ssse3 predict_4x4_vr_cache64_ssse3
PREDICT_4x4 b, bw, wd, dq
%endif
;-----------------------------------------------------------------------------
; void predict_4x4_hu( pixel *src )
;-----------------------------------------------------------------------------
%if HIGH_BIT_DEPTH
INIT_MMX
cglobal predict_4x4_hu_mmx2, 1,1
movq m0, [r0+0*FDEC_STRIDEB-8]
punpckhwd m0, [r0+1*FDEC_STRIDEB-8]
movq m1, [r0+2*FDEC_STRIDEB-8]
punpckhwd m1, [r0+3*FDEC_STRIDEB-8]
punpckhdq m0, m1
pshufw m1, m1, q3333
movq [r0+3*FDEC_STRIDEB], m1
pshufw m3, m0, q3321
pshufw m4, m0, q3332
pavgw m2, m0, m3
PRED8x8_LOWPASS m3, m0, m4, m3
punpcklwd m4, m2, m3
mova [r0+0*FDEC_STRIDEB], m4
psrlq m2, 16
psrlq m3, 16
punpcklwd m2, m3
mova [r0+1*FDEC_STRIDEB], m2
punpckhdq m2, m1
mova [r0+2*FDEC_STRIDEB], m2
RET
%else ; !HIGH_BIT_DEPTH
INIT_MMX
cglobal predict_4x4_hu_mmx2, 1,1
movd m1, [r0+0*FDEC_STRIDEB-4]
punpcklbw m1, [r0+1*FDEC_STRIDEB-4]
movd m0, [r0+2*FDEC_STRIDEB-4]
punpcklbw m0, [r0+3*FDEC_STRIDEB-4]
punpckhwd m1, m0
movq m0, m1
punpckhbw m1, m1
pshufw m1, m1, q3333
punpckhdq m0, m1
movq m2, m0
movq m3, m0
movq m5, m0
psrlq m3, 8
psrlq m2, 16
pavgb m5, m3
PRED8x8_LOWPASS m3, m0, m2, m3, m4
movd [r0+3*FDEC_STRIDEB], m1
punpcklbw m5, m3
movd [r0+0*FDEC_STRIDEB], m5
psrlq m5, 16
movd [r0+1*FDEC_STRIDEB], m5
psrlq m5, 16
movd [r0+2*FDEC_STRIDEB], m5
RET
%endif ; HIGH_BIT_DEPTH
;-----------------------------------------------------------------------------
; void predict_4x4_vl( pixel *src )
;-----------------------------------------------------------------------------
%macro PREDICT_4x4_V1 1
cglobal predict_4x4_vl, 1,1
movu m1, [r0-FDEC_STRIDEB]
PSRLPIX m3, m1, 1
PSRLPIX m2, m1, 2
pavg%1 m4, m3, m1
PRED8x8_LOWPASS m0, m1, m2, m3, m5
movh [r0+0*FDEC_STRIDEB], m4
movh [r0+1*FDEC_STRIDEB], m0
PSRLPIX m4, m4, 1
PSRLPIX m0, m0, 1
movh [r0+2*FDEC_STRIDEB], m4
movh [r0+3*FDEC_STRIDEB], m0
RET
%endmacro
%if HIGH_BIT_DEPTH
INIT_XMM sse2
PREDICT_4x4_V1 w
INIT_XMM avx
PREDICT_4x4_V1 w
INIT_MMX mmx2
cglobal predict_4x4_vl, 1,4
mova m1, [r0-FDEC_STRIDEB+0]
mova m2, [r0-FDEC_STRIDEB+8]
mova m0, m2
PALIGNR m2, m1, 4, m4
PALIGNR m0, m1, 2, m4
mova m3, m0
pavgw m3, m1
mova [r0+0*FDEC_STRIDEB], m3
psrlq m3, 16
mova [r0+2*FDEC_STRIDEB], m3
PRED8x8_LOWPASS m0, m1, m2, m0
mova [r0+1*FDEC_STRIDEB], m0
psrlq m0, 16
mova [r0+3*FDEC_STRIDEB], m0
movzx r1d, word [r0-FDEC_STRIDEB+ 8]
movzx r2d, word [r0-FDEC_STRIDEB+10]
movzx r3d, word [r0-FDEC_STRIDEB+12]
lea r1d, [r1+r2+1]
add r3d, r2d
lea r3d, [r3+r1+1]
shr r1d, 1
shr r3d, 2
mov [r0+2*FDEC_STRIDEB+6], r1w
mov [r0+3*FDEC_STRIDEB+6], r3w
RET
%else ; !HIGH_BIT_DEPTH
INIT_MMX mmx2
PREDICT_4x4_V1 b
%endif
;-----------------------------------------------------------------------------
; void predict_4x4_dc( pixel *src )
;-----------------------------------------------------------------------------
INIT_MMX mmx2
%if HIGH_BIT_DEPTH
cglobal predict_4x4_dc, 1,1
mova m2, [r0+0*FDEC_STRIDEB-4*SIZEOF_PIXEL]
paddw m2, [r0+1*FDEC_STRIDEB-4*SIZEOF_PIXEL]
paddw m2, [r0+2*FDEC_STRIDEB-4*SIZEOF_PIXEL]
paddw m2, [r0+3*FDEC_STRIDEB-4*SIZEOF_PIXEL]
psrlq m2, 48
mova m0, [r0-FDEC_STRIDEB]
HADDW m0, m1
paddw m0, [pw_4]
paddw m0, m2
psrlw m0, 3
SPLATW m0, m0
mova [r0+0*FDEC_STRIDEB], m0
mova [r0+1*FDEC_STRIDEB], m0
mova [r0+2*FDEC_STRIDEB], m0
mova [r0+3*FDEC_STRIDEB], m0
RET
%else ; !HIGH_BIT_DEPTH
cglobal predict_4x4_dc, 1,4
pxor mm7, mm7
movd mm0, [r0-FDEC_STRIDEB]
psadbw mm0, mm7
movd r3d, mm0
movzx r1d, byte [r0-1]
%assign Y 1
%rep 3
movzx r2d, byte [r0+FDEC_STRIDEB*Y-1]
add r1d, r2d
%assign Y Y+1
%endrep
lea r1d, [r1+r3+4]
shr r1d, 3
imul r1d, 0x01010101
mov [r0+FDEC_STRIDEB*0], r1d
mov [r0+FDEC_STRIDEB*1], r1d
mov [r0+FDEC_STRIDEB*2], r1d
mov [r0+FDEC_STRIDEB*3], r1d
RET
%endif ; HIGH_BIT_DEPTH
%macro PREDICT_FILTER 4
;-----------------------------------------------------------------------------
;void predict_8x8_filter( pixel *src, pixel edge[36], int i_neighbor, int i_filters )
;-----------------------------------------------------------------------------
cglobal predict_8x8_filter, 4,6,6
add r0, 0x58*SIZEOF_PIXEL
%define src r0-0x58*SIZEOF_PIXEL
%if ARCH_X86_64 == 0
mov r4, r1
%define t1 r4
%define t4 r1
%else
%define t1 r1
%define t4 r4
%endif
test r3b, 1
je .check_top
mov t4d, r2d
and t4d, 8
neg t4
mova m0, [src+0*FDEC_STRIDEB-8*SIZEOF_PIXEL]
punpckh%1%2 m0, [src+0*FDEC_STRIDEB-8*SIZEOF_PIXEL+t4*(FDEC_STRIDEB/8)]
mova m1, [src+2*FDEC_STRIDEB-8*SIZEOF_PIXEL]
punpckh%1%2 m1, [src+1*FDEC_STRIDEB-8*SIZEOF_PIXEL]
punpckh%2%3 m1, m0
mova m2, [src+4*FDEC_STRIDEB-8*SIZEOF_PIXEL]
punpckh%1%2 m2, [src+3*FDEC_STRIDEB-8*SIZEOF_PIXEL]
mova m3, [src+6*FDEC_STRIDEB-8*SIZEOF_PIXEL]
punpckh%1%2 m3, [src+5*FDEC_STRIDEB-8*SIZEOF_PIXEL]
punpckh%2%3 m3, m2
punpckh%3%4 m3, m1
mova m0, [src+7*FDEC_STRIDEB-8*SIZEOF_PIXEL]
mova m1, [src-1*FDEC_STRIDEB]
PALIGNR m4, m3, m0, 7*SIZEOF_PIXEL, m0
PALIGNR m1, m1, m3, 1*SIZEOF_PIXEL, m2
PRED8x8_LOWPASS m3, m1, m4, m3, m5
mova [t1+8*SIZEOF_PIXEL], m3
movzx t4d, pixel [src+7*FDEC_STRIDEB-1*SIZEOF_PIXEL]
movzx r5d, pixel [src+6*FDEC_STRIDEB-1*SIZEOF_PIXEL]
lea t4d, [t4*3+2]
add t4d, r5d
shr t4d, 2
mov [t1+7*SIZEOF_PIXEL], t4%1
mov [t1+6*SIZEOF_PIXEL], t4%1
test r3b, 2
je .done
.check_top:
%if SIZEOF_PIXEL==1 && cpuflag(ssse3)
INIT_XMM cpuname
movu m3, [src-1*FDEC_STRIDEB]
movhps m0, [src-1*FDEC_STRIDEB-8]
test r2b, 8
je .fix_lt_2
.do_top:
and r2d, 4
%if ARCH_X86_64
lea r3, [shuf_fixtr]
pshufb m3, [r3+r2*4]
%else
pshufb m3, [shuf_fixtr+r2*4] ; neighbor&MB_TOPRIGHT ? shuf_nop : shuf_fixtr
%endif
psrldq m1, m3, 15
PALIGNR m2, m3, m0, 15, m0
PALIGNR m1, m3, 1, m5
PRED8x8_LOWPASS m0, m2, m1, m3, m5
mova [t1+16*SIZEOF_PIXEL], m0
psrldq m0, 15
movd [t1+32*SIZEOF_PIXEL], m0
.done:
REP_RET
.fix_lt_2:
pslldq m0, m3, 15
jmp .do_top
%else
mova m0, [src-1*FDEC_STRIDEB-8*SIZEOF_PIXEL]
mova m3, [src-1*FDEC_STRIDEB]
mova m1, [src-1*FDEC_STRIDEB+8*SIZEOF_PIXEL]
test r2b, 8
je .fix_lt_2
test r2b, 4
je .fix_tr_1
.do_top:
PALIGNR m2, m3, m0, 7*SIZEOF_PIXEL, m0
PALIGNR m0, m1, m3, 1*SIZEOF_PIXEL, m5
PRED8x8_LOWPASS m4, m2, m0, m3, m5
mova [t1+16*SIZEOF_PIXEL], m4
test r3b, 4
je .done
PSRLPIX m5, m1, 7
PALIGNR m2, m1, m3, 7*SIZEOF_PIXEL, m3
PALIGNR m5, m1, 1*SIZEOF_PIXEL, m4
PRED8x8_LOWPASS m0, m2, m5, m1, m4
mova [t1+24*SIZEOF_PIXEL], m0
PSRLPIX m0, m0, 7
movd [t1+32*SIZEOF_PIXEL], m0
.done:
REP_RET
.fix_lt_2:
PSLLPIX m0, m3, 7
test r2b, 4
jne .do_top
.fix_tr_1:
punpckh%1%2 m1, m3, m3
pshuf%2 m1, m1, q3333
jmp .do_top
%endif
%endmacro
%if HIGH_BIT_DEPTH
INIT_XMM sse2
PREDICT_FILTER w, d, q, dq
INIT_XMM ssse3
PREDICT_FILTER w, d, q, dq
INIT_XMM avx
PREDICT_FILTER w, d, q, dq
%else
INIT_MMX mmx2
PREDICT_FILTER b, w, d, q
INIT_MMX ssse3
PREDICT_FILTER b, w, d, q
%endif
;-----------------------------------------------------------------------------
; void predict_8x8_v( pixel *src, pixel *edge )
;-----------------------------------------------------------------------------
%macro PREDICT_8x8_V 0
cglobal predict_8x8_v, 2,2
mova m0, [r1+16*SIZEOF_PIXEL]
STORE8 m0
RET
%endmacro
%if HIGH_BIT_DEPTH
INIT_XMM sse
PREDICT_8x8_V
%else
INIT_MMX mmx2
PREDICT_8x8_V
%endif
;-----------------------------------------------------------------------------
; void predict_8x8_h( pixel *src, pixel edge[36] )
;-----------------------------------------------------------------------------
%macro PREDICT_8x8_H 2
cglobal predict_8x8_h, 2,2
movu m1, [r1+7*SIZEOF_PIXEL]
add r0, 4*FDEC_STRIDEB
punpckl%1 m2, m1, m1
punpckh%1 m1, m1
%assign Y 0
%rep 8
%assign i 1+Y/4
SPLAT%2 m0, m %+ i, (3-Y)&3
mova [r0+(Y-4)*FDEC_STRIDEB], m0
%assign Y Y+1
%endrep
RET
%endmacro
%if HIGH_BIT_DEPTH
INIT_XMM sse2
PREDICT_8x8_H wd, D
%else
INIT_MMX mmx2
PREDICT_8x8_H bw, W
%endif
;-----------------------------------------------------------------------------
; void predict_8x8_dc( pixel *src, pixel *edge );
;-----------------------------------------------------------------------------
%if HIGH_BIT_DEPTH
INIT_XMM sse2
cglobal predict_8x8_dc, 2,2
movu m0, [r1+14]
paddw m0, [r1+32]
HADDW m0, m1
paddw m0, [pw_8]
psrlw m0, 4
SPLATW m0, m0
STORE8 m0
RET
%else ; !HIGH_BIT_DEPTH
INIT_MMX mmx2
cglobal predict_8x8_dc, 2,2
pxor mm0, mm0
pxor mm1, mm1
psadbw mm0, [r1+7]
psadbw mm1, [r1+16]
paddw mm0, [pw_8]
paddw mm0, mm1
psrlw mm0, 4
pshufw mm0, mm0, 0
packuswb mm0, mm0
STORE8 mm0
RET
%endif ; HIGH_BIT_DEPTH
;-----------------------------------------------------------------------------
; void predict_8x8_dc_top ( pixel *src, pixel *edge );
; void predict_8x8_dc_left( pixel *src, pixel *edge );
;-----------------------------------------------------------------------------
%if HIGH_BIT_DEPTH
%macro PREDICT_8x8_DC 3
cglobal %1, 2,2
%3 m0, [r1+%2]
HADDW m0, m1
paddw m0, [pw_4]
psrlw m0, 3
SPLATW m0, m0
STORE8 m0
RET
%endmacro
INIT_XMM sse2
PREDICT_8x8_DC predict_8x8_dc_top , 32, mova
PREDICT_8x8_DC predict_8x8_dc_left, 14, movu
%else ; !HIGH_BIT_DEPTH
%macro PREDICT_8x8_DC 2
cglobal %1, 2,2
pxor mm0, mm0
psadbw mm0, [r1+%2]
paddw mm0, [pw_4]
psrlw mm0, 3
pshufw mm0, mm0, 0
packuswb mm0, mm0
STORE8 mm0
RET
%endmacro
INIT_MMX
PREDICT_8x8_DC predict_8x8_dc_top_mmx2, 16
PREDICT_8x8_DC predict_8x8_dc_left_mmx2, 7
%endif ; HIGH_BIT_DEPTH
; sse2 is faster even on amd for 8-bit, so there's no sense in spending exe
; size on the 8-bit mmx functions below if we know sse2 is available.
%macro PREDICT_8x8_DDLR 0
;-----------------------------------------------------------------------------
; void predict_8x8_ddl( pixel *src, pixel *edge )
;-----------------------------------------------------------------------------
cglobal predict_8x8_ddl, 2,2,7
mova m0, [r1+16*SIZEOF_PIXEL]
mova m1, [r1+24*SIZEOF_PIXEL]
%if cpuflag(cache64)
movd m5, [r1+32*SIZEOF_PIXEL]
palignr m3, m1, m0, 1*SIZEOF_PIXEL
palignr m5, m5, m1, 1*SIZEOF_PIXEL
palignr m4, m1, m0, 7*SIZEOF_PIXEL
%else
movu m3, [r1+17*SIZEOF_PIXEL]
movu m4, [r1+23*SIZEOF_PIXEL]
movu m5, [r1+25*SIZEOF_PIXEL]
%endif
PSLLPIX m2, m0, 1
add r0, FDEC_STRIDEB*4
PRED8x8_LOWPASS m0, m2, m3, m0, m6
PRED8x8_LOWPASS m1, m4, m5, m1, m6
mova [r0+3*FDEC_STRIDEB], m1
%assign Y 2
%rep 6
PALIGNR m1, m0, 7*SIZEOF_PIXEL, m2
PSLLPIX m0, m0, 1
mova [r0+Y*FDEC_STRIDEB], m1
%assign Y (Y-1)
%endrep
PALIGNR m1, m0, 7*SIZEOF_PIXEL, m0
mova [r0+Y*FDEC_STRIDEB], m1
RET
;-----------------------------------------------------------------------------
; void predict_8x8_ddr( pixel *src, pixel *edge )
;-----------------------------------------------------------------------------
cglobal predict_8x8_ddr, 2,2,7
add r0, FDEC_STRIDEB*4
mova m0, [r1+ 8*SIZEOF_PIXEL]
mova m1, [r1+16*SIZEOF_PIXEL]
; edge[] is 32byte aligned, so some of the unaligned loads are known to be not cachesplit
movu m2, [r1+ 7*SIZEOF_PIXEL]
movu m5, [r1+17*SIZEOF_PIXEL]
%if cpuflag(cache64)
palignr m3, m1, m0, 1*SIZEOF_PIXEL
palignr m4, m1, m0, 7*SIZEOF_PIXEL
%else
movu m3, [r1+ 9*SIZEOF_PIXEL]
movu m4, [r1+15*SIZEOF_PIXEL]
%endif
PRED8x8_LOWPASS m0, m2, m3, m0, m6
PRED8x8_LOWPASS m1, m4, m5, m1, m6
mova [r0+3*FDEC_STRIDEB], m0
%assign Y -4
%rep 6
PALIGNR m1, m0, 7*SIZEOF_PIXEL, m2
PSLLPIX m0, m0, 1
mova [r0+Y*FDEC_STRIDEB], m1
%assign Y (Y+1)
%endrep
PALIGNR m1, m0, 7*SIZEOF_PIXEL, m0
mova [r0+Y*FDEC_STRIDEB], m1
RET
%endmacro ; PREDICT_8x8_DDLR
%if HIGH_BIT_DEPTH
INIT_XMM sse2
PREDICT_8x8_DDLR
INIT_XMM ssse3
PREDICT_8x8_DDLR
INIT_XMM cache64, ssse3
PREDICT_8x8_DDLR
%elif ARCH_X86_64 == 0
INIT_MMX mmx2
PREDICT_8x8_DDLR
%endif
;-----------------------------------------------------------------------------
; void predict_8x8_hu( pixel *src, pixel *edge )
;-----------------------------------------------------------------------------
%macro PREDICT_8x8_HU 2
cglobal predict_8x8_hu, 2,2,8
add r0, 4*FDEC_STRIDEB
%if HIGH_BIT_DEPTH
%if cpuflag(ssse3)
movu m5, [r1+7*SIZEOF_PIXEL]
pshufb m5, [pw_reverse]
%else
movq m6, [r1+7*SIZEOF_PIXEL]
movq m5, [r1+11*SIZEOF_PIXEL]
pshuflw m6, m6, q0123
pshuflw m5, m5, q0123
movlhps m5, m6
%endif ; cpuflag
psrldq m2, m5, 2
pshufd m3, m5, q0321
pshufhw m2, m2, q2210
pshufhw m3, m3, q1110
pavgw m4, m5, m2
%else ; !HIGH_BIT_DEPTH
movu m1, [r1+7*SIZEOF_PIXEL] ; l0 l1 l2 l3 l4 l5 l6 l7
pshufw m0, m1, q0123 ; l6 l7 l4 l5 l2 l3 l0 l1
psllq m1, 56 ; l7 .. .. .. .. .. .. ..
mova m2, m0
psllw m0, 8
psrlw m2, 8
por m2, m0
mova m3, m2
mova m4, m2
mova m5, m2 ; l7 l6 l5 l4 l3 l2 l1 l0
psrlq m3, 16
psrlq m2, 8
por m2, m1 ; l7 l7 l6 l5 l4 l3 l2 l1
punpckhbw m1, m1
por m3, m1 ; l7 l7 l7 l6 l5 l4 l3 l2
pavgb m4, m2
%endif ; !HIGH_BIT_DEPTH
PRED8x8_LOWPASS m2, m3, m5, m2, m6
punpckh%2 m0, m4, m2 ; p8 p7 p6 p5
punpckl%2 m4, m2 ; p4 p3 p2 p1
PALIGNR m5, m0, m4, 2*SIZEOF_PIXEL, m3
pshuf%1 m1, m0, q3321
PALIGNR m6, m0, m4, 4*SIZEOF_PIXEL, m3
pshuf%1 m2, m0, q3332
PALIGNR m7, m0, m4, 6*SIZEOF_PIXEL, m3
pshuf%1 m3, m0, q3333
mova [r0-4*FDEC_STRIDEB], m4
mova [r0-3*FDEC_STRIDEB], m5
mova [r0-2*FDEC_STRIDEB], m6
mova [r0-1*FDEC_STRIDEB], m7
mova [r0+0*FDEC_STRIDEB], m0
mova [r0+1*FDEC_STRIDEB], m1
mova [r0+2*FDEC_STRIDEB], m2
mova [r0+3*FDEC_STRIDEB], m3
RET
%endmacro
%if HIGH_BIT_DEPTH
INIT_XMM sse2
PREDICT_8x8_HU d, wd
INIT_XMM ssse3
PREDICT_8x8_HU d, wd
INIT_XMM avx
PREDICT_8x8_HU d, wd
%elif ARCH_X86_64 == 0
INIT_MMX mmx2
PREDICT_8x8_HU w, bw
%endif
;-----------------------------------------------------------------------------
; void predict_8x8_vr( pixel *src, pixel *edge )
;-----------------------------------------------------------------------------
%macro PREDICT_8x8_VR 1
cglobal predict_8x8_vr, 2,3
mova m2, [r1+16*SIZEOF_PIXEL]
%ifidn cpuname, ssse3
mova m0, [r1+8*SIZEOF_PIXEL]
palignr m3, m2, m0, 7*SIZEOF_PIXEL
palignr m1, m2, m0, 6*SIZEOF_PIXEL
%else
movu m3, [r1+15*SIZEOF_PIXEL]
movu m1, [r1+14*SIZEOF_PIXEL]
%endif
pavg%1 m4, m3, m2
add r0, FDEC_STRIDEB*4
PRED8x8_LOWPASS m3, m1, m2, m3, m5
mova [r0-4*FDEC_STRIDEB], m4
mova [r0-3*FDEC_STRIDEB], m3
mova m1, [r1+8*SIZEOF_PIXEL]
PSLLPIX m0, m1, 1
PSLLPIX m2, m1, 2
PRED8x8_LOWPASS m0, m1, m2, m0, m6
%assign Y -2
%rep 5
PALIGNR m4, m0, 7*SIZEOF_PIXEL, m5
mova [r0+Y*FDEC_STRIDEB], m4
PSLLPIX m0, m0, 1
SWAP 3, 4
%assign Y (Y+1)
%endrep
PALIGNR m4, m0, 7*SIZEOF_PIXEL, m0
mova [r0+Y*FDEC_STRIDEB], m4
RET
%endmacro
%if HIGH_BIT_DEPTH
INIT_XMM sse2
PREDICT_8x8_VR w
INIT_XMM ssse3
PREDICT_8x8_VR w
INIT_XMM avx
PREDICT_8x8_VR w
%elif ARCH_X86_64 == 0
INIT_MMX mmx2
PREDICT_8x8_VR b
%endif
%macro LOAD_PLANE_ARGS 0
%if cpuflag(avx2) && ARCH_X86_64 == 0
vpbroadcastw m0, r1m
vpbroadcastw m2, r2m
vpbroadcastw m4, r3m
%elif mmsize == 8 ; MMX is only used on x86_32
SPLATW m0, r1m
SPLATW m2, r2m
SPLATW m4, r3m
%else
movd xm0, r1m
movd xm2, r2m
movd xm4, r3m
SPLATW m0, xm0
SPLATW m2, xm2
SPLATW m4, xm4
%endif
%endmacro
;-----------------------------------------------------------------------------
; void predict_8x8c_p_core( uint8_t *src, int i00, int b, int c )
;-----------------------------------------------------------------------------
%if ARCH_X86_64 == 0 && HIGH_BIT_DEPTH == 0
%macro PREDICT_CHROMA_P_MMX 1
cglobal predict_8x%1c_p_core, 1,2
LOAD_PLANE_ARGS
movq m1, m2
pmullw m2, [pw_0to15]
psllw m1, 2
paddsw m0, m2 ; m0 = {i+0*b, i+1*b, i+2*b, i+3*b}
paddsw m1, m0 ; m1 = {i+4*b, i+5*b, i+6*b, i+7*b}
mov r1d, %1
ALIGN 4
.loop:
movq m5, m0
movq m6, m1
psraw m5, 5
psraw m6, 5
packuswb m5, m6
movq [r0], m5
paddsw m0, m4
paddsw m1, m4
add r0, FDEC_STRIDE
dec r1d
jg .loop
RET
%endmacro ; PREDICT_CHROMA_P_MMX
INIT_MMX mmx2
PREDICT_CHROMA_P_MMX 8
PREDICT_CHROMA_P_MMX 16
%endif ; !ARCH_X86_64 && !HIGH_BIT_DEPTH
%macro PREDICT_CHROMA_P 1
%if HIGH_BIT_DEPTH
cglobal predict_8x%1c_p_core, 1,2,7
LOAD_PLANE_ARGS
mova m3, [pw_pixel_max]
pxor m1, m1
pmullw m2, [pw_43210123] ; b
%if %1 == 16
pmullw m5, m4, [pw_m7] ; c
%else
pmullw m5, m4, [pw_m3]
%endif
paddw m5, [pw_16]
%if mmsize == 32
mova xm6, xm4
paddw m4, m4
paddw m5, m6
%endif
mov r1d, %1/(mmsize/16)
.loop:
paddsw m6, m2, m5
paddsw m6, m0
psraw m6, 5
CLIPW m6, m1, m3
paddw m5, m4
%if mmsize == 32
vextracti128 [r0], m6, 1
mova [r0+FDEC_STRIDEB], xm6
add r0, 2*FDEC_STRIDEB
%else
mova [r0], m6
add r0, FDEC_STRIDEB
%endif
dec r1d
jg .loop
RET
%else ; !HIGH_BIT_DEPTH
cglobal predict_8x%1c_p_core, 1,2
LOAD_PLANE_ARGS
%if mmsize == 32
vbroadcasti128 m1, [pw_0to15] ; 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7
pmullw m2, m1
mova xm1, xm4 ; zero upper half
paddsw m4, m4
paddsw m0, m1
%else
pmullw m2, [pw_0to15]
%endif
paddsw m0, m2 ; m0 = {i+0*b, i+1*b, i+2*b, i+3*b, i+4*b, i+5*b, i+6*b, i+7*b}
paddsw m1, m0, m4
paddsw m4, m4
mov r1d, %1/(mmsize/8)
.loop:
psraw m2, m0, 5
psraw m3, m1, 5
paddsw m0, m4
paddsw m1, m4
packuswb m2, m3
%if mmsize == 32
movq [r0+FDEC_STRIDE*1], xm2
movhps [r0+FDEC_STRIDE*3], xm2
vextracti128 xm2, m2, 1
movq [r0+FDEC_STRIDE*0], xm2
movhps [r0+FDEC_STRIDE*2], xm2
%else
movq [r0+FDEC_STRIDE*0], xm2
movhps [r0+FDEC_STRIDE*1], xm2
%endif
add r0, FDEC_STRIDE*mmsize/8
dec r1d
jg .loop
RET
%endif ; HIGH_BIT_DEPTH
%endmacro ; PREDICT_CHROMA_P
INIT_XMM sse2
PREDICT_CHROMA_P 8
PREDICT_CHROMA_P 16
INIT_XMM avx
PREDICT_CHROMA_P 8
PREDICT_CHROMA_P 16
INIT_YMM avx2
PREDICT_CHROMA_P 8
PREDICT_CHROMA_P 16
;-----------------------------------------------------------------------------
; void predict_16x16_p_core( uint8_t *src, int i00, int b, int c )
;-----------------------------------------------------------------------------
%if HIGH_BIT_DEPTH == 0 && ARCH_X86_64 == 0
INIT_MMX mmx2
cglobal predict_16x16_p_core, 1,2
LOAD_PLANE_ARGS
movq mm5, mm2
movq mm1, mm2
pmullw mm5, [pw_0to15]
psllw mm2, 3
psllw mm1, 2
movq mm3, mm2
paddsw mm0, mm5 ; mm0 = {i+ 0*b, i+ 1*b, i+ 2*b, i+ 3*b}
paddsw mm1, mm0 ; mm1 = {i+ 4*b, i+ 5*b, i+ 6*b, i+ 7*b}
paddsw mm2, mm0 ; mm2 = {i+ 8*b, i+ 9*b, i+10*b, i+11*b}
paddsw mm3, mm1 ; mm3 = {i+12*b, i+13*b, i+14*b, i+15*b}
mov r1d, 16
ALIGN 4
.loop:
movq mm5, mm0
movq mm6, mm1
psraw mm5, 5
psraw mm6, 5
packuswb mm5, mm6
movq [r0], mm5
movq mm5, mm2
movq mm6, mm3
psraw mm5, 5
psraw mm6, 5
packuswb mm5, mm6
movq [r0+8], mm5
paddsw mm0, mm4
paddsw mm1, mm4
paddsw mm2, mm4
paddsw mm3, mm4
add r0, FDEC_STRIDE
dec r1d
jg .loop
RET
%endif ; !HIGH_BIT_DEPTH && !ARCH_X86_64
%macro PREDICT_16x16_P 0
cglobal predict_16x16_p_core, 1,2,8
movd m0, r1m
movd m1, r2m
movd m2, r3m
SPLATW m0, m0, 0
SPLATW m1, m1, 0
SPLATW m2, m2, 0
pmullw m3, m1, [pw_0to15]
psllw m1, 3
%if HIGH_BIT_DEPTH
pxor m6, m6
mov r1d, 16
.loop:
mova m4, m0
mova m5, m0
mova m7, m3
paddsw m7, m6
paddsw m4, m7
paddsw m7, m1
paddsw m5, m7
psraw m4, 5
psraw m5, 5
CLIPW m4, [pb_0], [pw_pixel_max]
CLIPW m5, [pb_0], [pw_pixel_max]
mova [r0], m4
mova [r0+16], m5
add r0, FDEC_STRIDEB
paddw m6, m2
%else ; !HIGH_BIT_DEPTH
paddsw m0, m3 ; m0 = {i+ 0*b, i+ 1*b, i+ 2*b, i+ 3*b, i+ 4*b, i+ 5*b, i+ 6*b, i+ 7*b}
paddsw m1, m0 ; m1 = {i+ 8*b, i+ 9*b, i+10*b, i+11*b, i+12*b, i+13*b, i+14*b, i+15*b}
paddsw m7, m2, m2
mov r1d, 8
ALIGN 4
.loop:
psraw m3, m0, 5
psraw m4, m1, 5
paddsw m5, m0, m2
paddsw m6, m1, m2
psraw m5, 5
psraw m6, 5
packuswb m3, m4
packuswb m5, m6
mova [r0+FDEC_STRIDE*0], m3
mova [r0+FDEC_STRIDE*1], m5
paddsw m0, m7
paddsw m1, m7
add r0, FDEC_STRIDE*2
%endif ; !HIGH_BIT_DEPTH
dec r1d
jg .loop
RET
%endmacro ; PREDICT_16x16_P
INIT_XMM sse2
PREDICT_16x16_P
%if HIGH_BIT_DEPTH == 0
INIT_XMM avx
PREDICT_16x16_P
%endif
INIT_YMM avx2
cglobal predict_16x16_p_core, 1,2,8*HIGH_BIT_DEPTH
LOAD_PLANE_ARGS
%if HIGH_BIT_DEPTH
pmullw m2, [pw_0to15]
pxor m5, m5
pxor m6, m6
mova m7, [pw_pixel_max]
mov r1d, 8
.loop:
paddsw m1, m2, m5
paddw m5, m4
paddsw m1, m0
paddsw m3, m2, m5
psraw m1, 5
paddsw m3, m0
psraw m3, 5
CLIPW m1, m6, m7
mova [r0+0*FDEC_STRIDEB], m1
CLIPW m3, m6, m7
mova [r0+1*FDEC_STRIDEB], m3
paddw m5, m4
add r0, 2*FDEC_STRIDEB
%else ; !HIGH_BIT_DEPTH
vbroadcasti128 m1, [pw_0to15]
mova xm3, xm4 ; zero high bits
pmullw m1, m2
psllw m2, 3
paddsw m0, m3
paddsw m0, m1 ; X+1*C X+0*C
paddsw m1, m0, m2 ; Y+1*C Y+0*C
paddsw m4, m4
mov r1d, 4
.loop:
psraw m2, m0, 5
psraw m3, m1, 5
paddsw m0, m4
paddsw m1, m4
packuswb m2, m3 ; X+1*C Y+1*C X+0*C Y+0*C
vextracti128 [r0+0*FDEC_STRIDE], m2, 1
mova [r0+1*FDEC_STRIDE], xm2
psraw m2, m0, 5
psraw m3, m1, 5
paddsw m0, m4
paddsw m1, m4
packuswb m2, m3 ; X+3*C Y+3*C X+2*C Y+2*C
vextracti128 [r0+2*FDEC_STRIDE], m2, 1
mova [r0+3*FDEC_STRIDE], xm2
add r0, FDEC_STRIDE*4
%endif ; !HIGH_BIT_DEPTH
dec r1d
jg .loop
RET
%if HIGH_BIT_DEPTH == 0
%macro PREDICT_8x8 0
;-----------------------------------------------------------------------------
; void predict_8x8_ddl( uint8_t *src, uint8_t *edge )
;-----------------------------------------------------------------------------
cglobal predict_8x8_ddl, 2,2
mova m0, [r1+16]
%ifidn cpuname, ssse3
movd m2, [r1+32]
palignr m2, m0, 1
%else
movu m2, [r1+17]
%endif
pslldq m1, m0, 1
add r0, FDEC_STRIDE*4
PRED8x8_LOWPASS m0, m1, m2, m0, m3
%assign Y -4
%rep 8
psrldq m0, 1
movq [r0+Y*FDEC_STRIDE], m0
%assign Y (Y+1)
%endrep
RET
%ifnidn cpuname, ssse3
;-----------------------------------------------------------------------------
; void predict_8x8_ddr( uint8_t *src, uint8_t *edge )
;-----------------------------------------------------------------------------
cglobal predict_8x8_ddr, 2,2
movu m0, [r1+8]
movu m1, [r1+7]
psrldq m2, m0, 1
add r0, FDEC_STRIDE*4
PRED8x8_LOWPASS m0, m1, m2, m0, m3
psrldq m1, m0, 1
%assign Y 3
%rep 3
movq [r0+Y*FDEC_STRIDE], m0
movq [r0+(Y-1)*FDEC_STRIDE], m1
psrldq m0, 2
psrldq m1, 2
%assign Y (Y-2)
%endrep
movq [r0-3*FDEC_STRIDE], m0
movq [r0-4*FDEC_STRIDE], m1
RET
;-----------------------------------------------------------------------------
; void predict_8x8_vl( uint8_t *src, uint8_t *edge )
;-----------------------------------------------------------------------------
cglobal predict_8x8_vl, 2,2
mova m0, [r1+16]
pslldq m1, m0, 1
psrldq m2, m0, 1
pavgb m3, m0, m2
add r0, FDEC_STRIDE*4
PRED8x8_LOWPASS m0, m1, m2, m0, m5
; m0: (t0 + 2*t1 + t2 + 2) >> 2
; m3: (t0 + t1 + 1) >> 1
%assign Y -4
%rep 3
psrldq m0, 1
movq [r0+ Y *FDEC_STRIDE], m3
movq [r0+(Y+1)*FDEC_STRIDE], m0
psrldq m3, 1
%assign Y (Y+2)
%endrep
psrldq m0, 1
movq [r0+ Y *FDEC_STRIDE], m3
movq [r0+(Y+1)*FDEC_STRIDE], m0
RET
%endif ; !ssse3
;-----------------------------------------------------------------------------
; void predict_8x8_vr( uint8_t *src, uint8_t *edge )
;-----------------------------------------------------------------------------
cglobal predict_8x8_vr, 2,2
movu m2, [r1+8]
add r0, 4*FDEC_STRIDE
pslldq m1, m2, 2
pslldq m0, m2, 1
pavgb m3, m2, m0
PRED8x8_LOWPASS m0, m2, m1, m0, m4
movhps [r0-4*FDEC_STRIDE], m3
movhps [r0-3*FDEC_STRIDE], m0
%if cpuflag(ssse3)
punpckhqdq m3, m3
pshufb m0, [shuf_vr]
palignr m3, m0, 13
%else
mova m2, m0
mova m1, [pw_00ff]
pand m1, m0
psrlw m0, 8
packuswb m1, m0
pslldq m1, 4
movhlps m3, m1
shufps m1, m2, q3210
psrldq m3, 5
psrldq m1, 5
SWAP 0, 1
%endif
movq [r0+3*FDEC_STRIDE], m0
movq [r0+2*FDEC_STRIDE], m3
psrldq m0, 1
psrldq m3, 1
movq [r0+1*FDEC_STRIDE], m0
movq [r0+0*FDEC_STRIDE], m3
psrldq m0, 1
psrldq m3, 1
movq [r0-1*FDEC_STRIDE], m0
movq [r0-2*FDEC_STRIDE], m3
RET
%endmacro ; PREDICT_8x8
INIT_XMM sse2
PREDICT_8x8
INIT_XMM ssse3
PREDICT_8x8
INIT_XMM avx
PREDICT_8x8
%endif ; !HIGH_BIT_DEPTH
;-----------------------------------------------------------------------------
; void predict_8x8_vl( pixel *src, pixel *edge )
;-----------------------------------------------------------------------------
%macro PREDICT_8x8_VL_10 1
cglobal predict_8x8_vl, 2,2,8
mova m0, [r1+16*SIZEOF_PIXEL]
mova m1, [r1+24*SIZEOF_PIXEL]
PALIGNR m2, m1, m0, SIZEOF_PIXEL*1, m4
PSRLPIX m4, m1, 1
pavg%1 m6, m0, m2
pavg%1 m7, m1, m4
add r0, FDEC_STRIDEB*4
mova [r0-4*FDEC_STRIDEB], m6
PALIGNR m3, m7, m6, SIZEOF_PIXEL*1, m5
mova [r0-2*FDEC_STRIDEB], m3
PALIGNR m3, m7, m6, SIZEOF_PIXEL*2, m5
mova [r0+0*FDEC_STRIDEB], m3
PALIGNR m7, m7, m6, SIZEOF_PIXEL*3, m5
mova [r0+2*FDEC_STRIDEB], m7
PALIGNR m3, m1, m0, SIZEOF_PIXEL*7, m6
PSLLPIX m5, m0, 1
PRED8x8_LOWPASS m0, m5, m2, m0, m7
PRED8x8_LOWPASS m1, m3, m4, m1, m7
PALIGNR m4, m1, m0, SIZEOF_PIXEL*1, m2
mova [r0-3*FDEC_STRIDEB], m4
PALIGNR m4, m1, m0, SIZEOF_PIXEL*2, m2
mova [r0-1*FDEC_STRIDEB], m4
PALIGNR m4, m1, m0, SIZEOF_PIXEL*3, m2
mova [r0+1*FDEC_STRIDEB], m4
PALIGNR m1, m1, m0, SIZEOF_PIXEL*4, m2
mova [r0+3*FDEC_STRIDEB], m1
RET
%endmacro
%if HIGH_BIT_DEPTH
INIT_XMM sse2
PREDICT_8x8_VL_10 w
INIT_XMM ssse3
PREDICT_8x8_VL_10 w
INIT_XMM avx
PREDICT_8x8_VL_10 w
%else
INIT_MMX mmx2
PREDICT_8x8_VL_10 b
%endif
;-----------------------------------------------------------------------------
; void predict_8x8_hd( pixel *src, pixel *edge )
;-----------------------------------------------------------------------------
%macro PREDICT_8x8_HD 2
cglobal predict_8x8_hd, 2,2
add r0, 4*FDEC_STRIDEB
mova m0, [r1+ 8*SIZEOF_PIXEL] ; lt l0 l1 l2 l3 l4 l5 l6
movu m1, [r1+ 7*SIZEOF_PIXEL] ; l0 l1 l2 l3 l4 l5 l6 l7
%ifidn cpuname, ssse3
mova m2, [r1+16*SIZEOF_PIXEL] ; t7 t6 t5 t4 t3 t2 t1 t0
mova m4, m2 ; t7 t6 t5 t4 t3 t2 t1 t0
palignr m2, m0, 7*SIZEOF_PIXEL ; t6 t5 t4 t3 t2 t1 t0 lt
palignr m4, m0, 1*SIZEOF_PIXEL ; t0 lt l0 l1 l2 l3 l4 l5
%else
movu m2, [r1+15*SIZEOF_PIXEL]
movu m4, [r1+ 9*SIZEOF_PIXEL]
%endif ; cpuflag
pavg%1 m3, m0, m1
PRED8x8_LOWPASS m0, m4, m1, m0, m5
PSRLPIX m4, m2, 2 ; .. .. t6 t5 t4 t3 t2 t1
PSRLPIX m1, m2, 1 ; .. t6 t5 t4 t3 t2 t1 t0
PRED8x8_LOWPASS m1, m4, m2, m1, m5
; .. p11 p10 p9
punpckh%2 m2, m3, m0 ; p8 p7 p6 p5
punpckl%2 m3, m0 ; p4 p3 p2 p1
mova [r0+3*FDEC_STRIDEB], m3
PALIGNR m0, m2, m3, 2*SIZEOF_PIXEL, m5
mova [r0+2*FDEC_STRIDEB], m0
PALIGNR m0, m2, m3, 4*SIZEOF_PIXEL, m5
mova [r0+1*FDEC_STRIDEB], m0
PALIGNR m0, m2, m3, 6*SIZEOF_PIXEL, m3
mova [r0+0*FDEC_STRIDEB], m0
mova [r0-1*FDEC_STRIDEB], m2
PALIGNR m0, m1, m2, 2*SIZEOF_PIXEL, m5
mova [r0-2*FDEC_STRIDEB], m0
PALIGNR m0, m1, m2, 4*SIZEOF_PIXEL, m5
mova [r0-3*FDEC_STRIDEB], m0
PALIGNR m1, m1, m2, 6*SIZEOF_PIXEL, m2
mova [r0-4*FDEC_STRIDEB], m1
RET
%endmacro
%if HIGH_BIT_DEPTH
INIT_XMM sse2
PREDICT_8x8_HD w, wd
INIT_XMM ssse3
PREDICT_8x8_HD w, wd
INIT_XMM avx
PREDICT_8x8_HD w, wd
%else
INIT_MMX mmx2
PREDICT_8x8_HD b, bw
;-----------------------------------------------------------------------------
; void predict_8x8_hd( uint8_t *src, uint8_t *edge )
;-----------------------------------------------------------------------------
%macro PREDICT_8x8_HD 0
cglobal predict_8x8_hd, 2,2
add r0, 4*FDEC_STRIDE
movu m1, [r1+7]
movu m3, [r1+8]
movu m2, [r1+9]
pavgb m4, m1, m3
PRED8x8_LOWPASS m0, m1, m2, m3, m5
punpcklbw m4, m0
movhlps m0, m4
%assign Y 3
%rep 3
movq [r0+(Y)*FDEC_STRIDE], m4
movq [r0+(Y-4)*FDEC_STRIDE], m0
psrldq m4, 2
psrldq m0, 2
%assign Y (Y-1)
%endrep
movq [r0+(Y)*FDEC_STRIDE], m4
movq [r0+(Y-4)*FDEC_STRIDE], m0
RET
%endmacro
INIT_XMM sse2
PREDICT_8x8_HD
INIT_XMM avx
PREDICT_8x8_HD
%endif ; HIGH_BIT_DEPTH
%if HIGH_BIT_DEPTH == 0
;-----------------------------------------------------------------------------
; void predict_8x8_hu( uint8_t *src, uint8_t *edge )
;-----------------------------------------------------------------------------
INIT_MMX
cglobal predict_8x8_hu_sse2, 2,2
add r0, 4*FDEC_STRIDE
movq mm1, [r1+7] ; l0 l1 l2 l3 l4 l5 l6 l7
pshufw mm0, mm1, q0123 ; l6 l7 l4 l5 l2 l3 l0 l1
movq mm2, mm0
psllw mm0, 8
psrlw mm2, 8
por mm2, mm0 ; l7 l6 l5 l4 l3 l2 l1 l0
psllq mm1, 56 ; l7 .. .. .. .. .. .. ..
movq mm3, mm2
movq mm4, mm2
movq mm5, mm2
psrlq mm2, 8
psrlq mm3, 16
por mm2, mm1 ; l7 l7 l6 l5 l4 l3 l2 l1
punpckhbw mm1, mm1
por mm3, mm1 ; l7 l7 l7 l6 l5 l4 l3 l2
pavgb mm4, mm2
PRED8x8_LOWPASS mm1, mm3, mm5, mm2, mm6
movq2dq xmm0, mm4
movq2dq xmm1, mm1
punpcklbw xmm0, xmm1
punpckhbw mm4, mm1
%assign Y -4
%rep 3
movq [r0+Y*FDEC_STRIDE], xmm0
psrldq xmm0, 2
%assign Y (Y+1)
%endrep
pshufw mm5, mm4, q3321
pshufw mm6, mm4, q3332
pshufw mm7, mm4, q3333
movq [r0+Y*FDEC_STRIDE], xmm0
movq [r0+0*FDEC_STRIDE], mm4
movq [r0+1*FDEC_STRIDE], mm5
movq [r0+2*FDEC_STRIDE], mm6
movq [r0+3*FDEC_STRIDE], mm7
RET
INIT_XMM
cglobal predict_8x8_hu_ssse3, 2,2
add r0, 4*FDEC_STRIDE
movq m3, [r1+7]
pshufb m3, [shuf_hu]
psrldq m1, m3, 1
psrldq m2, m3, 2
pavgb m0, m1, m3
PRED8x8_LOWPASS m1, m3, m2, m1, m4
punpcklbw m0, m1
%assign Y -4
%rep 3
movq [r0+ Y *FDEC_STRIDE], m0
movhps [r0+(Y+4)*FDEC_STRIDE], m0
psrldq m0, 2
pshufhw m0, m0, q2210
%assign Y (Y+1)
%endrep
movq [r0+ Y *FDEC_STRIDE], m0
movhps [r0+(Y+4)*FDEC_STRIDE], m0
RET
%endif ; !HIGH_BIT_DEPTH
;-----------------------------------------------------------------------------
; void predict_8x8c_v( uint8_t *src )
;-----------------------------------------------------------------------------
%macro PREDICT_8x8C_V 0
cglobal predict_8x8c_v, 1,1
mova m0, [r0 - FDEC_STRIDEB]
STORE8 m0
RET
%endmacro
%if HIGH_BIT_DEPTH
INIT_XMM sse
PREDICT_8x8C_V
%else
INIT_MMX mmx
PREDICT_8x8C_V
%endif
%if HIGH_BIT_DEPTH
INIT_MMX
cglobal predict_8x8c_v_mmx, 1,1
mova m0, [r0 - FDEC_STRIDEB]
mova m1, [r0 - FDEC_STRIDEB + 8]
%assign Y 0
%rep 8
mova [r0 + (Y&1)*FDEC_STRIDEB], m0
mova [r0 + (Y&1)*FDEC_STRIDEB + 8], m1
%if (Y&1) && (Y!=7)
add r0, FDEC_STRIDEB*2
%endif
%assign Y Y+1
%endrep
RET
%endif
%macro PREDICT_8x16C_V 0
cglobal predict_8x16c_v, 1,1
mova m0, [r0 - FDEC_STRIDEB]
STORE16 m0
RET
%endmacro
%if HIGH_BIT_DEPTH
INIT_XMM sse
PREDICT_8x16C_V
%else
INIT_MMX mmx
PREDICT_8x16C_V
%endif
;-----------------------------------------------------------------------------
; void predict_8x8c_h( uint8_t *src )
;-----------------------------------------------------------------------------
%macro PREDICT_C_H 0
cglobal predict_8x8c_h, 1,1
%if cpuflag(ssse3) && notcpuflag(avx2)
mova m2, [pb_3]
%endif
PRED_H_4ROWS 8, 1
PRED_H_4ROWS 8, 0
RET
cglobal predict_8x16c_h, 1,2
%if cpuflag(ssse3) && notcpuflag(avx2)
mova m2, [pb_3]
%endif
mov r1d, 4
.loop:
PRED_H_4ROWS 8, 1
dec r1d
jg .loop
RET
%endmacro
INIT_MMX mmx2
PREDICT_C_H
%if HIGH_BIT_DEPTH
INIT_XMM sse2
PREDICT_C_H
INIT_XMM avx2
PREDICT_C_H
%else
INIT_MMX ssse3
PREDICT_C_H
%endif
;-----------------------------------------------------------------------------
; void predict_8x8c_dc( pixel *src )
;-----------------------------------------------------------------------------
%macro LOAD_LEFT 1
movzx r1d, pixel [r0+FDEC_STRIDEB*(%1-4)-SIZEOF_PIXEL]
movzx r2d, pixel [r0+FDEC_STRIDEB*(%1-3)-SIZEOF_PIXEL]
add r1d, r2d
movzx r2d, pixel [r0+FDEC_STRIDEB*(%1-2)-SIZEOF_PIXEL]
add r1d, r2d
movzx r2d, pixel [r0+FDEC_STRIDEB*(%1-1)-SIZEOF_PIXEL]
add r1d, r2d
%endmacro
%macro PREDICT_8x8C_DC 0
cglobal predict_8x8c_dc, 1,3
pxor m7, m7
%if HIGH_BIT_DEPTH
movq m0, [r0-FDEC_STRIDEB+0]
movq m1, [r0-FDEC_STRIDEB+8]
HADDW m0, m2
HADDW m1, m2
%else ; !HIGH_BIT_DEPTH
movd m0, [r0-FDEC_STRIDEB+0]
movd m1, [r0-FDEC_STRIDEB+4]
psadbw m0, m7 ; s0
psadbw m1, m7 ; s1
%endif
add r0, FDEC_STRIDEB*4
LOAD_LEFT 0 ; s2
movd m2, r1d
LOAD_LEFT 4 ; s3
movd m3, r1d
punpcklwd m0, m1
punpcklwd m2, m3
punpckldq m0, m2 ; s0, s1, s2, s3
pshufw m3, m0, q3312 ; s2, s1, s3, s3
pshufw m0, m0, q1310 ; s0, s1, s3, s1
paddw m0, m3
psrlw m0, 2
pavgw m0, m7 ; s0+s2, s1, s3, s1+s3
%if HIGH_BIT_DEPTH
%if cpuflag(sse2)
movq2dq xmm0, m0
punpcklwd xmm0, xmm0
pshufd xmm1, xmm0, q3322
punpckldq xmm0, xmm0
%assign Y 0
%rep 8
%assign i (0 + (Y/4))
movdqa [r0+FDEC_STRIDEB*(Y-4)+0], xmm %+ i
%assign Y Y+1
%endrep
%else ; !sse2
pshufw m1, m0, q0000
pshufw m2, m0, q1111
pshufw m3, m0, q2222
pshufw m4, m0, q3333
%assign Y 0
%rep 8
%assign i (1 + (Y/4)*2)
%assign j (2 + (Y/4)*2)
movq [r0+FDEC_STRIDEB*(Y-4)+0], m %+ i
movq [r0+FDEC_STRIDEB*(Y-4)+8], m %+ j
%assign Y Y+1
%endrep
%endif
%else ; !HIGH_BIT_DEPTH
packuswb m0, m0
punpcklbw m0, m0
movq m1, m0
punpcklbw m0, m0
punpckhbw m1, m1
%assign Y 0
%rep 8
%assign i (0 + (Y/4))
movq [r0+FDEC_STRIDEB*(Y-4)], m %+ i
%assign Y Y+1
%endrep
%endif
RET
%endmacro
INIT_MMX mmx2
PREDICT_8x8C_DC
%if HIGH_BIT_DEPTH
INIT_MMX sse2
PREDICT_8x8C_DC
%endif
%if HIGH_BIT_DEPTH
%macro STORE_4LINES 3
%if cpuflag(sse2)
movdqa [r0+FDEC_STRIDEB*(%3-4)], %1
movdqa [r0+FDEC_STRIDEB*(%3-3)], %1
movdqa [r0+FDEC_STRIDEB*(%3-2)], %1
movdqa [r0+FDEC_STRIDEB*(%3-1)], %1
%else
movq [r0+FDEC_STRIDEB*(%3-4)+0], %1
movq [r0+FDEC_STRIDEB*(%3-4)+8], %2
movq [r0+FDEC_STRIDEB*(%3-3)+0], %1
movq [r0+FDEC_STRIDEB*(%3-3)+8], %2
movq [r0+FDEC_STRIDEB*(%3-2)+0], %1
movq [r0+FDEC_STRIDEB*(%3-2)+8], %2
movq [r0+FDEC_STRIDEB*(%3-1)+0], %1
movq [r0+FDEC_STRIDEB*(%3-1)+8], %2
%endif
%endmacro
%else
%macro STORE_4LINES 2
movq [r0+FDEC_STRIDEB*(%2-4)], %1
movq [r0+FDEC_STRIDEB*(%2-3)], %1
movq [r0+FDEC_STRIDEB*(%2-2)], %1
movq [r0+FDEC_STRIDEB*(%2-1)], %1
%endmacro
%endif
%macro PREDICT_8x16C_DC 0
cglobal predict_8x16c_dc, 1,3
pxor m7, m7
%if HIGH_BIT_DEPTH
movq m0, [r0-FDEC_STRIDEB+0]
movq m1, [r0-FDEC_STRIDEB+8]
HADDW m0, m2
HADDW m1, m2
%else
movd m0, [r0-FDEC_STRIDEB+0]
movd m1, [r0-FDEC_STRIDEB+4]
psadbw m0, m7 ; s0
psadbw m1, m7 ; s1
%endif
punpcklwd m0, m1 ; s0, s1
add r0, FDEC_STRIDEB*4
LOAD_LEFT 0 ; s2
pinsrw m0, r1d, 2
LOAD_LEFT 4 ; s3
pinsrw m0, r1d, 3 ; s0, s1, s2, s3
add r0, FDEC_STRIDEB*8
LOAD_LEFT 0 ; s4
pinsrw m1, r1d, 2
LOAD_LEFT 4 ; s5
pinsrw m1, r1d, 3 ; s1, __, s4, s5
sub r0, FDEC_STRIDEB*8
pshufw m2, m0, q1310 ; s0, s1, s3, s1
pshufw m0, m0, q3312 ; s2, s1, s3, s3
pshufw m3, m1, q0302 ; s4, s1, s5, s1
pshufw m1, m1, q3322 ; s4, s4, s5, s5
paddw m0, m2
paddw m1, m3
psrlw m0, 2
psrlw m1, 2
pavgw m0, m7
pavgw m1, m7
%if HIGH_BIT_DEPTH
%if cpuflag(sse2)
movq2dq xmm0, m0
movq2dq xmm1, m1
punpcklwd xmm0, xmm0
punpcklwd xmm1, xmm1
pshufd xmm2, xmm0, q3322
pshufd xmm3, xmm1, q3322
punpckldq xmm0, xmm0
punpckldq xmm1, xmm1
STORE_4LINES xmm0, xmm0, 0
STORE_4LINES xmm2, xmm2, 4
STORE_4LINES xmm1, xmm1, 8
STORE_4LINES xmm3, xmm3, 12
%else
pshufw m2, m0, q0000
pshufw m3, m0, q1111
pshufw m4, m0, q2222
pshufw m5, m0, q3333
STORE_4LINES m2, m3, 0
STORE_4LINES m4, m5, 4
pshufw m2, m1, q0000
pshufw m3, m1, q1111
pshufw m4, m1, q2222
pshufw m5, m1, q3333
STORE_4LINES m2, m3, 8
STORE_4LINES m4, m5, 12
%endif
%else
packuswb m0, m0 ; dc0, dc1, dc2, dc3
packuswb m1, m1 ; dc4, dc5, dc6, dc7
punpcklbw m0, m0
punpcklbw m1, m1
pshufw m2, m0, q1100
pshufw m3, m0, q3322
pshufw m4, m1, q1100
pshufw m5, m1, q3322
STORE_4LINES m2, 0
STORE_4LINES m3, 4
add r0, FDEC_STRIDEB*8
STORE_4LINES m4, 0
STORE_4LINES m5, 4
%endif
RET
%endmacro
INIT_MMX mmx2
PREDICT_8x16C_DC
%if HIGH_BIT_DEPTH
INIT_MMX sse2
PREDICT_8x16C_DC
%endif
%macro PREDICT_C_DC_TOP 1
%if HIGH_BIT_DEPTH
INIT_XMM
cglobal predict_8x%1c_dc_top_sse2, 1,1
pxor m2, m2
mova m0, [r0 - FDEC_STRIDEB]
pshufd m1, m0, q2301
paddw m0, m1
pshuflw m1, m0, q2301
pshufhw m1, m1, q2301
paddw m0, m1
psrlw m0, 1
pavgw m0, m2
STORE%1 m0
RET
%else ; !HIGH_BIT_DEPTH
INIT_MMX
cglobal predict_8x%1c_dc_top_mmx2, 1,1
movq mm0, [r0 - FDEC_STRIDE]
pxor mm1, mm1
pxor mm2, mm2
punpckhbw mm1, mm0
punpcklbw mm0, mm2
psadbw mm1, mm2 ; s1
psadbw mm0, mm2 ; s0
psrlw mm1, 1
psrlw mm0, 1
pavgw mm1, mm2
pavgw mm0, mm2
pshufw mm1, mm1, 0
pshufw mm0, mm0, 0 ; dc0 (w)
packuswb mm0, mm1 ; dc0,dc1 (b)
STORE%1 mm0
RET
%endif
%endmacro
PREDICT_C_DC_TOP 8
PREDICT_C_DC_TOP 16
;-----------------------------------------------------------------------------
; void predict_16x16_v( pixel *src )
;-----------------------------------------------------------------------------
%macro PREDICT_16x16_V 0
cglobal predict_16x16_v, 1,2
%assign %%i 0
%rep 16*SIZEOF_PIXEL/mmsize
mova m %+ %%i, [r0-FDEC_STRIDEB+%%i*mmsize]
%assign %%i %%i+1
%endrep
%if 16*SIZEOF_PIXEL/mmsize == 4
STORE16 m0, m1, m2, m3
%elif 16*SIZEOF_PIXEL/mmsize == 2
STORE16 m0, m1
%else
STORE16 m0
%endif
RET
%endmacro
INIT_MMX mmx2
PREDICT_16x16_V
INIT_XMM sse
PREDICT_16x16_V
%if HIGH_BIT_DEPTH
INIT_YMM avx
PREDICT_16x16_V
%endif
;-----------------------------------------------------------------------------
; void predict_16x16_h( pixel *src )
;-----------------------------------------------------------------------------
%macro PREDICT_16x16_H 0
cglobal predict_16x16_h, 1,2
%if cpuflag(ssse3) && notcpuflag(avx2)
mova m2, [pb_3]
%endif
mov r1d, 4
.loop:
PRED_H_4ROWS 16, 1
dec r1d
jg .loop
RET
%endmacro
INIT_MMX mmx2
PREDICT_16x16_H
%if HIGH_BIT_DEPTH
INIT_XMM sse2
PREDICT_16x16_H
INIT_YMM avx2
PREDICT_16x16_H
%else
;no SSE2 for 8-bit, it's slower than MMX on all systems that don't support SSSE3
INIT_XMM ssse3
PREDICT_16x16_H
%endif
;-----------------------------------------------------------------------------
; void predict_16x16_dc( pixel *src )
;-----------------------------------------------------------------------------
%if WIN64
DECLARE_REG_TMP 6 ; Reduces code size due to fewer REX prefixes
%else
DECLARE_REG_TMP 3
%endif
INIT_XMM
; Returns the sum of the left pixels in r1d+r2d
cglobal predict_16x16_dc_left_internal, 0,4
movzx r1d, pixel [r0-SIZEOF_PIXEL]
movzx r2d, pixel [r0+FDEC_STRIDEB-SIZEOF_PIXEL]
%assign i 2*FDEC_STRIDEB
%rep 7
movzx t0d, pixel [r0+i-SIZEOF_PIXEL]
add r1d, t0d
movzx t0d, pixel [r0+i+FDEC_STRIDEB-SIZEOF_PIXEL]
add r2d, t0d
%assign i i+2*FDEC_STRIDEB
%endrep
RET
%macro PRED16x16_DC 2
%if HIGH_BIT_DEPTH
mova xm0, [r0 - FDEC_STRIDEB+ 0]
paddw xm0, [r0 - FDEC_STRIDEB+16]
HADDW xm0, xm2
paddw xm0, %1
psrlw xm0, %2
SPLATW m0, xm0
%if mmsize == 32
STORE16 m0
%else
STORE16 m0, m0
%endif
%else ; !HIGH_BIT_DEPTH
pxor m0, m0
psadbw m0, [r0 - FDEC_STRIDE]
MOVHL m1, m0
paddw m0, m1
paddusw m0, %1
psrlw m0, %2 ; dc
SPLATW m0, m0
packuswb m0, m0 ; dc in bytes
STORE16 m0
%endif
%endmacro
%macro PREDICT_16x16_DC 0
cglobal predict_16x16_dc, 1,3
call predict_16x16_dc_left_internal
lea r1d, [r1+r2+16]
movd xm3, r1d
PRED16x16_DC xm3, 5
RET
cglobal predict_16x16_dc_top, 1,2
PRED16x16_DC [pw_8], 4
RET
cglobal predict_16x16_dc_left, 1,3
call predict_16x16_dc_left_internal
lea r1d, [r1+r2+8]
shr r1d, 4
movd xm0, r1d
SPLATW m0, xm0
%if HIGH_BIT_DEPTH && mmsize == 16
STORE16 m0, m0
%else
%if HIGH_BIT_DEPTH == 0
packuswb m0, m0
%endif
STORE16 m0
%endif
RET
%endmacro
INIT_XMM sse2
PREDICT_16x16_DC
%if HIGH_BIT_DEPTH
INIT_YMM avx2
PREDICT_16x16_DC
%else
INIT_XMM avx2
PREDICT_16x16_DC
%endif
|
;; ======================================================================== ;;
;; Jean-Luc Project Feature Test ;;
;; ======================================================================== ;;
;* ======================================================================== *;
;* This program is free software; you can redistribute it and/or modify *;
;* it under the terms of the GNU General Public License as published by *;
;* the Free Software Foundation; either version 2 of the License, or *;
;* (at your option) any later version. *;
;* *;
;* 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 GNU *;
;* General Public License for more details. *;
;* *;
;* You should have received a copy of the GNU General Public License along *;
;* with this program; if not, write to the Free Software Foundation, Inc., *;
;* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *;
;* ======================================================================== *;
;* Copyright (c) 2009, Joseph Zbiciak *;
;* ======================================================================== *;
ROMW 16 ; Use 16-bit ROM width
CFGVAR "name" = "JLP Random Number Statistics"
CFGVAR "short_name" = "JLP Rand Stats"
CFGVAR "year" = 2011
CFGVAR "author" = "Joe Zbiciak"
CFGVAR "jlp" = 1
CFGVAR "license" = "GPLv2+"
;; ======================================================================== ;;
;; Scratch Memory ;;
;; ======================================================================== ;;
ORG $100, $100, "-RWBN"
ISRVEC RMB 2
BGC RMB 1
;; ======================================================================== ;;
;; System Memory ;;
;; ======================================================================== ;;
ORG $300, $300, "-RWBN"
SGCODE RMB 32 ; space for save-game spinner
STACK RMB 32
CURPOS RMB 1
DELAY RMB 1
;; ======================================================================== ;;
;; JLP Memory ;;
;; ======================================================================== ;;
ORG $8040, $8040, "-RWBN"
HIST1 RMB 256
HIST0 RMB 256
HIST2 RMB 256
;; ======================================================================== ;;
;; Macros and definitions ;;
;; ======================================================================== ;;
INCLUDE "library/gimini.asm"
INCLUDE "macro/util.mac"
INCLUDE "macro/stic.mac"
INCLUDE "macro/gfx.mac"
INCLUDE "macro/print.mac"
ORG $5000
REPEAT $1000
DECLE $
ENDR
ORG $5000 ; Use default memory map
;; ======================================================================== ;;
;; EXEC-friendly ROM header. ;;
;; ======================================================================== ;;
ROMHDR: BIDECLE ZERO ; MOB picture base (points to NULL list)
BIDECLE ZERO ; Process table (points to NULL list)
BIDECLE MAIN ; Program start address
BIDECLE ZERO ; Bkgnd picture base (points to NULL list)
BIDECLE ONES ; GRAM pictures (points to NULL list)
BIDECLE TITLE ; Cartridge title/date
DECLE $03C0 ; No ECS title, run code after title,
; ... no clicks
ZERO: DECLE $0000 ; Screen border control
DECLE $0000 ; 0 = color stack, 1 = f/b mode
ONES: DECLE 1, 1, 1, 1, 1 ; Initial color stack 0..3 and border: blue
;------------------------------------------------------------------------------
MACRO SETBG b, r
MVII #C_%b%, %r%
MVO %r%, BGC
ENDM
;; ======================================================================== ;;
;; TITLE -- Display our modified title screen & copyright date. ;;
;; ======================================================================== ;;
TITLE: PROC
BYTE 111, 'JLP Rand Stats', 0
MAIN:
MVII #$100, R4
MVII #$260, R1
CALL FILLZERO
SETISR ISRINIT,R0
MVII #STACK, R6
EIS
MVII #256 * 3, R1
MVII #$8040, R4
CALL FILLZERO
;01234567890123456789
PRINT_CSTK 0, 0, White, "Collecting numbers."
MVII #128, R0
@@o_loop:
PSHR R0
CLRR R5
@@loop:
MVI $9FFE, R0
MOVR R0, R1
MOVR R0, R2
SWAP R2
MOVR R2, R3
XORR R1, R3
ANDI #$FF, R1
ANDI #$FF, R2
ANDI #$FF, R3
ADDI #HIST0, R1
MVI@ R1, R0
INCR R0
MVO@ R0, R1
ADDI #HIST1, R2
MVI@ R2, R0
INCR R0
MVO@ R0, R2
ADDI #HIST2, R3
MVI@ R3, R0
INCR R0
MVO@ R0, R3
MOVR R5, R0
SLR R0, 2
SLR R0, 1
MVO@ R0, R4
DECR R4
DECR R5
BNEQ @@loop
MVII #(('.' - $20) * 8) OR 7, R0
MVO@ R0, R4
PULR R0
DECR R0
BNEQ @@o_loop
PRINT_CSTK 1, 15, White, "Done!"
CALL WAIT
DECLE 60
MACRO HPAG h,p,l,o
CALL CLRSCR
PRINT_CSTK 0, 0, White, "Histo %h% Page %p%"
CALL SHOWHIST
DECLE %l% + %o%
CALL WAITKEY
ENDM
@@d_loop
HPAG 0,0,HIST0,$00
HPAG 0,1,HIST0,$20
HPAG 0,2,HIST0,$40
HPAG 0,3,HIST0,$60
HPAG 0,4,HIST0,$80
HPAG 0,5,HIST0,$A0
HPAG 0,6,HIST0,$C0
HPAG 0,7,HIST0,$E0
HPAG 1,0,HIST1,$00
HPAG 1,1,HIST1,$20
HPAG 1,2,HIST1,$40
HPAG 1,3,HIST1,$60
HPAG 1,4,HIST1,$80
HPAG 1,5,HIST1,$A0
HPAG 1,6,HIST1,$C0
HPAG 1,7,HIST1,$E0
HPAG 2,0,HIST2,$00
HPAG 2,1,HIST2,$20
HPAG 2,2,HIST2,$40
HPAG 2,3,HIST2,$60
HPAG 2,4,HIST2,$80
HPAG 2,5,HIST2,$A0
HPAG 2,6,HIST2,$C0
HPAG 2,7,HIST2,$E0
B @@d_loop
ENDP
;; ======================================================================== ;;
;; WAIT ;;
;; ======================================================================== ;;
WAIT PROC
MVI@ R5, R0
@@1 MVO R0, DELAY
CLRR R0
@@loop: CMP DELAY, R0
BNEQ @@loop
JR R5
ENDP
;; ======================================================================== ;;
;; ISR ;;
;; ======================================================================== ;;
ISR PROC
MVO R0, $20
MVI $21, R0
MVI BGC, R0
MVII #$28, R4
MVO@ R0, R4
MVO@ R0, R4
MVO@ R0, R4
MVO@ R0, R4
MVO@ R0, R4
MVI DELAY, R0
DECR R0
BMI @@nodelay
MVO R0, DELAY
@@nodelay:
JR R5
ENDP
;; ======================================================================== ;;
;; ISRINIT ;;
;; ======================================================================== ;;
ISRINIT PROC
DIS
SETISR ISR, R0
JE $1014
ENDP
;; ======================================================================== ;;
;; LIBRARY INCLUDES ;;
;; ======================================================================== ;;
INCLUDE "library/fillmem.asm"
INCLUDE "library/hexdisp.asm"
INCLUDE "library/print.asm"
INCLUDE "library/wnk.asm"
SHOWHIST PROC
MVI@ R5, R3
PSHR R5
MOVR R3, R5
MVII #32, R3
MVII #disp_ptr(2,0), R4
@@loop
MVII #7, R1
MVI@ R5, R0
PSHR R3
PSHR R5
CALL HEX16
PULR R5
PULR R3
INCR R4
DECR R3
BNEQ @@loop
PULR PC
ENDP
|
.global s_prepare_buffers
s_prepare_buffers:
push %r13
push %r14
push %r8
push %r9
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0x1a4fb, %r9
sub %rbp, %rbp
mov (%r9), %r13d
nop
nop
inc %r14
lea addresses_UC_ht+0x14d5b, %rbx
nop
and $3431, %rcx
mov $0x6162636465666768, %r8
movq %r8, (%rbx)
nop
nop
sub $24645, %r14
lea addresses_A_ht+0x17b7b, %r9
nop
cmp $1052, %rbp
mov (%r9), %rcx
nop
cmp $23579, %rbx
lea addresses_A_ht+0x179bf, %rsi
lea addresses_D_ht+0x175fb, %rdi
nop
nop
xor %r9, %r9
mov $122, %rcx
rep movsw
nop
nop
nop
nop
and $58283, %r8
lea addresses_UC_ht+0x13f9b, %rsi
lea addresses_WC_ht+0x1e931, %rdi
clflush (%rsi)
nop
nop
nop
nop
sub $44890, %r8
mov $95, %rcx
rep movsw
nop
nop
nop
nop
nop
inc %rcx
lea addresses_UC_ht+0x14ecb, %r14
nop
nop
nop
cmp %rdi, %rdi
movb (%r14), %r13b
nop
nop
nop
nop
inc %rbx
lea addresses_normal_ht+0x17ffb, %rcx
nop
nop
nop
nop
dec %rbx
mov (%rcx), %r14
nop
nop
nop
nop
xor %r14, %r14
lea addresses_UC_ht+0x13ffb, %rsi
lea addresses_WT_ht+0x101fb, %rdi
nop
cmp %r8, %r8
mov $25, %rcx
rep movsb
and %rcx, %rcx
lea addresses_A_ht+0x12c3b, %rsi
lea addresses_UC_ht+0x19848, %rdi
clflush (%rsi)
nop
nop
sub %rbp, %rbp
mov $111, %rcx
rep movsl
nop
nop
xor %r8, %r8
lea addresses_A_ht+0x11ba3, %rsi
lea addresses_D_ht+0x103fb, %rdi
nop
nop
nop
nop
cmp $47691, %rbx
mov $121, %rcx
rep movsb
nop
nop
and $52353, %rcx
lea addresses_D_ht+0xa7fb, %r8
nop
nop
nop
sub %r9, %r9
movw $0x6162, (%r8)
nop
nop
xor $5656, %rbp
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r9
pop %r8
pop %r14
pop %r13
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r12
push %r8
push %r9
push %rbp
push %rdi
push %rsi
// Store
lea addresses_WC+0xa4fb, %r9
xor %r10, %r10
movl $0x51525354, (%r9)
mfence
// Store
lea addresses_D+0x1e7ab, %r8
and $6543, %r12
movl $0x51525354, (%r8)
nop
nop
nop
nop
nop
sub %r9, %r9
// Faulty Load
lea addresses_WT+0x74fb, %r12
nop
nop
nop
dec %rsi
movb (%r12), %r10b
lea oracles, %r12
and $0xff, %r10
shlq $12, %r10
mov (%r12,%r10,1), %r10
pop %rsi
pop %rdi
pop %rbp
pop %r9
pop %r8
pop %r12
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WC', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 11}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 2}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_WT', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WC_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 5}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': True, 'size': 8, 'congruent': 6}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 2, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 4, 'type': 'addresses_D_ht'}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 4, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 1, 'type': 'addresses_WC_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 4}}
{'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 8}}
{'OP': 'REPM', 'src': {'same': False, 'congruent': 7, 'type': 'addresses_UC_ht'}, 'dst': {'same': False, 'congruent': 8, 'type': 'addresses_WT_ht'}}
{'OP': 'REPM', 'src': {'same': True, 'congruent': 4, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_UC_ht'}}
{'OP': 'REPM', 'src': {'same': True, 'congruent': 2, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 7, 'type': 'addresses_D_ht'}}
{'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 6}}
{'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
*/
|
;LJMP addr16
LJMP 0x10
cseg at 0x10
mov a,#1
LJMP 0xFF00
cseg at 0xF0
mov a,#0xFF
LJMP 0x10
cseg at 0xff00
mov a,#0xF
LJMP 0xFFFB
cseg at 0xFFFB
mov a,#0xF0
LJMP 0xF0
|
.code
CallFunction PROC PUBLIC
; save r15, r14 which are nonvolatile registers
push r15
push r14
; save rsp into r15
mov r15, rsp
; save rcx into r14
mov r14, rcx
; align the stack to 16 bytes
sub rsp, 8
; move the stack arguments pointer into rax
mov rax, QWORD PTR [r14+40]
; is pointer 0? if so skip
cmp rax, 0
je SHORT $end_args
; advance pointer length bytes
add rax, QWORD PTR [r14+48]
$args_loop:
; subtract 8 bytes (1 64-bit pointer)
sub rax, 8
; push argument at [rax] onto stack
push QWORD PTR [rax]
; has pointer reached the beggining
cmp rax, QWORD PTR [r14+40]
ja SHORT $args_loop
$end_args:
; allocate spill space
sub rsp, 32
; clear rax
xor rax, rax
; mov first 4 arguments to registers
mov rcx, QWORD PTR [r14+8]
mov rdx, QWORD PTR [r14+16]
mov r8, QWORD PTR [r14+24]
mov r9, QWORD PTR [r14+32]
; call function
call QWORD PTR [r14]
; move return value (rax) into structure
mov QWORD PTR [r14+56], rax
; restore stack pointer
mov rsp, r15
; restore r14, r15
pop r14
pop r15
; clear return value, return ERROR_SUCCESS
xor rax, rax
ret 0
CallFunction ENDP
END |
ori $1, $0, 0
ori $2, $0, 1
ori $3, $0, 8
ori $4, $0, 15
sw $1, 0($0)
sw $1, 4($0)
sw $3, 8($0)
sw $2, 12($0)
sw $2, 16($0)
sw $1, 20($0)
sw $2, 24($0)
sw $4, 28($0)
sw $3, 32($0)
sw $2, 36($0)
sw $2, 40($0)
sw $2, 44($0)
sw $4, 48($0)
sw $3, 52($0)
sw $3, 56($0)
sw $3, 60($0)
sw $2, 64($0)
sw $3, 68($0)
sw $4, 72($0)
sw $3, 76($0)
sw $3, 80($0)
sw $2, 84($0)
sw $4, 88($0)
sw $1, 92($0)
sw $3, 96($0)
sw $1, 100($0)
sw $4, 104($0)
sw $3, 108($0)
sw $3, 112($0)
sw $2, 116($0)
sw $1, 120($0)
sw $3, 124($0)
srlv $3, $2, $2
mthi $3
mthi $2
lui $2, 8
TAG1:
bne $2, $2, TAG2
sll $0, $0, 0
xori $3, $2, 8
mtlo $3
TAG2:
bgez $3, TAG3
srlv $3, $3, $3
beq $3, $3, TAG3
mthi $3
TAG3:
sb $3, -2048($3)
sh $3, -2048($3)
subu $4, $3, $3
mfhi $2
TAG4:
bne $2, $2, TAG5
sb $2, 0($2)
lui $1, 1
sllv $1, $1, $2
TAG5:
divu $1, $1
sll $0, $0, 0
ori $3, $1, 8
addiu $1, $3, 1
TAG6:
bne $1, $1, TAG7
srlv $2, $1, $1
slt $2, $2, $1
mfhi $1
TAG7:
bltz $1, TAG8
multu $1, $1
addiu $3, $1, 10
lui $3, 0
TAG8:
addi $3, $3, 2
slt $2, $3, $3
ori $2, $3, 11
beq $3, $3, TAG9
TAG9:
multu $2, $2
divu $2, $2
sb $2, 0($2)
lb $4, 0($2)
TAG10:
addu $3, $4, $4
lui $1, 6
addu $2, $1, $3
mflo $4
TAG11:
bltz $4, TAG12
srav $4, $4, $4
sb $4, 0($4)
bltz $4, TAG12
TAG12:
mfhi $4
sllv $4, $4, $4
mtlo $4
subu $1, $4, $4
TAG13:
lui $3, 10
multu $3, $3
div $1, $3
mfhi $4
TAG14:
slti $2, $4, 8
sb $4, 0($2)
mtlo $4
mult $4, $4
TAG15:
mflo $2
addi $2, $2, 9
bltz $2, TAG16
addiu $2, $2, 6
TAG16:
div $2, $2
lui $2, 9
sll $0, $0, 0
lui $2, 7
TAG17:
sll $0, $0, 0
mthi $2
and $1, $2, $2
sll $0, $0, 0
TAG18:
addiu $2, $1, 15
mflo $2
mflo $4
mfhi $4
TAG19:
sll $0, $0, 0
mthi $4
mflo $4
div $4, $4
TAG20:
bne $4, $4, TAG21
mtlo $4
beq $4, $4, TAG21
mult $4, $4
TAG21:
beq $4, $4, TAG22
andi $1, $4, 13
mtlo $1
blez $1, TAG22
TAG22:
sb $1, 0($1)
lb $3, 0($1)
sb $1, 0($3)
sb $1, 0($1)
TAG23:
lui $1, 1
bne $3, $3, TAG24
sll $0, $0, 0
lui $4, 12
TAG24:
sll $0, $0, 0
sll $0, $0, 0
beq $1, $4, TAG25
lui $4, 12
TAG25:
blez $4, TAG26
mult $4, $4
srlv $1, $4, $4
bgez $1, TAG26
TAG26:
sll $0, $0, 0
lui $4, 2
sll $0, $0, 0
lui $3, 14
TAG27:
xor $2, $3, $3
sb $2, 0($2)
xori $4, $3, 11
mult $4, $2
TAG28:
mtlo $4
sllv $3, $4, $4
subu $4, $3, $4
sll $0, $0, 0
TAG29:
addu $1, $4, $4
ori $1, $1, 0
mthi $4
nor $2, $1, $4
TAG30:
sll $0, $0, 0
sll $0, $0, 0
sll $0, $0, 0
bgez $4, TAG31
TAG31:
div $4, $4
mtlo $4
lui $4, 3
mthi $4
TAG32:
sll $0, $0, 0
sltu $1, $4, $4
mtlo $1
sll $0, $0, 0
TAG33:
sll $0, $0, 0
blez $4, TAG34
mthi $4
mtlo $4
TAG34:
beq $4, $4, TAG35
mthi $4
blez $4, TAG35
sw $4, 0($4)
TAG35:
lui $1, 14
mflo $1
bne $1, $1, TAG36
mfhi $3
TAG36:
divu $3, $3
bgtz $3, TAG37
lui $2, 15
lhu $4, 0($3)
TAG37:
sll $0, $0, 0
div $4, $4
mthi $4
sll $0, $0, 0
TAG38:
divu $1, $1
srlv $1, $1, $1
mthi $1
mult $1, $1
TAG39:
sllv $1, $1, $1
mflo $4
lui $3, 5
addu $3, $1, $1
TAG40:
sll $0, $0, 0
sltiu $2, $3, 6
xor $1, $2, $3
mtlo $2
TAG41:
addu $1, $1, $1
bne $1, $1, TAG42
sll $0, $0, 0
slti $3, $1, 7
TAG42:
mfhi $3
lui $1, 12
slti $3, $3, 2
sh $3, 0($3)
TAG43:
bltz $3, TAG44
sw $3, 0($3)
lui $1, 9
blez $3, TAG44
TAG44:
divu $1, $1
sll $0, $0, 0
bne $1, $1, TAG45
sll $0, $0, 0
TAG45:
mtlo $1
sll $0, $0, 0
addi $1, $3, 13
mfhi $4
TAG46:
blez $4, TAG47
multu $4, $4
mtlo $4
srav $1, $4, $4
TAG47:
lui $4, 14
srav $1, $4, $1
mflo $4
lui $2, 9
TAG48:
mtlo $2
addiu $1, $2, 8
mtlo $1
lui $2, 15
TAG49:
srlv $4, $2, $2
mtlo $4
sltu $3, $4, $4
lui $3, 3
TAG50:
mthi $3
sll $2, $3, 3
lui $2, 11
sll $0, $0, 0
TAG51:
mtlo $2
xori $4, $2, 9
bne $4, $4, TAG52
addiu $1, $2, 13
TAG52:
sll $0, $0, 0
mflo $2
addiu $3, $2, 7
sll $0, $0, 0
TAG53:
multu $1, $1
bgtz $1, TAG54
sll $0, $0, 0
lbu $4, 0($4)
TAG54:
mthi $4
mult $4, $4
bgtz $4, TAG55
sll $0, $0, 0
TAG55:
mfhi $3
beq $3, $3, TAG56
srav $3, $3, $3
lbu $4, 0($3)
TAG56:
sll $0, $0, 0
bne $4, $4, TAG57
sll $4, $4, 10
sll $0, $0, 0
TAG57:
lw $4, 0($3)
mtlo $4
sb $4, 0($3)
blez $4, TAG58
TAG58:
mult $4, $4
sb $4, 0($4)
sub $4, $4, $4
multu $4, $4
TAG59:
srlv $3, $4, $4
subu $4, $4, $3
mtlo $3
or $1, $3, $4
TAG60:
lhu $4, 0($1)
lui $3, 4
sll $0, $0, 0
beq $3, $4, TAG61
TAG61:
or $1, $3, $3
bgez $3, TAG62
sll $0, $0, 0
addi $4, $1, 15
TAG62:
sh $4, 0($4)
mult $4, $4
multu $4, $4
bgez $4, TAG63
TAG63:
lhu $3, 0($4)
bne $4, $3, TAG64
sltu $3, $4, $3
mthi $3
TAG64:
lui $1, 6
lui $1, 14
bgez $1, TAG65
mfhi $4
TAG65:
sw $4, 0($4)
addi $4, $4, 6
lh $3, 0($4)
sh $4, 0($4)
TAG66:
mflo $1
mthi $3
mthi $3
beq $1, $1, TAG67
TAG67:
mult $1, $1
mult $1, $1
lbu $1, 0($1)
sh $1, 0($1)
TAG68:
sllv $2, $1, $1
bgez $1, TAG69
addi $3, $1, 13
sb $3, 0($3)
TAG69:
div $3, $3
lui $1, 3
andi $4, $1, 2
bne $3, $4, TAG70
TAG70:
multu $4, $4
bne $4, $4, TAG71
mfhi $1
bltz $1, TAG71
TAG71:
mthi $1
sra $4, $1, 12
beq $4, $4, TAG72
lbu $1, 0($4)
TAG72:
bgtz $1, TAG73
mthi $1
andi $2, $1, 9
sw $2, 0($2)
TAG73:
beq $2, $2, TAG74
lh $3, 0($2)
mflo $4
beq $3, $3, TAG74
TAG74:
lui $4, 7
mflo $1
addu $4, $4, $4
bgez $4, TAG75
TAG75:
sltu $3, $4, $4
bne $3, $3, TAG76
andi $3, $4, 12
mtlo $3
TAG76:
mflo $2
mthi $3
bne $3, $2, TAG77
sllv $4, $3, $2
TAG77:
sb $4, 0($4)
mult $4, $4
lui $2, 14
sh $2, 0($4)
TAG78:
sll $0, $0, 0
bltz $2, TAG79
sll $0, $0, 0
bne $2, $2, TAG79
TAG79:
srlv $4, $2, $2
xor $2, $2, $2
sll $0, $0, 0
mult $2, $2
TAG80:
blez $2, TAG81
mflo $3
mult $3, $2
mflo $3
TAG81:
mtlo $3
bne $3, $3, TAG82
sw $3, 0($3)
multu $3, $3
TAG82:
sra $1, $3, 5
sh $1, 0($3)
addi $3, $3, 4
mthi $3
TAG83:
mult $3, $3
mthi $3
xor $3, $3, $3
xori $2, $3, 10
TAG84:
lhu $3, 0($2)
divu $2, $3
beq $2, $3, TAG85
lbu $2, 0($2)
TAG85:
mult $2, $2
mult $2, $2
bgtz $2, TAG86
lui $1, 8
TAG86:
lui $1, 15
lui $2, 10
sll $1, $1, 2
sll $0, $0, 0
TAG87:
or $1, $3, $3
sll $1, $3, 8
sll $0, $0, 0
or $1, $1, $3
TAG88:
mtlo $1
mtlo $1
bne $1, $1, TAG89
lui $2, 9
TAG89:
lui $2, 4
sll $0, $0, 0
mflo $4
or $1, $2, $2
TAG90:
sll $2, $1, 4
multu $2, $1
sll $0, $0, 0
mult $2, $1
TAG91:
mflo $3
multu $2, $2
sll $4, $2, 9
sll $0, $0, 0
TAG92:
mthi $4
mtlo $4
lui $1, 8
andi $4, $1, 4
TAG93:
mtlo $4
srlv $3, $4, $4
bgtz $4, TAG94
sb $4, 0($4)
TAG94:
srlv $2, $3, $3
lw $3, 0($3)
bgez $3, TAG95
sw $2, 0($3)
TAG95:
bltz $3, TAG96
sh $3, 0($3)
and $3, $3, $3
multu $3, $3
TAG96:
lw $1, 0($3)
sb $3, 0($1)
sw $3, 0($3)
mflo $4
TAG97:
addiu $1, $4, 6
lbu $1, 0($1)
beq $1, $4, TAG98
mtlo $4
TAG98:
lui $1, 8
mult $1, $1
sll $0, $0, 0
mtlo $1
TAG99:
sw $2, 0($2)
mfhi $4
mult $2, $2
div $4, $4
TAG100:
sh $4, 0($4)
mflo $2
mthi $2
bltz $4, TAG101
TAG101:
lbu $2, 0($2)
lui $2, 2
mult $2, $2
srl $3, $2, 11
TAG102:
bgtz $3, TAG103
sltiu $4, $3, 5
mfhi $2
mthi $4
TAG103:
bltz $2, TAG104
mflo $1
ori $4, $1, 9
beq $2, $4, TAG104
TAG104:
mflo $4
bne $4, $4, TAG105
lh $1, 0($4)
mflo $3
TAG105:
blez $3, TAG106
lui $4, 12
lbu $2, 0($4)
mtlo $3
TAG106:
mflo $1
mthi $2
bgtz $1, TAG107
mfhi $2
TAG107:
xori $1, $2, 11
div $2, $2
nor $2, $2, $1
subu $1, $1, $2
TAG108:
lui $3, 5
bgtz $1, TAG109
sll $0, $0, 0
sub $3, $1, $3
TAG109:
lui $4, 2
beq $4, $4, TAG110
mthi $3
srav $1, $4, $4
TAG110:
bltz $1, TAG111
sll $0, $0, 0
bltz $1, TAG111
lui $3, 15
TAG111:
sra $4, $3, 6
slt $2, $3, $4
lbu $4, 0($2)
beq $4, $4, TAG112
TAG112:
lb $2, 0($4)
subu $4, $4, $4
lui $2, 11
mflo $3
TAG113:
beq $3, $3, TAG114
sb $3, 0($3)
mtlo $3
xori $2, $3, 15
TAG114:
sll $0, $0, 0
sll $0, $0, 0
multu $3, $2
addiu $4, $2, 10
TAG115:
mthi $4
srav $4, $4, $4
and $4, $4, $4
div $4, $4
TAG116:
mthi $4
addiu $2, $4, 12
mflo $2
sh $2, -704($4)
TAG117:
div $2, $2
slti $4, $2, 9
multu $2, $4
sb $2, 0($4)
TAG118:
sb $4, 0($4)
divu $4, $4
nor $3, $4, $4
sb $4, 0($4)
TAG119:
lui $4, 10
sll $0, $0, 0
sll $1, $4, 10
bltz $3, TAG120
TAG120:
addiu $3, $1, 4
sll $0, $0, 0
mflo $4
lbu $1, 0($4)
TAG121:
lbu $1, 0($1)
mthi $1
and $1, $1, $1
mtlo $1
TAG122:
beq $1, $1, TAG123
or $3, $1, $1
mflo $2
mfhi $3
TAG123:
bgtz $3, TAG124
sb $3, 0($3)
sb $3, 0($3)
lh $3, 0($3)
TAG124:
lui $1, 14
addiu $4, $1, 12
sll $0, $0, 0
bgtz $4, TAG125
TAG125:
lb $1, 0($3)
lui $1, 12
sll $0, $0, 0
mflo $3
TAG126:
sltu $1, $3, $3
mthi $1
mthi $3
lb $4, 0($3)
TAG127:
mult $4, $4
mfhi $2
mfhi $1
lbu $3, 0($1)
TAG128:
nor $1, $3, $3
mfhi $1
multu $3, $1
lbu $1, 0($3)
TAG129:
sb $1, 0($1)
lui $4, 5
mthi $1
beq $4, $1, TAG130
TAG130:
sll $0, $0, 0
bgez $4, TAG131
sll $0, $0, 0
mflo $4
TAG131:
mtlo $4
bne $4, $4, TAG132
addiu $3, $4, 1
lui $4, 15
TAG132:
xor $4, $4, $4
bne $4, $4, TAG133
andi $1, $4, 2
mult $1, $4
TAG133:
beq $1, $1, TAG134
mfhi $2
sll $2, $2, 10
div $2, $2
TAG134:
mthi $2
slt $3, $2, $2
mthi $2
bgez $2, TAG135
TAG135:
mflo $1
lbu $4, 0($1)
sra $4, $1, 3
sub $3, $4, $3
TAG136:
lui $1, 11
addiu $2, $1, 9
sh $2, 0($3)
mult $1, $3
TAG137:
lui $2, 1
multu $2, $2
divu $2, $2
bne $2, $2, TAG138
TAG138:
xor $2, $2, $2
addu $4, $2, $2
mult $2, $2
bne $2, $4, TAG139
TAG139:
mult $4, $4
multu $4, $4
sltu $3, $4, $4
lhu $3, 0($4)
TAG140:
sb $3, 0($3)
bne $3, $3, TAG141
sb $3, 0($3)
lui $1, 12
TAG141:
bne $1, $1, TAG142
mult $1, $1
addu $3, $1, $1
sll $0, $0, 0
TAG142:
mflo $2
mflo $3
lui $2, 12
mfhi $1
TAG143:
slti $1, $1, 0
sh $1, 0($1)
multu $1, $1
mflo $2
TAG144:
mthi $2
beq $2, $2, TAG145
lui $2, 14
sw $2, 0($2)
TAG145:
sll $0, $0, 0
sb $1, 0($1)
blez $2, TAG146
lui $2, 2
TAG146:
nor $3, $2, $2
mthi $3
sltu $2, $3, $3
lui $3, 7
TAG147:
blez $3, TAG148
sll $0, $0, 0
lui $2, 2
divu $2, $2
TAG148:
mthi $2
mtlo $2
lui $1, 3
slti $3, $1, 15
TAG149:
srlv $3, $3, $3
bne $3, $3, TAG150
lui $2, 12
lui $2, 1
TAG150:
bgez $2, TAG151
mflo $2
sw $2, 0($2)
mult $2, $2
TAG151:
sll $0, $0, 0
slti $4, $2, 5
mult $2, $4
mtlo $2
TAG152:
srlv $1, $4, $4
lb $1, 0($4)
mthi $1
lui $2, 15
TAG153:
mflo $1
div $1, $1
mfhi $3
div $1, $1
TAG154:
multu $3, $3
mult $3, $3
sra $3, $3, 10
mult $3, $3
TAG155:
lw $2, 0($3)
srlv $3, $2, $3
sra $2, $3, 13
mult $2, $3
TAG156:
addiu $1, $2, 1
blez $1, TAG157
divu $1, $1
beq $1, $2, TAG157
TAG157:
lb $3, 0($1)
lb $3, 0($3)
mult $1, $3
mtlo $1
TAG158:
or $2, $3, $3
lbu $2, 0($3)
sb $3, 0($3)
mflo $2
TAG159:
mtlo $2
slti $3, $2, 7
bne $3, $2, TAG160
lbu $3, 0($3)
TAG160:
mult $3, $3
mtlo $3
slti $2, $3, 12
xori $1, $3, 14
TAG161:
addiu $4, $1, 3
mthi $4
bltz $4, TAG162
mthi $1
TAG162:
bgez $4, TAG163
xori $2, $4, 4
lui $4, 3
lui $2, 3
TAG163:
sb $2, 0($2)
lui $2, 12
srlv $4, $2, $2
sll $0, $0, 0
TAG164:
sb $1, 0($1)
subu $3, $1, $1
bgtz $3, TAG165
subu $2, $3, $3
TAG165:
sllv $2, $2, $2
srav $3, $2, $2
lui $1, 5
bgtz $3, TAG166
TAG166:
sll $0, $0, 0
mfhi $2
lui $4, 5
mthi $4
TAG167:
bgez $4, TAG168
lui $1, 13
lb $1, 0($1)
bgez $4, TAG168
TAG168:
sll $0, $0, 0
nor $2, $1, $1
addu $2, $2, $2
mfhi $2
TAG169:
lui $1, 11
bne $2, $2, TAG170
mult $1, $1
mtlo $2
TAG170:
lui $3, 2
xori $4, $1, 9
sll $0, $0, 0
srl $3, $3, 15
TAG171:
sw $3, 0($3)
sw $3, 0($3)
lw $2, 0($3)
addu $2, $3, $3
TAG172:
mfhi $3
bne $2, $3, TAG173
lbu $1, 0($3)
slti $4, $1, 1
TAG173:
lui $3, 4
mult $4, $3
mfhi $4
lhu $4, 0($4)
TAG174:
addu $4, $4, $4
lui $4, 2
mult $4, $4
sll $0, $0, 0
TAG175:
bgtz $4, TAG176
nor $3, $4, $4
sllv $2, $4, $3
sltu $3, $3, $4
TAG176:
sll $0, $0, 0
beq $4, $3, TAG177
addiu $4, $4, 5
div $4, $4
TAG177:
lui $3, 13
subu $3, $3, $3
sll $0, $0, 0
mthi $4
TAG178:
lui $3, 15
slt $3, $3, $3
sw $3, 0($3)
sllv $2, $3, $3
TAG179:
mult $2, $2
multu $2, $2
lb $4, 0($2)
sh $4, 0($4)
TAG180:
bltz $4, TAG181
mfhi $3
beq $4, $3, TAG181
mflo $2
TAG181:
lui $2, 15
lui $2, 10
sll $0, $0, 0
srlv $3, $2, $2
TAG182:
sltiu $3, $3, 3
mflo $2
mtlo $3
mult $3, $2
TAG183:
bgez $2, TAG184
mthi $2
beq $2, $2, TAG184
sw $2, 0($2)
TAG184:
bgtz $2, TAG185
slti $1, $2, 14
mtlo $2
mthi $1
TAG185:
addiu $3, $1, 13
bgez $3, TAG186
lui $3, 6
ori $3, $1, 13
TAG186:
mfhi $1
lui $4, 8
beq $3, $4, TAG187
lbu $1, 0($1)
TAG187:
mflo $1
sh $1, 0($1)
sltiu $3, $1, 8
sh $1, 0($1)
TAG188:
srav $4, $3, $3
lb $1, 0($3)
beq $1, $3, TAG189
lui $1, 11
TAG189:
mult $1, $1
mthi $1
mult $1, $1
sll $1, $1, 14
TAG190:
sll $0, $0, 0
mfhi $1
blez $1, TAG191
sb $1, 0($1)
TAG191:
bgez $1, TAG192
nor $1, $1, $1
bgez $1, TAG192
mtlo $1
TAG192:
mfhi $1
sb $1, 0($1)
srlv $3, $1, $1
lbu $3, 0($1)
TAG193:
sb $3, 0($3)
blez $3, TAG194
sll $3, $3, 5
mult $3, $3
TAG194:
addu $2, $3, $3
sb $3, -7744($2)
beq $3, $2, TAG195
mfhi $2
TAG195:
bltz $2, TAG196
mthi $2
mflo $2
mfhi $4
TAG196:
bgez $4, TAG197
lui $3, 9
xor $3, $4, $3
sb $3, 0($3)
TAG197:
divu $3, $3
sll $0, $0, 0
sll $0, $0, 0
mtlo $3
TAG198:
multu $4, $4
mult $4, $4
mflo $2
bgez $2, TAG199
TAG199:
addiu $2, $2, 8
beq $2, $2, TAG200
andi $3, $2, 6
sw $2, 0($3)
TAG200:
bltz $3, TAG201
lui $1, 13
mult $1, $1
lui $4, 5
TAG201:
lui $4, 11
xori $1, $4, 6
bne $1, $1, TAG202
mthi $4
TAG202:
beq $1, $1, TAG203
addiu $2, $1, 4
slt $3, $1, $2
divu $2, $1
TAG203:
mult $3, $3
mfhi $2
lh $3, 0($2)
lui $4, 4
TAG204:
sll $0, $0, 0
lui $1, 7
sll $0, $0, 0
mfhi $2
TAG205:
mfhi $1
lui $2, 6
lui $4, 8
blez $1, TAG206
TAG206:
lui $4, 11
bltz $4, TAG207
mtlo $4
sll $3, $4, 11
TAG207:
mult $3, $3
mult $3, $3
divu $3, $3
mthi $3
TAG208:
mtlo $3
lui $4, 11
or $3, $3, $4
mfhi $2
TAG209:
sll $0, $0, 0
lh $2, 0($1)
blez $1, TAG210
mtlo $1
TAG210:
or $4, $2, $2
sb $2, 0($2)
bgez $4, TAG211
lui $4, 13
TAG211:
beq $4, $4, TAG212
mult $4, $4
beq $4, $4, TAG212
mfhi $1
TAG212:
mflo $3
sra $4, $3, 11
mfhi $3
lui $3, 12
TAG213:
mthi $3
xori $2, $3, 1
bgtz $3, TAG214
sll $0, $0, 0
TAG214:
sb $4, 0($4)
lui $4, 2
bne $4, $4, TAG215
lui $4, 14
TAG215:
lui $1, 9
bgez $1, TAG216
sll $0, $0, 0
sw $1, 0($4)
TAG216:
mthi $2
beq $2, $2, TAG217
sll $0, $0, 0
beq $2, $4, TAG217
TAG217:
xor $4, $4, $4
mult $4, $4
sw $4, 0($4)
sllv $3, $4, $4
TAG218:
mult $3, $3
blez $3, TAG219
lui $2, 10
lui $2, 8
TAG219:
mflo $2
bne $2, $2, TAG220
srav $2, $2, $2
mflo $3
TAG220:
lh $4, 0($3)
bne $4, $4, TAG221
addiu $2, $4, 12
mthi $4
TAG221:
mult $2, $2
lui $4, 9
multu $4, $4
addu $1, $4, $4
TAG222:
div $1, $1
addiu $4, $1, 9
mflo $4
subu $1, $1, $4
TAG223:
sll $0, $0, 0
sll $0, $0, 0
lui $2, 3
bltz $2, TAG224
TAG224:
mthi $2
subu $2, $2, $2
bne $2, $2, TAG225
sh $2, 0($2)
TAG225:
nor $1, $2, $2
blez $1, TAG226
sh $2, 1($1)
blez $2, TAG226
TAG226:
multu $1, $1
mflo $2
lw $3, 1($1)
subu $1, $2, $1
TAG227:
mflo $4
sllv $2, $4, $1
divu $4, $2
lh $4, 0($1)
TAG228:
mtlo $4
sh $4, 0($4)
mtlo $4
bgez $4, TAG229
TAG229:
lbu $3, 0($4)
srav $3, $3, $3
bne $3, $3, TAG230
mflo $3
TAG230:
sw $3, 0($3)
mfhi $2
multu $3, $3
lui $3, 1
TAG231:
sltiu $4, $3, 14
beq $4, $4, TAG232
sllv $2, $4, $4
lui $4, 7
TAG232:
multu $4, $4
beq $4, $4, TAG233
lui $1, 1
lui $1, 3
TAG233:
divu $1, $1
sll $0, $0, 0
lui $2, 9
beq $1, $1, TAG234
TAG234:
sll $0, $0, 0
bne $2, $2, TAG235
mflo $1
lui $4, 5
TAG235:
divu $4, $4
bgez $4, TAG236
mfhi $4
ori $4, $4, 7
TAG236:
lh $1, 0($4)
srlv $3, $1, $4
lui $1, 11
mthi $1
TAG237:
mtlo $1
div $1, $1
addu $3, $1, $1
lui $4, 10
TAG238:
beq $4, $4, TAG239
mtlo $4
lb $1, 0($4)
divu $1, $4
TAG239:
div $1, $1
mfhi $4
beq $1, $4, TAG240
mthi $1
TAG240:
bltz $4, TAG241
mflo $1
beq $4, $4, TAG241
or $4, $4, $1
TAG241:
sb $4, 0($4)
andi $2, $4, 3
sb $4, 0($4)
sb $4, 0($4)
TAG242:
sb $2, 0($2)
mfhi $1
sltiu $4, $2, 1
mtlo $1
TAG243:
lui $4, 3
mflo $1
srl $4, $4, 15
beq $4, $4, TAG244
TAG244:
mfhi $3
div $3, $4
mfhi $4
subu $2, $4, $4
TAG245:
sb $2, 0($2)
multu $2, $2
srlv $3, $2, $2
lui $4, 15
TAG246:
mfhi $2
lhu $4, 0($2)
sw $4, -256($4)
multu $4, $2
TAG247:
div $4, $4
beq $4, $4, TAG248
divu $4, $4
mflo $3
TAG248:
beq $3, $3, TAG249
sb $3, 0($3)
mult $3, $3
bne $3, $3, TAG249
TAG249:
lb $1, 0($3)
mult $1, $1
multu $1, $1
mfhi $3
TAG250:
sllv $2, $3, $3
lb $2, 0($3)
lui $1, 2
lhu $2, 0($3)
TAG251:
sll $0, $0, 0
sb $2, -256($2)
bne $2, $1, TAG252
sltiu $2, $1, 5
TAG252:
lbu $3, 0($2)
andi $1, $2, 14
bgtz $1, TAG253
add $2, $3, $3
TAG253:
bgtz $2, TAG254
mthi $2
mflo $4
sh $2, 0($4)
TAG254:
mult $4, $4
mtlo $4
ori $4, $4, 12
and $2, $4, $4
TAG255:
mfhi $1
lui $2, 9
sll $0, $0, 0
mfhi $1
TAG256:
beq $1, $1, TAG257
sb $1, 0($1)
lui $3, 4
mult $1, $1
TAG257:
bgez $3, TAG258
slti $4, $3, 8
divu $3, $3
mfhi $2
TAG258:
sll $0, $0, 0
slti $2, $1, 13
bne $2, $1, TAG259
mult $2, $2
TAG259:
srav $2, $2, $2
bne $2, $2, TAG260
mfhi $1
srlv $4, $1, $2
TAG260:
bgtz $4, TAG261
mflo $4
mfhi $1
srav $1, $4, $4
TAG261:
mflo $2
lw $1, 0($1)
lui $1, 3
mfhi $1
TAG262:
lui $4, 13
bgez $1, TAG263
subu $2, $1, $1
addu $3, $2, $1
TAG263:
mfhi $3
sllv $1, $3, $3
bne $3, $3, TAG264
sh $3, 0($1)
TAG264:
lh $3, 0($1)
mflo $4
bne $4, $3, TAG265
mflo $4
TAG265:
bgtz $4, TAG266
slt $4, $4, $4
srl $4, $4, 0
add $1, $4, $4
TAG266:
ori $3, $1, 4
bne $1, $3, TAG267
div $3, $3
addi $1, $1, 5
TAG267:
lb $3, 0($1)
and $1, $1, $3
mult $1, $3
srav $4, $1, $3
TAG268:
bgez $4, TAG269
mtlo $4
lh $3, 0($4)
mflo $2
TAG269:
addiu $4, $2, 7
lb $4, 0($4)
addi $2, $4, 8
srl $1, $2, 12
TAG270:
mfhi $4
lui $1, 13
or $1, $4, $1
mflo $1
TAG271:
lb $2, 0($1)
addu $2, $1, $2
mult $1, $2
blez $2, TAG272
TAG272:
lbu $2, 0($2)
bgtz $2, TAG273
subu $4, $2, $2
beq $4, $4, TAG273
TAG273:
sltiu $2, $4, 11
lbu $1, 0($4)
lb $4, 0($2)
beq $4, $2, TAG274
TAG274:
multu $4, $4
beq $4, $4, TAG275
mtlo $4
mult $4, $4
TAG275:
mtlo $4
xori $2, $4, 2
mtlo $4
divu $4, $2
TAG276:
multu $2, $2
lhu $3, 0($2)
bne $3, $3, TAG277
lui $1, 6
TAG277:
sll $0, $0, 0
lui $2, 9
srl $4, $1, 7
bne $2, $2, TAG278
TAG278:
addiu $1, $4, 6
sllv $3, $4, $4
mfhi $3
lhu $4, -3072($4)
TAG279:
sh $4, 0($4)
lui $1, 6
sll $0, $0, 0
lhu $2, 0($4)
TAG280:
slt $1, $2, $2
lui $4, 5
bgez $2, TAG281
mfhi $1
TAG281:
mthi $1
lhu $3, 0($1)
sltu $2, $3, $1
mult $1, $3
TAG282:
beq $2, $2, TAG283
mfhi $2
sh $2, 0($2)
slti $4, $2, 8
TAG283:
multu $4, $4
mflo $4
bne $4, $4, TAG284
lh $3, 0($4)
TAG284:
mthi $3
or $3, $3, $3
lui $4, 11
sh $4, 0($3)
TAG285:
multu $4, $4
blez $4, TAG286
sll $0, $0, 0
bgtz $4, TAG286
TAG286:
mtlo $4
xori $4, $4, 3
srl $2, $4, 1
mtlo $4
TAG287:
sltiu $4, $2, 5
bgtz $4, TAG288
addiu $3, $2, 8
lhu $2, 0($4)
TAG288:
bne $2, $2, TAG289
ori $2, $2, 1
nor $2, $2, $2
mthi $2
TAG289:
sra $3, $2, 15
div $3, $3
divu $3, $3
slt $1, $2, $2
TAG290:
bltz $1, TAG291
sw $1, 0($1)
sll $2, $1, 4
mult $1, $2
TAG291:
mthi $2
andi $4, $2, 2
mflo $3
lui $4, 2
TAG292:
nor $1, $4, $4
multu $1, $4
sll $0, $0, 0
sra $3, $4, 10
TAG293:
lui $3, 11
mflo $2
divu $3, $3
sll $0, $0, 0
TAG294:
addiu $1, $3, 12
mthi $3
sll $0, $0, 0
divu $3, $3
TAG295:
div $1, $1
div $1, $1
mfhi $2
mtlo $1
TAG296:
nor $3, $2, $2
mthi $2
blez $2, TAG297
lw $1, 1($3)
TAG297:
lui $1, 12
lui $3, 7
addiu $3, $3, 0
addiu $2, $3, 2
TAG298:
slt $4, $2, $2
multu $2, $4
blez $2, TAG299
sll $0, $0, 0
TAG299:
sb $4, 0($4)
blez $4, TAG300
xor $2, $4, $4
bgtz $2, TAG300
TAG300:
mflo $2
mflo $1
lhu $1, 0($1)
mfhi $4
TAG301:
beq $4, $4, TAG302
lui $3, 10
subu $1, $3, $4
blez $1, TAG302
TAG302:
lh $4, 0($1)
lhu $4, 0($1)
lui $2, 14
addiu $4, $4, 13
TAG303:
or $3, $4, $4
divu $4, $4
mtlo $4
mthi $3
TAG304:
beq $3, $3, TAG305
mtlo $3
sra $2, $3, 3
mtlo $3
TAG305:
mtlo $2
and $3, $2, $2
mtlo $2
mtlo $2
TAG306:
mtlo $3
lui $1, 6
div $3, $1
lui $1, 13
TAG307:
sll $0, $0, 0
lui $2, 10
beq $2, $2, TAG308
sll $1, $1, 13
TAG308:
mfhi $1
bgez $1, TAG309
mult $1, $1
mthi $1
TAG309:
andi $3, $1, 10
mthi $3
lw $3, 0($3)
addiu $3, $1, 14
TAG310:
mult $3, $3
and $4, $3, $3
bne $4, $3, TAG311
addu $2, $3, $3
TAG311:
divu $2, $2
mfhi $3
sll $0, $0, 0
bltz $3, TAG312
TAG312:
nor $3, $3, $3
beq $3, $3, TAG313
lui $1, 4
lw $2, 0($3)
TAG313:
mtlo $2
lui $1, 10
mtlo $2
mtlo $2
TAG314:
multu $1, $1
beq $1, $1, TAG315
addu $4, $1, $1
bgez $1, TAG315
TAG315:
srlv $4, $4, $4
addiu $2, $4, 4
div $2, $4
sll $0, $0, 0
TAG316:
divu $1, $1
mthi $1
addu $4, $1, $1
addiu $4, $1, 4
TAG317:
sll $0, $0, 0
bgez $4, TAG318
lui $4, 14
lui $1, 1
TAG318:
addiu $2, $1, 10
lui $1, 12
beq $2, $1, TAG319
multu $1, $1
TAG319:
beq $1, $1, TAG320
subu $1, $1, $1
mfhi $1
lb $2, 0($1)
TAG320:
multu $2, $2
blez $2, TAG321
addiu $3, $2, 7
sll $0, $0, 0
TAG321:
sll $0, $0, 0
mtlo $3
and $3, $3, $3
beq $3, $3, TAG322
TAG322:
subu $3, $3, $3
lbu $3, 0($3)
sw $3, 0($3)
mthi $3
TAG323:
nor $2, $3, $3
mthi $3
sh $2, 0($3)
lui $4, 10
TAG324:
beq $4, $4, TAG325
or $2, $4, $4
mthi $4
mflo $4
TAG325:
mtlo $4
bltz $4, TAG326
mfhi $1
bgtz $4, TAG326
TAG326:
lui $1, 13
bltz $1, TAG327
sll $0, $0, 0
sll $0, $0, 0
TAG327:
sllv $2, $1, $1
blez $1, TAG328
lui $4, 5
divu $4, $2
TAG328:
mthi $4
bne $4, $4, TAG329
lui $2, 15
multu $2, $4
TAG329:
sll $0, $0, 0
mfhi $3
multu $3, $3
bltz $3, TAG330
TAG330:
mtlo $3
bltz $3, TAG331
lui $2, 8
srav $4, $2, $3
TAG331:
lui $4, 11
lui $3, 2
bne $4, $3, TAG332
lui $2, 9
TAG332:
mflo $1
lui $1, 1
lui $2, 6
beq $1, $2, TAG333
TAG333:
sll $0, $0, 0
sll $0, $0, 0
beq $2, $2, TAG334
sll $0, $0, 0
TAG334:
lui $2, 3
srav $2, $2, $2
mfhi $2
sw $2, 0($2)
TAG335:
sra $3, $2, 14
beq $3, $2, TAG336
sltiu $4, $2, 9
addi $3, $3, 9
TAG336:
mthi $3
sh $3, 0($3)
srav $2, $3, $3
lw $4, 0($3)
TAG337:
bgtz $4, TAG338
lh $3, 0($4)
mult $4, $3
lbu $2, 0($4)
TAG338:
mfhi $4
multu $4, $4
beq $2, $2, TAG339
mthi $4
TAG339:
mfhi $4
mthi $4
sb $4, 0($4)
multu $4, $4
TAG340:
mflo $4
beq $4, $4, TAG341
sh $4, 0($4)
blez $4, TAG341
TAG341:
mthi $4
mthi $4
multu $4, $4
mflo $2
TAG342:
sllv $4, $2, $2
lbu $4, 0($4)
srlv $4, $4, $4
sb $4, 0($4)
TAG343:
mflo $1
sltu $4, $4, $1
lui $2, 9
mflo $3
TAG344:
bne $3, $3, TAG345
andi $2, $3, 2
bltz $3, TAG345
lui $4, 3
TAG345:
bne $4, $4, TAG346
lui $4, 7
lui $4, 11
sll $0, $0, 0
TAG346:
mfhi $2
sll $0, $0, 0
ori $3, $2, 15
mflo $3
TAG347:
sb $3, 0($3)
andi $1, $3, 15
mthi $1
addiu $4, $3, 2
TAG348:
and $2, $4, $4
lui $3, 8
mfhi $2
lui $4, 14
TAG349:
mfhi $2
slti $4, $4, 5
lb $2, 0($4)
lui $4, 3
TAG350:
bltz $4, TAG351
srav $3, $4, $4
mtlo $3
sll $0, $0, 0
TAG351:
mflo $3
and $1, $3, $3
sra $2, $1, 1
sll $0, $0, 0
TAG352:
subu $2, $2, $2
bne $2, $2, TAG353
mflo $1
bltz $1, TAG353
TAG353:
mflo $3
lui $1, 10
mthi $1
sll $0, $0, 0
TAG354:
blez $2, TAG355
or $4, $2, $2
mtlo $4
sll $2, $2, 8
TAG355:
lui $4, 2
bne $4, $2, TAG356
sltu $4, $4, $2
beq $4, $4, TAG356
TAG356:
multu $4, $4
mfhi $1
xori $3, $1, 3
sh $1, 0($1)
TAG357:
mfhi $2
xor $1, $3, $2
multu $3, $2
lbu $3, 0($1)
TAG358:
add $4, $3, $3
mfhi $2
lhu $4, 0($2)
lh $1, 0($4)
TAG359:
mflo $3
lui $1, 6
addiu $3, $3, 11
mthi $1
TAG360:
lui $3, 2
bne $3, $3, TAG361
lui $2, 10
addiu $2, $3, 9
TAG361:
sll $0, $0, 0
slt $2, $2, $1
divu $2, $1
addu $4, $1, $2
TAG362:
beq $4, $4, TAG363
div $4, $4
lui $2, 9
lui $3, 13
TAG363:
bgtz $3, TAG364
lui $2, 3
sb $3, 0($2)
div $2, $2
TAG364:
sll $0, $0, 0
lui $3, 2
lui $2, 14
nor $2, $3, $3
TAG365:
mult $2, $2
bne $2, $2, TAG366
sll $0, $0, 0
sll $0, $0, 0
TAG366:
lui $4, 4
multu $4, $4
bgez $2, TAG367
lui $4, 0
TAG367:
lui $3, 4
lui $2, 1
mtlo $4
bne $4, $2, TAG368
TAG368:
divu $2, $2
sll $0, $0, 0
sll $0, $0, 0
multu $2, $2
TAG369:
lui $1, 14
xori $2, $2, 14
mfhi $1
div $1, $2
TAG370:
lb $4, 0($1)
bgez $1, TAG371
nor $4, $1, $1
mfhi $3
TAG371:
sra $4, $3, 1
bgtz $3, TAG372
mthi $3
addi $1, $4, 15
TAG372:
sb $1, 0($1)
sb $1, 0($1)
sb $1, 0($1)
bltz $1, TAG373
TAG373:
xori $2, $1, 1
beq $2, $1, TAG374
mthi $2
sltu $4, $2, $2
TAG374:
addiu $1, $4, 10
mflo $3
beq $3, $3, TAG375
mult $4, $4
TAG375:
sb $3, 0($3)
lui $1, 6
sll $0, $0, 0
multu $1, $3
TAG376:
bne $1, $1, TAG377
ori $2, $1, 14
bgez $2, TAG377
mtlo $2
TAG377:
slti $4, $2, 9
multu $4, $4
and $3, $4, $2
sll $3, $2, 9
TAG378:
mult $3, $3
sll $0, $0, 0
divu $3, $2
div $3, $3
TAG379:
beq $2, $2, TAG380
ori $2, $2, 4
bltz $2, TAG380
sw $2, 0($2)
TAG380:
divu $2, $2
bltz $2, TAG381
sll $0, $0, 0
mult $2, $2
TAG381:
blez $4, TAG382
sh $4, 0($4)
lbu $1, 0($4)
sltiu $3, $1, 4
TAG382:
xor $1, $3, $3
sll $0, $0, 0
lui $3, 3
sllv $1, $3, $3
TAG383:
lui $1, 12
sll $0, $0, 0
sltiu $2, $1, 4
bne $1, $1, TAG384
TAG384:
lui $4, 4
div $2, $4
mtlo $4
mult $2, $4
TAG385:
sll $0, $0, 0
bgtz $4, TAG386
mtlo $4
mfhi $4
TAG386:
bne $4, $4, TAG387
mtlo $4
sll $0, $0, 0
sll $0, $0, 0
TAG387:
mthi $2
sh $2, 0($2)
srav $1, $2, $2
beq $2, $2, TAG388
TAG388:
mthi $1
beq $1, $1, TAG389
sra $1, $1, 1
lhu $2, 0($1)
TAG389:
slti $4, $2, 3
mfhi $4
lui $2, 4
lui $3, 15
TAG390:
div $3, $3
bgtz $3, TAG391
srav $2, $3, $3
lui $3, 9
TAG391:
mthi $3
sll $0, $0, 0
mflo $2
sltiu $1, $3, 11
TAG392:
lhu $2, 0($1)
bne $1, $2, TAG393
lui $1, 0
xori $1, $2, 5
TAG393:
lb $3, 0($1)
mfhi $3
lui $2, 10
mfhi $1
TAG394:
bgez $1, TAG395
div $1, $1
lh $4, 0($1)
mtlo $1
TAG395:
sw $4, 0($4)
addu $1, $4, $4
addiu $3, $4, 5
subu $2, $1, $4
TAG396:
lbu $3, 0($2)
mtlo $3
multu $3, $2
lui $3, 13
TAG397:
lui $2, 10
mfhi $1
bne $3, $3, TAG398
subu $2, $1, $2
TAG398:
bne $2, $2, TAG399
mtlo $2
bne $2, $2, TAG399
sll $0, $0, 0
TAG399:
multu $1, $1
bgtz $1, TAG400
addi $3, $1, 0
bne $3, $3, TAG400
TAG400:
mthi $3
lui $4, 4
bgtz $3, TAG401
mflo $2
TAG401:
sw $2, 0($2)
multu $2, $2
bne $2, $2, TAG402
slti $4, $2, 2
TAG402:
multu $4, $4
divu $4, $4
lui $4, 14
mthi $4
TAG403:
div $4, $4
sltu $2, $4, $4
slti $4, $4, 4
mfhi $4
TAG404:
nor $2, $4, $4
addi $2, $4, 10
mthi $2
mfhi $2
TAG405:
mthi $2
lui $3, 11
bltz $2, TAG406
sra $2, $3, 5
TAG406:
mult $2, $2
bne $2, $2, TAG407
sb $2, -22528($2)
lhu $2, -22528($2)
TAG407:
addiu $4, $2, 5
xori $3, $4, 0
multu $3, $2
divu $4, $4
TAG408:
beq $3, $3, TAG409
div $3, $3
mtlo $3
add $3, $3, $3
TAG409:
sb $3, 0($3)
mflo $1
and $2, $1, $3
sb $1, 0($1)
TAG410:
lbu $4, 0($2)
bgtz $2, TAG411
sb $4, 0($2)
mflo $2
TAG411:
bgtz $2, TAG412
lui $4, 10
lw $2, 0($4)
nor $4, $4, $2
TAG412:
mtlo $4
multu $4, $4
lui $4, 6
beq $4, $4, TAG413
TAG413:
lui $2, 8
mfhi $2
sll $0, $0, 0
subu $3, $4, $4
TAG414:
lui $1, 10
sllv $4, $1, $1
blez $4, TAG415
mtlo $3
TAG415:
addu $4, $4, $4
sll $0, $0, 0
srl $3, $4, 12
mflo $2
TAG416:
bne $2, $2, TAG417
sw $2, 0($2)
sw $2, 0($2)
sltiu $4, $2, 10
TAG417:
bgtz $4, TAG418
mtlo $4
ori $4, $4, 1
slt $2, $4, $4
TAG418:
andi $4, $2, 5
blez $4, TAG419
sb $2, 0($2)
srav $4, $2, $4
TAG419:
sh $4, 0($4)
mfhi $3
beq $3, $4, TAG420
lui $3, 9
TAG420:
divu $3, $3
mfhi $2
beq $2, $2, TAG421
mtlo $3
TAG421:
sw $2, 0($2)
sltiu $4, $2, 2
lhu $4, 0($2)
mfhi $4
TAG422:
sw $4, 0($4)
sw $4, 0($4)
blez $4, TAG423
mthi $4
TAG423:
lui $4, 8
addiu $1, $4, 13
sll $0, $0, 0
mult $4, $4
TAG424:
mthi $1
lui $1, 11
divu $1, $1
mfhi $1
TAG425:
lui $4, 13
beq $1, $4, TAG426
sll $3, $1, 13
lb $1, 0($3)
TAG426:
srlv $3, $1, $1
mthi $3
lui $1, 7
bgtz $1, TAG427
TAG427:
multu $1, $1
sll $0, $0, 0
mthi $1
subu $4, $1, $1
TAG428:
ori $3, $4, 4
beq $4, $4, TAG429
mult $4, $4
multu $4, $3
TAG429:
addu $1, $3, $3
lbu $2, 0($1)
lhu $4, 0($2)
beq $2, $2, TAG430
TAG430:
divu $4, $4
lw $2, -2312($4)
beq $4, $4, TAG431
mflo $4
TAG431:
bgtz $4, TAG432
mtlo $4
mtlo $4
lw $1, 0($4)
TAG432:
beq $1, $1, TAG433
lui $2, 0
mthi $1
srav $2, $2, $1
TAG433:
sra $2, $2, 5
addu $1, $2, $2
multu $2, $1
multu $2, $2
TAG434:
bgtz $1, TAG435
mult $1, $1
bltz $1, TAG435
sb $1, 0($1)
TAG435:
mult $1, $1
mfhi $4
andi $1, $4, 14
lw $1, 0($1)
TAG436:
sh $1, 0($1)
mflo $1
mult $1, $1
slti $3, $1, 13
TAG437:
or $4, $3, $3
mflo $3
xor $3, $3, $4
slti $1, $4, 11
TAG438:
divu $1, $1
bgtz $1, TAG439
mtlo $1
sh $1, 0($1)
TAG439:
or $4, $1, $1
divu $4, $1
bgez $1, TAG440
lb $4, 0($4)
TAG440:
sw $4, 0($4)
sb $4, 0($4)
srl $4, $4, 5
bne $4, $4, TAG441
TAG441:
lb $3, 0($4)
lbu $4, 0($4)
addiu $4, $4, 4
mthi $4
TAG442:
or $1, $4, $4
mflo $4
lb $2, 0($4)
lb $2, 0($4)
TAG443:
mult $2, $2
mult $2, $2
multu $2, $2
mtlo $2
TAG444:
or $2, $2, $2
mult $2, $2
lbu $4, 0($2)
mthi $4
TAG445:
lb $3, 0($4)
mthi $3
mult $3, $3
mflo $1
TAG446:
slt $2, $1, $1
lhu $4, 0($1)
lw $3, 0($1)
bne $1, $3, TAG447
TAG447:
andi $3, $3, 5
multu $3, $3
nor $1, $3, $3
sh $1, 0($3)
TAG448:
bgez $1, TAG449
divu $1, $1
sll $4, $1, 2
mtlo $4
TAG449:
bne $4, $4, TAG450
lui $3, 9
mflo $3
mfhi $1
TAG450:
mflo $4
sltu $3, $4, $1
bgez $3, TAG451
lui $4, 1
TAG451:
sltiu $2, $4, 1
lui $2, 4
slt $4, $4, $2
mthi $4
TAG452:
mtlo $4
lui $3, 6
mfhi $4
srl $2, $4, 5
TAG453:
lui $2, 0
ori $4, $2, 8
bne $2, $2, TAG454
addi $1, $2, 15
TAG454:
lui $3, 5
mtlo $1
multu $1, $1
lui $4, 7
TAG455:
mflo $4
xori $3, $4, 14
lui $4, 0
mtlo $4
TAG456:
bgtz $4, TAG457
sltiu $2, $4, 9
beq $4, $4, TAG457
mflo $4
TAG457:
blez $4, TAG458
srav $1, $4, $4
andi $1, $4, 10
nor $4, $1, $1
TAG458:
mfhi $2
mthi $2
mtlo $4
mfhi $3
TAG459:
addu $1, $3, $3
bne $3, $1, TAG460
multu $3, $1
ori $1, $1, 1
TAG460:
lui $1, 1
sllv $3, $1, $1
bltz $1, TAG461
mfhi $3
TAG461:
bgtz $3, TAG462
mflo $1
mfhi $3
lui $2, 14
TAG462:
bgez $2, TAG463
sll $0, $0, 0
lui $1, 1
bne $1, $1, TAG463
TAG463:
lui $2, 14
sw $1, 0($1)
mult $2, $2
multu $1, $1
TAG464:
div $2, $2
sll $3, $2, 13
sll $0, $0, 0
beq $3, $2, TAG465
TAG465:
subu $3, $2, $2
multu $2, $3
lui $1, 7
blez $1, TAG466
TAG466:
divu $1, $1
sll $0, $0, 0
beq $4, $4, TAG467
lui $3, 14
TAG467:
mtlo $3
divu $3, $3
mfhi $3
lb $3, 0($3)
TAG468:
sra $3, $3, 4
mtlo $3
mthi $3
blez $3, TAG469
TAG469:
sb $3, 0($3)
lw $4, 0($3)
sw $4, 0($3)
slti $3, $3, 3
TAG470:
mtlo $3
blez $3, TAG471
sllv $1, $3, $3
bltz $1, TAG471
TAG471:
lbu $3, 0($1)
mflo $2
sh $2, 0($1)
bne $1, $3, TAG472
TAG472:
and $3, $2, $2
lbu $2, 0($3)
mflo $1
lb $1, 0($3)
TAG473:
multu $1, $1
slti $1, $1, 13
lbu $4, 0($1)
blez $1, TAG474
TAG474:
mfhi $1
lb $4, 0($4)
mflo $4
mfhi $1
TAG475:
slt $4, $1, $1
lui $2, 6
addu $1, $2, $1
sll $0, $0, 0
TAG476:
mfhi $1
xori $3, $1, 1
mfhi $4
sltu $4, $3, $3
TAG477:
bne $4, $4, TAG478
subu $2, $4, $4
mfhi $4
bne $4, $2, TAG478
TAG478:
lui $4, 15
mfhi $4
bgtz $4, TAG479
mtlo $4
TAG479:
lui $2, 14
mflo $3
mult $4, $3
mtlo $3
TAG480:
sh $3, 0($3)
blez $3, TAG481
mult $3, $3
and $2, $3, $3
TAG481:
multu $2, $2
sll $0, $0, 0
multu $3, $2
mult $2, $3
TAG482:
srl $2, $3, 13
beq $2, $2, TAG483
multu $3, $2
addiu $1, $3, 0
TAG483:
lbu $4, 0($1)
lui $4, 11
andi $1, $4, 12
mfhi $3
TAG484:
addiu $1, $3, 8
sh $1, 0($1)
sh $1, 0($1)
bne $1, $1, TAG485
TAG485:
sw $1, 0($1)
subu $4, $1, $1
lh $3, 0($4)
mfhi $2
TAG486:
lui $3, 12
lbu $4, 0($2)
sw $3, 0($2)
slti $2, $3, 4
TAG487:
mfhi $3
mflo $4
mult $4, $3
andi $1, $2, 4
TAG488:
mflo $1
sw $1, 0($1)
beq $1, $1, TAG489
multu $1, $1
TAG489:
mult $1, $1
srav $4, $1, $1
mflo $2
mflo $4
TAG490:
or $1, $4, $4
lui $3, 8
mtlo $1
mtlo $1
TAG491:
bgez $3, TAG492
sll $0, $0, 0
divu $3, $3
sw $3, 0($3)
TAG492:
sll $0, $0, 0
bne $4, $3, TAG493
mthi $4
lui $1, 15
TAG493:
nor $3, $1, $1
bne $3, $1, TAG494
sw $3, 0($1)
mflo $3
TAG494:
srav $4, $3, $3
blez $3, TAG495
lh $1, 1($4)
addiu $3, $1, 14
TAG495:
beq $3, $3, TAG496
sltiu $4, $3, 10
lw $1, 0($3)
mthi $1
TAG496:
mtlo $1
srav $2, $1, $1
bne $2, $1, TAG497
mflo $3
TAG497:
bne $3, $3, TAG498
sra $1, $3, 1
bltz $1, TAG498
sb $3, 1($1)
TAG498:
sra $1, $1, 13
bne $1, $1, TAG499
ori $4, $1, 8
lui $1, 8
TAG499:
bgez $1, TAG500
mtlo $1
mthi $1
lhu $1, 0($1)
TAG500:
bltz $1, TAG501
mtlo $1
sll $0, $0, 0
sll $0, $0, 0
TAG501:
sll $0, $0, 0
sra $4, $3, 2
sltu $3, $1, $3
bgtz $4, TAG502
TAG502:
mtlo $3
bltz $3, TAG503
subu $2, $3, $3
bgez $3, TAG503
TAG503:
sw $2, 0($2)
lui $3, 12
lui $2, 7
lui $4, 10
TAG504:
sll $0, $0, 0
div $2, $4
srl $4, $2, 6
sll $0, $0, 0
TAG505:
bne $4, $4, TAG506
srl $2, $4, 11
sll $2, $4, 14
lui $3, 0
TAG506:
lw $4, 0($3)
bgtz $3, TAG507
sb $3, 0($4)
sh $3, 0($3)
TAG507:
mflo $4
lh $3, 0($4)
xor $3, $4, $4
addiu $1, $3, 5
TAG508:
lb $1, 0($1)
blez $1, TAG509
lui $1, 6
sll $0, $0, 0
TAG509:
sll $0, $0, 0
bne $1, $1, TAG510
mthi $1
and $1, $1, $1
TAG510:
sll $0, $0, 0
mfhi $2
sll $0, $0, 0
mtlo $1
TAG511:
mthi $2
blez $2, TAG512
mfhi $3
sll $0, $0, 0
TAG512:
bne $3, $3, TAG513
mtlo $3
bne $3, $3, TAG513
sll $0, $0, 0
TAG513:
bgtz $3, TAG514
lui $2, 12
lbu $1, 0($3)
bne $1, $1, TAG514
TAG514:
sltiu $1, $1, 13
sltiu $4, $1, 6
beq $1, $1, TAG515
lui $2, 3
TAG515:
sll $4, $2, 5
mfhi $4
div $2, $2
mtlo $2
TAG516:
mtlo $4
slti $1, $4, 9
slt $4, $1, $1
sllv $2, $4, $4
TAG517:
xor $2, $2, $2
mfhi $3
sw $3, 0($3)
srl $1, $3, 4
TAG518:
blez $1, TAG519
multu $1, $1
lui $4, 11
srl $3, $1, 2
TAG519:
lui $3, 5
srlv $1, $3, $3
blez $1, TAG520
mtlo $3
TAG520:
mflo $4
sll $0, $0, 0
sll $0, $0, 0
mtlo $4
TAG521:
mthi $4
mthi $4
mthi $4
bne $4, $4, TAG522
TAG522:
and $4, $4, $4
bne $4, $4, TAG523
sll $0, $0, 0
slt $2, $4, $4
TAG523:
beq $2, $2, TAG524
mfhi $1
mflo $2
beq $2, $1, TAG524
TAG524:
mthi $2
sw $2, 0($2)
beq $2, $2, TAG525
mult $2, $2
TAG525:
multu $2, $2
sltiu $1, $2, 11
lui $4, 2
lui $4, 8
TAG526:
mthi $4
sll $0, $0, 0
mtlo $4
bne $4, $4, TAG527
TAG527:
mtlo $4
bne $4, $4, TAG528
addu $1, $4, $4
sltu $3, $1, $4
TAG528:
bne $3, $3, TAG529
sll $4, $3, 8
sll $3, $3, 0
bne $3, $3, TAG529
TAG529:
lui $2, 0
lh $3, 0($3)
blez $3, TAG530
mtlo $2
TAG530:
lhu $3, 0($3)
mflo $3
beq $3, $3, TAG531
mtlo $3
TAG531:
sub $2, $3, $3
sh $2, 0($2)
multu $3, $3
mthi $2
TAG532:
mult $2, $2
andi $1, $2, 9
mthi $1
ori $4, $2, 13
TAG533:
bne $4, $4, TAG534
sb $4, 0($4)
div $4, $4
beq $4, $4, TAG534
TAG534:
divu $4, $4
mtlo $4
multu $4, $4
multu $4, $4
TAG535:
bgez $4, TAG536
mtlo $4
mtlo $4
multu $4, $4
TAG536:
divu $4, $4
mfhi $4
srav $2, $4, $4
bgtz $2, TAG537
TAG537:
lw $4, 0($2)
sh $2, 0($4)
addiu $3, $2, 8
xori $1, $3, 10
TAG538:
bltz $1, TAG539
sb $1, 0($1)
lui $2, 9
lui $1, 6
TAG539:
xori $2, $1, 7
sll $0, $0, 0
srav $1, $2, $2
multu $2, $1
TAG540:
multu $1, $1
sw $1, -3072($1)
blez $1, TAG541
lh $2, -3072($1)
TAG541:
mult $2, $2
mflo $3
lb $2, -3072($2)
or $1, $2, $2
TAG542:
mflo $4
bltz $1, TAG543
lui $1, 1
bne $1, $1, TAG543
TAG543:
addiu $3, $1, 5
bgez $3, TAG544
nor $4, $3, $3
beq $4, $4, TAG544
TAG544:
mflo $2
bgez $2, TAG545
sll $0, $0, 0
sh $4, 0($4)
TAG545:
beq $2, $2, TAG546
sll $0, $0, 0
sll $1, $2, 11
multu $1, $1
TAG546:
sll $0, $0, 0
sltiu $1, $2, 13
sll $0, $0, 0
multu $2, $2
TAG547:
bltz $1, TAG548
lui $3, 6
bne $3, $3, TAG548
sll $0, $0, 0
TAG548:
mflo $1
mthi $3
mtlo $3
blez $3, TAG549
TAG549:
sw $1, 0($1)
lui $2, 14
addu $2, $2, $1
div $2, $2
TAG550:
sll $0, $0, 0
sll $0, $0, 0
mtlo $2
bgez $2, TAG551
TAG551:
sll $0, $0, 0
mflo $2
lui $1, 11
bgtz $2, TAG552
TAG552:
lui $2, 12
subu $4, $1, $1
mthi $1
mtlo $1
TAG553:
sub $4, $4, $4
mthi $4
xor $2, $4, $4
sw $4, 0($4)
TAG554:
sll $4, $2, 14
lui $4, 12
mthi $4
bne $4, $2, TAG555
TAG555:
lui $4, 0
mthi $4
mtlo $4
sb $4, 0($4)
TAG556:
sll $2, $4, 7
sw $4, 0($2)
andi $3, $2, 10
lh $2, 0($3)
TAG557:
slti $3, $2, 14
srl $3, $2, 9
bne $3, $3, TAG558
srl $1, $2, 14
TAG558:
lui $2, 8
lbu $4, 0($1)
bltz $2, TAG559
lh $2, 0($4)
TAG559:
beq $2, $2, TAG560
mtlo $2
srav $1, $2, $2
lhu $4, 0($2)
TAG560:
lui $2, 12
bne $2, $2, TAG561
sltu $2, $2, $2
lhu $3, 0($4)
TAG561:
lui $4, 15
sll $0, $0, 0
lui $2, 11
beq $4, $4, TAG562
TAG562:
addiu $2, $2, 14
mult $2, $2
addiu $2, $2, 13
mflo $3
TAG563:
sll $0, $0, 0
lhu $3, 0($1)
mtlo $3
mult $3, $3
TAG564:
sh $3, 0($3)
lw $1, 0($3)
beq $3, $3, TAG565
mtlo $1
TAG565:
mtlo $1
mult $1, $1
sltiu $3, $1, 10
bltz $1, TAG566
TAG566:
nor $3, $3, $3
sll $2, $3, 4
lb $3, 32($2)
mult $2, $3
TAG567:
bne $3, $3, TAG568
mult $3, $3
bltz $3, TAG568
mfhi $2
TAG568:
lw $1, 0($2)
lui $4, 5
sh $2, 0($1)
sll $1, $2, 8
TAG569:
sw $1, 0($1)
sllv $1, $1, $1
mtlo $1
mult $1, $1
TAG570:
mtlo $1
lbu $3, 0($1)
bgtz $1, TAG571
sltiu $3, $1, 14
TAG571:
mflo $3
sb $3, 0($3)
addiu $1, $3, 8
sw $3, 0($3)
TAG572:
mfhi $4
addiu $1, $1, 13
sll $1, $1, 5
xori $1, $1, 13
TAG573:
sll $0, $0, 0
nor $2, $3, $1
blez $2, TAG574
mfhi $4
TAG574:
sltiu $4, $4, 15
lb $2, 0($4)
sll $4, $4, 8
lui $1, 1
TAG575:
sll $0, $0, 0
lhu $4, 0($3)
xor $3, $4, $3
bltz $3, TAG576
TAG576:
mflo $4
sll $2, $4, 1
srl $1, $3, 0
multu $2, $4
TAG577:
mflo $3
sh $1, 0($1)
sub $3, $1, $3
lui $3, 3
TAG578:
divu $3, $3
sll $0, $0, 0
mfhi $2
bgez $3, TAG579
TAG579:
slt $3, $2, $2
addiu $4, $2, 12
slt $1, $4, $4
addu $3, $1, $3
TAG580:
mflo $2
beq $2, $3, TAG581
mtlo $3
lbu $2, 0($2)
TAG581:
sh $2, 0($2)
ori $2, $2, 3
bgez $2, TAG582
sltiu $4, $2, 8
TAG582:
sb $4, 0($4)
mthi $4
lui $4, 8
beq $4, $4, TAG583
TAG583:
and $4, $4, $4
sra $2, $4, 15
mfhi $2
lui $2, 5
TAG584:
mtlo $2
mult $2, $2
mtlo $2
sltiu $3, $2, 14
TAG585:
srl $1, $3, 7
mtlo $3
slt $2, $1, $3
sb $2, 0($1)
TAG586:
bne $2, $2, TAG587
mflo $2
sw $2, 0($2)
sh $2, 0($2)
TAG587:
sb $2, 0($2)
mflo $4
bgez $2, TAG588
mtlo $4
TAG588:
lui $2, 8
sra $2, $2, 0
bltz $4, TAG589
sll $0, $0, 0
TAG589:
bltz $1, TAG590
slti $3, $1, 6
lhu $2, 0($1)
bgez $3, TAG590
TAG590:
multu $2, $2
bne $2, $2, TAG591
mult $2, $2
bltz $2, TAG591
TAG591:
lh $1, 0($2)
mthi $2
lh $4, 0($2)
bgez $2, TAG592
TAG592:
lw $1, 0($4)
bne $1, $1, TAG593
mtlo $1
addiu $2, $1, 10
TAG593:
lui $4, 13
slt $2, $2, $4
lui $4, 11
mflo $1
TAG594:
sltu $2, $1, $1
bne $2, $1, TAG595
mthi $1
mflo $2
TAG595:
sltiu $1, $2, 15
lui $3, 15
mult $1, $1
mtlo $1
TAG596:
multu $3, $3
sll $0, $0, 0
blez $3, TAG597
sll $0, $0, 0
TAG597:
lui $3, 5
sw $2, 0($2)
beq $2, $3, TAG598
mfhi $4
TAG598:
mtlo $4
div $4, $4
nor $1, $4, $4
mfhi $2
TAG599:
lui $4, 9
add $2, $2, $2
mthi $2
mfhi $4
TAG600:
mflo $2
mflo $4
lui $4, 6
beq $4, $2, TAG601
TAG601:
slt $3, $4, $4
mult $4, $3
sll $0, $0, 0
div $3, $4
TAG602:
slti $3, $3, 7
beq $3, $3, TAG603
sb $3, 0($3)
sw $3, 0($3)
TAG603:
mtlo $3
lui $2, 5
sll $0, $0, 0
sll $0, $0, 0
TAG604:
srlv $1, $3, $3
mult $1, $1
mthi $3
lui $2, 1
TAG605:
xori $3, $2, 14
mflo $1
sll $0, $0, 0
lui $2, 14
TAG606:
addiu $3, $2, 6
srl $4, $2, 0
bgez $3, TAG607
mtlo $3
TAG607:
sra $3, $4, 8
mflo $1
mflo $4
sll $0, $0, 0
TAG608:
lui $2, 0
srl $2, $4, 4
bltz $2, TAG609
mthi $2
TAG609:
sll $2, $2, 9
mthi $2
bgez $2, TAG610
sll $0, $0, 0
TAG610:
lui $4, 13
mtlo $3
subu $2, $3, $3
lui $2, 9
TAG611:
beq $2, $2, TAG612
ori $3, $2, 8
and $1, $3, $2
sb $1, 0($2)
TAG612:
sll $0, $0, 0
andi $4, $1, 3
sll $0, $0, 0
bgtz $4, TAG613
TAG613:
sh $4, 0($4)
srav $3, $4, $4
bne $3, $3, TAG614
mthi $4
TAG614:
mtlo $3
multu $3, $3
sw $3, 0($3)
mfhi $1
TAG615:
bgez $1, TAG616
sb $1, 0($1)
lh $3, 0($1)
sb $3, 0($3)
TAG616:
beq $3, $3, TAG617
sub $3, $3, $3
beq $3, $3, TAG617
lui $1, 12
TAG617:
lw $1, 0($1)
lw $1, 0($1)
bgtz $1, TAG618
sw $1, 0($1)
TAG618:
xori $4, $1, 11
addiu $2, $4, 5
bltz $1, TAG619
lbu $1, 0($4)
TAG619:
mthi $1
mfhi $3
bne $1, $1, TAG620
lui $3, 7
TAG620:
sltu $4, $3, $3
beq $3, $4, TAG621
addiu $3, $4, 2
xori $2, $3, 5
TAG621:
sb $2, 0($2)
sb $2, 0($2)
sb $2, 0($2)
srav $2, $2, $2
TAG622:
subu $4, $2, $2
mthi $4
multu $4, $4
mthi $2
TAG623:
bne $4, $4, TAG624
lh $4, 0($4)
nor $4, $4, $4
beq $4, $4, TAG624
TAG624:
sll $0, $0, 0
sh $4, 0($2)
multu $2, $2
slt $1, $4, $2
TAG625:
addu $2, $1, $1
lui $3, 9
srlv $3, $1, $3
lhu $4, 0($2)
TAG626:
sh $4, 0($4)
mtlo $4
mflo $1
sh $4, 0($1)
TAG627:
lbu $4, 0($1)
lui $4, 2
mfhi $1
mthi $4
TAG628:
sh $1, 0($1)
mtlo $1
lb $2, 0($1)
sh $2, 0($1)
TAG629:
mult $2, $2
mtlo $2
beq $2, $2, TAG630
mtlo $2
TAG630:
beq $2, $2, TAG631
lh $3, 0($2)
bgez $3, TAG631
mthi $3
TAG631:
lui $1, 8
bgtz $3, TAG632
mflo $2
xori $3, $1, 1
TAG632:
bgtz $3, TAG633
sll $0, $0, 0
sltu $3, $3, $3
sw $1, 0($3)
TAG633:
lui $2, 15
lui $2, 13
div $2, $2
mtlo $3
TAG634:
mfhi $1
mtlo $1
multu $1, $1
mult $2, $1
TAG635:
sh $1, 0($1)
bne $1, $1, TAG636
sub $3, $1, $1
mthi $1
TAG636:
lui $2, 5
mult $2, $3
lui $1, 3
mflo $2
TAG637:
mtlo $2
beq $2, $2, TAG638
multu $2, $2
addi $3, $2, 2
TAG638:
bgez $3, TAG639
sw $3, 0($3)
lui $3, 15
div $3, $3
TAG639:
multu $3, $3
sw $3, 0($3)
sh $3, 0($3)
xor $4, $3, $3
TAG640:
bgtz $4, TAG641
mult $4, $4
lui $3, 7
sra $2, $3, 2
TAG641:
sll $0, $0, 0
divu $2, $2
subu $4, $2, $2
xori $2, $2, 10
TAG642:
andi $2, $2, 7
mflo $4
sb $2, 0($2)
bltz $2, TAG643
TAG643:
lbu $1, 0($4)
blez $1, TAG644
mflo $3
bgez $4, TAG644
TAG644:
lui $4, 14
addiu $2, $3, 6
bgez $4, TAG645
mtlo $4
TAG645:
mthi $2
sb $2, 0($2)
sltiu $3, $2, 6
multu $2, $2
TAG646:
mthi $3
mflo $2
blez $2, TAG647
multu $3, $2
TAG647:
bne $2, $2, TAG648
subu $1, $2, $2
mult $2, $1
xor $1, $1, $1
TAG648:
bgtz $1, TAG649
mthi $1
mult $1, $1
lh $1, 0($1)
TAG649:
srl $2, $1, 7
mult $1, $2
beq $2, $1, TAG650
and $3, $2, $2
TAG650:
mflo $1
mfhi $3
mfhi $1
sra $1, $3, 12
TAG651:
mthi $1
sb $1, 0($1)
mthi $1
beq $1, $1, TAG652
TAG652:
lui $4, 10
mfhi $1
lhu $2, 0($1)
bne $1, $2, TAG653
TAG653:
mflo $4
mflo $2
lhu $3, 0($2)
lbu $1, 0($4)
TAG654:
mflo $1
lui $1, 9
addiu $4, $1, 14
sll $1, $1, 2
TAG655:
xori $4, $1, 6
bne $1, $1, TAG656
xor $3, $1, $1
multu $3, $3
TAG656:
mflo $4
beq $4, $3, TAG657
mult $4, $4
mthi $4
TAG657:
xori $1, $4, 2
sw $4, 0($4)
bgtz $4, TAG658
srlv $1, $4, $4
TAG658:
xor $4, $1, $1
multu $4, $4
lui $1, 0
subu $2, $4, $4
TAG659:
mflo $4
lui $1, 6
sw $2, 0($2)
mtlo $2
TAG660:
bltz $1, TAG661
mfhi $2
bne $2, $2, TAG661
sh $2, 0($2)
TAG661:
lh $3, 0($2)
bltz $2, TAG662
addu $2, $2, $3
bne $2, $3, TAG662
TAG662:
subu $1, $2, $2
mtlo $2
multu $2, $2
xori $2, $2, 13
TAG663:
mtlo $2
bne $2, $2, TAG664
lui $4, 9
xori $4, $2, 5
TAG664:
beq $4, $4, TAG665
mtlo $4
mthi $4
beq $4, $4, TAG665
TAG665:
div $4, $4
lbu $3, 0($4)
bltz $3, TAG666
lw $4, 0($4)
TAG666:
mfhi $4
mthi $4
sw $4, 0($4)
lui $1, 13
TAG667:
ori $4, $1, 9
bgtz $1, TAG668
sll $3, $1, 9
mflo $3
TAG668:
lui $3, 11
div $3, $3
lui $4, 8
mthi $3
TAG669:
beq $4, $4, TAG670
sltu $2, $4, $4
srav $4, $2, $2
mfhi $2
TAG670:
lui $1, 13
sll $0, $0, 0
lui $2, 6
sll $0, $0, 0
TAG671:
sll $0, $0, 0
sll $0, $0, 0
mflo $4
bltz $4, TAG672
TAG672:
addiu $3, $4, 5
bgez $3, TAG673
subu $2, $4, $4
mflo $1
TAG673:
sll $0, $0, 0
mult $1, $1
mtlo $1
mflo $3
TAG674:
sll $0, $0, 0
sll $0, $0, 0
mflo $1
mfhi $3
TAG675:
sll $0, $0, 0
multu $4, $4
mflo $2
mflo $4
TAG676:
srl $1, $4, 11
sb $1, 0($4)
mult $1, $4
bne $4, $1, TAG677
TAG677:
sllv $1, $1, $1
xori $3, $1, 15
mfhi $4
sb $1, 0($1)
TAG678:
sh $4, 0($4)
srl $2, $4, 15
lui $2, 12
lw $2, 0($4)
TAG679:
lhu $3, 0($2)
bgez $3, TAG680
multu $2, $3
ori $3, $3, 0
TAG680:
sub $2, $3, $3
ori $2, $2, 6
mtlo $3
divu $2, $2
TAG681:
bgtz $2, TAG682
mflo $4
bgtz $2, TAG682
lui $3, 13
TAG682:
mthi $3
andi $1, $3, 4
beq $1, $3, TAG683
multu $1, $1
TAG683:
lw $3, 0($1)
mfhi $3
mult $1, $1
blez $3, TAG684
TAG684:
mult $3, $3
lhu $3, 0($3)
multu $3, $3
multu $3, $3
TAG685:
bgez $3, TAG686
mfhi $1
sb $1, 0($3)
mult $3, $3
TAG686:
mtlo $1
lbu $1, 0($1)
mult $1, $1
bltz $1, TAG687
TAG687:
lui $2, 0
mfhi $2
sw $1, 0($1)
mfhi $3
TAG688:
bgez $3, TAG689
nor $2, $3, $3
mfhi $2
div $2, $2
TAG689:
sll $3, $2, 13
mflo $2
mtlo $3
blez $2, TAG690
TAG690:
lh $2, 0($2)
lui $1, 4
bgtz $2, TAG691
nor $3, $2, $1
TAG691:
bgtz $3, TAG692
and $3, $3, $3
div $3, $3
sll $0, $0, 0
TAG692:
bne $3, $3, TAG693
sll $0, $0, 0
blez $3, TAG693
lui $4, 9
TAG693:
lui $1, 8
mflo $4
lbu $3, 0($4)
mtlo $3
TAG694:
sw $3, 0($3)
bltz $3, TAG695
add $3, $3, $3
mthi $3
TAG695:
lui $1, 13
mtlo $3
mflo $2
bne $2, $1, TAG696
TAG696:
lw $2, 0($2)
bne $2, $2, TAG697
multu $2, $2
multu $2, $2
TAG697:
slt $4, $2, $2
bne $4, $4, TAG698
mflo $4
xori $3, $4, 8
TAG698:
lui $2, 6
mtlo $3
mtlo $3
mfhi $2
TAG699:
mfhi $4
lui $4, 6
slt $1, $2, $2
bltz $4, TAG700
TAG700:
xori $4, $1, 11
multu $4, $1
mfhi $4
lui $2, 0
TAG701:
addi $1, $2, 9
bne $2, $1, TAG702
mult $1, $1
xor $4, $1, $2
TAG702:
mflo $4
mtlo $4
blez $4, TAG703
srlv $1, $4, $4
TAG703:
mtlo $1
xor $1, $1, $1
mtlo $1
mult $1, $1
TAG704:
sb $1, 0($1)
multu $1, $1
bne $1, $1, TAG705
mult $1, $1
TAG705:
multu $1, $1
mult $1, $1
mult $1, $1
multu $1, $1
TAG706:
mfhi $3
lui $1, 2
lh $1, 0($3)
sb $1, 0($1)
TAG707:
lb $3, 0($1)
sh $3, 0($1)
lw $1, 0($1)
bltz $1, TAG708
TAG708:
slt $1, $1, $1
addu $2, $1, $1
mtlo $1
multu $1, $2
TAG709:
bltz $2, TAG710
sb $2, 0($2)
beq $2, $2, TAG710
lui $4, 2
TAG710:
subu $3, $4, $4
mthi $3
beq $4, $4, TAG711
xor $2, $4, $3
TAG711:
lui $3, 4
mflo $3
mfhi $3
bgtz $3, TAG712
TAG712:
sw $3, 0($3)
sb $3, 0($3)
xori $1, $3, 5
bne $3, $3, TAG713
TAG713:
lui $2, 6
mfhi $1
lui $2, 7
xori $4, $1, 2
TAG714:
lui $2, 6
beq $2, $4, TAG715
slti $3, $2, 1
mthi $3
TAG715:
addiu $2, $3, 14
sub $2, $3, $3
mult $2, $2
multu $3, $3
TAG716:
mtlo $2
lui $2, 1
srav $1, $2, $2
sll $0, $0, 0
TAG717:
multu $2, $2
sll $0, $0, 0
bgtz $4, TAG718
multu $4, $2
TAG718:
multu $4, $4
beq $4, $4, TAG719
mthi $4
xor $1, $4, $4
TAG719:
div $1, $1
sltu $3, $1, $1
sh $3, 0($3)
bltz $3, TAG720
TAG720:
sw $3, 0($3)
mtlo $3
bgez $3, TAG721
lui $2, 7
TAG721:
mfhi $2
lui $4, 12
xor $3, $4, $2
sll $0, $0, 0
TAG722:
mthi $1
or $1, $1, $1
mtlo $1
sll $0, $0, 0
TAG723:
beq $2, $2, TAG724
lui $2, 3
multu $2, $2
bne $2, $2, TAG724
TAG724:
mult $2, $2
lui $3, 0
srlv $2, $3, $3
sll $1, $2, 10
TAG725:
mtlo $1
add $4, $1, $1
blez $1, TAG726
or $1, $1, $1
TAG726:
lui $4, 14
mflo $4
lui $1, 0
sh $1, 0($1)
TAG727:
sh $1, 0($1)
mfhi $4
bne $1, $1, TAG728
mthi $1
TAG728:
sb $4, 0($4)
sb $4, 0($4)
sb $4, 0($4)
subu $4, $4, $4
TAG729:
lb $1, 0($4)
andi $1, $1, 0
multu $1, $4
andi $2, $1, 0
TAG730:
sb $2, 0($2)
lui $4, 10
addi $4, $2, 6
mflo $2
TAG731:
lh $4, 0($2)
lui $3, 15
sb $3, 0($2)
subu $2, $2, $3
TAG732:
lui $1, 6
mflo $2
beq $2, $2, TAG733
lw $2, 0($2)
TAG733:
srl $1, $2, 4
sb $2, 0($1)
sh $1, 0($1)
mflo $2
TAG734:
addu $2, $2, $2
lhu $1, 0($2)
lbu $3, 0($1)
mtlo $1
TAG735:
mfhi $1
and $1, $3, $3
lh $1, 0($1)
srl $2, $3, 12
TAG736:
bgez $2, TAG737
srl $1, $2, 0
div $2, $2
lw $4, 0($2)
TAG737:
andi $2, $4, 12
mthi $2
mfhi $3
mtlo $4
TAG738:
bltz $3, TAG739
mult $3, $3
mtlo $3
lbu $3, 0($3)
TAG739:
mfhi $4
bgtz $3, TAG740
lui $1, 8
mflo $1
TAG740:
slt $4, $1, $1
beq $1, $1, TAG741
lhu $1, 0($4)
blez $4, TAG741
TAG741:
sltu $1, $1, $1
xori $2, $1, 14
beq $1, $1, TAG742
sh $1, 0($1)
TAG742:
lui $1, 3
sll $4, $2, 7
divu $1, $2
lui $1, 0
TAG743:
mflo $1
sb $1, -14043($1)
sllv $3, $1, $1
sra $4, $3, 3
TAG744:
addiu $4, $4, 13
mfhi $4
blez $4, TAG745
divu $4, $4
TAG745:
divu $4, $4
lui $4, 11
or $2, $4, $4
bgtz $4, TAG746
TAG746:
sltu $2, $2, $2
mthi $2
lh $4, 0($2)
lui $4, 7
TAG747:
sll $0, $0, 0
or $1, $4, $4
bne $1, $4, TAG748
sll $0, $0, 0
TAG748:
mult $2, $2
sll $1, $2, 6
lui $1, 10
lui $2, 9
TAG749:
mflo $1
blez $2, TAG750
sll $0, $0, 0
lui $4, 4
TAG750:
nop
nop
test_end:
beq $0, $0, test_end
nop |
/**
* @file data_algorithm_chunk.hpp
* @author Jichan (development@jc-lab.net / http://ablog.jc-lab.net/ )
* @date 2019/07/23
* @copyright Copyright (C) 2019 jichan.\n
* This software may be modified and distributed under the terms
* of the Apache License 2.0. See the LICENSE file for details.
*/
#pragma once
#include <asymsecurefile/chunk.hpp>
#include "jasf3_chunk_type.hpp"
#include <asymsecurefile/data_algorithm.hpp>
namespace asymsecurefile {
namespace internal {
namespace jasf3 {
class DataAlgorithmChunk : public Chunk
{
private:
const DataAlgorithm *data_algorithm_;
public:
enum common {
CHUNK_TYPE = DATA_ALGORITHM
};
DataAlgorithmChunk(uint16_t data_size, const unsigned char* data)
: Chunk(CHUNK_TYPE, 0, data_size, data), data_algorithm_(NULL)
{
const std::vector<const DataAlgorithm*> data_algorithms = DataAlgorithm::values();
for(auto iter = data_algorithms.cbegin(); iter != data_algorithms.cend(); iter++) {
const DataAlgorithm* item = (*iter);
if(item->getIdentifier().size() == data_size) {
if(memcmp(item->getIdentifier().data(), data, data_size) == 0) {
data_algorithm_ = item;
break;
}
}
}
}
const DataAlgorithm *dataAlgorithmPtr() const {
return data_algorithm_;
}
};
} // namesppace jasf3
} // namespace internal
} // namespace src
|
/**
* Copyright (C) 2021 All rights reserved.
*
* FileName :result.cpp
* Author :C.K
* Email :theck17@163.com
* DateTime :2021-08-01 20:02:42
* Description :
*/
using namespace std;
class Solution
{
public:
string addBinary(string a, string b)
{
string s = "";
int c = 0, i = a.size() - 1, j = b.size() - 1;
while(i >= 0 || j >= 0 || c == 1)
{
c += i >= 0 ? a[i --] - '0' : 0;
c += j >= 0 ? b[j --] - '0' : 0;
s = char(c % 2 + '0') + s;
c /= 2;
}
return s;
}
};
int main(){
return 0;
}
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/ssa/v20180608/model/DescribeComplianceAssetListResponse.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Ssa::V20180608::Model;
using namespace std;
DescribeComplianceAssetListResponse::DescribeComplianceAssetListResponse() :
m_checkAssetsListHasBeenSet(false),
m_totalHasBeenSet(false)
{
}
CoreInternalOutcome DescribeComplianceAssetListResponse::Deserialize(const string &payload)
{
rapidjson::Document d;
d.Parse(payload.c_str());
if (d.HasParseError() || !d.IsObject())
{
return CoreInternalOutcome(Core::Error("response not json format"));
}
if (!d.HasMember("Response") || !d["Response"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `Response` is null or not object"));
}
rapidjson::Value &rsp = d["Response"];
if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.RequestId` is null or not string"));
}
string requestId(rsp["RequestId"].GetString());
SetRequestId(requestId);
if (rsp.HasMember("Error"))
{
if (!rsp["Error"].IsObject() ||
!rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() ||
!rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString())
{
return CoreInternalOutcome(Core::Error("response `Response.Error` format error").SetRequestId(requestId));
}
string errorCode(rsp["Error"]["Code"].GetString());
string errorMsg(rsp["Error"]["Message"].GetString());
return CoreInternalOutcome(Core::Error(errorCode, errorMsg).SetRequestId(requestId));
}
if (rsp.HasMember("CheckAssetsList") && !rsp["CheckAssetsList"].IsNull())
{
if (!rsp["CheckAssetsList"].IsArray())
return CoreInternalOutcome(Core::Error("response `CheckAssetsList` is not array type"));
const rapidjson::Value &tmpValue = rsp["CheckAssetsList"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
CheckAssetItem item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_checkAssetsList.push_back(item);
}
m_checkAssetsListHasBeenSet = true;
}
if (rsp.HasMember("Total") && !rsp["Total"].IsNull())
{
if (!rsp["Total"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `Total` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_total = rsp["Total"].GetInt64();
m_totalHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
string DescribeComplianceAssetListResponse::ToJsonString() const
{
rapidjson::Document value;
value.SetObject();
rapidjson::Document::AllocatorType& allocator = value.GetAllocator();
if (m_checkAssetsListHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "CheckAssetsList";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_checkAssetsList.begin(); itr != m_checkAssetsList.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
if (m_totalHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Total";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_total, allocator);
}
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RequestId";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value().SetString(GetRequestId().c_str(), allocator), allocator);
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
value.Accept(writer);
return buffer.GetString();
}
vector<CheckAssetItem> DescribeComplianceAssetListResponse::GetCheckAssetsList() const
{
return m_checkAssetsList;
}
bool DescribeComplianceAssetListResponse::CheckAssetsListHasBeenSet() const
{
return m_checkAssetsListHasBeenSet;
}
int64_t DescribeComplianceAssetListResponse::GetTotal() const
{
return m_total;
}
bool DescribeComplianceAssetListResponse::TotalHasBeenSet() const
{
return m_totalHasBeenSet;
}
|
// This file is part of VSTGUI. It is subject to the license terms
// in the LICENSE file found in the top-level directory of this
// distribution and at http://github.com/steinbergmedia/vstgui/LICENSE
#include "../unittests.h"
#include "../../../lib/cinvalidrectlist.h"
namespace VSTGUI {
TESTCASE(CInvalidRectListTest,
TEST(rectEqual,
CInvalidRectList list;
EXPECT (list.add ({0, 0, 100, 100}));
EXPECT (list.add ({0, 0, 100, 100}) == false);
EXPECT (list.data ().size () == 1u);
);
TEST(addBiggerOne,
CInvalidRectList list;
EXPECT (list.add ({0, 0, 100, 100}));
EXPECT (list.add ({0, 0, 200, 200}));
EXPECT (list.data ().size () == 1u);
);
TEST(addSmallerOne,
CInvalidRectList list;
EXPECT (list.add ({0, 0, 100, 100}));
EXPECT (list.add ({10, 10, 20, 20}) == false);
EXPECT (list.data ().size () == 1u);
);
TEST(addOverlappingOne,
CInvalidRectList list;
EXPECT (list.add ({0, 0, 100, 100}));
EXPECT (list.add ({90, 0, 120, 100}));
EXPECT (list.data ().size () == 1u);
);
);
} // VSTGUI
|
.global s_prepare_buffers
s_prepare_buffers:
push %r13
push %r14
push %r15
push %r9
push %rax
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_A_ht+0x1d16, %rax
nop
nop
nop
nop
nop
sub $6767, %r14
mov $0x6162636465666768, %rsi
movq %rsi, %xmm4
movups %xmm4, (%rax)
xor %r13, %r13
lea addresses_WT_ht+0xc4c5, %r15
nop
nop
sub %rdx, %rdx
mov (%r15), %r9d
nop
nop
nop
add %rdx, %rdx
lea addresses_normal_ht+0x15bbe, %rax
and %rdx, %rdx
mov (%rax), %r14
nop
nop
dec %rsi
lea addresses_WT_ht+0x812e, %r9
clflush (%r9)
nop
nop
nop
nop
inc %rdx
movb (%r9), %al
nop
nop
nop
nop
nop
add %r15, %r15
lea addresses_WT_ht+0x1d90e, %rdx
nop
nop
nop
nop
nop
add $37082, %r13
movb $0x61, (%rdx)
nop
nop
nop
xor %r15, %r15
lea addresses_A_ht+0x8ebe, %rsi
lea addresses_normal_ht+0xca9e, %rdi
clflush (%rdi)
nop
nop
nop
nop
add $63929, %r15
mov $67, %rcx
rep movsb
nop
nop
nop
nop
nop
xor $272, %rdx
lea addresses_WT_ht+0xe18e, %rsi
lea addresses_normal_ht+0x1cbbe, %rdi
and %rdx, %rdx
mov $71, %rcx
rep movsb
nop
cmp $58362, %rdx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rax
pop %r9
pop %r15
pop %r14
pop %r13
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %r8
push %r9
push %rax
push %rdx
// Faulty Load
mov $0x7014520000000bbe, %r13
clflush (%r13)
nop
nop
nop
nop
add $3692, %r9
mov (%r13), %edx
lea oracles, %r13
and $0xff, %rdx
shlq $12, %rdx
mov (%r13,%rdx,1), %rdx
pop %rdx
pop %rax
pop %r9
pop %r8
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_NC', 'same': False, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'type': 'addresses_NC', 'same': True, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 16, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_WT_ht', 'same': False, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_normal_ht', 'same': True, 'size': 8, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WT_ht', 'same': False, 'size': 1, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 1, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_A_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 5, 'same': True}, 'OP': 'REPM'}
{'src': {'type': 'addresses_WT_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM'}
{'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
*/
|
; A124610: a(n) = 5*a(n-1) + 2*a(n-2), n>1; a(0) = a(1) = 1.
; 1,1,7,37,199,1069,5743,30853,165751,890461,4783807,25699957,138067399,741736909,3984819343,21407570533,115007491351,617852597821,3319277971807,17832095054677,95799031216999,514659346194349,2764894793405743
mov $1,8
lpb $0
sub $0,1
add $3,$1
add $1,$3
mul $1,2
mov $2,$3
mov $3,$1
sub $3,$2
lpe
sub $1,$3
mul $1,2
div $1,96
mul $1,6
add $1,1
|
; int fzx_putc(struct fzx_state *fs, int c)
SECTION code_font_fzx
PUBLIC _fzx_putc
EXTERN l0_fzx_putc_callee
_fzx_putc:
pop af
pop ix
pop bc
push bc
push hl
push af
jp l0_fzx_putc_callee
|
.global s_prepare_buffers
s_prepare_buffers:
push %r14
push %r15
push %r9
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0xdb96, %rsi
nop
nop
nop
and $46797, %r14
mov $0x6162636465666768, %r9
movq %r9, %xmm7
and $0xffffffffffffffc0, %rsi
movaps %xmm7, (%rsi)
nop
nop
nop
nop
nop
and $11815, %rbx
lea addresses_WT_ht+0x4996, %rsi
lea addresses_normal_ht+0x1a996, %rdi
nop
nop
nop
nop
sub $8360, %rbp
mov $26, %rcx
rep movsq
nop
nop
nop
nop
nop
and %r14, %r14
lea addresses_WT_ht+0x7196, %rsi
nop
nop
nop
nop
add %rbx, %rbx
movl $0x61626364, (%rsi)
nop
nop
nop
and %rcx, %rcx
lea addresses_A_ht+0xd996, %rsi
lea addresses_UC_ht+0x10196, %rdi
nop
nop
nop
nop
nop
xor $43936, %rbx
mov $39, %rcx
rep movsb
and $33722, %r9
lea addresses_A_ht+0x5596, %rsi
lea addresses_A_ht+0x3f4e, %rdi
sub %r15, %r15
mov $61, %rcx
rep movsw
nop
nop
nop
dec %r9
lea addresses_normal_ht+0x1434e, %rsi
nop
nop
nop
and $32687, %r9
mov $0x6162636465666768, %rbp
movq %rbp, (%rsi)
nop
nop
cmp $44093, %r9
lea addresses_A_ht+0xa396, %r9
nop
nop
nop
nop
nop
inc %rbp
movups (%r9), %xmm7
vpextrq $0, %xmm7, %rsi
nop
and %rsi, %rsi
lea addresses_normal_ht+0x1752e, %r14
nop
nop
nop
nop
and $24291, %rsi
vmovups (%r14), %ymm7
vextracti128 $0, %ymm7, %xmm7
vpextrq $1, %xmm7, %r15
nop
and $29131, %r14
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r9
pop %r15
pop %r14
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %r13
push %r15
push %rbp
push %rdi
// Faulty Load
lea addresses_RW+0x10996, %r11
nop
add $29008, %rdi
vmovups (%r11), %ymm2
vextracti128 $0, %ymm2, %xmm2
vpextrq $0, %xmm2, %rbp
lea oracles, %r13
and $0xff, %rbp
shlq $12, %rbp
mov (%r13,%rbp,1), %rbp
pop %rdi
pop %rbp
pop %r15
pop %r13
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_RW', 'same': True, 'AVXalign': False, 'congruent': 0}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_RW', 'same': True, 'AVXalign': False, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'size': 16, 'NT': True, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': True, 'congruent': 9}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 11}, 'dst': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 10}}
{'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_WT_ht', 'same': True, 'AVXalign': False, 'congruent': 11}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_A_ht', 'congruent': 11}, 'dst': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 10}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_A_ht', 'congruent': 5}, 'dst': {'same': False, 'type': 'addresses_A_ht', 'congruent': 3}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 3}}
{'OP': 'LOAD', 'src': {'size': 16, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 7}}
{'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, '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
*/
|
INCLUDE "config_private.inc"
SECTION code_driver
SECTION code_driver_terminal_output
PUBLIC vgl_01_output_2000_oterm_msg_printc
EXTERN vgl_01_output_2000_refresh
vgl_01_output_2000_oterm_msg_printc:
; enter : c = ascii code
; b = parameter (foreground colour, 255 if none specified)
; l = absolute x coordinate
; h = absolute y coordinate
; can use: af, bc, de, hl
;ld b, h ; Save for later (refresh)
; call vgl_01_output_2000_set_cursor_coord
; Show cursor on screen
; ofs = Y*64 + X
ld a, h
;ld d, 6
;sla d
add a ; 2
add a ; 4
add a ; 8
add a ; 16
add a ; 32
add a ; 64
add l
inc a ; Show NEXT pos
ld (__VGL_2000_DISPLAY_CURSOR_OFS_ADDRESS), a
ld a, 1 ;0=off, 1=block 2=line
ld (__VGL_2000_DISPLAY_CURSOR_MODE_ADDRESS), a
; Put character to VRAM at 0xdca0 + (Y*COLS) + X
; a := Y*20
ld a, h
add a ; *2
add a ; *4
add a ; *8
add a ; *16
;ld b, 4
;sla b ; *16 (shl 4)
add h ; *17
add h ; *18
add h ; *19
add h ; *20
; Convert to VGL_VRAM_ADDRESS offset 0xdca0 + A + X
add l ; Add X coordinate to A
add __VGL_2000_DISPLAY_VRAM_START & 0x00ff ;0xa0
ld h, __VGL_2000_DISPLAY_VRAM_START >> 8 ;0xdc
ld l, a
ld (hl), c ; Put character to calculated VRAM offset
jp vgl_01_output_2000_refresh
|
TITLE Binary Search Procedure (BinarySearch.asm)
; Binary Search procedure
INCLUDE Irvine32.inc
.code
;-------------------------------------------------------------
BinarySearch PROC USES ebx edx esi edi,
pArray:PTR DWORD, ; pointer to array
Count:DWORD, ; array size
searchVal:DWORD ; search value
LOCAL first:DWORD, ; first position
last:DWORD, ; last position
mid:DWORD ; midpoint
;
; Search an array of signed integers for a single value.
; Receives: Pointer to array, array size, search value.
; Returns: If a match is found, EAX = the array position of the
; matching element; otherwise, EAX = -1.
;-------------------------------------------------------------
mov first,0 ; first = 0
mov eax,Count ; last = (count - 1)
dec eax
mov last,eax
mov edi,searchVal ; EDI = searchVal
mov ebx,pArray ; EBX points to the array
L1: ; while first <= last
mov eax,first
cmp eax,last
jg L5 ; exit search
; mid = (last + first) / 2
mov eax,last
add eax,first
shr eax,1
mov mid,eax
; EDX = values[mid]
mov esi,mid
shl esi,2 ; scale mid value by 4
mov edx,[ebx+esi] ; EDX = values[mid]
; if ( EDX < searchval(EDI) )
; first = mid + 1;
cmp edx,edi
jge L2
mov eax,mid ; first = mid + 1
inc eax
mov first,eax
jmp L4
; else if( EDX > searchVal(EDI) )
; last = mid - 1;
L2: cmp edx,edi
jle L3
mov eax,mid ; last = mid - 1
dec eax
mov last,eax
jmp L4
; else return mid
L3: mov eax,mid ; value found
jmp L9 ; return (mid)
L4: jmp L1 ; continue the loop
L5: mov eax,-1 ; search failed
L9: ret
BinarySearch ENDP
END |
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2017-2018 The RareShares Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/rareshares-config.h"
#endif
#include "init.h"
#include "addrman.h"
#include "amount.h"
#include "chain.h"
#include "chainparams.h"
#include "checkpoints.h"
#include "compat/sanity.h"
#include "consensus/validation.h"
#include "httpserver.h"
#include "httprpc.h"
#include "key.h"
#include "main.h"
#include "miner.h"
#include "net.h"
#include "netfulfilledman.h"
#include "policy/policy.h"
#include "rpcserver.h"
#include "script/standard.h"
#include "script/sigcache.h"
#include "scheduler.h"
#include "txdb.h"
#include "txmempool.h"
#include "torcontrol.h"
#include "ui_interface.h"
#include "util.h"
#include "utilmoneystr.h"
#include "utilstrencodings.h"
#include "validationinterface.h"
#ifdef ENABLE_WALLET
#include "wallet/db.h"
#include "wallet/wallet.h"
#include "wallet/walletdb.h"
#endif
#include "activemasternode.h"
#include "darksend.h"
#include "dsnotificationinterface.h"
#include "flat-database.h"
#include "governance.h"
#include "instantx.h"
#ifdef ENABLE_WALLET
#include "keepass.h"
#endif
#include "masternode-payments.h"
#include "masternode-sync.h"
#include "masternodeman.h"
#include "masternodeconfig.h"
#include "netfulfilledman.h"
#include "spork.h"
#include <stdint.h>
#include <stdio.h>
#ifndef WIN32
#include <signal.h>
#endif
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/bind.hpp>
#include <boost/filesystem.hpp>
#include <boost/function.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/thread.hpp>
#include <openssl/crypto.h>
#if ENABLE_ZMQ
#include "zmq/zmqnotificationinterface.h"
#endif
using namespace std;
extern void ThreadSendAlert();
#ifdef ENABLE_WALLET
CWallet* pwalletMain = NULL;
#endif
bool fFeeEstimatesInitialized = false;
bool fRestartRequested = false; // true: restart false: shutdown
static const bool DEFAULT_PROXYRANDOMIZE = true;
static const bool DEFAULT_REST_ENABLE = false;
static const bool DEFAULT_DISABLE_SAFEMODE = false;
static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false;
#if ENABLE_ZMQ
static CZMQNotificationInterface* pzmqNotificationInterface = NULL;
#endif
static CDSNotificationInterface* pdsNotificationInterface = NULL;
#ifdef WIN32
// Win32 LevelDB doesn't use filedescriptors, and the ones used for
// accessing block files don't count towards the fd_set size limit
// anyway.
#define MIN_CORE_FILEDESCRIPTORS 0
#else
#define MIN_CORE_FILEDESCRIPTORS 150
#endif
/** Used to pass flags to the Bind() function */
enum BindFlags {
BF_NONE = 0,
BF_EXPLICIT = (1U << 0),
BF_REPORT_ERROR = (1U << 1),
BF_WHITELIST = (1U << 2),
};
static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat";
CClientUIInterface uiInterface; // Declared but not defined in ui_interface.h
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
//
// Thread management and startup/shutdown:
//
// The network-processing threads are all part of a thread group
// created by AppInit() or the Qt main() function.
//
// A clean exit happens when StartShutdown() or the SIGTERM
// signal handler sets fRequestShutdown, which triggers
// the DetectShutdownThread(), which interrupts the main thread group.
// DetectShutdownThread() then exits, which causes AppInit() to
// continue (it .joins the shutdown thread).
// Shutdown() is then
// called to clean up database connections, and stop other
// threads that should only be stopped after the main network-processing
// threads have exited.
//
// Note that if running -daemon the parent process returns from AppInit2
// before adding any threads to the threadGroup, so .join_all() returns
// immediately and the parent exits from main().
//
// Shutdown for Qt is very similar, only it uses a QTimer to detect
// fRequestShutdown getting set, and then does the normal Qt
// shutdown thing.
//
volatile bool fRequestShutdown = false;
void StartShutdown()
{
fRequestShutdown = true;
}
bool ShutdownRequested()
{
return fRequestShutdown || fRestartRequested;
}
class CCoinsViewErrorCatcher : public CCoinsViewBacked
{
public:
CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
bool GetCoins(const uint256 &txid, CCoins &coins) const {
try {
return CCoinsViewBacked::GetCoins(txid, coins);
} catch(const std::runtime_error& e) {
uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
LogPrintf("Error reading from database: %s\n", e.what());
// Starting the shutdown sequence and returning false to the caller would be
// interpreted as 'entry not found' (as opposed to unable to read data), and
// could lead to invalid interpretation. Just exit immediately, as we can't
// continue anyway, and all writes should be atomic.
abort();
}
}
// Writes do not need similar protection, as failure to write is handled by the caller.
};
static CCoinsViewDB *pcoinsdbview = NULL;
static CCoinsViewErrorCatcher *pcoinscatcher = NULL;
static boost::scoped_ptr<ECCVerifyHandle> globalVerifyHandle;
void Interrupt(boost::thread_group& threadGroup)
{
InterruptHTTPServer();
InterruptHTTPRPC();
InterruptRPC();
InterruptREST();
InterruptTorControl();
threadGroup.interrupt_all();
}
/** Preparing steps before shutting down or restarting the wallet */
void PrepareShutdown()
{
fRequestShutdown = true; // Needed when we shutdown the wallet
fRestartRequested = true; // Needed when we restart the wallet
LogPrintf("%s: In progress...\n", __func__);
static CCriticalSection cs_Shutdown;
TRY_LOCK(cs_Shutdown, lockShutdown);
if (!lockShutdown)
return;
/// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way,
/// for example if the data directory was found to be locked.
/// Be sure that anything that writes files or flushes caches only does this if the respective
/// module was initialized.
RenameThread("rareshares-shutoff");
mempool.AddTransactionsUpdated(1);
StopHTTPRPC();
StopREST();
StopRPC();
StopHTTPServer();
#ifdef ENABLE_WALLET
if (pwalletMain)
pwalletMain->Flush(false);
#endif
GenerateBitcoins(false, 0, Params());
StopNode();
// STORE DATA CACHES INTO SERIALIZED DAT FILES
CFlatDB<CMasternodeMan> flatdb1("mncache.dat", "magicMasternodeCache");
flatdb1.Dump(mnodeman);
CFlatDB<CMasternodePayments> flatdb2("mnpayments.dat", "magicMasternodePaymentsCache");
flatdb2.Dump(mnpayments);
CFlatDB<CGovernanceManager> flatdb3("governance.dat", "magicGovernanceCache");
flatdb3.Dump(governance);
CFlatDB<CNetFulfilledRequestManager> flatdb4("netfulfilled.dat", "magicFulfilledCache");
flatdb4.Dump(netfulfilledman);
UnregisterNodeSignals(GetNodeSignals());
if (fFeeEstimatesInitialized)
{
boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION);
if (!est_fileout.IsNull())
mempool.WriteFeeEstimates(est_fileout);
else
LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
fFeeEstimatesInitialized = false;
}
{
LOCK(cs_main);
if (pcoinsTip != NULL) {
FlushStateToDisk();
}
delete pcoinsTip;
pcoinsTip = NULL;
delete pcoinscatcher;
pcoinscatcher = NULL;
delete pcoinsdbview;
pcoinsdbview = NULL;
delete pblocktree;
pblocktree = NULL;
}
#ifdef ENABLE_WALLET
if (pwalletMain)
pwalletMain->Flush(true);
#endif
#if ENABLE_ZMQ
if (pzmqNotificationInterface) {
UnregisterValidationInterface(pzmqNotificationInterface);
delete pzmqNotificationInterface;
pzmqNotificationInterface = NULL;
}
#endif
if (pdsNotificationInterface) {
UnregisterValidationInterface(pdsNotificationInterface);
delete pdsNotificationInterface;
pdsNotificationInterface = NULL;
}
#ifndef WIN32
try {
boost::filesystem::remove(GetPidFile());
} catch (const boost::filesystem::filesystem_error& e) {
LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
}
#endif
UnregisterAllValidationInterfaces();
}
/**
* Shutdown is split into 2 parts:
* Part 1: shut down everything but the main wallet instance (done in PrepareShutdown() )
* Part 2: delete wallet instance
*
* In case of a restart PrepareShutdown() was already called before, but this method here gets
* called implicitly when the parent object is deleted. In this case we have to skip the
* PrepareShutdown() part because it was already executed and just delete the wallet instance.
*/
void Shutdown()
{
// Shutdown part 1: prepare shutdown
if(!fRestartRequested){
PrepareShutdown();
}
// Shutdown part 2: Stop TOR thread and delete wallet instance
StopTorControl();
#ifdef ENABLE_WALLET
delete pwalletMain;
pwalletMain = NULL;
#endif
globalVerifyHandle.reset();
ECC_Stop();
LogPrintf("%s: done\n", __func__);
}
/**
* Signal handlers are very limited in what they are allowed to do, so:
*/
void HandleSIGTERM(int)
{
fRequestShutdown = true;
}
void HandleSIGHUP(int)
{
fReopenDebugLog = true;
}
bool static InitError(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
return false;
}
bool static InitWarning(const std::string &str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
return true;
}
bool static Bind(const CService &addr, unsigned int flags) {
if (!(flags & BF_EXPLICIT) && IsLimited(addr))
return false;
std::string strError;
if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
if (flags & BF_REPORT_ERROR)
return InitError(strError);
return false;
}
return true;
}
void OnRPCStopped()
{
cvBlockChange.notify_all();
LogPrint("rpc", "RPC stopped.\n");
}
void OnRPCPreCommand(const CRPCCommand& cmd)
{
// Observe safe mode
string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode", DEFAULT_DISABLE_SAFEMODE) &&
!cmd.okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, string("Safe mode: ") + strWarning);
}
std::string HelpMessage(HelpMessageMode mode)
{
const bool showDebug = GetBoolArg("-help-debug", false);
// When adding new options to the categories, please keep and ensure alphabetical ordering.
// Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators.
string strUsage = HelpMessageGroup(_("Options:"));
strUsage += HelpMessageOpt("-?", _("This help message"));
strUsage += HelpMessageOpt("-version", _("Print version and exit"));
strUsage += HelpMessageOpt("-alerts", strprintf(_("Receive and display P2P network alerts (default: %u)"), DEFAULT_ALERTS));
strUsage += HelpMessageOpt("-alertnotify=<cmd>", _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)"));
strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
if (showDebug)
strUsage += HelpMessageOpt("-blocksonly", strprintf(_("Whether to operate in a blocks only mode (default: %u)"), DEFAULT_BLOCKSONLY));
strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS));
strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL));
strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME));
if (mode == HMM_BITCOIND)
{
#ifndef WIN32
strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
#endif
}
strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file on startup"));
strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
strUsage += HelpMessageOpt("-maxmempool=<n>", strprintf(_("Keep the transaction memory pool below <n> megabytes (default: %u)"), DEFAULT_MAX_MEMPOOL_SIZE));
strUsage += HelpMessageOpt("-mempoolexpiry=<n>", strprintf(_("Do not keep transactions in the mempool longer than <n> hours (default: %u)"), DEFAULT_MEMPOOL_EXPIRY));
strUsage += HelpMessageOpt("-par=<n>", strprintf(_("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"),
-GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
#ifndef WIN32
strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), BITCOIN_PID_FILENAME));
#endif
strUsage += HelpMessageOpt("-prune=<n>", strprintf(_("Reduce storage requirements by pruning (deleting) old blocks. This mode is incompatible with -txindex and -rescan. "
"Warning: Reverting this setting requires re-downloading the entire blockchain. "
"(default: 0 = disable pruning blocks, >%u = target size in MiB to use for block files)"), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
strUsage += HelpMessageOpt("-reindex", _("Rebuild block chain index from current blk000??.dat files on startup"));
#ifndef WIN32
strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
#endif
strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), DEFAULT_TXINDEX));
strUsage += HelpMessageOpt("-addressindex", strprintf(_("Maintain a full address index, used to query for the balance, txids and unspent outputs for addresses (default: %u)"), DEFAULT_ADDRESSINDEX));
strUsage += HelpMessageOpt("-timestampindex", strprintf(_("Maintain a timestamp index for block hashes, used to query blocks hashes by a range of timestamps (default: %u)"), DEFAULT_TIMESTAMPINDEX));
strUsage += HelpMessageOpt("-spentindex", strprintf(_("Maintain a full spent index, used to query the spending txid and input index for an outpoint (default: %u)"), DEFAULT_SPENTINDEX));
strUsage += HelpMessageGroup(_("Connection options:"));
strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), DEFAULT_BANSCORE_THRESHOLD));
strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), DEFAULT_MISBEHAVING_BANTIME));
strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s)"));
strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)"));
strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + strprintf(_("(default: %u)"), DEFAULT_NAME_LOOKUP));
strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)"));
strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), DEFAULT_FORCEDNSSEED));
strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (temporary service connections excluded) (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS));
strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXRECEIVEBUFFER));
strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXSENDBUFFER));
strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG));
strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), 1));
if (showDebug)
strUsage += HelpMessageOpt("-enforcenodebloom", strprintf("Enforce minimum protocol version to limit use of bloom filters (default: %u)", 0));
strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), Params(CBaseChainParams::MAIN).GetDefaultPort(), Params(CBaseChainParams::TESTNET).GetDefaultPort()));
strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE));
strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
#ifdef USE_UPNP
#if USE_UPNP
strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)"));
#else
strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
#endif
#endif
strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") +
" " + _("Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway"));
strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY));
strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY));
strUsage += HelpMessageOpt("-maxuploadtarget=<n>", strprintf(_("Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)"), DEFAULT_MAX_UPLOAD_TARGET));
#ifdef ENABLE_WALLET
strUsage += HelpMessageGroup(_("Wallet options:"));
strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), DEFAULT_KEYPOOL_SIZE));
strUsage += HelpMessageOpt("-fallbackfee=<amt>", strprintf(_("A fee rate (in %s/kB) that will be used when fee estimation has insufficient data (default: %s)"),
CURRENCY_UNIT, FormatMoney(DEFAULT_FALLBACK_FEE)));
strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for transaction creation (default: %s)"),
CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MINFEE)));
strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in %s/kB) to add to transactions you send (default: %s)"),
CURRENCY_UNIT, FormatMoney(payTxFee.GetFeePerK())));
strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions on startup"));
strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat on startup"));
strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), DEFAULT_SEND_FREE_TRANSACTIONS));
strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), DEFAULT_SPEND_ZEROCONF_CHANGE));
strUsage += HelpMessageOpt("-txconfirmtarget=<n>", strprintf(_("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)"), DEFAULT_TX_CONFIRM_TARGET));
strUsage += HelpMessageOpt("-maxtxfee=<amt>", strprintf(_("Maximum total fees (in %s) to use in a single wallet transaction; setting this too low may abort large transactions (default: %s)"),
CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE)));
strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format on startup"));
strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), "wallet.dat"));
strUsage += HelpMessageOpt("-walletbroadcast", _("Make the wallet broadcast transactions") + " " + strprintf(_("(default: %u)"), DEFAULT_WALLETBROADCAST));
strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
" " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
strUsage += HelpMessageOpt("-createwalletbackups=<n>", strprintf(_("Number of automatic wallet backups (default: %u)"), nWalletBackups));
strUsage += HelpMessageOpt("-walletbackupsdir=<dir>", _("Specify full path to directory for automatic wallet backups (must exist)"));
strUsage += HelpMessageOpt("-keepass", strprintf(_("Use KeePass 2 integration using KeePassHttp plugin (default: %u)"), 0));
strUsage += HelpMessageOpt("-keepassport=<port>", strprintf(_("Connect to KeePassHttp on port <port> (default: %u)"), DEFAULT_KEEPASS_HTTP_PORT));
strUsage += HelpMessageOpt("-keepasskey=<key>", _("KeePassHttp key for AES encrypted communication with KeePass"));
strUsage += HelpMessageOpt("-keepassid=<name>", _("KeePassHttp id for the established association"));
strUsage += HelpMessageOpt("-keepassname=<name>", _("Name to construct url for KeePass entry that stores the wallet passphrase"));
if (mode == HMM_BITCOIN_QT)
strUsage += HelpMessageOpt("-windowtitle=<name>", _("Wallet window title"));
#endif
#if ENABLE_ZMQ
strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
strUsage += HelpMessageOpt("-zmqpubhashtxlock=<address>", _("Enable publish hash transaction (locked via InstantSend) in <address>"));
strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
strUsage += HelpMessageOpt("-zmqpubrawtxlock=<address>", _("Enable publish raw transaction (locked via InstantSend) in <address>"));
#endif
strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string"));
if (showDebug)
{
strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks()));
strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks()));
strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED));
#ifdef ENABLE_WALLET
strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf("Flush wallet database activity from memory to disk log every <n> megabytes (default: %u)", DEFAULT_WALLET_DBLOGSIZE));
#endif
strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE));
strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE));
strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages");
strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages");
#ifdef ENABLE_WALLET
strUsage += HelpMessageOpt("-flushwallet", strprintf("Run a thread to flush wallet periodically (default: %u)", DEFAULT_FLUSHWALLET));
#endif
strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT));
strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT));
strUsage += HelpMessageOpt("-limitancestorsize=<n>", strprintf("Do not accept transactions whose size with all in-mempool ancestors exceeds <n> kilobytes (default: %u)", DEFAULT_ANCESTOR_SIZE_LIMIT));
strUsage += HelpMessageOpt("-limitdescendantcount=<n>", strprintf("Do not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u)", DEFAULT_DESCENDANT_LIMIT));
strUsage += HelpMessageOpt("-limitdescendantsize=<n>", strprintf("Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT));
}
string debugCategories = "addrman, alert, bench, coindb, db, lock, rand, rpc, selectcoins, mempool, mempoolrej, net, proxy, prune, http, libevent, tor, zmq, "
"rareshares (or specifically: privatesend, instantsend, masternode, spork, keepass, mnpayments, gobject)"; // Don't translate these and qt below
if (mode == HMM_BITCOIN_QT)
debugCategories += ", qt";
strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
_("If <category> is not supplied or if <category> = 1, output all debugging information.") + _("<category> can be:") + " " + debugCategories + ".");
if (showDebug)
strUsage += HelpMessageOpt("-nodebug", "Turn off debugging messages, same as -debug=0");
strUsage += HelpMessageOpt("-gen", strprintf(_("Generate coins (default: %u)"), DEFAULT_GENERATE));
strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), DEFAULT_GENERATE_THREADS));
strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS));
strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS));
if (showDebug)
{
strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS));
strUsage += HelpMessageOpt("-logthreadnames", strprintf("Add thread names to debug messages (default: %u)", DEFAULT_LOGTHREADNAMES));
strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)");
strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default: %u)", DEFAULT_LIMITFREERELAY));
strUsage += HelpMessageOpt("-relaypriority", strprintf("Require high priority for relaying free or low-fee transactions (default: %u)", DEFAULT_RELAYPRIORITY));
strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE));
}
strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"),
CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE)));
strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file"));
strUsage += HelpMessageOpt("-printtodebuglog", strprintf(_("Send trace/debug info to debug.log file (default: %u)"), 1));
if (showDebug)
{
strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction priority and fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY));
#ifdef ENABLE_WALLET
strUsage += HelpMessageOpt("-privdb", strprintf("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)", DEFAULT_WALLET_PRIVDB));
#endif
}
strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
AppendParamsHelpMessages(strUsage, showDebug);
strUsage += HelpMessageOpt("-litemode=<n>", strprintf(_("Disable all RareShares specific functionality (Masternodes, PrivateSend, InstantSend, Governance) (0-1, default: %u)"), 0));
strUsage += HelpMessageGroup(_("Masternode options:"));
strUsage += HelpMessageOpt("-masternode=<n>", strprintf(_("Enable the client to act as a masternode (0-1, default: %u)"), 0));
strUsage += HelpMessageOpt("-mnconf=<file>", strprintf(_("Specify masternode configuration file (default: %s)"), "masternode.conf"));
strUsage += HelpMessageOpt("-mnconflock=<n>", strprintf(_("Lock masternodes from masternode configuration file (default: %u)"), 1));
strUsage += HelpMessageOpt("-masternodeprivkey=<n>", _("Set the masternode private key"));
strUsage += HelpMessageGroup(_("PrivateSend options:"));
strUsage += HelpMessageOpt("-enableprivatesend=<n>", strprintf(_("Enable use of automated PrivateSend for funds stored in this wallet (0-1, default: %u)"), 0));
strUsage += HelpMessageOpt("-privatesendmultisession=<n>", strprintf(_("Enable multiple PrivateSend mixing sessions per block, experimental (0-1, default: %u)"), DEFAULT_PRIVATESEND_MULTISESSION));
strUsage += HelpMessageOpt("-privatesendrounds=<n>", strprintf(_("Use N separate masternodes for each denominated input to mix funds (2-16, default: %u)"), DEFAULT_PRIVATESEND_ROUNDS));
strUsage += HelpMessageOpt("-privatesendamount=<n>", strprintf(_("Keep N RS anonymized (default: %u)"), DEFAULT_PRIVATESEND_AMOUNT));
strUsage += HelpMessageOpt("-liquidityprovider=<n>", strprintf(_("Provide liquidity to PrivateSend by infrequently mixing coins on a continual basis (0-100, default: %u, 1=very frequent, high fees, 100=very infrequent, low fees)"), DEFAULT_PRIVATESEND_LIQUIDITY));
strUsage += HelpMessageGroup(_("InstantSend options:"));
strUsage += HelpMessageOpt("-enableinstantsend=<n>", strprintf(_("Enable InstantSend, show confirmations for locked transactions (0-1, default: %u)"), 1));
strUsage += HelpMessageOpt("-instantsenddepth=<n>", strprintf(_("Show N confirmations for a successfully locked transaction (0-9999, default: %u)"), DEFAULT_INSTANTSEND_DEPTH));
strUsage += HelpMessageOpt("-instantsendnotify=<cmd>", _("Execute command when a wallet InstantSend transaction is successfully locked (%s in cmd is replaced by TxID)"));
strUsage += HelpMessageGroup(_("Node relay options:"));
if (showDebug)
strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !Params(CBaseChainParams::TESTNET).RequireStandard()));
strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Minimum bytes per sigop in transactions we relay and mine (default: %u)"), DEFAULT_BYTES_PER_SIGOP));
strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER));
strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
strUsage += HelpMessageOpt("-mempoolreplacement", strprintf(_("Enable transaction replacement in the memory pool (default: %u)"), DEFAULT_ENABLE_REPLACEMENT));
strUsage += HelpMessageGroup(_("Block creation options:"));
strUsage += HelpMessageOpt("-blockminsize=<n>", strprintf(_("Set minimum block size in bytes (default: %u)"), DEFAULT_BLOCK_MIN_SIZE));
strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
strUsage += HelpMessageOpt("-blockprioritysize=<n>", strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE));
if (showDebug)
strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
strUsage += HelpMessageGroup(_("RPC server options:"));
strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE));
strUsage += HelpMessageOpt("-rpcbind=<addr>", _("Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)"));
strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)"));
strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcauth=<userpw>", _("Username and hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcuser. This option can be specified multiple times"));
strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), BaseParams(CBaseChainParams::MAIN).RPCPort(), BaseParams(CBaseChainParams::TESTNET).RPCPort()));
strUsage += HelpMessageOpt("-rpcallowip=<ip>", _("Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"));
strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
if (showDebug) {
strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
}
return strUsage;
}
std::string LicenseInfo()
{
// todo: remove urls from translations on next change
return FormatParagraph(strprintf(_("Copyright (C) 2009-%i The Bitcoin Core Developers"), COPYRIGHT_YEAR)) + "\n" +
"\n" +
FormatParagraph(strprintf(_("Copyright (C) 2014-%i The Dash Core Developers"), COPYRIGHT_YEAR)) + "\n" +
"\n" +
FormatParagraph(strprintf(_("Copyright (C) 2017-%i The RareShares Core Developers"), COPYRIGHT_YEAR)) + "\n" +
"\n" +
FormatParagraph(_("This is experimental software.")) + "\n" +
"\n" +
FormatParagraph(_("Distributed under the MIT software license, see the accompanying file COPYING or <http://www.opensource.org/licenses/mit-license.php>.")) + "\n" +
"\n" +
FormatParagraph(_("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.")) +
"\n";
}
static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex)
{
if (initialSync || !pBlockIndex)
return;
std::string strCmd = GetArg("-blocknotify", "");
boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
struct CImportingNow
{
CImportingNow() {
assert(fImporting == false);
fImporting = true;
}
~CImportingNow() {
assert(fImporting == true);
fImporting = false;
}
};
// If we're using -prune with -reindex, then delete block files that will be ignored by the
// reindex. Since reindexing works by starting at block file 0 and looping until a blockfile
// is missing, do the same here to delete any later block files after a gap. Also delete all
// rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile
// is in sync with what's actually on disk by the time we start downloading, so that pruning
// works correctly.
void CleanupBlockRevFiles()
{
using namespace boost::filesystem;
map<string, path> mapBlockFiles;
// Glob all blk?????.dat and rev?????.dat files from the blocks directory.
// Remove the rev files immediately and insert the blk file paths into an
// ordered map keyed by block file index.
LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n");
path blocksdir = GetDataDir() / "blocks";
for (directory_iterator it(blocksdir); it != directory_iterator(); it++) {
if (is_regular_file(*it) &&
it->path().filename().string().length() == 12 &&
it->path().filename().string().substr(8,4) == ".dat")
{
if (it->path().filename().string().substr(0,3) == "blk")
mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path();
else if (it->path().filename().string().substr(0,3) == "rev")
remove(it->path());
}
}
// Remove all block files that aren't part of a contiguous set starting at
// zero by walking the ordered map (keys are block file indices) by
// keeping a separate counter. Once we hit a gap (or if 0 doesn't exist)
// start removing block files.
int nContigCounter = 0;
BOOST_FOREACH(const PAIRTYPE(string, path)& item, mapBlockFiles) {
if (atoi(item.first) == nContigCounter) {
nContigCounter++;
continue;
}
remove(item.second);
}
}
void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
{
const CChainParams& chainparams = Params();
RenameThread("rareshares-loadblk");
// -reindex
if (fReindex) {
CImportingNow imp;
int nFile = 0;
while (true) {
CDiskBlockPos pos(nFile, 0);
if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk")))
break; // No block files left to reindex
FILE *file = OpenBlockFile(pos, true);
if (!file)
break; // This error is logged in OpenBlockFile
LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
LoadExternalBlockFile(chainparams, file, &pos);
nFile++;
}
pblocktree->WriteReindexing(false);
fReindex = false;
LogPrintf("Reindexing finished\n");
// To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
InitBlockIndex(chainparams);
}
// hardcoded $DATADIR/bootstrap.dat
boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
if (boost::filesystem::exists(pathBootstrap)) {
FILE *file = fopen(pathBootstrap.string().c_str(), "rb");
if (file) {
CImportingNow imp;
boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
LogPrintf("Importing bootstrap.dat...\n");
LoadExternalBlockFile(chainparams, file);
RenameOver(pathBootstrap, pathBootstrapOld);
} else {
LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
}
}
// -loadblock=
BOOST_FOREACH(const boost::filesystem::path& path, vImportFiles) {
FILE *file = fopen(path.string().c_str(), "rb");
if (file) {
CImportingNow imp;
LogPrintf("Importing blocks file %s...\n", path.string());
LoadExternalBlockFile(chainparams, file);
} else {
LogPrintf("Warning: Could not open blocks file %s\n", path.string());
}
}
if (GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) {
LogPrintf("Stopping after block import\n");
StartShutdown();
}
}
/** Sanity checks
* Ensure that RareShares Core is running in a usable environment with all
* necessary library support.
*/
bool InitSanityCheck(void)
{
if(!ECC_InitSanityCheck()) {
InitError("Elliptic curve cryptography sanity check failure. Aborting.");
return false;
}
if (!glibc_sanity_test() || !glibcxx_sanity_test())
return false;
return true;
}
bool AppInitServers(boost::thread_group& threadGroup)
{
RPCServer::OnStopped(&OnRPCStopped);
RPCServer::OnPreCommand(&OnRPCPreCommand);
if (!InitHTTPServer())
return false;
if (!StartRPC())
return false;
if (!StartHTTPRPC())
return false;
if (GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST())
return false;
if (!StartHTTPServer())
return false;
return true;
}
// Parameter interaction based on rules
void InitParameterInteraction()
{
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
if (mapArgs.count("-bind")) {
if (SoftSetBoolArg("-listen", true))
LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__);
}
if (mapArgs.count("-whitebind")) {
if (SoftSetBoolArg("-listen", true))
LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__);
}
if (GetBoolArg("-masternode", false)) {
// masternodes must accept connections from outside
if (SoftSetBoolArg("-listen", true))
LogPrintf("%s: parameter interaction: -masternode=1 -> setting -listen=1\n", __func__);
}
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default
if (SoftSetBoolArg("-dnsseed", false))
LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__);
if (SoftSetBoolArg("-listen", false))
LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__);
}
if (mapArgs.count("-proxy")) {
// to protect privacy, do not listen by default if a default proxy server is specified
if (SoftSetBoolArg("-listen", false))
LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
// to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
// to listen locally, so don't rely on this happening through -listen below.
if (SoftSetBoolArg("-upnp", false))
LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
// to protect privacy, do not discover addresses by default
if (SoftSetBoolArg("-discover", false))
LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__);
}
if (!GetBoolArg("-listen", DEFAULT_LISTEN)) {
// do not map ports or try to retrieve public IP when not listening (pointless)
if (SoftSetBoolArg("-upnp", false))
LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__);
if (SoftSetBoolArg("-discover", false))
LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__);
if (SoftSetBoolArg("-listenonion", false))
LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__);
}
if (mapArgs.count("-externalip")) {
// if an explicit public IP is specified, do not try to find others
if (SoftSetBoolArg("-discover", false))
LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__);
}
if (GetBoolArg("-salvagewallet", false)) {
// Rewrite just private keys: rescan to find transactions
if (SoftSetBoolArg("-rescan", true))
LogPrintf("%s: parameter interaction: -salvagewallet=1 -> setting -rescan=1\n", __func__);
}
// -zapwallettx implies a rescan
if (GetBoolArg("-zapwallettxes", false)) {
if (SoftSetBoolArg("-rescan", true))
LogPrintf("%s: parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n", __func__);
}
// disable walletbroadcast and whitelistrelay in blocksonly mode
if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) {
if (SoftSetBoolArg("-whitelistrelay", false))
LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__);
#ifdef ENABLE_WALLET
if (SoftSetBoolArg("-walletbroadcast", false))
LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -walletbroadcast=0\n", __func__);
#endif
}
// Forcing relay from whitelisted hosts implies we will accept relays from them in the first place.
if (GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) {
if (SoftSetBoolArg("-whitelistrelay", true))
LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__);
}
if(!GetBoolArg("-enableinstantsend", fEnableInstantSend)){
if (SoftSetArg("-instantsenddepth", 0))
LogPrintf("%s: parameter interaction: -enableinstantsend=false -> setting -nInstantSendDepth=0\n", __func__);
}
int nLiqProvTmp = GetArg("-liquidityprovider", DEFAULT_PRIVATESEND_LIQUIDITY);
if (nLiqProvTmp > 0) {
mapArgs["-enableprivatesend"] = "1";
LogPrintf("%s: parameter interaction: -liquidityprovider=%d -> setting -enableprivatesend=1\n", __func__, nLiqProvTmp);
mapArgs["-privatesendrounds"] = "99999";
LogPrintf("%s: parameter interaction: -liquidityprovider=%d -> setting -privatesendrounds=99999\n", __func__, nLiqProvTmp);
mapArgs["-privatesendamount"] = "999999";
LogPrintf("%s: parameter interaction: -liquidityprovider=%d -> setting -privatesendamount=999999\n", __func__, nLiqProvTmp);
mapArgs["-privatesendmultisession"] = "0";
LogPrintf("%s: parameter interaction: -liquidityprovider=%d -> setting -privatesendmultisession=0\n", __func__, nLiqProvTmp);
}
}
void InitLogging()
{
fPrintToConsole = GetBoolArg("-printtoconsole", false);
fPrintToDebugLog = GetBoolArg("-printtodebuglog", true) && !fPrintToConsole;
fLogTimestamps = GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
fLogTimeMicros = GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
fLogThreadNames = GetBoolArg("-logthreadnames", DEFAULT_LOGTHREADNAMES);
fLogIPs = GetBoolArg("-logips", DEFAULT_LOGIPS);
LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
LogPrintf("RareShares Core version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);
}
/** Initialize RareShares Core.
* @pre Parameters should be parsed and config file should be read.
*/
bool AppInit2(boost::thread_group& threadGroup, CScheduler& scheduler)
{
// ********************************************************* Step 1: setup
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
// Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
// Enable Data Execution Prevention (DEP)
// Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
// A failure is non-critical and needs no further attention!
#ifndef PROCESS_DEP_ENABLE
// We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
// which is not correct. Can be removed, when GCCs winbase.h is fixed!
#define PROCESS_DEP_ENABLE 0x00000001
#endif
typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD);
PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
#endif
if (!SetupNetworking())
return InitError("Initializing networking failed");
#ifndef WIN32
if (GetBoolArg("-sysperms", false)) {
#ifdef ENABLE_WALLET
if (!GetBoolArg("-disablewallet", false))
return InitError("-sysperms is not allowed in combination with enabled wallet functionality");
#endif
} else {
umask(077);
}
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
// Reopen debug.log on SIGHUP
struct sigaction sa_hup;
sa_hup.sa_handler = HandleSIGHUP;
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0;
sigaction(SIGHUP, &sa_hup, NULL);
// Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
signal(SIGPIPE, SIG_IGN);
#endif
// ********************************************************* Step 2: parameter interactions
const CChainParams& chainparams = Params();
// also see: InitParameterInteraction()
// if using block pruning, then disable txindex
if (GetArg("-prune", 0)) {
if (GetBoolArg("-txindex", DEFAULT_TXINDEX))
return InitError(_("Prune mode is incompatible with -txindex."));
#ifdef ENABLE_WALLET
if (GetBoolArg("-rescan", false)) {
return InitError(_("Rescans are not possible in pruned mode. You will need to use -reindex which will download the whole blockchain again."));
}
#endif
}
// Make sure enough file descriptors are available
int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1);
int nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS);
nMaxConnections = std::max(nUserMaxConnections, 0);
// Trim requested connection counts, to fit into system limitations
nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
if (nFD < MIN_CORE_FILEDESCRIPTORS)
return InitError(_("Not enough file descriptors available."));
nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS, nMaxConnections);
if (nMaxConnections < nUserMaxConnections)
InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections));
// ********************************************************* Step 3: parameter-to-internal-flags
fDebug = !mapMultiArgs["-debug"].empty();
// Special-case: if -debug=0/-nodebug is set, turn off debugging messages
const vector<string>& categories = mapMultiArgs["-debug"];
if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end())
fDebug = false;
// Check for -debugnet
if (GetBoolArg("-debugnet", false))
InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net."));
// Check for -socks - as this is a privacy risk to continue, exit here
if (mapArgs.count("-socks"))
return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
// Check for -tor - as this is a privacy risk to continue, exit here
if (GetBoolArg("-tor", false))
return InitError(_("Unsupported argument -tor found, use -onion."));
if (GetBoolArg("-benchmark", false))
InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench."));
if (GetBoolArg("-whitelistalwaysrelay", false))
InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay."));
// Checkmempool and checkblockindex default to true in regtest mode
int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000);
if (ratio != 0) {
mempool.setSanityCheck(1.0 / ratio);
}
fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks());
fCheckpointsEnabled = GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED);
// mempool limits
int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000;
int64_t nMempoolSizeMin = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40;
if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin)
return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0)));
// -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
if (nScriptCheckThreads <= 0)
nScriptCheckThreads += GetNumCores();
if (nScriptCheckThreads <= 1)
nScriptCheckThreads = 0;
else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
fServer = GetBoolArg("-server", false);
// block pruning; get the amount of disk space (in MiB) to allot for block & undo files
int64_t nSignedPruneTarget = GetArg("-prune", 0) * 1024 * 1024;
if (nSignedPruneTarget < 0) {
return InitError(_("Prune cannot be configured with a negative value."));
}
nPruneTarget = (uint64_t) nSignedPruneTarget;
if (nPruneTarget) {
if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) {
return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024));
}
LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024);
fPruneMode = true;
}
#ifdef ENABLE_WALLET
bool fDisableWallet = GetBoolArg("-disablewallet", false);
#endif
nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
if (nConnectTimeout <= 0)
nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
// Fee-per-kilobyte amount considered the same as "free"
// If you are mining, be careful setting this:
// if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
if (mapArgs.count("-minrelaytxfee"))
{
CAmount n = 0;
if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
::minRelayTxFee = CFeeRate(n);
else
return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"]));
}
fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !Params().RequireStandard());
if (Params().RequireStandard() && !fRequireStandard)
return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString()));
nBytesPerSigOp = GetArg("-bytespersigop", nBytesPerSigOp);
#ifdef ENABLE_WALLET
if (mapArgs.count("-mintxfee"))
{
CAmount n = 0;
if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
CWallet::minTxFee = CFeeRate(n);
else
return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"]));
}
if (mapArgs.count("-fallbackfee"))
{
CAmount nFeePerK = 0;
if (!ParseMoney(mapArgs["-fallbackfee"], nFeePerK))
return InitError(strprintf(_("Invalid amount for -fallbackfee=<amount>: '%s'"), mapArgs["-fallbackfee"]));
if (nFeePerK > nHighTransactionFeeWarning)
InitWarning(_("-fallbackfee is set very high! This is the transaction fee you may pay when fee estimates are not available."));
CWallet::fallbackFee = CFeeRate(nFeePerK);
}
if (mapArgs.count("-paytxfee"))
{
CAmount nFeePerK = 0;
if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK))
return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"]));
if (nFeePerK > nHighTransactionFeeWarning)
InitWarning(_("-paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
payTxFee = CFeeRate(nFeePerK, 1000);
if (payTxFee < ::minRelayTxFee)
{
return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
mapArgs["-paytxfee"], ::minRelayTxFee.ToString()));
}
}
if (mapArgs.count("-maxtxfee"))
{
CAmount nMaxFee = 0;
if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee))
return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s'"), mapArgs["-maxtxfee"]));
if (nMaxFee > nHighTransactionMaxFeeWarning)
InitWarning(_("-maxtxfee is set very high! Fees this large could be paid on a single transaction."));
maxTxFee = nMaxFee;
if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee)
{
return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
mapArgs["-maxtxfee"], ::minRelayTxFee.ToString()));
}
}
nTxConfirmTarget = GetArg("-txconfirmtarget", DEFAULT_TX_CONFIRM_TARGET);
bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", DEFAULT_SPEND_ZEROCONF_CHANGE);
fSendFreeTransactions = GetBoolArg("-sendfreetransactions", DEFAULT_SEND_FREE_TRANSACTIONS);
std::string strWalletFile = GetArg("-wallet", "wallet.dat");
#endif // ENABLE_WALLET
fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG);
fAcceptDatacarrier = GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER);
nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
fAlerts = GetBoolArg("-alerts", DEFAULT_ALERTS);
// Option to startup with mocktime set (used for regression testing):
SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op
if (GetBoolArg("-peerbloomfilters", true))
nLocalServices |= NODE_BLOOM;
fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT);
if ((!fEnableReplacement) && mapArgs.count("-mempoolreplacement")) {
// Minimal effort at forwards compatibility
std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible
std::vector<std::string> vstrReplacementModes;
boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(","));
fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end());
}
// ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log, seed insecure_rand()
// Initialize fast PRNG
seed_insecure_rand(false);
// Initialize elliptic curve code
ECC_Start();
globalVerifyHandle.reset(new ECCVerifyHandle());
// Sanity check
if (!InitSanityCheck())
return InitError(_("Initialization sanity check failed. RareShares Core is shutting down."));
std::string strDataDir = GetDataDir().string();
#ifdef ENABLE_WALLET
// Wallet file must be a plain filename without a directory
if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile))
return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
#endif
// Make sure only a single RareShares Core process is using the data directory.
boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
try {
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
// Wait maximum 10 seconds if an old wallet is still running. Avoids lockup during restart
if (!lock.timed_lock(boost::get_system_time() + boost::posix_time::seconds(10)))
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. RareShares Core is probably already running."), strDataDir));
} catch(const boost::interprocess::interprocess_exception& e) {
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. RareShares Core is probably already running.") + " %s.", strDataDir, e.what()));
}
#ifndef WIN32
CreatePidFile(GetPidFile(), getpid());
#endif
if (GetBoolArg("-shrinkdebugfile", !fDebug))
ShrinkDebugFile();
if (fPrintToDebugLog)
OpenDebugLog();
#ifdef ENABLE_WALLET
LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
#endif
if (!fLogTimestamps)
LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
LogPrintf("Using data directory %s\n", strDataDir);
LogPrintf("Using config file %s\n", GetConfigFile().string());
LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
std::ostringstream strErrors;
LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
if (nScriptCheckThreads) {
for (int i=0; i<nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
}
if (mapArgs.count("-sporkkey")) // spork priv key
{
if (!sporkManager.SetPrivKey(GetArg("-sporkkey", "")))
return InitError(_("Unable to sign spork message, wrong key?"));
}
// Start the lightweight task scheduler thread
CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
/* Start the RPC server already. It will be started in "warmup" mode
* and not really process calls already (but it will signify connections
* that the server is there and will be ready later). Warmup mode will
* be disabled when initialisation is finished.
*/
if (fServer)
{
uiInterface.InitMessage.connect(SetRPCWarmupStatus);
if (!AppInitServers(threadGroup))
return InitError(_("Unable to start HTTP server. See debug log for details."));
}
int64_t nStart;
// ********************************************************* Step 5: Backup wallet and verify wallet database integrity
#ifdef ENABLE_WALLET
if (!fDisableWallet) {
std::string strWarning;
std::string strError;
nWalletBackups = GetArg("-createwalletbackups", 10);
nWalletBackups = std::max(0, std::min(10, nWalletBackups));
if(!AutoBackupWallet(NULL, strWalletFile, strWarning, strError)) {
if (!strWarning.empty())
InitWarning(strWarning);
if (!strError.empty())
return InitError(strError);
}
LogPrintf("Using wallet %s\n", strWalletFile);
uiInterface.InitMessage(_("Verifying wallet..."));
// reset warning string
strWarning = "";
if (!CWallet::Verify(strWalletFile, strWarning, strError))
return false;
if (!strWarning.empty())
InitWarning(strWarning);
if (!strError.empty())
return InitError(strError);
// Initialize KeePass Integration
keePassInt.init();
} // (!fDisableWallet)
#endif // ENABLE_WALLET
// ********************************************************* Step 6: network initialization
RegisterNodeSignals(GetNodeSignals());
// sanitize comments per BIP-0014, format user agent and check total size
std::vector<string> uacomments;
BOOST_FOREACH(string cmt, mapMultiArgs["-uacomment"])
{
if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
uacomments.push_back(SanitizeString(cmt, SAFE_CHARS_UA_COMMENT));
}
strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
strSubVersion.size(), MAX_SUBVERSION_LENGTH));
}
if (mapArgs.count("-onlynet")) {
std::set<enum Network> nets;
BOOST_FOREACH(const std::string& snet, mapMultiArgs["-onlynet"]) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
nets.insert(net);
}
for (int n = 0; n < NET_MAX; n++) {
enum Network net = (enum Network)n;
if (!nets.count(net))
SetLimited(net);
}
}
if (mapArgs.count("-whitelist")) {
BOOST_FOREACH(const std::string& net, mapMultiArgs["-whitelist"]) {
CSubNet subnet(net);
if (!subnet.IsValid())
return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
CNode::AddWhitelistedRange(subnet);
}
}
bool proxyRandomize = GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE);
// -proxy sets a proxy for all outgoing network traffic
// -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
std::string proxyArg = GetArg("-proxy", "");
SetLimited(NET_TOR);
if (proxyArg != "" && proxyArg != "0") {
proxyType addrProxy = proxyType(CService(proxyArg, 9050), proxyRandomize);
if (!addrProxy.IsValid())
return InitError(strprintf(_("Invalid -proxy address: '%s'"), proxyArg));
SetProxy(NET_IPV4, addrProxy);
SetProxy(NET_IPV6, addrProxy);
SetProxy(NET_TOR, addrProxy);
SetNameProxy(addrProxy);
SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
}
// -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
// -noonion (or -onion=0) disables connecting to .onion entirely
// An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
std::string onionArg = GetArg("-onion", "");
if (onionArg != "") {
if (onionArg == "0") { // Handle -noonion/-onion=0
SetLimited(NET_TOR); // set onions as unreachable
} else {
proxyType addrOnion = proxyType(CService(onionArg, 9050), proxyRandomize);
if (!addrOnion.IsValid())
return InitError(strprintf(_("Invalid -onion address: '%s'"), onionArg));
SetProxy(NET_TOR, addrOnion);
SetLimited(NET_TOR, false);
}
}
// see Step 2: parameter interactions for more information about these
fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
fDiscover = GetBoolArg("-discover", true);
fNameLookup = GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
bool fBound = false;
if (fListen) {
if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-bind"]) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind));
fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
}
BOOST_FOREACH(const std::string& strBind, mapMultiArgs["-whitebind"]) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, 0, false))
return InitError(strprintf(_("Cannot resolve -whitebind address: '%s'"), strBind));
if (addrBind.GetPort() == 0)
return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
}
}
else {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE);
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
}
if (!fBound)
return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
}
if (mapArgs.count("-externalip")) {
BOOST_FOREACH(const std::string& strAddr, mapMultiArgs["-externalip"]) {
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
if (!addrLocal.IsValid())
return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr));
AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
}
}
BOOST_FOREACH(const std::string& strDest, mapMultiArgs["-seednode"])
AddOneShot(strDest);
#if ENABLE_ZMQ
pzmqNotificationInterface = CZMQNotificationInterface::CreateWithArguments(mapArgs);
if (pzmqNotificationInterface) {
RegisterValidationInterface(pzmqNotificationInterface);
}
#endif
pdsNotificationInterface = new CDSNotificationInterface();
RegisterValidationInterface(pdsNotificationInterface);
if (mapArgs.count("-maxuploadtarget")) {
CNode::SetMaxOutboundTarget(GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024);
}
// ********************************************************* Step 7: load block chain
fReindex = GetBoolArg("-reindex", false);
// Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/
boost::filesystem::path blocksDir = GetDataDir() / "blocks";
if (!boost::filesystem::exists(blocksDir))
{
boost::filesystem::create_directories(blocksDir);
bool linked = false;
for (unsigned int i = 1; i < 10000; i++) {
boost::filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i);
if (!boost::filesystem::exists(source)) break;
boost::filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1);
try {
boost::filesystem::create_hard_link(source, dest);
LogPrintf("Hardlinked %s -> %s\n", source.string(), dest.string());
linked = true;
} catch (const boost::filesystem::filesystem_error& e) {
// Note: hardlink creation failing is not a disaster, it just means
// blocks will get re-downloaded from peers.
LogPrintf("Error hardlinking blk%04u.dat: %s\n", i, e.what());
break;
}
}
if (linked)
{
fReindex = true;
}
}
// cache size calculations
int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache
nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greated than nMaxDbcache
int64_t nBlockTreeDBCache = nTotalCache / 8;
if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", DEFAULT_TXINDEX))
nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
nTotalCache -= nBlockTreeDBCache;
int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache
nTotalCache -= nCoinDBCache;
nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache
LogPrintf("Cache configuration:\n");
LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024));
LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024));
LogPrintf("* Using %.1fMiB for in-memory UTXO set\n", nCoinCacheUsage * (1.0 / 1024 / 1024));
bool fLoaded = false;
while (!fLoaded) {
bool fReset = fReindex;
std::string strLoadError;
uiInterface.InitMessage(_("Loading block index..."));
nStart = GetTimeMillis();
do {
try {
UnloadBlockIndex();
delete pcoinsTip;
delete pcoinsdbview;
delete pcoinscatcher;
delete pblocktree;
pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
pcoinsTip = new CCoinsViewCache(pcoinscatcher);
if (fReindex) {
pblocktree->WriteReindexing(true);
//If we're reindexing in prune mode, wipe away unusable block files and all undo data files
if (fPruneMode)
CleanupBlockRevFiles();
}
if (!LoadBlockIndex()) {
strLoadError = _("Error loading block database");
break;
}
// If the loaded chain has a wrong genesis, bail out immediately
// (we're likely using a testnet datadir, or the other way around).
if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0)
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
// Initialize the block index (no-op if non-empty database was already loaded)
if (!InitBlockIndex(chainparams)) {
strLoadError = _("Error initializing block database");
break;
}
// Check for changed -txindex state
if (fTxIndex != GetBoolArg("-txindex", DEFAULT_TXINDEX)) {
strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
break;
}
// Check for changed -prune state. What we are concerned about is a user who has pruned blocks
// in the past, but is now trying to run unpruned.
if (fHavePruned && !fPruneMode) {
strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain");
break;
}
uiInterface.InitMessage(_("Verifying blocks..."));
if (fHavePruned && GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) {
LogPrintf("Prune: pruned datadir may not have more than %d blocks; -checkblocks=%d may fail\n",
MIN_BLOCKS_TO_KEEP, GetArg("-checkblocks", DEFAULT_CHECKBLOCKS));
}
{
LOCK(cs_main);
CBlockIndex* tip = chainActive.Tip();
if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
strLoadError = _("The block database contains a block which appears to be from the future. "
"This may be due to your computer's date and time being set incorrectly. "
"Only rebuild the block database if you are sure that your computer's date and time are correct");
break;
}
}
if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, GetArg("-checklevel", DEFAULT_CHECKLEVEL),
GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) {
strLoadError = _("Corrupted block database detected");
break;
}
} catch (const std::exception& e) {
if (fDebug) LogPrintf("%s\n", e.what());
strLoadError = _("Error opening block database");
break;
}
fLoaded = true;
} while(false);
if (!fLoaded) {
// first suggest a reindex
if (!fReset) {
bool fRet = uiInterface.ThreadSafeMessageBox(
strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
"", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
if (fRet) {
fReindex = true;
fRequestShutdown = false;
} else {
LogPrintf("Aborted block database rebuild. Exiting.\n");
return false;
}
} else {
return InitError(strLoadError);
}
}
}
// As LoadBlockIndex can take several minutes, it's possible the user
// requested to kill the GUI during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (fRequestShutdown)
{
LogPrintf("Shutdown requested. Exiting.\n");
return false;
}
LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
// Allowed to fail as this file IS missing on first startup.
if (!est_filein.IsNull())
mempool.ReadFeeEstimates(est_filein);
fFeeEstimatesInitialized = true;
// ********************************************************* Step 8: load wallet
#ifdef ENABLE_WALLET
if (fDisableWallet) {
pwalletMain = NULL;
LogPrintf("Wallet disabled!\n");
} else {
// needed to restore wallet transaction meta data after -zapwallettxes
std::vector<CWalletTx> vWtx;
if (GetBoolArg("-zapwallettxes", false)) {
uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
pwalletMain = new CWallet(strWalletFile);
DBErrors nZapWalletRet = pwalletMain->ZapWalletTx(vWtx);
if (nZapWalletRet != DB_LOAD_OK) {
uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
return false;
}
delete pwalletMain;
pwalletMain = NULL;
}
uiInterface.InitMessage(_("Loading wallet..."));
nStart = GetTimeMillis();
bool fFirstRun = true;
pwalletMain = new CWallet(strWalletFile);
DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT)
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
InitWarning(_("Error reading wallet.dat! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."));
}
else if (nLoadWalletRet == DB_TOO_NEW)
strErrors << _("Error loading wallet.dat: Wallet requires newer version of RareShares Core") << "\n";
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
strErrors << _("Wallet needed to be rewritten: restart RareShares Core to complete") << "\n";
LogPrintf("%s", strErrors.str());
return InitError(strErrors.str());
}
else
strErrors << _("Error loading wallet.dat") << "\n";
}
if (GetBoolArg("-upgradewallet", fFirstRun))
{
int nMaxVersion = GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
}
else
LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < pwalletMain->GetVersion())
strErrors << _("Cannot downgrade wallet") << "\n";
pwalletMain->SetMaxVersion(nMaxVersion);
}
if (fFirstRun)
{
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (pwalletMain->GetKeyFromPool(newDefaultKey)) {
pwalletMain->SetDefaultKey(newDefaultKey);
if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive"))
strErrors << _("Cannot write default address") << "\n";
}
pwalletMain->SetBestChain(chainActive.GetLocator());
// Try to create wallet backup right after new wallet was created
std::string strBackupWarning;
std::string strBackupError;
if(!AutoBackupWallet(pwalletMain, "", strBackupWarning, strBackupError)) {
if (!strBackupWarning.empty())
InitWarning(strBackupWarning);
if (!strBackupError.empty())
return InitError(strBackupError);
}
}
LogPrintf("%s", strErrors.str());
LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
RegisterValidationInterface(pwalletMain);
CBlockIndex *pindexRescan = chainActive.Tip();
if (GetBoolArg("-rescan", false))
pindexRescan = chainActive.Genesis();
else
{
CWalletDB walletdb(strWalletFile);
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = FindForkInGlobalIndex(chainActive, locator);
else
pindexRescan = chainActive.Genesis();
}
if (chainActive.Tip() && chainActive.Tip() != pindexRescan)
{
//We can't rescan beyond non-pruned blocks, stop and throw an error
//this might happen if a user uses a old wallet within a pruned node
// or if he ran -disablewallet for a longer time, then decided to re-enable
if (fPruneMode)
{
CBlockIndex *block = chainActive.Tip();
while (block && block->pprev && (block->pprev->nStatus & BLOCK_HAVE_DATA) && block->pprev->nTx > 0 && pindexRescan != block)
block = block->pprev;
if (pindexRescan != block)
return InitError(_("Prune: last wallet synchronisation goes beyond pruned data. You need to -reindex (download the whole blockchain again in case of pruned node)"));
}
uiInterface.InitMessage(_("Rescanning..."));
LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
pwalletMain->SetBestChain(chainActive.GetLocator());
nWalletDBUpdated++;
// Restore wallet transaction metadata after -zapwallettxes=1
if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2")
{
CWalletDB walletdb(strWalletFile);
BOOST_FOREACH(const CWalletTx& wtxOld, vWtx)
{
uint256 hash = wtxOld.GetHash();
std::map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
if (mi != pwalletMain->mapWallet.end())
{
const CWalletTx* copyFrom = &wtxOld;
CWalletTx* copyTo = &mi->second;
copyTo->mapValue = copyFrom->mapValue;
copyTo->vOrderForm = copyFrom->vOrderForm;
copyTo->nTimeReceived = copyFrom->nTimeReceived;
copyTo->nTimeSmart = copyFrom->nTimeSmart;
copyTo->fFromMe = copyFrom->fFromMe;
copyTo->strFromAccount = copyFrom->strFromAccount;
copyTo->nOrderPos = copyFrom->nOrderPos;
copyTo->WriteToDisk(&walletdb);
}
}
}
}
pwalletMain->SetBroadcastTransactions(GetBoolArg("-walletbroadcast", DEFAULT_WALLETBROADCAST));
} // (!fDisableWallet)
#else // ENABLE_WALLET
LogPrintf("No wallet support compiled in!\n");
#endif // !ENABLE_WALLET
// ********************************************************* Step 9: data directory maintenance
// if pruning, unset the service bit and perform the initial blockstore prune
// after any wallet rescanning has taken place.
if (fPruneMode) {
LogPrintf("Unsetting NODE_NETWORK on prune mode\n");
nLocalServices &= ~NODE_NETWORK;
if (!fReindex) {
uiInterface.InitMessage(_("Pruning blockstore..."));
PruneAndFlush();
}
}
// ********************************************************* Step 10: import blocks
if (mapArgs.count("-blocknotify"))
uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
uiInterface.InitMessage(_("Activating best chain..."));
// scan for better chains in the block chain database, that are not yet connected in the active best chain
CValidationState state;
if (!ActivateBestChain(state, chainparams))
strErrors << "Failed to connect best block";
std::vector<boost::filesystem::path> vImportFiles;
if (mapArgs.count("-loadblock"))
{
BOOST_FOREACH(const std::string& strFile, mapMultiArgs["-loadblock"])
vImportFiles.push_back(strFile);
}
threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
if (chainActive.Tip() == NULL) {
LogPrintf("Waiting for genesis block to be imported...\n");
while (!fRequestShutdown && chainActive.Tip() == NULL)
MilliSleep(10);
}
// ********************************************************* Step 11a: setup PrivateSend
fMasterNode = GetBoolArg("-masternode", false);
if((fMasterNode || masternodeConfig.getCount() > -1) && fTxIndex == false) {
return InitError("Enabling Masternode support requires turning on transaction indexing."
"Please add txindex=1 to your configuration and start with -reindex");
}
if(fMasterNode) {
LogPrintf("MASTERNODE:\n");
if(!GetArg("-masternodeaddr", "").empty()) {
// Hot masternode (either local or remote) should get its address in
// CActiveMasternode::ManageState() automatically and no longer relies on masternodeaddr.
return InitError(_("masternodeaddr option is deprecated. Please use masternode.conf to manage your remote masternodes."));
}
std::string strMasterNodePrivKey = GetArg("-masternodeprivkey", "");
if(!strMasterNodePrivKey.empty()) {
if(!darkSendSigner.GetKeysFromSecret(strMasterNodePrivKey, activeMasternode.keyMasternode, activeMasternode.pubKeyMasternode))
return InitError(_("Invalid masternodeprivkey. Please see documenation."));
LogPrintf(" pubKeyMasternode: %s\n", CBitcoinAddress(activeMasternode.pubKeyMasternode.GetID()).ToString());
} else {
return InitError(_("You must specify a masternodeprivkey in the configuration. Please see documentation for help."));
}
}
LogPrintf("Using masternode config file %s\n", GetMasternodeConfigFile().string());
if(GetBoolArg("-mnconflock", true) && pwalletMain && (masternodeConfig.getCount() > 0)) {
LOCK(pwalletMain->cs_wallet);
LogPrintf("Locking Masternodes:\n");
uint256 mnTxHash;
int outputIndex;
BOOST_FOREACH(CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) {
mnTxHash.SetHex(mne.getTxHash());
outputIndex = boost::lexical_cast<unsigned int>(mne.getOutputIndex());
COutPoint outpoint = COutPoint(mnTxHash, outputIndex);
// don't lock non-spendable outpoint (i.e. it's already spent or it's not from this wallet at all)
if(pwalletMain->IsMine(CTxIn(outpoint)) != ISMINE_SPENDABLE) {
LogPrintf(" %s %s - IS NOT SPENDABLE, was not locked\n", mne.getTxHash(), mne.getOutputIndex());
continue;
}
pwalletMain->LockCoin(outpoint);
LogPrintf(" %s %s - locked successfully\n", mne.getTxHash(), mne.getOutputIndex());
}
}
nLiquidityProvider = GetArg("-liquidityprovider", nLiquidityProvider);
nLiquidityProvider = std::min(std::max(nLiquidityProvider, 0), 100);
darkSendPool.SetMinBlockSpacing(nLiquidityProvider * 15);
fEnablePrivateSend = GetBoolArg("-enableprivatesend", 0);
fPrivateSendMultiSession = GetBoolArg("-privatesendmultisession", DEFAULT_PRIVATESEND_MULTISESSION);
nPrivateSendRounds = GetArg("-privatesendrounds", DEFAULT_PRIVATESEND_ROUNDS);
nPrivateSendRounds = std::min(std::max(nPrivateSendRounds, 2), nLiquidityProvider ? 99999 : 16);
nPrivateSendAmount = GetArg("-privatesendamount", DEFAULT_PRIVATESEND_AMOUNT);
nPrivateSendAmount = std::min(std::max(nPrivateSendAmount, 2), 999999);
fEnableInstantSend = GetBoolArg("-enableinstantsend", 1);
nInstantSendDepth = GetArg("-instantsenddepth", DEFAULT_INSTANTSEND_DEPTH);
nInstantSendDepth = std::min(std::max(nInstantSendDepth, 0), 60);
//lite mode disables all Masternode and Darksend related functionality
fLiteMode = GetBoolArg("-litemode", false);
if(fMasterNode && fLiteMode){
return InitError("You can not start a masternode in litemode");
}
LogPrintf("fLiteMode %d\n", fLiteMode);
LogPrintf("nInstantSendDepth %d\n", nInstantSendDepth);
LogPrintf("PrivateSend rounds %d\n", nPrivateSendRounds);
LogPrintf("PrivateSend amount %d\n", nPrivateSendAmount);
darkSendPool.InitDenominations();
// ********************************************************* Step 11b: Load cache data
// LOAD SERIALIZED DAT FILES INTO DATA CACHES FOR INTERNAL USE
uiInterface.InitMessage(_("Loading masternode cache..."));
CFlatDB<CMasternodeMan> flatdb1("mncache.dat", "magicMasternodeCache");
if(!flatdb1.Load(mnodeman)) {
return InitError("Failed to load masternode cache from mncache.dat");
}
if(mnodeman.size()) {
uiInterface.InitMessage(_("Loading masternode payment cache..."));
CFlatDB<CMasternodePayments> flatdb2("mnpayments.dat", "magicMasternodePaymentsCache");
if(!flatdb2.Load(mnpayments)) {
return InitError("Failed to load masternode payments cache from mnpayments.dat");
}
uiInterface.InitMessage(_("Loading governance cache..."));
CFlatDB<CGovernanceManager> flatdb3("governance.dat", "magicGovernanceCache");
if(!flatdb3.Load(governance)) {
return InitError("Failed to load governance cache from governance.dat");
}
governance.InitOnLoad();
} else {
uiInterface.InitMessage(_("Masternode cache is empty, skipping payments and governance cache..."));
}
uiInterface.InitMessage(_("Loading fulfilled requests cache..."));
CFlatDB<CNetFulfilledRequestManager> flatdb4("netfulfilled.dat", "magicFulfilledCache");
if(!flatdb4.Load(netfulfilledman)) {
return InitError("Failed to load fulfilled requests cache from netfulfilled.dat");
}
// ********************************************************* Step 11c: update block tip in RareShares modules
// force UpdatedBlockTip to initialize pCurrentBlockIndex for DS, MN payments and budgets
// but don't call it directly to prevent triggering of other listeners like zmq etc.
// GetMainSignals().UpdatedBlockTip(chainActive.Tip());
mnodeman.UpdatedBlockTip(chainActive.Tip());
darkSendPool.UpdatedBlockTip(chainActive.Tip());
mnpayments.UpdatedBlockTip(chainActive.Tip());
masternodeSync.UpdatedBlockTip(chainActive.Tip());
governance.UpdatedBlockTip(chainActive.Tip());
// ********************************************************* Step 11d: start rareshares-privatesend thread
threadGroup.create_thread(boost::bind(&ThreadCheckDarkSendPool));
// ********************************************************* Step 12: start node
if (!CheckDiskSpace())
return false;
if (!strErrors.str().empty())
return InitError(strErrors.str());
RandAddSeedPerfmon();
//// debug print
LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
LogPrintf("chainActive.Height() = %d\n", chainActive.Height());
#ifdef ENABLE_WALLET
LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
#endif
if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
StartTorControl(threadGroup, scheduler);
StartNode(threadGroup, scheduler);
// Monitor the chain, and alert if we get blocks much quicker or slower than expected
// The "bad chain alert" scheduler has been disabled because the current system gives far
// too many false positives, such that users are starting to ignore them.
// This code will be disabled for 0.12.1 while a fix is deliberated in #7568
// this was discussed in the IRC meeting on 2016-03-31.
//
// --- disabled ---
//int64_t nPowTargetSpacing = Params().GetConsensus().nPowTargetSpacing;
//CScheduler::Function f = boost::bind(&PartitionCheck, &IsInitialBlockDownload,
// boost::ref(cs_main), boost::cref(pindexBestHeader), nPowTargetSpacing);
//scheduler.scheduleEvery(f, nPowTargetSpacing);
// --- end disabled ---
// Generate coins in the background
GenerateBitcoins(GetBoolArg("-gen", DEFAULT_GENERATE), GetArg("-genproclimit", DEFAULT_GENERATE_THREADS), chainparams);
// ********************************************************* Step 13: finished
SetRPCWarmupFinished();
uiInterface.InitMessage(_("Done loading"));
#ifdef ENABLE_WALLET
if (pwalletMain) {
// Add wallet transactions that aren't already in a block to mapTransactions
pwalletMain->ReacceptWalletTransactions();
// Run a thread to flush wallet periodically
threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
}
#endif
threadGroup.create_thread(boost::bind(&ThreadSendAlert));
return !fRequestShutdown;
}
|
dnl ARM64 mpn_add_n and mpn_sub_n
dnl Contributed to the GNU project by Torbjörn Granlund.
dnl Copyright 2013, 2017 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of either:
dnl
dnl * the GNU Lesser General Public License as published by the Free
dnl Software Foundation; either version 3 of the License, or (at your
dnl option) any later version.
dnl
dnl or
dnl
dnl * the GNU General Public License as published by the Free Software
dnl Foundation; either version 2 of the License, or (at your option) any
dnl later version.
dnl
dnl or both in parallel, as here.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
dnl for more details.
dnl
dnl You should have received copies of the GNU General Public License and the
dnl GNU Lesser General Public License along with the GNU MP Library. If not,
dnl see https://www.gnu.org/licenses/.
include(`../config.m4')
C cycles/limb
C Cortex-A53 2.75-3.25
C Cortex-A57 1.5
C X-Gene 2.0
changecom(blah)
define(`rp', `x0')
define(`up', `x1')
define(`vp', `x2')
define(`n', `x3')
ifdef(`OPERATION_add_n', `
define(`ADDSUBC', adcs)
define(`CLRCY', `cmn xzr, xzr')
define(`SETCY', `cmp $1, #1')
define(`RETVAL', `cset x0, cs')
define(`func_n', mpn_add_n)
define(`func_nc', mpn_add_nc)')
ifdef(`OPERATION_sub_n', `
define(`ADDSUBC', sbcs)
define(`CLRCY', `cmp xzr, xzr')
define(`SETCY', `cmp xzr, $1')
define(`RETVAL', `cset x0, cc')
define(`func_n', mpn_sub_n)
define(`func_nc', mpn_sub_nc)')
MULFUNC_PROLOGUE(mpn_add_n mpn_add_nc mpn_sub_n mpn_sub_nc)
ASM_START()
PROLOGUE(func_nc)
SETCY( x4)
b L(ent)
EPILOGUE()
PROLOGUE(func_n)
CLRCY
L(ent): lsr x18, n, #2
tbz n, #0, L(bx0)
L(bx1): ldr x7, [up]
ldr x11, [vp]
ADDSUBC x13, x7, x11
str x13, [rp],#8
tbnz n, #1, L(b11)
L(b01): cbz x18, L(ret)
ldp x4, x5, [up,#8]
ldp x8, x9, [vp,#8]
sub up, up, #8
sub vp, vp, #8
b L(mid)
L(b11): ldp x6, x7, [up,#8]
ldp x10, x11, [vp,#8]
add up, up, #8
add vp, vp, #8
cbz x18, L(end)
b L(top)
L(bx0): tbnz n, #1, L(b10)
L(b00): ldp x4, x5, [up]
ldp x8, x9, [vp]
sub up, up, #16
sub vp, vp, #16
b L(mid)
L(b10): ldp x6, x7, [up]
ldp x10, x11, [vp]
cbz x18, L(end)
ALIGN(16)
L(top): ldp x4, x5, [up,#16]
ldp x8, x9, [vp,#16]
ADDSUBC x12, x6, x10
ADDSUBC x13, x7, x11
stp x12, x13, [rp],#16
L(mid): ldp x6, x7, [up,#32]!
ldp x10, x11, [vp,#32]!
ADDSUBC x12, x4, x8
ADDSUBC x13, x5, x9
stp x12, x13, [rp],#16
sub x18, x18, #1
cbnz x18, L(top)
L(end): ADDSUBC x12, x6, x10
ADDSUBC x13, x7, x11
stp x12, x13, [rp]
L(ret): RETVAL
ret
EPILOGUE()
|
// ======================================================================== //
// Copyright 2009-2018 Intel Corporation //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ======================================================================== //
#include "subdivpatch1base.h"
namespace embree
{
namespace isa
{
Vec3fa patchEval(const SubdivPatch1Base& patch, const float uu, const float vv)
{
if (likely(patch.type == SubdivPatch1Base::BEZIER_PATCH))
return ((BezierPatch3fa*)patch.patch_v)->eval(uu,vv);
else if (likely(patch.type == SubdivPatch1Base::BSPLINE_PATCH))
return ((BSplinePatch3fa*)patch.patch_v)->eval(uu,vv);
else if (likely(patch.type == SubdivPatch1Base::GREGORY_PATCH))
return ((DenseGregoryPatch3fa*)patch.patch_v)->eval(uu,vv);
else if (likely(patch.type == SubdivPatch1Base::BILINEAR_PATCH))
return ((BilinearPatch3fa*)patch.patch_v)->eval(uu,vv);
return Vec3fa( zero );
}
Vec3fa patchNormal(const SubdivPatch1Base& patch, const float uu, const float vv)
{
if (likely(patch.type == SubdivPatch1Base::BEZIER_PATCH))
return ((BezierPatch3fa*)patch.patch_v)->normal(uu,vv);
else if (likely(patch.type == SubdivPatch1Base::BSPLINE_PATCH))
return ((BSplinePatch3fa*)patch.patch_v)->normal(uu,vv);
else if (likely(patch.type == SubdivPatch1Base::GREGORY_PATCH))
return ((DenseGregoryPatch3fa*)patch.patch_v)->normal(uu,vv);
else if (likely(patch.type == SubdivPatch1Base::BILINEAR_PATCH))
return ((BilinearPatch3fa*)patch.patch_v)->normal(uu,vv);
return Vec3fa( zero );
}
template<typename simdf>
Vec3<simdf> patchEval(const SubdivPatch1Base& patch, const simdf& uu, const simdf& vv)
{
if (likely(patch.type == SubdivPatch1Base::BEZIER_PATCH))
return ((BezierPatch3fa*)patch.patch_v)->eval(uu,vv);
else if (likely(patch.type == SubdivPatch1Base::BSPLINE_PATCH))
return ((BSplinePatch3fa*)patch.patch_v)->eval(uu,vv);
else if (likely(patch.type == SubdivPatch1Base::GREGORY_PATCH))
return ((DenseGregoryPatch3fa*)patch.patch_v)->eval(uu,vv);
else if (likely(patch.type == SubdivPatch1Base::BILINEAR_PATCH))
return ((BilinearPatch3fa*)patch.patch_v)->eval(uu,vv);
return Vec3<simdf>( zero );
}
template<typename simdf>
Vec3<simdf> patchNormal(const SubdivPatch1Base& patch, const simdf& uu, const simdf& vv)
{
if (likely(patch.type == SubdivPatch1Base::BEZIER_PATCH))
return ((BezierPatch3fa*)patch.patch_v)->normal(uu,vv);
else if (likely(patch.type == SubdivPatch1Base::BSPLINE_PATCH))
return ((BSplinePatch3fa*)patch.patch_v)->normal(uu,vv);
else if (likely(patch.type == SubdivPatch1Base::GREGORY_PATCH))
return ((DenseGregoryPatch3fa*)patch.patch_v)->normal(uu,vv);
else if (likely(patch.type == SubdivPatch1Base::BILINEAR_PATCH))
return ((BilinearPatch3fa*)patch.patch_v)->normal(uu,vv);
return Vec3<simdf>( zero );
}
/* eval grid over patch and stich edges when required */
void evalGrid(const SubdivPatch1Base& patch,
const unsigned x0, const unsigned x1,
const unsigned y0, const unsigned y1,
const unsigned swidth, const unsigned sheight,
float *__restrict__ const grid_x,
float *__restrict__ const grid_y,
float *__restrict__ const grid_z,
float *__restrict__ const grid_u,
float *__restrict__ const grid_v,
const SubdivMesh* const geom)
{
const unsigned dwidth = x1-x0+1;
const unsigned dheight = y1-y0+1;
const unsigned M = dwidth*dheight+VSIZEX;
const unsigned grid_size_simd_blocks = (M-1)/VSIZEX;
if (unlikely(patch.type == SubdivPatch1Base::EVAL_PATCH))
{
const bool displ = geom->displFunc;
const unsigned N = displ ? M : 0;
dynamic_large_stack_array(float,grid_Ng_x,N,32*32*sizeof(float));
dynamic_large_stack_array(float,grid_Ng_y,N,32*32*sizeof(float));
dynamic_large_stack_array(float,grid_Ng_z,N,32*32*sizeof(float));
if (geom->patch_eval_trees.size())
{
feature_adaptive_eval_grid<PatchEvalGrid>
(geom->patch_eval_trees[geom->numTimeSteps*patch.primID()+patch.time()], patch.subPatch(), patch.needsStitching() ? patch.level : nullptr,
x0,x1,y0,y1,swidth,sheight,
grid_x,grid_y,grid_z,grid_u,grid_v,
displ ? (float*)grid_Ng_x : nullptr, displ ? (float*)grid_Ng_y : nullptr, displ ? (float*)grid_Ng_z : nullptr,
dwidth,dheight);
}
else
{
GeneralCatmullClarkPatch3fa ccpatch(patch.edge(),geom->getVertexBuffer(patch.time()));
feature_adaptive_eval_grid<FeatureAdaptiveEvalGrid,GeneralCatmullClarkPatch3fa>
(ccpatch, patch.subPatch(), patch.needsStitching() ? patch.level : nullptr,
x0,x1,y0,y1,swidth,sheight,
grid_x,grid_y,grid_z,grid_u,grid_v,
displ ? (float*)grid_Ng_x : nullptr, displ ? (float*)grid_Ng_y : nullptr, displ ? (float*)grid_Ng_z : nullptr,
dwidth,dheight);
}
/* convert sub-patch UVs to patch UVs*/
const Vec2f uv0 = patch.getUV(0);
const Vec2f uv1 = patch.getUV(1);
const Vec2f uv2 = patch.getUV(2);
const Vec2f uv3 = patch.getUV(3);
for (unsigned i=0; i<grid_size_simd_blocks; i++)
{
const vfloatx u = vfloatx::load(&grid_u[i*VSIZEX]);
const vfloatx v = vfloatx::load(&grid_v[i*VSIZEX]);
const vfloatx patch_u = lerp2(uv0.x,uv1.x,uv3.x,uv2.x,u,v);
const vfloatx patch_v = lerp2(uv0.y,uv1.y,uv3.y,uv2.y,u,v);
vfloatx::store(&grid_u[i*VSIZEX],patch_u);
vfloatx::store(&grid_v[i*VSIZEX],patch_v);
}
/* call displacement shader */
if (unlikely(geom->displFunc)) {
RTCDisplacementFunctionNArguments args;
args.geometryUserPtr = geom->userPtr;
args.geometry = (RTCGeometry)geom;
//args.geomID = patch.geomID();
args.primID = patch.primID();
args.timeStep = patch.time();
args.u = grid_u;
args.v = grid_v;
args.Ng_x = grid_Ng_x;
args.Ng_y = grid_Ng_y;
args.Ng_z = grid_Ng_z;
args.P_x = grid_x;
args.P_y = grid_y;
args.P_z = grid_z;
args.N = dwidth*dheight;
geom->displFunc(&args);
}
/* set last elements in u,v array to 1.0f */
const float last_u = grid_u[dwidth*dheight-1];
const float last_v = grid_v[dwidth*dheight-1];
const float last_x = grid_x[dwidth*dheight-1];
const float last_y = grid_y[dwidth*dheight-1];
const float last_z = grid_z[dwidth*dheight-1];
for (unsigned i=dwidth*dheight;i<grid_size_simd_blocks*VSIZEX;i++)
{
grid_u[i] = last_u;
grid_v[i] = last_v;
grid_x[i] = last_x;
grid_y[i] = last_y;
grid_z[i] = last_z;
}
}
else
{
/* grid_u, grid_v need to be padded as we write with SIMD granularity */
gridUVTessellator(patch.level,swidth,sheight,x0,y0,dwidth,dheight,grid_u,grid_v);
/* set last elements in u,v array to last valid point */
const float last_u = grid_u[dwidth*dheight-1];
const float last_v = grid_v[dwidth*dheight-1];
for (unsigned i=dwidth*dheight;i<grid_size_simd_blocks*VSIZEX;i++) {
grid_u[i] = last_u;
grid_v[i] = last_v;
}
/* stitch edges if necessary */
if (unlikely(patch.needsStitching()))
stitchUVGrid(patch.level,swidth,sheight,x0,y0,dwidth,dheight,grid_u,grid_v);
/* iterates over all grid points */
for (unsigned i=0; i<grid_size_simd_blocks; i++)
{
const vfloatx u = vfloatx::load(&grid_u[i*VSIZEX]);
const vfloatx v = vfloatx::load(&grid_v[i*VSIZEX]);
Vec3vfx vtx = patchEval(patch,u,v);
/* evaluate displacement function */
if (unlikely(geom->displFunc != nullptr))
{
const Vec3vfx normal = normalize_safe(patchNormal(patch, u, v));
RTCDisplacementFunctionNArguments args;
args.geometryUserPtr = geom->userPtr;
args.geometry = (RTCGeometry)geom;
//args.geomID = patch.geomID();
args.primID = patch.primID();
args.timeStep = patch.time();
args.u = &u[0];
args.v = &v[0];
args.Ng_x = &normal.x[0];
args.Ng_y = &normal.y[0];
args.Ng_z = &normal.z[0];
args.P_x = &vtx.x[0];
args.P_y = &vtx.y[0];
args.P_z = &vtx.z[0];
args.N = VSIZEX;
geom->displFunc(&args);
}
vfloatx::store(&grid_x[i*VSIZEX],vtx.x);
vfloatx::store(&grid_y[i*VSIZEX],vtx.y);
vfloatx::store(&grid_z[i*VSIZEX],vtx.z);
}
}
}
/* eval grid over patch and stich edges when required */
BBox3fa evalGridBounds(const SubdivPatch1Base& patch,
const unsigned x0, const unsigned x1,
const unsigned y0, const unsigned y1,
const unsigned swidth, const unsigned sheight,
const SubdivMesh* const geom)
{
BBox3fa b(empty);
const unsigned dwidth = x1-x0+1;
const unsigned dheight = y1-y0+1;
const unsigned M = dwidth*dheight+VSIZEX;
const unsigned grid_size_simd_blocks = (M-1)/VSIZEX;
dynamic_large_stack_array(float,grid_u,M,64*64*sizeof(float));
dynamic_large_stack_array(float,grid_v,M,64*64*sizeof(float));
if (unlikely(patch.type == SubdivPatch1Base::EVAL_PATCH))
{
const bool displ = geom->displFunc;
dynamic_large_stack_array(float,grid_x,M,64*64*sizeof(float));
dynamic_large_stack_array(float,grid_y,M,64*64*sizeof(float));
dynamic_large_stack_array(float,grid_z,M,64*64*sizeof(float));
dynamic_large_stack_array(float,grid_Ng_x,displ ? M : 0,64*64*sizeof(float));
dynamic_large_stack_array(float,grid_Ng_y,displ ? M : 0,64*64*sizeof(float));
dynamic_large_stack_array(float,grid_Ng_z,displ ? M : 0,64*64*sizeof(float));
if (geom->patch_eval_trees.size())
{
feature_adaptive_eval_grid<PatchEvalGrid>
(geom->patch_eval_trees[geom->numTimeSteps*patch.primID()+patch.time()], patch.subPatch(), patch.needsStitching() ? patch.level : nullptr,
x0,x1,y0,y1,swidth,sheight,
grid_x,grid_y,grid_z,grid_u,grid_v,
displ ? (float*)grid_Ng_x : nullptr, displ ? (float*)grid_Ng_y : nullptr, displ ? (float*)grid_Ng_z : nullptr,
dwidth,dheight);
}
else
{
GeneralCatmullClarkPatch3fa ccpatch(patch.edge(),geom->getVertexBuffer(patch.time()));
feature_adaptive_eval_grid <FeatureAdaptiveEvalGrid,GeneralCatmullClarkPatch3fa>
(ccpatch, patch.subPatch(), patch.needsStitching() ? patch.level : nullptr,
x0,x1,y0,y1,swidth,sheight,
grid_x,grid_y,grid_z,grid_u,grid_v,
displ ? (float*)grid_Ng_x : nullptr, displ ? (float*)grid_Ng_y : nullptr, displ ? (float*)grid_Ng_z : nullptr,
dwidth,dheight);
}
/* call displacement shader */
if (unlikely(geom->displFunc))
{
RTCDisplacementFunctionNArguments args;
args.geometryUserPtr = geom->userPtr;
args.geometry = (RTCGeometry)geom;
//args.geomID = patch.geomID();
args.primID = patch.primID();
args.timeStep = patch.time();
args.u = grid_u;
args.v = grid_v;
args.Ng_x = grid_Ng_x;
args.Ng_y = grid_Ng_y;
args.Ng_z = grid_Ng_z;
args.P_x = grid_x;
args.P_y = grid_y;
args.P_z = grid_z;
args.N = dwidth*dheight;
geom->displFunc(&args);
}
/* set last elements in u,v array to 1.0f */
const float last_u = grid_u[dwidth*dheight-1];
const float last_v = grid_v[dwidth*dheight-1];
const float last_x = grid_x[dwidth*dheight-1];
const float last_y = grid_y[dwidth*dheight-1];
const float last_z = grid_z[dwidth*dheight-1];
for (unsigned i=dwidth*dheight;i<grid_size_simd_blocks*VSIZEX;i++)
{
grid_u[i] = last_u;
grid_v[i] = last_v;
grid_x[i] = last_x;
grid_y[i] = last_y;
grid_z[i] = last_z;
}
vfloatx bounds_min_x = pos_inf;
vfloatx bounds_min_y = pos_inf;
vfloatx bounds_min_z = pos_inf;
vfloatx bounds_max_x = neg_inf;
vfloatx bounds_max_y = neg_inf;
vfloatx bounds_max_z = neg_inf;
for (unsigned i = 0; i<grid_size_simd_blocks; i++)
{
vfloatx x = vfloatx::loadu(&grid_x[i * VSIZEX]);
vfloatx y = vfloatx::loadu(&grid_y[i * VSIZEX]);
vfloatx z = vfloatx::loadu(&grid_z[i * VSIZEX]);
bounds_min_x = min(bounds_min_x,x);
bounds_min_y = min(bounds_min_y,y);
bounds_min_z = min(bounds_min_z,z);
bounds_max_x = max(bounds_max_x,x);
bounds_max_y = max(bounds_max_y,y);
bounds_max_z = max(bounds_max_z,z);
}
b.lower.x = reduce_min(bounds_min_x);
b.lower.y = reduce_min(bounds_min_y);
b.lower.z = reduce_min(bounds_min_z);
b.upper.x = reduce_max(bounds_max_x);
b.upper.y = reduce_max(bounds_max_y);
b.upper.z = reduce_max(bounds_max_z);
b.lower.a = 0;
b.upper.a = 0;
}
else
{
/* grid_u, grid_v need to be padded as we write with SIMD granularity */
gridUVTessellator(patch.level,swidth,sheight,x0,y0,dwidth,dheight,grid_u,grid_v);
/* set last elements in u,v array to last valid point */
const float last_u = grid_u[dwidth*dheight-1];
const float last_v = grid_v[dwidth*dheight-1];
for (unsigned i=dwidth*dheight;i<grid_size_simd_blocks*VSIZEX;i++) {
grid_u[i] = last_u;
grid_v[i] = last_v;
}
/* stitch edges if necessary */
if (unlikely(patch.needsStitching()))
stitchUVGrid(patch.level,swidth,sheight,x0,y0,dwidth,dheight,grid_u,grid_v);
/* iterates over all grid points */
Vec3vfx bounds_min;
bounds_min[0] = pos_inf;
bounds_min[1] = pos_inf;
bounds_min[2] = pos_inf;
Vec3vfx bounds_max;
bounds_max[0] = neg_inf;
bounds_max[1] = neg_inf;
bounds_max[2] = neg_inf;
for (unsigned i=0; i<grid_size_simd_blocks; i++)
{
const vfloatx u = vfloatx::load(&grid_u[i*VSIZEX]);
const vfloatx v = vfloatx::load(&grid_v[i*VSIZEX]);
Vec3vfx vtx = patchEval(patch,u,v);
/* evaluate displacement function */
if (unlikely(geom->displFunc != nullptr))
{
const Vec3vfx normal = normalize_safe(patchNormal(patch,u,v));
RTCDisplacementFunctionNArguments args;
args.geometryUserPtr = geom->userPtr;
args.geometry = (RTCGeometry)geom;
//args.geomID = patch.geomID();
args.primID = patch.primID();
args.timeStep = patch.time();
args.u = &u[0];
args.v = &v[0];
args.Ng_x = &normal.x[0];
args.Ng_y = &normal.y[0];
args.Ng_z = &normal.z[0];
args.P_x = &vtx.x[0];
args.P_y = &vtx.y[0];
args.P_z = &vtx.z[0];
args.N = VSIZEX;
geom->displFunc(&args);
}
bounds_min[0] = min(bounds_min[0],vtx.x);
bounds_max[0] = max(bounds_max[0],vtx.x);
bounds_min[1] = min(bounds_min[1],vtx.y);
bounds_max[1] = max(bounds_max[1],vtx.y);
bounds_min[2] = min(bounds_min[2],vtx.z);
bounds_max[2] = max(bounds_max[2],vtx.z);
}
b.lower.x = reduce_min(bounds_min[0]);
b.lower.y = reduce_min(bounds_min[1]);
b.lower.z = reduce_min(bounds_min[2]);
b.upper.x = reduce_max(bounds_max[0]);
b.upper.y = reduce_max(bounds_max[1]);
b.upper.z = reduce_max(bounds_max[2]);
b.lower.a = 0;
b.upper.a = 0;
}
assert( std::isfinite(b.lower.x) );
assert( std::isfinite(b.lower.y) );
assert( std::isfinite(b.lower.z) );
assert( std::isfinite(b.upper.x) );
assert( std::isfinite(b.upper.y) );
assert( std::isfinite(b.upper.z) );
assert(b.lower.x <= b.upper.x);
assert(b.lower.y <= b.upper.y);
assert(b.lower.z <= b.upper.z);
return b;
}
}
}
|
; A288876: a(n) = binomial(n+4, n)^2. Square of the fifth diagonal sequence of A007318 (Pascal). Fifth diagonal sequence of A008459.
; 1,25,225,1225,4900,15876,44100,108900,245025,511225,1002001,1863225,3312400,5664400,9363600,15023376,23474025,35820225,53509225,78411025,112911876,160022500,223502500,308002500,419225625,564110001,751034025,990046225,1293121600,1674446400,2150733376
add $0,4
bin $0,4
pow $0,2
mov $1,$0
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/proxy_resolution/mojo_proxy_resolver_v8_tracing_bindings.h"
#include <string>
#include <utility>
#include <vector>
#include "base/macros.h"
#include "base/strings/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace net {
class MojoProxyResolverV8TracingBindingsTest : public testing::Test {
public:
MojoProxyResolverV8TracingBindingsTest() = default;
void SetUp() override {
bindings_.reset(new MojoProxyResolverV8TracingBindings<
MojoProxyResolverV8TracingBindingsTest>(this));
}
void Alert(const std::string& message) { alerts_.push_back(message); }
void OnError(int32_t line_number, const std::string& message) {
errors_.push_back(std::make_pair(line_number, message));
}
void ResolveDns(std::unique_ptr<HostResolver::RequestInfo> request_info,
interfaces::HostResolverRequestClientPtr client) {}
protected:
std::unique_ptr<MojoProxyResolverV8TracingBindings<
MojoProxyResolverV8TracingBindingsTest>>
bindings_;
std::vector<std::string> alerts_;
std::vector<std::pair<int, std::string>> errors_;
private:
DISALLOW_COPY_AND_ASSIGN(MojoProxyResolverV8TracingBindingsTest);
};
TEST_F(MojoProxyResolverV8TracingBindingsTest, Basic) {
bindings_->Alert(base::ASCIIToUTF16("alert"));
bindings_->OnError(-1, base::ASCIIToUTF16("error"));
EXPECT_TRUE(bindings_->GetHostResolver());
EXPECT_FALSE(bindings_->GetNetLogWithSource().net_log());
ASSERT_EQ(1u, alerts_.size());
EXPECT_EQ("alert", alerts_[0]);
ASSERT_EQ(1u, errors_.size());
EXPECT_EQ(-1, errors_[0].first);
EXPECT_EQ("error", errors_[0].second);
}
} // namespace net
|
;
; Fast CLS for the Robotron Z9001
; Stefano - Sept 2016
;
;
; $Id: clg.asm,v 1.2 2017/01/02 22:57:59 aralbrec Exp $
;
SECTION code_clib
PUBLIC clg
PUBLIC _clg
.clg
._clg
ld hl,0
ld d,h
ld e,h
add hl,sp
ld b,8
ld a,@00001000 ; GFX mode bit
.g_gcls1
out ($B8), a
ld sp,$ec00+960
ld b,30 ; 30*16*2 = 960 bytes bank
.clgloop
push de
push de
push de
push de
push de
push de
push de
push de
push de
push de
push de
push de
push de
push de
push de
push de
djnz clgloop
inc a
cp 16
jr nz,g_gcls1
ld sp,$e800+960 ; color attributes
ld b,40 ; 40*12*2 = 960 bytes
ld a,7
ld ($0027),a ; ATRIB - current color attribute
ld d,a
ld e,a
.attrloop
push de
push de
push de
push de
push de
push de
push de
push de
push de
push de
push de
push de
djnz attrloop
ld sp,hl
ret
|
; A070923: a(n) is the smallest value >= 0 of the form x^3 - n^2.
; 0,4,18,11,2,28,15,0,44,25,4,72,47,20,118,87,54,19,151,112,71,28,200,153,104,53,0,216,159,100,39,307,242,175,106,35,359,284,207,128,47,433,348,261,172,81,535,440,343,244,143,40,566,459,350,239,126,11,615,496,375,252,127,0,688,557,424,289,152,13,791,648,503,356,207,56,930,775,618,459,298,135,1111,944,775,604,431,256,79,1161,980,797,612,425,236,45,1239,1044,847,648
add $0,1
pow $0,2
lpb $0
mov $1,$0
seq $1,48763 ; Smallest cube >= n.
sub $1,$0
mov $0,0
lpe
mov $0,$1
|
; A055364: Number of asymmetric mobiles (circular rooted trees) with n nodes and 3 leaves.
; 1,4,10,22,42,73,119,184,272,389,540,731,969,1261,1614,2037,2538,3126,3811,4603,5512,6550,7728,9058,10553,12226,14090,16160,18450,20975,23751,26794,30120,33747,37692,41973,46609,51619,57022,62839,69090,75796,82979
mov $2,$0
add $2,1
mov $4,$0
lpb $2
mov $0,$4
sub $2,1
sub $0,$2
mov $5,$0
add $5,1
mov $9,$0
mov $10,0
lpb $5
mov $0,$9
sub $5,1
sub $0,$5
mov $6,$0
mov $7,0
mov $8,$0
add $8,1
lpb $8
mov $0,$6
sub $8,1
sub $0,$8
mov $3,$0
gcd $3,3
add $3,$0
div $3,2
add $7,$3
lpe
add $10,$7
lpe
add $1,$10
lpe
mov $0,$1
|
; A116483: Expansion of (1 + x) / (5*x^2 - 2*x + 1).
; Submitted by Jon Maiga
; 1,3,1,-13,-31,3,161,307,-191,-1917,-2879,3827,22049,24963,-60319,-245453,-189311,848643,2643841,1044467,-11130271,-27482877,685601,138785587,274143169,-145641597,-1661999039,-2595790093,3118415009,19215780483,22839485921,-50399930573,-214997290751,-177994928637,718996596481,2327967836147,1060952689889,-9517933800957,-24340631051359,-1091593097933,119519969060929,244497903611523,-108604038081599,-1439697594220813,-2336374998033631,2525737975036803,16733350940241761,20838012005299507
mov $1,2
mov $2,-1
lpb $0
sub $0,1
add $1,$2
mul $2,5
sub $1,$2
add $2,$1
lpe
mov $0,$1
div $0,2
|
; A289748: Thue-Morse constant converted to base -2.
; Submitted by Jamie Morken(w2)
; 1,1,0,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,1,1,0,1,0,1,1,1,0,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,1,1,0,1,0,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,0,1,1,1,0,1,0,1,1,1,0,1
sub $0,1
dif $0,-2
max $0,0
seq $0,10060 ; Thue-Morse sequence: let A_k denote the first 2^k terms; then A_0 = 0 and for k >= 0, A_{k+1} = A_k B_k, where B_k is obtained from A_k by interchanging 0's and 1's.
add $0,1
mod $0,2
|
/*
D
1 2 E Q T A C Z
4 3 E W S D C X
6 5 R T G F B V
8 7 U Y H J N SPACE
0 9 O I L K M ,
^ - @ P ; : / .
C [ E ] 4 SH \ CT
L C 7 8 5 1 2 0
U R D 9 6 3 E .
*/
DEFINE KEYB_X 21
DEFINE KEYB_Y 25
KeyboardLocationsMatrix:
;; Column, row, char
;; 0
db KEYB_X+KEYB_COL_SPACING*1, KEYB_ROW_10 ; # Key number 00 : ↑
db KEYB_X+KEYB_COL_SPACING*2, KEYB_ROW_10 ; # Key number 01 : →
db KEYB_X+KEYB_COL_SPACING*3, KEYB_ROW_10 ; # Key number 02 : ↓
db KEYB_X+KEYB_COL_SPACING*4, KEYB_ROW_10 ; # Key number 03 : f9
db KEYB_X+KEYB_COL_SPACING*5, KEYB_ROW_10 ; # Key number 04 : f6
db KEYB_X+KEYB_COL_SPACING*6, KEYB_ROW_10 ; # Key number 05 : f3
db KEYB_X+KEYB_COL_SPACING*7, KEYB_ROW_10 ; # Key number 06 : ENTER
db KEYB_X+KEYB_COL_SPACING*8, KEYB_ROW_10 ; # Key number 07 : .
;; 1
db KEYB_X+KEYB_COL_SPACING*1, KEYB_ROW_9 ; # Key number 08 : ←
db KEYB_X+KEYB_COL_SPACING*2, KEYB_ROW_9 ; # Key number 09 : COPY
db KEYB_X+KEYB_COL_SPACING*3, KEYB_ROW_9 ; # Key number 10 : f7
db KEYB_X+KEYB_COL_SPACING*4, KEYB_ROW_9 ; # Key number 11 : f8
db KEYB_X+KEYB_COL_SPACING*5, KEYB_ROW_9 ; # Key number 12 : f5
db KEYB_X+KEYB_COL_SPACING*6, KEYB_ROW_9 ; # Key number 13 : f1
db KEYB_X+KEYB_COL_SPACING*7, KEYB_ROW_9 ; # Key number 14 : f2
db KEYB_X+KEYB_COL_SPACING*8, KEYB_ROW_9 ; # Key number 15 : f0
;; 2
db KEYB_X+KEYB_COL_SPACING*1, KEYB_ROW_8 ; # Key number 16 : CLR
db KEYB_X+KEYB_COL_SPACING*2, KEYB_ROW_8 ; # Key number 17 : {[
db KEYB_X+KEYB_COL_SPACING*3, KEYB_ROW_8 ; # Key number 18 : RETURN
db KEYB_X+KEYB_COL_SPACING*4, KEYB_ROW_8 ; # Key number 19 : }]
db KEYB_X+KEYB_COL_SPACING*5, KEYB_ROW_8 ; # Key number 20 : f4
db KEYB_X+KEYB_COL_SPACING*6, KEYB_ROW_8 ; # Key number 21 : SHIFT
db KEYB_X+KEYB_COL_SPACING*7, KEYB_ROW_8 ; # Key number 22 : `\
db KEYB_X+KEYB_COL_SPACING*8, KEYB_ROW_8 ; # Key number 23 : CONTROL
;; 3
db KEYB_X+KEYB_COL_SPACING*1, KEYB_ROW_7 ; # Key number 24 : £^
db KEYB_X+KEYB_COL_SPACING*2, KEYB_ROW_7 ; # Key number 25 : =-
db KEYB_X+KEYB_COL_SPACING*3, KEYB_ROW_7 ; # Key number 26 : ¦@
db KEYB_X+KEYB_COL_SPACING*4, KEYB_ROW_7 ; # Key number 27 : P
db KEYB_X+KEYB_COL_SPACING*5, KEYB_ROW_7 ; # Key number 28 : +;
db KEYB_X+KEYB_COL_SPACING*6, KEYB_ROW_7 ; # Key number 29 : *:
db KEYB_X+KEYB_COL_SPACING*7, KEYB_ROW_7 ; # Key number 30 : ?/
db KEYB_X+KEYB_COL_SPACING*8, KEYB_ROW_7 ; # Key number 31 : >.
;; 4
db KEYB_X+KEYB_COL_SPACING*1, KEYB_ROW_6 ; # Key number 32 : _0
db KEYB_X+KEYB_COL_SPACING*2, KEYB_ROW_6 ; # Key number 33 : )9
db KEYB_X+KEYB_COL_SPACING*3, KEYB_ROW_6 ; # Key number 34 : O
db KEYB_X+KEYB_COL_SPACING*4, KEYB_ROW_6 ; # Key number 35 : I
db KEYB_X+KEYB_COL_SPACING*5, KEYB_ROW_6 ; # Key number 36 : L
db KEYB_X+KEYB_COL_SPACING*6, KEYB_ROW_6 ; # Key number 37 : K
db KEYB_X+KEYB_COL_SPACING*7, KEYB_ROW_6 ; # Key number 38 : M
db KEYB_X+KEYB_COL_SPACING*8, KEYB_ROW_6 ; # Key number 39 : <,
;; 5
db KEYB_X+KEYB_COL_SPACING*1, KEYB_ROW_5 ; # Key number 40 : (8
db KEYB_X+KEYB_COL_SPACING*2, KEYB_ROW_5 ; # Key number 41 : '7
db KEYB_X+KEYB_COL_SPACING*3, KEYB_ROW_5 ; # Key number 42 : U
db KEYB_X+KEYB_COL_SPACING*4, KEYB_ROW_5 ; # Key number 43 : Y
db KEYB_X+KEYB_COL_SPACING*5, KEYB_ROW_5 ; # Key number 44 : H
db KEYB_X+KEYB_COL_SPACING*6, KEYB_ROW_5 ; # Key number 45 : J
db KEYB_X+KEYB_COL_SPACING*7, KEYB_ROW_5 ; # Key number 46 : N
db KEYB_X+KEYB_COL_SPACING*8, KEYB_ROW_5 ; # Key number 47 : SPACE
;; 6
db KEYB_X+KEYB_COL_SPACING*1, KEYB_ROW_4 ; # Key number 48 : &6
db KEYB_X+KEYB_COL_SPACING*2, KEYB_ROW_4 ; # Key number 49 : %5
db KEYB_X+KEYB_COL_SPACING*3, KEYB_ROW_4 ; # Key number 50 : R
db KEYB_X+KEYB_COL_SPACING*4, KEYB_ROW_4 ; # Key number 51 : T
db KEYB_X+KEYB_COL_SPACING*5, KEYB_ROW_4 ; # Key number 52 : G
db KEYB_X+KEYB_COL_SPACING*6, KEYB_ROW_4 ; # Key number 53 : F
db KEYB_X+KEYB_COL_SPACING*7, KEYB_ROW_4 ; # Key number 54 : B
db KEYB_X+KEYB_COL_SPACING*8, KEYB_ROW_4 ; # Key number 55 : V
;; 7
db KEYB_X+KEYB_COL_SPACING*1, KEYB_ROW_3 ; # Key number 56 : $4
db KEYB_X+KEYB_COL_SPACING*2, KEYB_ROW_3 ; # Key number 57 : #3
db KEYB_X+KEYB_COL_SPACING*3, KEYB_ROW_3 ; # Key number 58 : E
db KEYB_X+KEYB_COL_SPACING*4, KEYB_ROW_3 ; # Key number 59 : W
db KEYB_X+KEYB_COL_SPACING*5, KEYB_ROW_3 ; # Key number 60 : S
db KEYB_X+KEYB_COL_SPACING*6, KEYB_ROW_3 ; # Key number 61 : D
db KEYB_X+KEYB_COL_SPACING*7, KEYB_ROW_3 ; # Key number 62 : C
db KEYB_X+KEYB_COL_SPACING*8, KEYB_ROW_3 ; # Key number 63 : X
;; 8
db KEYB_X+KEYB_COL_SPACING*1, KEYB_ROW_2 ; # Key number 64 : !1
db KEYB_X+KEYB_COL_SPACING*2, KEYB_ROW_2 ; # Key number 65 : "2
db KEYB_X+KEYB_COL_SPACING*3, KEYB_ROW_2 ; # Key number 66 : ESC
db KEYB_X+KEYB_COL_SPACING*4, KEYB_ROW_2 ; # Key number 67 : Q
db KEYB_X+KEYB_COL_SPACING*5, KEYB_ROW_2 ; # Key number 68 : TAB
db KEYB_X+KEYB_COL_SPACING*6, KEYB_ROW_2 ; # Key number 69 : A
db KEYB_X+KEYB_COL_SPACING*7, KEYB_ROW_2 ; # Key number 70 : CAPSLOCK
db KEYB_X+KEYB_COL_SPACING*8, KEYB_ROW_2 ; # Key number 71 : Z
;; 9
db KEYB_X+KEYB_COL_SPACING*1, KEYB_ROW_1 ; # Key number 72 : Joystick Up
db KEYB_X+KEYB_COL_SPACING*2, KEYB_ROW_1 ; # Key number 73 : Joystick Down
db KEYB_X+KEYB_COL_SPACING*3, KEYB_ROW_1 ; # Key number 74 : Joystick Left
db KEYB_X+KEYB_COL_SPACING*4, KEYB_ROW_1 ; # Key number 75 : Joystick Right
db KEYB_X+KEYB_COL_SPACING*5, KEYB_ROW_1 ; # Key number 76 : Joystick Fire 1
db KEYB_X+KEYB_COL_SPACING*6, KEYB_ROW_1 ; # Key number 77 : Joystick Fire 2
db KEYB_X+KEYB_COL_SPACING*7, KEYB_ROW_1 ; # Key number 78 : Joystick Fire 3
db KEYB_X+KEYB_COL_SPACING*8, KEYB_ROW_1 ; # Key number 79 : DEL
db KEYB_Z_X+KEYB_COL_SPACING*11, KEYB_ROW_4, SPECIALKEY_SHIFTR ; # Key number 21 : SHIFT
SpecialKeysTableMatrix:
db KEY_HEIGHT ; RETURN
dw TxtKeyReturn+1
db KEY_HEIGHT ; SPACE
dw TxtKeySpaceShort
db KEY_HEIGHT ; CONTROL
dw TxtKeyControlShort
db KEY_HEIGHT ; COPY
dw TxtKeyCopyShort
db KEY_HEIGHT ; CAPS LOCK
dw TxtKeyCapsShort
db KEY_HEIGHT ; TAB
dw TxtKeyTabShort
db KEY_HEIGHT ; ENTER
dw TxtKeyEnterShort
db KEY_HEIGHT ; LEFT SHIFT
dw TxtKeyShiftShort
db KEY_HEIGHT ; RIGHT SHIFT
dw TxtKeyShiftShort
db KEY_HEIGHT ; DEL
dw TxtKeyDelShort
UNDEFINE KEYB_X
UNDEFINE KEYB_Y
|
// Copyright (c) 2014-2015 The Dash developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "masternode.h"
#include "addrman.h"
#include "masternodeman.h"
#include "obfuscation.h"
#include "sync.h"
#include "util.h"
#include <boost/lexical_cast.hpp>
// keep track of the scanning errors I've seen
map<uint256, int> mapSeenMasternodeScanningErrors;
// cache block hashes as we calculate them
std::map<int64_t, uint256> mapCacheBlockHashes;
//Get the last hash that matches the modulus given. Processed in reverse order
bool GetBlockHash(uint256& hash, int nBlockHeight)
{
if (chainActive.Tip() == NULL)
return false;
if (nBlockHeight == 0)
nBlockHeight = chainActive.Tip()->nHeight;
if (mapCacheBlockHashes.count(nBlockHeight)) {
hash = mapCacheBlockHashes[nBlockHeight];
return true;
}
const CBlockIndex* BlockLastSolved = chainActive.Tip();
const CBlockIndex* BlockReading = chainActive.Tip();
if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || chainActive.Tip()->nHeight + 1 < nBlockHeight)
return false;
int nBlocksAgo = 0;
if (nBlockHeight > 0)
nBlocksAgo = (chainActive.Tip()->nHeight + 1) - nBlockHeight;
assert(nBlocksAgo >= 0);
int n = 0;
for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
if (n >= nBlocksAgo) {
hash = BlockReading->GetBlockHash();
mapCacheBlockHashes[nBlockHeight] = hash;
return true;
}
n++;
if (BlockReading->pprev == NULL) {
assert(BlockReading);
break;
}
BlockReading = BlockReading->pprev;
}
return false;
}
CMasternode::CMasternode()
{
LOCK(cs);
vin = CTxIn();
addr = CService();
pubkey = CPubKey();
pubkey2 = CPubKey();
sig = std::vector<unsigned char>();
activeState = MASTERNODE_ENABLED;
sigTime = GetAdjustedTime();
lastPing = CMasternodePing();
cacheInputAge = 0;
cacheInputAgeBlock = 0;
unitTest = false;
allowFreeTx = true;
protocolVersion = PROTOCOL_VERSION;
nLastDsq = 0;
nScanningErrorCount = 0;
nLastScanningErrorBlockHeight = 0;
lastTimeChecked = 0;
}
CMasternode::CMasternode(const CMasternode& other)
{
LOCK(cs);
vin = other.vin;
addr = other.addr;
pubkey = other.pubkey;
pubkey2 = other.pubkey2;
sig = other.sig;
activeState = other.activeState;
sigTime = other.sigTime;
lastPing = other.lastPing;
cacheInputAge = other.cacheInputAge;
cacheInputAgeBlock = other.cacheInputAgeBlock;
unitTest = other.unitTest;
allowFreeTx = other.allowFreeTx;
protocolVersion = other.protocolVersion;
nLastDsq = other.nLastDsq;
nScanningErrorCount = other.nScanningErrorCount;
nLastScanningErrorBlockHeight = other.nLastScanningErrorBlockHeight;
lastTimeChecked = 0;
}
CMasternode::CMasternode(const CMasternodeBroadcast& mnb)
{
LOCK(cs);
vin = mnb.vin;
addr = mnb.addr;
pubkey = mnb.pubkey;
pubkey2 = mnb.pubkey2;
sig = mnb.sig;
activeState = MASTERNODE_ENABLED;
sigTime = mnb.sigTime;
lastPing = mnb.lastPing;
cacheInputAge = 0;
cacheInputAgeBlock = 0;
unitTest = false;
allowFreeTx = true;
protocolVersion = mnb.protocolVersion;
nLastDsq = mnb.nLastDsq;
nScanningErrorCount = 0;
nLastScanningErrorBlockHeight = 0;
lastTimeChecked = 0;
}
//
// When a new masternode broadcast is sent, update our information
//
bool CMasternode::UpdateFromNewBroadcast(CMasternodeBroadcast& mnb)
{
if (mnb.sigTime > sigTime) {
pubkey2 = mnb.pubkey2;
sigTime = mnb.sigTime;
sig = mnb.sig;
protocolVersion = mnb.protocolVersion;
addr = mnb.addr;
lastTimeChecked = 0;
int nDoS = 0;
if (mnb.lastPing == CMasternodePing() || (mnb.lastPing != CMasternodePing() && mnb.lastPing.CheckAndUpdate(nDoS, false))) {
lastPing = mnb.lastPing;
mnodeman.mapSeenMasternodePing.insert(make_pair(lastPing.GetHash(), lastPing));
}
return true;
}
return false;
}
//
// Deterministically calculate a given "score" for a Masternode depending on how close it's hash is to
// the proof of work for that block. The further away they are the better, the furthest will win the election
// and get paid this block
//
uint256 CMasternode::CalculateScore(int mod, int64_t nBlockHeight)
{
if (chainActive.Tip() == NULL)
return 0;
uint256 hash = 0;
uint256 aux = vin.prevout.hash + vin.prevout.n;
if (!GetBlockHash(hash, nBlockHeight)) {
LogPrintf("CalculateScore ERROR - nHeight %d - Returned 0\n", nBlockHeight);
return 0;
}
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << hash;
uint256 hash2 = ss.GetHash();
CHashWriter ss2(SER_GETHASH, PROTOCOL_VERSION);
ss2 << hash;
ss2 << aux;
uint256 hash3 = ss2.GetHash();
uint256 r = (hash3 > hash2 ? hash3 - hash2 : hash2 - hash3);
return r;
}
void CMasternode::Check(bool forceCheck)
{
if (ShutdownRequested())
return;
if (!forceCheck && (GetTime() - lastTimeChecked < MASTERNODE_CHECK_SECONDS))
return;
lastTimeChecked = GetTime();
//once spent, stop doing the checks
if (activeState == MASTERNODE_VIN_SPENT)
return;
if (!IsPingedWithin(MASTERNODE_REMOVAL_SECONDS)) {
activeState = MASTERNODE_REMOVE;
return;
}
if (!IsPingedWithin(MASTERNODE_EXPIRATION_SECONDS)) {
activeState = MASTERNODE_EXPIRED;
return;
}
if (!unitTest) {
CValidationState state;
CMutableTransaction tx = CMutableTransaction();
CTxOut vout = CTxOut(999.99 * COIN, obfuScationPool.collateralPubKey);
tx.vin.push_back(vin);
tx.vout.push_back(vout);
{
TRY_LOCK(cs_main, lockMain);
if (!lockMain)
return;
if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL)) {
activeState = MASTERNODE_VIN_SPENT;
return;
}
}
}
activeState = MASTERNODE_ENABLED; // OK
}
bool CMasternode::IsValidNetAddr()
{
return true;
}
std::string CMasternode::StateToString(int nStateIn)
{
switch(nStateIn) {
case MASTERNODE_ENABLED: return "ENABLED";
case MASTERNODE_EXPIRED: return "EXPIRED";
case MASTERNODE_VIN_SPENT: return "OUTPOINT_SPENT";
case MASTERNODE_REMOVE: return "REMOVE";
case MASTERNODE_POS_ERROR: return "POS_ERROR";
default: return "UNKNOWN";
}
}
std::string CMasternode::GetStateString() const
{
return StateToString(activeState);
}
std::string CMasternode::GetStatus() const
{
// TODO: return smth a bit more human readable here
return GetStateString();
}
int64_t CMasternode::SecondsSincePayment()
{
CScript pubkeyScript;
pubkeyScript = GetScriptForDestination(pubkey.GetID());
int64_t sec = (GetAdjustedTime() - GetLastPaid());
int64_t month = 60 * 60 * 24 * 30;
if (sec < month)
return sec; //if it's less than 30 days, give seconds
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << vin;
ss << sigTime;
uint256 hash = ss.GetHash();
// return some deterministic value for unknown/unpaid but force it to be more than 30 days old
return month + hash.GetCompact(false);
}
int64_t CMasternode::GetLastPaid()
{
CBlockIndex* pindexPrev = chainActive.Tip();
if (pindexPrev == NULL)
return false;
CScript mnpayee;
mnpayee = GetScriptForDestination(pubkey.GetID());
CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION);
ss << vin;
ss << sigTime;
uint256 hash = ss.GetHash();
// use a deterministic offset to break a tie -- 2.5 minutes
int64_t nOffset = hash.GetCompact(false) % 150;
if (chainActive.Tip() == NULL)
return false;
const CBlockIndex* BlockReading = chainActive.Tip();
int nMnCount = mnodeman.CountEnabled() * 1.25;
int n = 0;
for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
if (n >= nMnCount) {
return 0;
}
n++;
if (masternodePayments.mapMasternodeBlocks.count(BlockReading->nHeight)) {
/*
Search for this payee, with at least 2 votes. This will aid in consensus allowing the network
to converge on the same payees quickly, then keep the same schedule.
*/
if (masternodePayments.mapMasternodeBlocks[BlockReading->nHeight].HasPayeeWithVotes(mnpayee, 2)) {
return BlockReading->nTime + nOffset;
}
}
if (BlockReading->pprev == NULL) {
assert(BlockReading);
break;
}
BlockReading = BlockReading->pprev;
}
return 0;
}
bool CMasternodeBroadcast::Create(std::string strService, std::string strKeyMasternode, std::string strTxHash, std::string strOutputIndex, std::string& strErrorRet, CMasternodeBroadcast &mnbRet, bool fOffline)
{
CTxIn txin;
CPubKey pubKeyCollateralAddressNew;
CKey keyCollateralAddressNew;
CPubKey pubKeyMasternodeNew;
CKey keyMasternodeNew;
//need correct blocks to send ping
if(!fOffline && !masternodeSync.IsBlockchainSynced()) {
strErrorRet = "Sync in progress. Must wait until sync is complete to start Masternode";
LogPrintf("CMasternodeBroadcast::Create -- %s\n", strErrorRet);
return false;
}
if(!obfuScationSigner.GetKeysFromSecret(strKeyMasternode, keyMasternodeNew, pubKeyMasternodeNew)) {
strErrorRet = strprintf("Invalid masternode key %s", strKeyMasternode);
LogPrintf("CMasternodeBroadcast::Create -- %s\n", strErrorRet);
return false;
}
if(!pwalletMain->GetMasternodeVinAndKeys(txin, pubKeyCollateralAddressNew, keyCollateralAddressNew, strTxHash, strOutputIndex)) {
strErrorRet = strprintf("Could not allocate txin %s:%s for masternode %s", strTxHash, strOutputIndex, strService);
LogPrintf("CMasternodeBroadcast::Create -- %s\n", strErrorRet);
return false;
}
CService service = CService(strService);
int mainnetDefaultPort = Params(CBaseChainParams::MAIN).GetDefaultPort();
if(service.GetPort() != mainnetDefaultPort) {
strErrorRet = strprintf("Invalid port %u for masternode %s, only %d is supported on mainnet.", service.GetPort(), strService, mainnetDefaultPort);
LogPrintf("CMasternodeBroadcast::Create -- %s\n", strErrorRet);
return false;
}
return Create(txin, CService(strService), keyCollateralAddressNew, pubKeyCollateralAddressNew, keyMasternodeNew, pubKeyMasternodeNew, strErrorRet, mnbRet);
}
bool CMasternodeBroadcast::Create(CTxIn txin, CService service, CKey keyCollateralAddressNew, CPubKey pubKeyCollateralAddressNew, CKey keyMasternodeNew, CPubKey pubKeyMasternodeNew, std::string &strErrorRet, CMasternodeBroadcast &mnbRet)
{
// wait for reindex and/or import to finish
if (fImporting || fReindex) return false;
LogPrint("masternode", "CMasternodeBroadcast::Create -- pubKeyCollateralAddressNew = %s, pubKeyMasternodeNew.GetID() = %s\n",
CBitcoinAddress(pubKeyCollateralAddressNew.GetID()).ToString(),
pubKeyMasternodeNew.GetID().ToString());
CMasternodePing mnp(txin);
if(!mnp.Sign(keyMasternodeNew, pubKeyMasternodeNew)) {
strErrorRet = strprintf("Failed to sign ping, masternode=%s", txin.prevout.ToStringShort());
LogPrintf("CMasternodeBroadcast::Create -- %s\n", strErrorRet);
mnbRet = CMasternodeBroadcast();
return false;
}
mnbRet = CMasternodeBroadcast(service, txin, pubKeyCollateralAddressNew, pubKeyMasternodeNew, PROTOCOL_VERSION);
if(!mnbRet.IsValidNetAddr()) {
strErrorRet = strprintf("Invalid IP address, masternode=%s", txin.prevout.ToStringShort());
LogPrintf("CMasternodeBroadcast::Create -- %s\n", strErrorRet);
mnbRet = CMasternodeBroadcast();
return false;
}
mnbRet.lastPing = mnp;
if(!mnbRet.Sign(keyCollateralAddressNew)) {
strErrorRet = strprintf("Failed to sign broadcast, masternode=%s", txin.prevout.ToStringShort());
LogPrintf("CMasternodeBroadcast::Create -- %s\n", strErrorRet);
mnbRet = CMasternodeBroadcast();
return false;
}
return true;
}
CMasternodeBroadcast::CMasternodeBroadcast()
{
vin = CTxIn();
addr = CService();
pubkey = CPubKey();
pubkey2 = CPubKey();
sig = std::vector<unsigned char>();
activeState = MASTERNODE_ENABLED;
sigTime = GetAdjustedTime();
lastPing = CMasternodePing();
cacheInputAge = 0;
cacheInputAgeBlock = 0;
unitTest = false;
allowFreeTx = true;
protocolVersion = PROTOCOL_VERSION;
nLastDsq = 0;
nScanningErrorCount = 0;
nLastScanningErrorBlockHeight = 0;
}
CMasternodeBroadcast::CMasternodeBroadcast(CService newAddr, CTxIn newVin, CPubKey newPubkey, CPubKey newPubkey2, int protocolVersionIn)
{
vin = newVin;
addr = newAddr;
pubkey = newPubkey;
pubkey2 = newPubkey2;
sig = std::vector<unsigned char>();
activeState = MASTERNODE_ENABLED;
sigTime = GetAdjustedTime();
lastPing = CMasternodePing();
cacheInputAge = 0;
cacheInputAgeBlock = 0;
unitTest = false;
allowFreeTx = true;
protocolVersion = protocolVersionIn;
nLastDsq = 0;
nScanningErrorCount = 0;
nLastScanningErrorBlockHeight = 0;
}
CMasternodeBroadcast::CMasternodeBroadcast(const CMasternode& mn)
{
vin = mn.vin;
addr = mn.addr;
pubkey = mn.pubkey;
pubkey2 = mn.pubkey2;
sig = mn.sig;
activeState = mn.activeState;
sigTime = mn.sigTime;
lastPing = mn.lastPing;
cacheInputAge = mn.cacheInputAge;
cacheInputAgeBlock = mn.cacheInputAgeBlock;
unitTest = mn.unitTest;
allowFreeTx = mn.allowFreeTx;
protocolVersion = mn.protocolVersion;
nLastDsq = mn.nLastDsq;
nScanningErrorCount = mn.nScanningErrorCount;
nLastScanningErrorBlockHeight = mn.nLastScanningErrorBlockHeight;
}
bool CMasternodeBroadcast::CheckAndUpdate(int& nDos)
{
nDos = 0;
// make sure signature isn't in the future (past is OK)
if (sigTime > GetAdjustedTime() + 60 * 60) {
LogPrintf("mnb - Signature rejected, too far into the future %s\n", vin.ToString());
nDos = 1;
return false;
}
if (protocolVersion < masternodePayments.GetMinMasternodePaymentsProto()) {
LogPrintf("mnb - ignoring outdated Masternode %s protocol version %d\n", vin.ToString(), protocolVersion);
return false;
}
CScript pubkeyScript;
pubkeyScript = GetScriptForDestination(pubkey.GetID());
if (pubkeyScript.size() != 25) {
LogPrintf("mnb - pubkey the wrong size\n");
nDos = 100;
return false;
}
CScript pubkeyScript2;
pubkeyScript2 = GetScriptForDestination(pubkey2.GetID());
if (pubkeyScript2.size() != 25) {
LogPrintf("mnb - pubkey2 the wrong size\n");
nDos = 100;
return false;
}
if (!vin.scriptSig.empty()) {
LogPrintf("mnb - Ignore Not Empty ScriptSig %s\n", vin.ToString());
return false;
}
// incorrect ping or its sigTime
if (lastPing == CMasternodePing() || !lastPing.CheckAndUpdate(nDos, false, true))
return false;
std::string strMessage;
std::string errorMessage = "";
if (protocolVersion < 70201) {
std::string vchPubKey(pubkey.begin(), pubkey.end());
std::string vchPubKey2(pubkey2.begin(), pubkey2.end());
strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(protocolVersion);
LogPrint("masternode", "mnb - sanitized strMessage: %s, pubkey address: %s, sig: %s\n",
SanitizeString(strMessage), CBitcoinAddress(pubkey.GetID()).ToString(),
EncodeBase64(&sig[0], sig.size()));
if (!obfuScationSigner.VerifyMessage(pubkey, sig, strMessage, errorMessage)) {
// maybe it's wrong format, try again with the old one
strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(protocolVersion);
LogPrint("masternode", "mnb - sanitized strMessage: %s, pubkey address: %s, sig: %s\n",
SanitizeString(strMessage), CBitcoinAddress(pubkey.GetID()).ToString(),
EncodeBase64(&sig[0], sig.size()));
if (!obfuScationSigner.VerifyMessage(pubkey, sig, strMessage, errorMessage)) {
// didn't work either
LogPrintf("mnb - Got bad Masternode address signature, sanitized error: %s\n", SanitizeString(errorMessage));
// there is a bug in old MN signatures, ignore such MN but do not ban the peer we got this from
return false;
}
}
} else {
strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + pubkey.GetID().ToString() + pubkey2.GetID().ToString() + boost::lexical_cast<std::string>(protocolVersion);
LogPrint("masternode", "mnb - strMessage: %s, pubkey address: %s, sig: %s\n",
strMessage, CBitcoinAddress(pubkey.GetID()).ToString(), EncodeBase64(&sig[0], sig.size()));
if (!obfuScationSigner.VerifyMessage(pubkey, sig, strMessage, errorMessage)) {
LogPrintf("mnb - Got bad Masternode address signature, error: %s\n", errorMessage);
nDos = 100;
return false;
}
}
if (Params().NetworkID() == CBaseChainParams::MAIN) {
if (addr.GetPort() != 40000)
return false;
} else if (addr.GetPort() == 40000)
return false;
//search existing Masternode list, this is where we update existing Masternodes with new mnb broadcasts
CMasternode* pmn = mnodeman.Find(vin);
// no such masternode, nothing to update
if (pmn == NULL)
return true;
// this broadcast is older or equal than the one that we already have - it's bad and should never happen
// unless someone is doing something fishy
// (mapSeenMasternodeBroadcast in CMasternodeMan::ProcessMessage should filter legit duplicates)
if (pmn->sigTime >= sigTime) {
LogPrintf("CMasternodeBroadcast::CheckAndUpdate - Bad sigTime %d for Masternode %20s %105s (existing broadcast is at %d)\n",
sigTime, addr.ToString(), vin.ToString(), pmn->sigTime);
return false;
}
// masternode is not enabled yet/already, nothing to update
if (!pmn->IsEnabled())
return true;
// mn.pubkey = pubkey, IsVinAssociatedWithPubkey is validated once below,
// after that they just need to match
if (pmn->pubkey == pubkey && !pmn->IsBroadcastedWithin(MASTERNODE_MIN_MNB_SECONDS)) {
//take the newest entry
LogPrintf("mnb - Got updated entry for %s\n", addr.ToString());
if (pmn->UpdateFromNewBroadcast((*this))) {
pmn->Check();
if (pmn->IsEnabled())
Relay();
}
masternodeSync.AddedMasternodeList(GetHash());
}
return true;
}
bool CMasternodeBroadcast::CheckInputsAndAdd(int& nDoS)
{
// we are a masternode with the same vin (i.e. already activated) and this mnb is ours (matches our Masternode privkey)
// so nothing to do here for us
if (fMasterNode && vin.prevout == activeMasternode.vin.prevout && pubkey2 == activeMasternode.pubKeyMasternode)
return true;
// incorrect ping or its sigTime
if (lastPing == CMasternodePing() || !lastPing.CheckAndUpdate(nDoS, false, true))
return false;
// search existing Masternode list
CMasternode* pmn = mnodeman.Find(vin);
if (pmn != NULL) {
// nothing to do here if we already know about this masternode and it's enabled
if (pmn->IsEnabled())
return true;
// if it's not enabled, remove old MN first and continue
else
mnodeman.Remove(pmn->vin);
}
CValidationState state;
CMutableTransaction tx = CMutableTransaction();
CTxOut vout = CTxOut(999.99 * COIN, obfuScationPool.collateralPubKey);
tx.vin.push_back(vin);
tx.vout.push_back(vout);
{
TRY_LOCK(cs_main, lockMain);
if (!lockMain) {
// not mnb fault, let it to be checked again later
mnodeman.mapSeenMasternodeBroadcast.erase(GetHash());
masternodeSync.mapSeenSyncMNB.erase(GetHash());
return false;
}
if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL)) {
//set nDos
state.IsInvalid(nDoS);
return false;
}
}
LogPrint("masternode", "mnb - Accepted Masternode entry\n");
if (GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS) {
LogPrintf("mnb - Input must have at least %d confirmations\n", MASTERNODE_MIN_CONFIRMATIONS);
// maybe we miss few blocks, let this mnb to be checked again later
mnodeman.mapSeenMasternodeBroadcast.erase(GetHash());
masternodeSync.mapSeenSyncMNB.erase(GetHash());
return false;
}
// verify that sig time is legit in past
// should be at least not earlier than block when 1000 DASH tx got MASTERNODE_MIN_CONFIRMATIONS
uint256 hashBlock = 0;
CTransaction tx2;
GetTransaction(vin.prevout.hash, tx2, hashBlock, true);
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end() && (*mi).second) {
CBlockIndex* pMNIndex = (*mi).second; // block for 1000 DASH tx -> 1 confirmation
CBlockIndex* pConfIndex = chainActive[pMNIndex->nHeight + MASTERNODE_MIN_CONFIRMATIONS - 1]; // block where tx got MASTERNODE_MIN_CONFIRMATIONS
if (pConfIndex->GetBlockTime() > sigTime) {
LogPrintf("mnb - Bad sigTime %d for Masternode %20s %105s (%i conf block is at %d)\n",
sigTime, addr.ToString(), vin.ToString(), MASTERNODE_MIN_CONFIRMATIONS, pConfIndex->GetBlockTime());
return false;
}
}
LogPrintf("mnb - Got NEW Masternode entry - %s - %s - %s - %lli \n", GetHash().ToString(), addr.ToString(), vin.ToString(), sigTime);
CMasternode mn(*this);
mnodeman.Add(mn);
// if it matches our Masternode privkey, then we've been remotely activated
if (pubkey2 == activeMasternode.pubKeyMasternode && protocolVersion == PROTOCOL_VERSION) {
activeMasternode.EnableHotColdMasterNode(vin, addr);
}
bool isLocal = addr.IsRFC1918() || addr.IsLocal();
if (Params().NetworkID() == CBaseChainParams::REGTEST)
isLocal = false;
if (!isLocal)
Relay();
return true;
}
void CMasternodeBroadcast::Relay()
{
CInv inv(MSG_MASTERNODE_ANNOUNCE, GetHash());
RelayInv(inv);
}
bool CMasternodeBroadcast::Sign(CKey& keyCollateralAddress)
{
std::string errorMessage;
std::string vchPubKey(pubkey.begin(), pubkey.end());
std::string vchPubKey2(pubkey2.begin(), pubkey2.end());
sigTime = GetAdjustedTime();
std::string strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(protocolVersion);
if (!obfuScationSigner.SignMessage(strMessage, errorMessage, sig, keyCollateralAddress)) {
LogPrintf("CMasternodeBroadcast::Sign() - Error: %s\n", errorMessage);
return false;
}
return true;
}
bool CMasternodeBroadcast::VerifySignature()
{
std::string errorMessage;
std::string vchPubKey(pubkey.begin(), pubkey.end());
std::string vchPubKey2(pubkey2.begin(), pubkey2.end());
std::string strMessage = addr.ToString() + boost::lexical_cast<std::string>(sigTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(protocolVersion);
if (!obfuScationSigner.VerifyMessage(pubkey, sig, strMessage, errorMessage)) {
LogPrintf("CMasternodeBroadcast::VerifySignature() - Error: %s\n", errorMessage);
return false;
}
return true;
}
CMasternodePing::CMasternodePing()
{
vin = CTxIn();
blockHash = uint256(0);
sigTime = 0;
vchSig = std::vector<unsigned char>();
}
CMasternodePing::CMasternodePing(CTxIn& newVin)
{
vin = newVin;
blockHash = chainActive[chainActive.Height() - 12]->GetBlockHash();
sigTime = GetAdjustedTime();
vchSig = std::vector<unsigned char>();
}
bool CMasternodePing::Sign(CKey& keyMasternode, CPubKey& pubKeyMasternode)
{
std::string errorMessage;
std::string strMasterNodeSignMessage;
sigTime = GetAdjustedTime();
std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast<std::string>(sigTime);
if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, keyMasternode)) {
LogPrintf("CMasternodePing::Sign() - Error: %s\n", errorMessage);
return false;
}
if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) {
LogPrintf("CMasternodePing::Sign() - Error: %s\n", errorMessage);
return false;
}
return true;
}
bool CMasternodePing::VerifySignature(CPubKey& pubKeyMasternode, int& nDos)
{
std::string strMessage = vin.ToString() + blockHash.ToString() + boost::lexical_cast<std::string>(sigTime);
std::string errorMessage = "";
if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchSig, strMessage, errorMessage)) {
LogPrintf("CMasternodePing::VerifySignature - Got bad Masternode ping signature %s Error: %s\n", vin.ToString(), errorMessage);
nDos = 33;
return false;
}
return true;
}
bool CMasternodePing::CheckAndUpdate(int& nDos, bool fRequireEnabled, bool fCheckSigTimeOnly)
{
if (sigTime > GetAdjustedTime() + 60 * 60) {
LogPrintf("CMasternodePing::CheckAndUpdate - Signature rejected, too far into the future %s\n", vin.ToString());
nDos = 1;
return false;
}
if (sigTime <= GetAdjustedTime() - 60 * 60) {
LogPrintf("CMasternodePing::CheckAndUpdate - Signature rejected, too far into the past %s - %d %d \n", vin.ToString(), sigTime, GetAdjustedTime());
nDos = 1;
return false;
}
if (fCheckSigTimeOnly) {
CMasternode* pmn = mnodeman.Find(vin);
if (pmn)
return VerifySignature(pmn->pubkey2, nDos);
return true;
}
LogPrint("masternode", "CMasternodePing::CheckAndUpdate - New Ping - %s - %s - %lli\n", GetHash().ToString(), blockHash.ToString(), sigTime);
// see if we have this Masternode
CMasternode* pmn = mnodeman.Find(vin);
if (pmn != NULL && pmn->protocolVersion >= masternodePayments.GetMinMasternodePaymentsProto()) {
if (fRequireEnabled && !pmn->IsEnabled())
return false;
// LogPrintf("mnping - Found corresponding mn for vin: %s\n", vin.ToString());
// update only if there is no known ping for this masternode or
// last ping was more then MASTERNODE_MIN_MNP_SECONDS-60 ago comparing to this one
if (!pmn->IsPingedWithin(MASTERNODE_MIN_MNP_SECONDS - 60, sigTime)) {
if (!VerifySignature(pmn->pubkey2, nDos))
return false;
BlockMap::iterator mi = mapBlockIndex.find(blockHash);
if (mi != mapBlockIndex.end() && (*mi).second) {
if ((*mi).second->nHeight < chainActive.Height() - 24) {
LogPrintf("CMasternodePing::CheckAndUpdate - Masternode %s block hash %s is too old\n", vin.ToString(), blockHash.ToString());
// Do nothing here (no Masternode update, no mnping relay)
// Let this node to be visible but fail to accept mnping
return false;
}
} else {
if (fDebug)
LogPrintf("CMasternodePing::CheckAndUpdate - Masternode %s block hash %s is unknown\n", vin.ToString(), blockHash.ToString());
// maybe we stuck so we shouldn't ban this node, just fail to accept it
// TODO: or should we also request this block?
return false;
}
pmn->lastPing = *this;
//mnodeman.mapSeenMasternodeBroadcast.lastPing is probably outdated, so we'll update it
CMasternodeBroadcast mnb(*pmn);
uint256 hash = mnb.GetHash();
if (mnodeman.mapSeenMasternodeBroadcast.count(hash)) {
mnodeman.mapSeenMasternodeBroadcast[hash].lastPing = *this;
}
pmn->Check(true);
if (!pmn->IsEnabled())
return false;
LogPrint("masternode", "CMasternodePing::CheckAndUpdate - Masternode ping accepted, vin: %s\n", vin.ToString());
Relay();
return true;
}
LogPrint("masternode", "CMasternodePing::CheckAndUpdate - Masternode ping arrived too early, vin: %s\n", vin.ToString());
//nDos = 1; //disable, this is happening frequently and causing banned peers
return false;
}
LogPrint("masternode", "CMasternodePing::CheckAndUpdate - Couldn't find compatible Masternode entry, vin: %s\n", vin.ToString());
return false;
}
void CMasternodePing::Relay()
{
CInv inv(MSG_MASTERNODE_PING, GetHash());
RelayInv(inv);
}
|
/*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "mitkConnectomicsRenderingNodeRadiusParameterProperty.h"
#include "mitkConnectomicsRenderingProperties.h"
#define NODE_RADIUS_CONSTANT 0
#define NODE_RADIUS_DEGREE 1
#define NODE_RADIUS_BETWEENNESS 2
#define NODE_RADIUS_CLUSTERING 3
mitk::ConnectomicsRenderingNodeRadiusParameterProperty::ConnectomicsRenderingNodeRadiusParameterProperty( )
{
AddRenderingNodeRadiusParameters();
SetValue( NODE_RADIUS_CONSTANT );
}
mitk::ConnectomicsRenderingNodeRadiusParameterProperty::ConnectomicsRenderingNodeRadiusParameterProperty( const IdType& value )
{
AddRenderingNodeRadiusParameters();
if ( IsValidEnumerationValue( value ) )
{
SetValue( value ) ;
}
else
{
SetValue( NODE_RADIUS_CONSTANT );
}
}
mitk::ConnectomicsRenderingNodeRadiusParameterProperty::ConnectomicsRenderingNodeRadiusParameterProperty( const std::string& value )
{
AddRenderingNodeRadiusParameters();
if ( IsValidEnumerationValue( value ) )
{
SetValue( value );
}
else
{
SetValue( NODE_RADIUS_CONSTANT );
}
}
void mitk::ConnectomicsRenderingNodeRadiusParameterProperty::AddRenderingNodeRadiusParameters()
{
AddEnum( connectomicsRenderingNodeParameterConstant, NODE_RADIUS_CONSTANT );
AddEnum( connectomicsRenderingNodeParameterDegree , NODE_RADIUS_DEGREE );
AddEnum( connectomicsRenderingNodeParameterBetweenness , NODE_RADIUS_BETWEENNESS );
AddEnum( connectomicsRenderingNodeParameterClustering , NODE_RADIUS_CLUSTERING );
}
bool mitk::ConnectomicsRenderingNodeRadiusParameterProperty::AddEnum( const std::string& name, const IdType& id )
{
return Superclass::AddEnum( name, id );
}
|
; Ex__4_16_bit_addition.asm
; Try running this code at
; https://skilldrick.github.io/easy6502/
; Set up the values to be added
; Remove the appropriate semicolons to select the bytes to add:
; ($0000 + $0001) or ($00FF + $0001) or ($1234 + $5678)
LDA #$00
;LDA #$FF
;LDA #$34
STA $00
LDA #$00
;LDA #$00
;LDA #$12
STA $01
LDA #$01
;LDA #$01
;LDA #$78
STA $02
LDA #$00
;LDA #$00
;LDA #$56
STA $03
; Add the two 16-bit values
CLC
LDA $00
ADC $02
STA $04
LDA $01
ADC $03
STA $05
|
; A134142: List of quadruples: 2*(-4)^n, -3*(-4)^n, 2*(-4^n), 2*(-4)^n, n >= 0.
; 2,-3,2,2,-8,12,-8,-8,32,-48,32,32,-128,192,-128,-128,512,-768,512,512,-2048,3072,-2048,-2048,8192,-12288,8192,8192,-32768,49152,-32768,-32768,131072,-196608,131072,131072,-524288,786432,-524288,-524288,2097152,-3145728,2097152,2097152,-8388608
mov $1,4
mov $2,$0
mov $4,4
lpb $2
add $4,$1
add $1,1
mov $3,2
add $3,$1
sub $1,$1
sub $1,$4
mul $1,2
sub $2,1
add $3,7
mov $4,$3
lpe
sub $1,4
div $1,20
mul $1,5
add $1,2
|
; A112697: Partial sum of Catalan numbers A000108 multiplied by powers of 3.
; Submitted by Jamie Morken(s2)
; 1,4,22,157,1291,11497,107725,1045948,10428178,106126924,1097913928,11511677470,122057782762,1306480339462,14098243951822,153208673236237,1675240428936307,18417589741637077,203464608460961377,2257486516245461107,25145159202987029527,281070953791097294587,3151890736562073311347,35448613292735553499897,399755643726372410026741,4519227449399035326137977,51206574580355881708731985,581441445567651494196763933,6615148598181705015612299893,75399410137981915159749409837,860871299979571411644411891133
lpb $0
mov $2,$0
sub $0,1
seq $2,108 ; Catalan numbers: C(n) = binomial(2n,n)/(n+1) = (2n)!/(n!(n+1)!).
add $1,$2
mul $1,3
lpe
add $1,1
mov $0,$1
|
; draw the string 'F00' to the screen
; (C) Tamer Aly, 2018
; the beginning of the actual program
start
; draw the 'F'
ILOAD f_char ; load the 'F' into index
LOAD R0, $A ; load 10 into register 0
LOAD R1, $5 ; load 5 into register 1
DRAW R0, R1, $5 ; draw a 5 byte character
; draw the '0'
ILOAD o_char
ADD R0, $A ; move 10 pixels to the right
DRAW R0, R1, $5
; draw another '0'
ADD R0, $A ; move 10 pixels to the right
DRAW R0, R1, $5
end
JMP end ; loop indefinitely
; the character buffer for 'F'
f_char
LB $F0
LB $80
LB $F0
LB $80
LB $80
; the character buffer for '0' (poor man's zero)
o_char
LB $F0
LB $90
LB $90
LB $90
LB $F0 |
; A086228: Determinant of n X n matrix M(i,j)=binomial(2i+1, j).
; Submitted by Christian Krause
; 1,3,15,140,2520,88704,6150144,843448320,229417943040,123987652771840,133311524260282368,285432092670742757376,1217843595395169098137600,10360289146303272377017958400,175805226564926843718814452940800,5952811852882173575477382393762938880,402314836265188818925063411700074461265920,54283157578331735605738438307127223310195097600,14625281950775699901370438759683102128189666544844800,7869645608234824101202591559500858834073364522238948147200
mov $1,1
mov $2,$0
seq $0,86229 ; Determinant of n X n matrix M(i,j) = binomial(2i-1,j), (i,j) ranging from 1 to n.
add $1,$2
add $1,$2
mul $1,$0
mov $0,$1
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) erkeley Softworks 1990 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: Screen Dumps -- PostScript Common Code
FILE: psc.asm
AUTHOR: Adam de Boor, Jan 17, 1990
ROUTINES:
Name Description
---- -----------
PSCPreFreeze Fetch the strings we need from the UI before
the screen freezes and deadlock results.
PSCPrintf2 Print a formatted string with two possible
parameters.
PSCSlice Write a slice out to the file.
PSCPutChar Write a character to the inherited file buffer
PSCFlush Flush the inherited file buffer
PSCPrologue Produce a standard prologue with header comments
needed by EPS (does not take centering of
image by FPS module into account, but does
handle rotation)
PSCFormatInt Convert a 16-bit unsigned integer to ascii
in a passed buffer.
REVISION HISTORY:
Name Date Description
---- ---- -----------
Adam 1/17/90 Initial revision
DESCRIPTION:
Common postscript code required by both full-page and encapsulated
postscript output.
$Id: psc.asm,v 1.2 98/02/23 19:35:07 gene Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
include dump.def
include file.def
;include event.def
; NEW
include psc.def
include Objects/vTextC.def
MAX_LINE equ 70 ; Longest a line of image data may be
MAX_RUN equ 129 ; Longest a run of pixels may be
idata segment
widthText char 10 dup(0) ; Buffer for formatting width
heightText char 10 dup(0) ; Buffer for formatting height
iwidthText char 6 dup(0) ; Buffer for formatting image width
iheightText char 6 dup(0) ; Buffer for formatting image height
bboxWidth char 6 dup(0) ; Buffer for bounding box width
bboxHeight char 6 dup(0) ; Buffer for bounding box height
docTitle char MAX_LENGTH_IMAGE_NAME+1 dup(0) ; Buffer for text from ImageName
; object
DBCS< docTitleDBCS wchar MAX_LENGTH_IMAGE_NAME+1 dup(0) ; DBCS version of Image Name >
idata ends
PSC segment resource
;------------------------------------------------------------------------------
;
; POSTSCRIPT SNIPPETS
;
;------------------------------------------------------------------------------
;
; We always list the EPS version, even if producing a full-page version, as it
; is necessary for EPS, and doesn't hurt for FPS.
;
stdHeader char '\
%%!PS-Adobe-2.0 EPSF-2.0\n\
%%%%BoundingBox: 0 0 %1 %2\n\
%%%%Creator: dump.geo\n\
%%%%DocumentFonts: \n', 0
stdHeaderTheSequel char '\
%%%%Title: %1\n\
%%%%EndComments\n\
\n\
64 dict begin %% It is recommended that we have our own dictionary...\n',0
;
; Decoder for run-length encoding.
;
rlestring char '\
% Screen pixels are run-length encoded exactly as received from the kernel,\n\
% decoded by the procedure readrlestring, which returns a single packet of\n\
% pixels and translated to whatever format is appropriate for the type of\n\
% image being displayed (4-color, 4-bit greyscale, etc.) by some other\n\
% procedure that comes after readrlestring.\n\
\n\
/rlestr1 1 string def % single-element string for reading initial packet byte\n\
/rlestr 129 string def\n\
/readrlestring {\n\
currentfile rlestr1 readhexstring pop 0 get\n\
dup 127 le {\n\
currentfile rlestr 0\n\
4 3 roll % stack now (file rlestr 0 #)\n\
1 add % # is string index and we need length\n\
getinterval\n\
readhexstring\n\
pop % discard eof status\n\
} {\n\
257 exch sub % figure number of repetitions\n\
dup % save for after the loop\n\
currentfile rlestr1 readhexstring % read the byte to duplicate\n\
pop % discard eof status\n\
0 get % fetch the byte from rlestr1\n\
exch % bring count to the top\n\
0 exch % push initial loop value under count\n\
1 exch % push increment value under count\n\
1 sub % set terminate value. count is 1-origin, though\n\
{ rlestr exch 2 index put } % given index, fetch byte and store in rlestr\n\
for\n\
pop % discard replicated byte. original count still there\n\
rlestr exch 0 exch getinterval\n\
} ifelse\n\
} bind def\n'
;============================================================
; Prologues for the different formats we support
;============================================================
;
; File prologue for 4-bit greyscale images. Requires only a single buffer for
; unpacking a packet of bytes. EGA pixels are mapped to greyscale according to
; the normal formula (.57 green, .37 red and .18 blue, or thereabout) and ranked
; according to the results. The pixelToGrey array encodes this mapping given
; the indices used in the EGA screen.
;
greyPrologueStr char '\
/pixelToGreyMap [0 1 5 7 2 3 9 11 4 6 12 13 8 10 14 15] def\n\
/pixelToGrey {\n\
dup\n\
{\n\
dup % duplicate double-pixel\n\
-4 bitshift % bring left-most pixel into low nibble\n\
pixelToGreyMap exch get % map to proper greyscale using pixelToGreyMap\n\
4 bitshift % shift back up to high nibble\n\
exch 15 and % fetch double-pixel again and extract low nibble\n\
pixelToGreyMap exch get % map it to proper greyscale\n\
or % merge with high nibble greyscale\n\
exch % place under array we were passed\n\
} forall\n\
dup length 1 sub -1 0 {exch dup 4 2 roll exch put} for\n\
} bind def\n'
;
; Prologue and image command for 3-color, full-color images. Each packet is
; decoded once and stored, the individual procedures for the red, green and
; blue components translate that stored string using a different map and
; return the result (using 4-bit RGB)
;
threeColorPrologueStr char '\
/redMap [0 0 0 0 10 10 10 10 5 5 5 5 15 15 15 15] def\n\
/greenMap [0 0 10 10 0 0 5 10 5 5 15 15 5 5 15 15] def\n\
/blueMap [0 10 0 10 0 10 0 10 5 15 5 15 5 15 5 15] def\n\
/mapPixels {\n\
dup\n\
{\n\
dup % duplicate double-pixel\n\
-4 bitshift % bring left-most pixel into low nibble\n\
curMap exch get % map to proper value using current map\n\
4 bitshift % shift back up to high nibble\n\
exch 15 and % fetch double-pixel again and extract low nibble\n\
curMap exch get % map it to proper value\n\
or % merge with high nibble value\n\
exch % place under array we were passed\n\
} forall\n\
dup length 1 sub -1 0 {exch dup 4 2 roll exch put} for\n\
} bind def\n\
/greenStr 129 string def /blueStr 129 string def\n'
;
; Prologue and image command for 4-color, full-color images. Each packet is
; decoded once and stored, the individual procedures for the cyan, magenta,
; yellow and black components translate that stored string using a different
; map and return the result (using 4-bit CMYK)
;
fourColorPrologueStr char '\
/cyanMap [0 15 10 12 0 11 0 0 0 15 8 9 0 6 0 0] def\n\
/magentaMap [0 6 0 0 12 15 9 0 0 0 0 0 11 9 0 0] def\n\
/yellowMap [0 0 13 4 12 0 15 0 0 0 15 0 6 0 15 0] def\n\
/blackMap [15 0 0 0 4 0 4 6 12 0 0 0 0 0 0 0] def\n\
/mapPixels {\n\
dup\n\
{\n\
dup % duplicate double-pixel\n\
-4 bitshift % bring left-most pixel into low nibble\n\
curMap exch get % map to proper value using current map\n\
4 bitshift % shift back up to high nibble\n\
exch 15 and % fetch double-pixel again and extract low nibble\n\
curMap exch get % map it to proper value\n\
or % merge with high nibble value\n\
exch % place under array we were passed\n\
} forall\n\
dup length 1 sub -1 0 {exch dup 4 2 roll exch put} for\n\
} bind def\n\
/magentaStr 129 string def /yellowStr 129 string def /blackStr 129 string def\n'
;============================================================
; Image commands for the different formats we support
;============================================================
monoImageCmd char '\
%1 %2 1\n\
[ %1 0 0 -%2 0 %2 ]\n\
{ readrlestring }\n\
image\n', 0
greyImageCmd char '\
%1 %2 4\n\
[ %1 0 0 -%2 0 %2 ]\n\
{ readrlestring pixelToGrey }\n\
image\n', 0
threeColorImageCmd char '\
%1 %2 4\n\
[ %1 0 0 -%2 0 %2 ]\n\
{ readrlestring\n\
dup greenStr copy /greenPacket exch def\n\
dup blueStr copy /bluePacket exch def\n\
/curMap redMap def mapPixels }\n\
{ /curMap greenMap def greenPacket mapPixels }\n\
{ /curMap blueMap def bluePacket mapPixels }\n\
true 3 colorimage\n', 0
fourColorImageCmd char '\
%1 %2 4\n\
[ %1 0 0 -%2 0 %2 ]\n\
{ readrlestring\n\
dup magentaStr copy /magentaPacket exch def\n\
dup yellowStr copy /yellowPacket exch def\n\
dup blackStr copy /blackPacket exch def\n\
/curMap cyanMap def mapPixels }\n\
{ /curMap magentaMap def magentaPacket mapPixels }\n\
{ /curMap yellowMap def yellowPacket mapPixels }\n\
{ /curMap blackMap def blackPacket mapPixels }\n\
true 4 colorimage\n', 0
;============================================================
; COLOR SCHEME TABLE
;============================================================
ColorSchemeTable struct
CST_prologue nptr ; Extra prologue string
CST_prologueLen word ; Length of same
CST_image nptr ; Image command
ColorSchemeTable ends
colorSchemes ColorSchemeTable < ; PSCS_GREY
greyPrologueStr, length greyPrologueStr, greyImageCmd
>, < ; PSCS_RGB
threeColorPrologueStr, length threeColorPrologueStr, threeColorImageCmd
>, < ; PSCS_CMYK
fourColorPrologueStr, length fourColorPrologueStr, fourColorImageCmd
>
;============================================================
; Orientation set-up strings for different paper sizes.
; %1 is the user-specified width string, %2 is the user-specified height.
;============================================================
pageSetup char '\
%%EndProlog\n\
%%Page: 1 1\n'
pageSizeDef char \
'/width %1 def /height %2 def\n', 0
fpsPortraitSetup char '\
width %1 sub 2 div height %2 sub 2 div translate\n\
%1 %2 scale\n', 0
fpsLandscapeSetup char '\
width %2 sub 2 div %2 add height %1 sub 2 div translate\n\
90 rotate\n\
%1 %2 scale\n',0
epsPortraitSetup char '\
%1 %2 scale\n', 0
epsLandscapeSetup char '\
90 rotate\n\
%1 %2 scale\n',0
SetupTable struct
ST_epsPortrait nptr
ST_epsLandscape nptr
ST_fpsPortrait nptr
ST_fpsLandscape nptr
SetupTable ends
setupStrings SetupTable <
epsPortraitSetup, epsLandscapeSetup,
fpsPortraitSetup, fpsLandscapeSetup
>
;------------------------------------------------------------------------------
;
; BUFFERED OUTPUT
;
;------------------------------------------------------------------------------
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PSCWriteBuffer
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Write the PSCBuffer out to its file.
CALLED BY: PSCPutChar, PSCFlush
PASS: cx = number of bytes to write
PSCBuffer as first local variable of inherited stack frame
RETURN: carry set on error
DESTROYED: ax
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/17/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PSCWriteBuffer proc near uses bx, dx, ds
buffer local PSCBuffer
.enter inherit
segmov ds, ss, bx
mov bx, buffer.PB_file
lea dx, buffer.PB_data
clr al
call FileWrite
mov buffer.PB_ptr, 0
.leave
ret
PSCWriteBuffer endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PSCPutChar
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Write a single character to the current file.
CALLED BY: INTERNAL
PASS: al = character to write
PSCBuffer as first local variable for calling function
RETURN: carry set if an error occurred
DESTROYED: al
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/16/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PSCPutChar proc near uses di
buffer local PSCBuffer
.enter inherit
mov di, buffer.PB_ptr
mov buffer.PB_data[di], al
inc di
mov buffer.PB_ptr, di
cmp di, size (buffer.PB_data)
clc
jl done
push cx
mov cx, di
call PSCWriteBuffer
pop cx
done:
.leave
ret
PSCPutChar endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PSCFlush
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Flush any remaining characters in the buffer out to the file
CALLED BY: INTERNAL
PASS: PSCBuffer as first local variable for calling function
RETURN: carry set if an error occurred
DESTROYED: al
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/16/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PSCFlush proc near uses cx
buffer local PSCBuffer
.enter inherit
clc
mov cx, buffer.PB_ptr
jcxz done
call PSCWriteBuffer
done:
.leave
ret
PSCFlush endp
if 0 ; flagged as unused -- ardeb 9/4/91
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PSCWriteString
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Write a string to the output file using a buffer inherited
from our caller.
CALLED BY: PSCPrologue, EXTERNAL
PASS: cs:si = null-terminated string to be written
PSCBuffer as first local variable of caller's stack frame
RETURN: carry on error
DESTROYED: ax, si
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/17/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PSCWriteString proc near
buffer local PSCBuffer
.enter inherit
writeLoop:
lodsb cs:
tst al
jz done
call PSCPutChar
jmp writeLoop
done:
.leave
ret
PSCWriteString endp
endif
;------------------------------------------------------------------------------
;
; FORMATTED OUTPUT
;
;------------------------------------------------------------------------------
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PSCPrintf2
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Write a string out to the file, inserting arg1 for all
occurrences of %1 and arg2 for all occurrences of %2
CALLED BY: PSCPrologue
PASS: bp = file handle
cs:di = string to print
on stack (pushed in reverse order):
arg1 = offset in dgroup of buffer holding
null-terminated string for %1
arg2 = offset in dgroup of buffer holding
null-terminated string for %2
RETURN: carry set if couldn't write it all
args popped
DESTROYED: ax, di
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/16/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PSCPrintf2 proc near uses si arg1:word, arg2:word
buffer local PSCBuffer
.enter
mov ax, ss:[bp]
mov buffer.PB_file, ax
mov buffer.PB_ptr, 0
charLoopTop:
mov si, di
charLoop:
lodsb cs: ; Fetch next char
tst al ; Null terminator?
jz done
cmp al, '%' ; Format escape?
je special
putchar:
call PSCPutChar
jmp charLoop
done:
;
; String written -- flush the buffer to disk.
;
call PSCFlush
.leave
ret @ArgSize ; pop args on the way out
special:
;
; Extract the formatting code from the string and act on
; it. '1' => insert arg1, '2' => insert arg2, '%' => write
; a single '%'
;
lodsb cs:
cmp al, '%'
je putchar ; Double % => write single %
mov di, arg1
cmp al, '1'
je haveStr
EC < cmp al, '2' >
EC < ERROR_NE UNKNOWN_PRINTF2_CODE >
mov di, arg2
haveStr:
xchg si, di ; ds:si = string to write, di saves
; our position in formatting string.
specialLoop:
lodsb
tst al
jz charLoopTop ; => end of string, so discard si
; and pick up the other string where
; we left off.
call PSCPutChar
jmp specialLoop
PSCPrintf2 endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PSCFormatInt
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Convert an integer to ASCII in a buffer.
CALLED BY: INTERNAL/EXTERNAL
PASS: dx = number to convert
es:di = buffer in which to store the result
RETURN: buffer filled with null-terminated string
es:di = after null terminator
DESTROYED: ax, dx
PSEUDO CODE/STRATEGY:
The digits are gotten by repeatedly dividing the number
by 10 and pushing the remainder onto the stack. This leaves
us with the most significant digit on the top of the stack
when we reach a quotient of 0.
From there, we can just pop the digits off the stack, convert
them to ascii and store them away.
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/16/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PSCFormatInt proc near uses cx, bx
.enter
mov bx, 10
clr cx
mov ax, dx ; dividend is dx:ax...
divLoop:
clr dx ; Make sure high word is clear
div bx ; ax <- quotient, dx <- remainder
push dx ; the remainder makes up the next digit.
inc cx
tst ax ; Was number < 10?
jnz divLoop ; Nope -- more digits to get
cvtLoop:
pop ax ; Fetch next digit of lesser significance
add al, '0' ; Convert to ascii
stosb
loop cvtLoop
clr al ; null-terminate
stosb
.leave
ret
PSCFormatInt endp
;------------------------------------------------------------------------------
;
; PROLOGUE PIECES
;
;------------------------------------------------------------------------------
if 0 ; flagged as unused -- ardeb 9/4/91
;
; Table of powers of ten indexed by the number of converted digits.
;
powersOfTen word 1, 10, 100, 1000, 10000, 10000
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PSCCvtInt
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Convert a string to an integer until a non-integer character
is found.
CALLED BY: PSCAToWWFixed
PASS: ds:si = string to convert
RETURN: bh = number of characters converted
bl = terminating character
ds:si = address of al + 1
ax = result
DESTROYED: nothing
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/18/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PSCCvtInt proc near uses cx
.enter
clr ax
mov bh, al ; No digits converted yet
mov cx, 10 ; For multiplication
intLoop:
xchg ax, bx
lodsb
xchg ax, bx
cmp bl, '0'
jb doneInt
cmp bl, '9'
ja doneInt
inc bh ; Another digit converted
sub bl, '0' ; Convert to binary
mul cx ; Make room for new digit
add al, bl
adc ah, 0
jmp intLoop
doneInt:
.leave
ret
PSCCvtInt endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PSCAToWWFixed
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Convert a floating-point number (w/o exponent) to a WWFixed
CALLED BY: PSCPrologue
PASS: ds:si = string to convert
es:di = WWFixed in which to store the result.
RETURN:
DESTROYED: si
PSEUDO CODE/STRATEGY:
To make this reasonably fast, we first convert the integer
portion and store it away in the normal manner.
We then convert the fractional portion in the same way, keeping
track of the number of digits so converted. When done, we choose
the power of 10 that corresponds to the number of digits (we
keep a table of the powers...) and use GrUDivWWFixed to divide
what we've got by that power, obtaining a number that is all
fraction, which we stuff in the fractional part of the result.
If the number of converted digits is 5 (no more will fit in a
word), we will need to divide the result by 10 again to obtain
the true value (we can't represent 100,000 in a WWFixed).
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/18/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PSCAToWWFixed proc near uses cx, dx, ax, bx
.enter
mov es:[di].WWF_frac, 0 ; in case no fraction
call PSCCvtInt
mov es:[di].WWF_int, ax
cmp bl, '.'
jne done ; not end on '.' => no fraction
call PSCCvtInt
push bx ; Save count in case it's > 5
mov dx, ax ; dx = integer part
clr cx ; cx = fraction of divisor (0)
mov ax, cx ; ax = fraction of dividend (0)
mov bl, bh ; bx = index in powersOfTen
mov bh, al ; ...
shl bx ; ...
mov bx, cs:powersOfTen[bx] ; bx = integer of divisor
call GrUDivWWFixed
pop bx ; Was divisor too big to fit
cmp bh, 5 ; in a word?
jl haveFrac ; >= 5 is yes
mov bx, 10 ; Perform extra divide (if #
call GrUDivWWFixed ; digits > 5, we've lost
; precision anyway...
haveFrac:
mov es:[di].WWF_frac, cx
done:
.leave
ret
PSCAToWWFixed endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PSCFloatToUnits
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Convert a string in floating-point notation signifying
inches into a string in decimal signifying PostScript
default-coordinate units (1/72 of an inch)
CALLED BY: PSCPrologue
PASS: ds:si = floating-point string
es:di = decimal string
RETURN: nothing
DESTROYED: si, di
PSEUDO CODE/STRATEGY:
Convert the floating-point string to WWFixed
Multiply it by 72 to get the number of units
Convert the integer portion of the result back to ascii
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/18/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
seventyTwo WWFixed <0,72>
PSCFloatToUnits proc near
temp local WWFixed
.enter
push es, di
segmov es, ss, di
lea di, temp
call PSCAToWWFixed
push ds
segmov ds, cs, si
lea si, seventyTwo
call GrMulWWFixedPtr
pop ds
pop es, di
call PSCFormatInt
.leave
ret
PSCFloatToUnits endp
endif
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PSCStartImage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Put out the image/colorimage command to print the bitmap
CALLED BY: PSCPrologue
PASS: cx = image width
dx = image height
si = bitmap format
ds = dgroup
bp = file handle
bx = 0 for EPS, 4 for FPS (indexes setupStrings)
RETURN: carry set if couldn't write the string.
DESTROYED: cx, dx, di
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/16/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PSCStartImage proc near
.enter
;
; Define the paper width and height, in case they're needed by the
; setup string.
;
push dx
mov dx, ds:[procVars].DI_psPageHeight
mov di, offset iheightText
push di
call PSCFormatInt
mov dx, ds:[procVars].DI_psPageWidth
mov di, offset iwidthText
push di
call PSCFormatInt
mov di, offset pageSizeDef
call PSCPrintf2
pop dx
;
; Put out the proper commands to setup the orientation and
; scaling of the image.
;
tst ds:procVars.DI_psRotate?
jz 10$
add bx, 2
10$:
mov di, {nptr.char}cs:setupStrings[bx]
mov ax, offset heightText
push ax
mov ax, offset widthText
push ax
call PSCPrintf2
;
; Convert the image height to ascii and push it to pass to
; PSCPrintf2
;
mov di, offset iheightText
push di
call PSCFormatInt
;
; Convert the image width to ascii and push it to pass to
; PSCPrintf2
;
mov di, offset iwidthText
push di
mov dx, cx
call PSCFormatInt
;
; Figure which image snippet to use:
; BMF_MONO monoImageCmd
; BMF_4BIT use DI_psColorScheme as index into
; colorSchemes to get CST_image
;
mov di, offset monoImageCmd
cmp si, BMF_MONO
je haveStr
cmp si, BMF_4BIT
jne choke
mov di, ds:procVars.DI_psColorScheme
mov di, cs:colorSchemes[di].CST_image
haveStr:
call PSCPrintf2
done:
.leave
ret
choke:
add sp, 2*(size word) ;clean up stack
stc
jmp done
PSCStartImage endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PSCFormatImageDim
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Format one of the image dimensions into a floating-point
string (in points)
CALLED BY: PSCPreFreeze
PASS: ax = dimension to format (points * 8, so low 3 bits are
fraction)
ds:di = buffer in which to place the result
RETURN: ds:di = after null-terminator
DESTROYED: ax
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 9/ 4/91 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
dimFracStrings nptr.char dimFrac_0, dimFrac_125, dimFrac_25,
dimFrac_375, dimFrac_5, dimFrac_625,
dimFrac_75, dimFrac_875
dimFrac_0 char 0
dimFrac_125 char '.125', 0
dimFrac_25 char '.25', 0
dimFrac_375 char '.375', 0
dimFrac_5 char '.5', 0
dimFrac_625 char '.625', 0
dimFrac_75 char '.75', 0
dimFrac_875 char '.875', 0
PSCFormatImageDim proc near
uses es, dx, si
.enter
segmov es, ds ; es:di <- buffer
mov si, ax ; save for fraction
;
; Truncate the dimension by shifting right 3 bits to right-justify
; the integer, then format it into the buffer.
;
shr ax
shr ax
shr ax
mov_trash dx, ax
call PSCFormatInt
dec di ; es:di <- null terminator
;
; Now use the fraction to index into the table and copy the proper
; string at the end of the buffer, including its null-terminator
;
andnf si, 0x7
shl si
mov si, cs:[dimFracStrings][si]
copyFrac:
lodsb cs:
stosb
tst al
jnz copyFrac
.leave
ret
PSCFormatImageDim endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PSCPreFreeze
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Fetch the strings from the various text objects in which
the user can type them.
CALLED BY: DumpPreFreeze
PASS: ds = dgroup
RETURN: carry set if either the width or the height is empty
widthText, heightText filled from their objects
docTitle filled from ImageName or empty (0 at the front)
DESTROYED: bx, si, cx, dx, ax, di, bp
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/18/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PSCPreFreeze proc far
.enter
GetText macro sourceObj, destBuf
mov bx, handle sourceObj
mov si, offset sourceObj
mov dx, ds
mov bp, offset destBuf
mov ax, MSG_VIS_TEXT_GET_ALL_PTR
mov di, mask MF_CALL
call ObjMessage
endm
mov di, offset widthText
mov ax, ds:[procVars].DI_psImageWidth
call PSCFormatImageDim
mov di, offset heightText
mov ax, ds:[procVars].DI_psImageHeight
call PSCFormatImageDim
;
; Fetch the title from the text object. If none there, use
; the file name.
;
mov {char} ds:docTitle[0], 0
if DBCS_PCGEOS
push es
GetText ImageName, docTitleDBCS ; strlen -> cx
; dx:bp = text ptr
;
; Pass a Unicode length that does include NULL.
; This means the converted string will be null terminated
;
mov si, bp ; ds:si = Unicode buffer
segmov es, ds, ax
mov di, offset docTitle ; es:di = DOS char buffer
clr ax, bx, dx
inc cx ; count that NULL
call LocalGeosToDos ; strlen(DOS) w/NULL -> cx
pop es
else
GetText ImageName, docTitle
endif
;
; Fetch paper size from the paper size list.
;
sub sp, size PageSizeReport
mov dx, ss
mov bp, sp
mov bx, handle PaperControl
mov si, offset PaperControl
mov ax, MSG_PZC_GET_PAGE_SIZE
mov di, mask MF_CALL
call ObjMessage
mov cx, ss:[bp].PSR_width.low
mov ds:[procVars].DI_psPageWidth, cx
mov dx, ss:[bp].PSR_height.low
mov ds:[procVars].DI_psPageHeight, dx
add sp, size PageSizeReport
clc
.leave
ret
PSCPreFreeze endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PSCPrologue
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Produce the standard file prologue, including the required
image command
CALLED BY: EXTERNAL
PASS: bx = PSTypes
cx = image width (pixels)
dx = image height (pixels)
si = image format (BMFormat)
bp = file handle
RETURN: carry if couldn't write the whole header
DESTROYED: lots of neat things
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/18/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PSCPrologue proc near uses bx
.enter
push bx, cx, dx, si
;
; Convert final width to units, storing the result in bboxWidth
; or bboxHeight, depending on whether the image is being
; rotated.
;
mov ax, ds:[procVars].DI_psImageWidth
mov di, offset bboxWidth
tst ds:procVars.DI_psRotate?
jz 10$
mov di, offset bboxHeight
10$:
add ax, 7 ; round up
andnf ax, not 7
call PSCFormatImageDim
;
; Convert final height to units, storing the result in
; bboxHeight or bboxWidth, depending on whether the image is
; being rotated.
;
mov ax, ds:[procVars].DI_psImageHeight
mov si, offset heightText
mov di, offset bboxHeight
tst ds:procVars.DI_psRotate?
jz 20$
mov di, offset bboxWidth
20$:
add ax, 7
andnf ax, not 7
call PSCFormatImageDim
;
; Print the version string and the bounding box.
;
mov ax, offset bboxHeight
push ax
mov ax, offset bboxWidth
push ax
mov di, offset stdHeader
call PSCPrintf2
;
; Give the thing a title and start our dictionary
;
mov ax, offset docTitle
push ax
push ax
mov di, offset stdHeaderTheSequel
call PSCPrintf2
;
; Spew the standard run-length decoder.
;
push ds
mov bx, bp
segmov ds, cs, dx
mov dx, offset rlestring
mov cx, size rlestring
clr al
call FileWrite
pop ds
jc popErrorSI_DX_CX_BX
;
; Spew any additional code required by the output format before
; the start of the page.
;
pop si ; Recover bitmap format
push ds
mov di, ds:procVars.DI_psColorScheme
segmov ds, cs, dx
cmp si, BMF_MONO
je headerWritten
;XXX: DEAL WITH > 4 BITS HERE
mov dx, cs:colorSchemes[di].CST_prologue
mov cx, cs:colorSchemes[di].CST_prologueLen
clr al
call FileWrite
jc 40$
headerWritten:
;
; Finish the prologue and start the page.
;
mov dx, offset pageSetup
mov cx, size pageSetup
clr al
call FileWrite
40$:
pop ds
jc popErrorDX_CX_BX
;
; Now produce the proper image command to start the whole thing
; off.
;
pop dx ; image height
pop cx ; image width
pop bx ; extra index for setupStrings
call PSCStartImage
done:
.leave
ret
error:
stc
jmp done
popErrorSI_DX_CX_BX:
pop si
popErrorDX_CX_BX:
pop bx, cx, dx
jmp error
PSCPrologue endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PSCOutByte
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Spew a byte to the output file as two hex digits, dealing
with wrapping lines at a resonable point.
CALLED BY: PSCSlice, PSCFlushNonRun
PASS: al = byte to write
PSCBuffer as first local variable of current stack frame
RETURN: nothing
DESTROYED: ax
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/17/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PSCOutByte proc near
buffer local PSCBuffer
lineCount local word
.enter inherit
mov ah, al
shr al
shr al
shr al
shr al
add al, '0'
cmp al, '9'
jle notHex
add al, 'A' - ('9' + 1)
notHex:
push ax
call PSCPutChar
pop ax
mov al, ah
andnf al, 0xf
add al, '0'
cmp al, '9'
jle notHex2
add al, 'A' - ('9' + 1)
notHex2:
call PSCPutChar
sub lineCount, 2
ja noNL
mov al, '\n'
call PSCPutChar
mov lineCount, MAX_LINE
noNL:
.leave
ret
PSCOutByte endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PSCFlushNonRun
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Flush any pending non-run packet to the file
CALLED BY: PSCSlice
PASS: bh = count of non-run bytes in current packet
ds:dx = start of non-run packet
RETURN: bh = new non-run count (> 0 if bh was too large on input;
note the size can only be off by one since we can
only add two bytes [for a run of only two matching
bytes] to the packet at a time)
ds:dx = adjusted to start of packet if bh non-zero
DESTROYED:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/17/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PSCFlushNonRun proc near uses si, cx
.enter inherit PSCSlice
tst bh
jz done
mov si, dx
mov al, bh ; Transfer count to AL for writing
clr cx ; Need in CX as well for looping
mov cl, al
clr bh ; Assume packet small enough
dec al ; By definition, reduce the count by 1
jns smallEnough ; => not 128, so we're ok.
dec cx
dec ax ; bring w/in range (one-byte
; instruction when use ax)...
inc bh ; Indicate extra byte hanging around
smallEnough:
call PSCOutByte ; Ship off the count byte
flushLoop:
lodsb
xor al, ss:[invert]
call PSCOutByte
loop flushLoop
tst bh
jz done
mov dx, si ; Point dx to the start of the new
; packet
done:
.leave
ret
PSCFlushNonRun endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PSCSlice
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Write a single bitmap slice out to the file
CALLED BY: DumpScreen
PASS: bp = file handle
si = bitmap block handle
cx = size of bitmap (bytes)
RETURN: Carry set on error
Block is *not* freed.
DESTROYED: ax, bx, cx
PSEUDO CODE/STRATEGY:
while (count > 0) {
count--;
match = *bp++;
matchCount = 1;
count matches until find non-matching or hit matchCount of 129;
if (matchCount > 2) {
/*
* worthwhile repeating. Flush previous non-run, if any.
*/
if (nonrunCount != 0) {
write non-run packet, subtracting 1 from initial
count byte.
}
nonrunCount = 0
output 257 - matchCount and match byte
} else {
/*
* Merge unmatching data into existing non-run packet unless
* it won't fit.
*/
if (nonrunCount + matchCount > 128) {
/*
* Flush previous non-run
*/
write non-run packet, subtracting 1 from initial
count byte.
nonrunCount = matchCount
} else {
nonrunCount += matchCount
}
}
}
if (nonrunCount != 0) {
flush pending non-run
}
register assignments:
ds:si = bp
ah = match
cx = count
bl = matchCount
bh = nonrunCount
dx = start of non-run
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 12/ 4/89 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PSCSlice proc near uses ds, dx
buffer local PSCBuffer
lineCount local word
invert local byte
.enter
mov ax, ss:[bp]
mov buffer.PB_file, ax
mov buffer.PB_ptr, 0
mov lineCount, MAX_LINE ; Initialize for PSCOutByte
push si ; Save block handle for free
mov bx, si
call MemLock
mov ds, ax
;
; Figure whether we need to invert the data we get from
; the bitmap (required only for monochrome bitmaps)
;
CheckHack <BMF_MONO eq 0>
clr ax
test ds:[B_type], mask BMT_FORMAT
jnz setInvert
dec ax
setInvert:
mov ss:[invert], al
mov si, size Bitmap
sub cx, size Bitmap
clr bx ; initialize non-run
; count
byteLoop:
lodsb ; Fetch next byte
xor al, ss:[invert]
mov ah, al ; Save it for comparison
clr bl ; Initialize run counter
matchLoop:
inc bl ; Another byte matched
dec cx ; and consumed
jcxz endMatchLoop
cmp bl, MAX_RUN ; Hit bounds of run?
je endMatchLoop ; Oui.
lodsb ; Non. See if next byte matches
xor al, ss:[invert]
cmp ah, al
je matchLoop
mov al, ah ; Need repeated byte in al...
dec si ; Don't skip non-match
endMatchLoop:
cmp bl, 2 ; Worth repeating?
jbe dontBother
push ax
call PSCFlushNonRun ; Flush any pending non-run
pop ax
xchg al, bl ; Preserve repeated byte and
clr ah ; get count into ax
sub ax, 257 ; Figure repeat count byte
neg ax ; Operands in wrong order...
call PSCOutByte ; Print repeat count
mov al, bl ; Recover repeated byte
call PSCOutByte ; and ship it off too
endLoop:
jcxz done ; Out of bytes?
jmp byteLoop ; Back into the fray
dontBother:
;
; Add the non-matching bytes into any current non-run packet.
; If this is the start of one (bh [nonrunCount] is 0), we need
; to record the start address of the packet for later flushing.
;
tst bh
jnz alreadyStarted
mov dx, si
sub dl, bl ; Point back at start of non-
sbb dh, 0 ; matching range.
alreadyStarted:
add bh, bl ; Increase the length of the
; packet
jno endLoop ; => < 128, so we're still ok
call PSCFlushNonRun ; Flush the run. If bh > 128,
; this will take care of it.
jmp endLoop ; Test for finish...
done:
;
; Flush any pending non-run packet and free the block,
; signalling our success by returning with the carry clear.
;
call PSCFlushNonRun
mov al, '\n'
call PSCPutChar
call PSCFlush
pop si ; Recover block handle
mov bx, si
call MemUnlock
clc
.leave
ret
PSCSlice endp
;
; Universal epilogue -- just add the Trailer comment (required) and pop our
; dictionary off the stack.
;
pscEpilogue char '\
%%Trailer\n\
end\n'
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
PSCEpilogue
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Finish whatever we started here.
CALLED BY: EXTERNAL
PASS: bp = file handle
RETURN: carry set on error
DESTROYED:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
ardeb 1/19/90 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
PSCEpilogue proc near uses ds, dx, cx
.enter
mov bx, bp
segmov ds, cs, dx
mov dx, offset pscEpilogue
mov cx, size pscEpilogue
clr al
call FileWrite
.leave
ret
PSCEpilogue endp
PSC ends
|
Music_MagnetTrain:
musicheader 4, 1, Music_MagnetTrain_Ch1
musicheader 1, 2, Music_MagnetTrain_Ch2
musicheader 1, 3, Music_MagnetTrain_Ch3
musicheader 1, 4, Music_MagnetTrain_Ch4
Music_MagnetTrain_Ch1:
tempo 110
volume $77
stereopanning $f
vibrato $14, $23
dutycycle $2
notetype $c, $b2
note __, 16
note __, 16
intensity $b7
octave 4
note D_, 1
note C_, 1
octave 3
note G_, 1
octave 4
note C_, 1
note D_, 1
note C_, 1
octave 3
note G_, 1
octave 4
note C_, 1
note D_, 1
note C_, 1
octave 3
note G_, 1
octave 4
note C_, 1
note D_, 1
note C_, 1
octave 3
note G_, 1
octave 4
note C_, 1
note E_, 1
note C_, 1
octave 3
note A_, 1
octave 4
note C_, 1
note E_, 1
note C_, 1
octave 3
note A_, 1
octave 4
note C_, 1
note E_, 1
note C_, 1
octave 3
note A_, 1
octave 4
note C_, 1
note E_, 1
note C_, 1
notetype $6, $b7
note F#, 1
note __, 1
note F#, 1
note __, 1
notetype $c, $b7
note D_, 16
endchannel
Music_MagnetTrain_Ch2:
vibrato $14, $23
dutycycle $1
notetype $c, $d2
stereopanning $f0
notetype $c, $d8
octave 1
note F_, 12
note __, 2
notetype $6, $d7
note F_, 1
note __, 1
note F_, 1
note __, 1
octave 2
note F_, 4
note __, 4
note F_, 4
note __, 4
note F_, 4
note __, 4
note F_, 4
note __, 4
dutycycle $3
notetype $c, $d7
octave 4
note G_, 16
note A_, 13
note __, 1
notetype $6, $d7
note A_, 1
note __, 1
note A_, 1
note __, 1
notetype $c, $d7
note A_, 16
endchannel
Music_MagnetTrain_Ch3:
stereopanning $ff
vibrato $10, $23
notetype $c, $15
octave 6
note C_, 1
octave 5
note G_, 1
note D#, 1
note C_, 1
note G_, 1
note D#, 1
note C_, 1
octave 4
note G_, 1
octave 5
note D#, 1
note C_, 1
octave 4
note G_, 1
note D#, 1
octave 5
note C_, 1
octave 4
note G_, 1
note D#, 1
note C_, 1
note G_, 1
note D#, 1
note C_, 1
octave 3
note G_, 1
octave 4
note C_, 1
note D#, 1
note G_, 1
note C_, 1
note D#, 1
note G_, 1
octave 5
note C_, 1
octave 4
note G_, 1
octave 5
note C_, 1
note D#, 1
note G_, 1
note C_, 1
octave 2
note D_, 1
octave 3
note D_, 1
octave 2
note D_, 1
octave 3
note D_, 1
octave 2
note D_, 1
octave 3
note D_, 1
octave 2
note D_, 1
octave 3
note D_, 1
octave 2
note D_, 1
octave 3
note D_, 1
octave 2
note D_, 1
octave 3
note D_, 1
octave 2
note D_, 1
octave 3
note D_, 1
octave 2
note D_, 1
octave 3
note D_, 1
octave 2
note D_, 1
octave 3
note D_, 1
octave 2
note D_, 1
octave 3
note D_, 1
octave 2
note D_, 1
octave 3
note D_, 1
octave 2
note D_, 1
octave 3
note D_, 1
octave 2
note D_, 1
octave 3
note D_, 1
octave 2
note D_, 1
octave 3
note D_, 1
octave 2
note D_, 1
octave 3
note D_, 1
octave 2
note D_, 1
octave 3
note D_, 1
octave 2
note D_, 16
endchannel
Music_MagnetTrain_Ch4:
togglenoise $3
notetype $c
note B_, 12
note D_, 2
note A#, 1
note A#, 1
notetype $6
note D#, 4
note F#, 4
note D#, 4
note F#, 4
note A#, 4
note F#, 4
note A#, 4
note D_, 2
note D_, 2
callchannel Music_MagnetTrain_branch_ef71e
callchannel Music_MagnetTrain_branch_ef71e
notetype $c
note B_, 16
endchannel
; unused
Music_MagnetTrain_branch_ef711:
note G#, 1
note G_, 1
note G_, 1
note G#, 1
note G_, 1
note G_, 1
note G#, 1
note G_, 1
note G_, 1
note G#, 1
note G_, 1
note G_, 1
endchannel
Music_MagnetTrain_branch_ef71e:
note G#, 2
note G_, 2
note G_, 2
note G_, 2
note G#, 2
note G_, 2
note G_, 2
note G_, 2
note G#, 2
note G_, 2
note G_, 2
note G_, 2
note G#, 2
note G_, 2
note G_, 2
note G_, 2
endchannel
|
/*
* (C) Copyright 1996-2012 ECMWF.
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
* In applying this licence, ECMWF does not waive the privileges and immunities
* granted to it by virtue of its status as an intergovernmental organisation nor
* does it submit to any jurisdiction.
*/
#include "eckit/sql/type/SQLType.h"
#include <map>
#include <memory>
#include <mutex>
#include "eckit/exception/Exceptions.h"
#include "eckit/log/Log.h"
#include "eckit/sql/type/SQLDouble.h"
#include "eckit/sql/type/SQLInt.h"
#include "eckit/sql/type/SQLReal.h"
#include "eckit/sql/type/SQLString.h"
#include "eckit/thread/ThreadSingleton.h"
#include "eckit/utils/Translator.h"
using namespace eckit;
namespace eckit {
namespace sql {
namespace type {
//----------------------------------------------------------------------------------------------------------------------
class TypeRegistry {
public:
TypeRegistry();
~TypeRegistry() = default;
static TypeRegistry& instance();
// enregister takes ownership
void enregister(SQLType* t);
void registerAlias(const std::string& name, const std::string& alias);
const SQLType* lookup(const std::string& name);
private:
void enregisterInternal(SQLType* t);
std::mutex m_;
std::map<std::string, std::unique_ptr<SQLType>> map_;
std::map<std::string, const SQLType*> aliases_;
};
//----------------------------------------------------------------------------------------------------------------------
TypeRegistry::TypeRegistry() {
enregisterInternal(new SQLInt("integer"));
enregisterInternal(new SQLReal("real"));
enregisterInternal(new SQLDouble("double"));
}
TypeRegistry& TypeRegistry::instance() {
static TypeRegistry theRegistry;
return theRegistry;
}
void TypeRegistry::enregister(SQLType* t) {
std::lock_guard<std::mutex> lock(m_);
enregisterInternal(t);
}
void TypeRegistry::enregisterInternal(SQLType* t) {
map_.emplace(std::make_pair(t->name(), std::unique_ptr<SQLType>(t)));
}
void TypeRegistry::registerAlias(const std::string& name, const std::string& alias) {
std::lock_guard<std::mutex> lock(m_);
auto it = map_.find(name);
ASSERT(it != map_.end());
aliases_.emplace(std::make_pair(alias, it->second.get()));
}
const SQLType* TypeRegistry::lookup(const std::string& name) {
std::lock_guard<std::mutex> lock(m_);
auto it = map_.find(name);
if (it != map_.end())
return it->second.get();
auto it2 = aliases_.find(name);
if (it2 != aliases_.end())
return it2->second;
return nullptr;
}
SQLType::SQLType(const std::string& name) :
name_(name) {}
SQLType::~SQLType() {}
size_t SQLType::width() const {
return 14;
}
SQLType::manipulator SQLType::format() const {
return &std::right;
}
bool SQLType::exists(const std::string& name) {
const SQLType* typ = TypeRegistry::instance().lookup(name);
return !!typ;
}
const SQLType& SQLType::lookup(const std::string& name, size_t sizeDoubles) {
std::string lookupName = name;
if (name == "string") {
lookupName += Translator<size_t, std::string>()(sizeof(double) * sizeDoubles);
}
else {
ASSERT(sizeDoubles == 1);
}
const SQLType* typ = TypeRegistry::instance().lookup(lookupName);
if (!typ && name == "string") {
typ = SQLType::registerType(new SQLString(lookupName, sizeof(double) * sizeDoubles));
}
if (!typ)
throw eckit::SeriousBug(name + ": type not defined");
return *typ;
}
void SQLType::createAlias(const std::string& name, const std::string& alias) {
TypeRegistry::instance().registerAlias(name, alias);
}
SQLType* SQLType::registerType(SQLType* t) {
TypeRegistry::instance().enregister(t);
return t;
}
void SQLType::print(std::ostream& s) const {
s << name_;
}
const SQLType* SQLType::subType(const std::string&) const {
return this;
}
} // namespace type
} // namespace sql
} // namespace eckit
|
; this example gets the number from the user,
; and calculates factorial for it.
; supported input from 0 to 8 inclusive!
name "fact"
; this macro prints a char in AL and advances
; the current cursor position:
putc macro char
push ax
mov al, char
mov ah, 0eh
int 10h
pop ax
endm
org 100h
jmp start
result dw ?
start:
; get first number:
mov dx, offset msg1
mov ah, 9
int 21h
jmp n1
msg1 db 0Dh,0Ah, 'enter the number: $'
n1:
call scan_num
; factorial of 0 = 1:
mov ax, 1
cmp cx, 0
je print_result
; move the number to bx:
; cx will be a counter:
mov bx, cx
mov ax, 1
mov bx, 1
calc_it:
mul bx
cmp dx, 0
jne overflow
inc bx
loop calc_it
mov result, ax
print_result:
; print result in ax:
mov dx, offset msg2
mov ah, 9
int 21h
jmp n2
msg2 db 0Dh,0Ah, 'factorial: $'
n2:
mov ax, result
call print_num_uns
jmp exit
overflow:
mov dx, offset msg3
mov ah, 9
int 21h
jmp n3
msg3 db 0Dh,0Ah, 'the result is too big!', 0Dh,0Ah, 'use values from 0 to 8.$'
n3:
jmp start
exit:
; wait for any key press:
mov ah, 0
int 16h
ret
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; these functions are copied from emu8086.inc ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; gets the multi-digit SIGNED number from the keyboard,
; and stores the result in CX register:
SCAN_NUM PROC NEAR
PUSH DX
PUSH AX
PUSH SI
MOV CX, 0
; reset flag:
MOV CS:make_minus, 0
next_digit:
; get char from keyboard
; into AL:
MOV AH, 00h
INT 16h
; and print it:
MOV AH, 0Eh
INT 10h
; check for MINUS:
CMP AL, '-'
JE set_minus
; check for ENTER key:
CMP AL, 0Dh ; carriage return?
JNE not_cr
JMP stop_input
not_cr:
CMP AL, 8 ; 'BACKSPACE' pressed?
JNE backspace_checked
MOV DX, 0 ; remove last digit by
MOV AX, CX ; division:
DIV CS:ten ; AX = DX:AX / 10 (DX-rem).
MOV CX, AX
PUTC ' ' ; clear position.
PUTC 8 ; backspace again.
JMP next_digit
backspace_checked:
; allow only digits:
CMP AL, '0'
JAE ok_AE_0
JMP remove_not_digit
ok_AE_0:
CMP AL, '9'
JBE ok_digit
remove_not_digit:
PUTC 8 ; backspace.
PUTC ' ' ; clear last entered not digit.
PUTC 8 ; backspace again.
JMP next_digit ; wait for next input.
ok_digit:
; multiply CX by 10 (first time the result is zero)
PUSH AX
MOV AX, CX
MUL CS:ten ; DX:AX = AX*10
MOV CX, AX
POP AX
; check if the number is too big
; (result should be 16 bits)
CMP DX, 0
JNE too_big
; convert from ASCII code:
SUB AL, 30h
; add AL to CX:
MOV AH, 0
MOV DX, CX ; backup, in case the result will be too big.
ADD CX, AX
JC too_big2 ; jump if the number is too big.
JMP next_digit
set_minus:
MOV CS:make_minus, 1
JMP next_digit
too_big2:
MOV CX, DX ; restore the backuped value before add.
MOV DX, 0 ; DX was zero before backup!
too_big:
MOV AX, CX
DIV CS:ten ; reverse last DX:AX = AX*10, make AX = DX:AX / 10
MOV CX, AX
PUTC 8 ; backspace.
PUTC ' ' ; clear last entered digit.
PUTC 8 ; backspace again.
JMP next_digit ; wait for Enter/Backspace.
stop_input:
; check flag:
CMP CS:make_minus, 0
JE not_minus
NEG CX
not_minus:
POP SI
POP AX
POP DX
RET
make_minus DB ? ; used as a flag.
SCAN_NUM ENDP
; this procedure prints number in AX,
; used with PRINT_NUM_UNS to print signed numbers:
PRINT_NUM PROC NEAR
PUSH DX
PUSH AX
CMP AX, 0
JNZ not_zero
PUTC '0'
JMP printed
not_zero:
; the check SIGN of AX,
; make absolute if it's negative:
CMP AX, 0
JNS positive
NEG AX
PUTC '-'
positive:
CALL PRINT_NUM_UNS
printed:
POP AX
POP DX
RET
PRINT_NUM ENDP
; this procedure prints out an unsigned
; number in AX (not just a single digit)
; allowed values are from 0 to 65535 (FFFF)
PRINT_NUM_UNS PROC NEAR
PUSH AX
PUSH BX
PUSH CX
PUSH DX
; flag to prevent printing zeros before number:
MOV CX, 1
; (result of "/ 10000" is always less or equal to 9).
MOV BX, 10000 ; 2710h - divider.
; AX is zero?
CMP AX, 0
JZ print_zero
begin_print:
; check divider (if zero go to end_print):
CMP BX,0
JZ end_print
; avoid printing zeros before number:
CMP CX, 0
JE calc
; if AX<BX then result of DIV will be zero:
CMP AX, BX
JB skip
calc:
MOV CX, 0 ; set flag.
MOV DX, 0
DIV BX ; AX = DX:AX / BX (DX=remainder).
; print last digit
; AH is always ZERO, so it's ignored
ADD AL, 30h ; convert to ASCII code.
PUTC AL
MOV AX, DX ; get remainder from last div.
skip:
; calculate BX=BX/10
PUSH AX
MOV DX, 0
MOV AX, BX
DIV CS:ten ; AX = DX:AX / 10 (DX=remainder).
MOV BX, AX
POP AX
JMP begin_print
print_zero:
PUTC '0'
end_print:
POP DX
POP CX
POP BX
POP AX
RET
PRINT_NUM_UNS ENDP
ten DW 10 ; used as multiplier/divider by SCAN_NUM & PRINT_NUM_UNS.
|
;--------------------------------------------------------------------------------
; Init_Primary
;--------------------------------------------------------------------------------
; This can be as inefficient as we want. Interrupts are off when this gets
; called and it only gets called once ever during RESET.
;--------------------------------------------------------------------------------
Init_Primary:
LDA #$00
LDX #$00 ; initalize our ram
-
STA $7EC025, X
STA $7F5000, X
INX
CPX #$10 : !BLT -
LDX #$10 ; initalize more ram
-
STA $7F5000, X
INX
CPX #$FF : !BLT -
LDX #$00
-
LDA $702000, X : CMP $00FFC0, X : BNE .clear
INX
CPX #$15 : !BLT -
BRA .done
.clear
REP #$30 ; set 16-bit accumulator & index registers
LDA.w #$0000
-
STA $700000, X
INX
CPX #$2000 : !BLT -
SEP #$30 ; set 8-bit accumulator & index registers
LDX #$00
-
LDA $00FFC0, X : STA $702000, X
INX
CPX #$15 : !BLT -
.done
LDA DeathLink : STA $702000, X ; move death link byte to just after the sram copy of rom header
LDA.b #$01 : STA $420D ; enable fastrom access on upper banks
LDA.b #$10 : STA $BC ; set default player sprite bank
LDA.b #$81 : STA $4200 ; thing we wrote over, turn on NMI & gamepad
RTL
;--------------------------------------------------------------------------------
; Init_PostRAMClear
;--------------------------------------------------------------------------------
; This gets called after banks $7E and $7F get cleared, so if we need to
; initialize RAM in those banks, do it here
;--------------------------------------------------------------------------------
Init_PostRAMClear:
JSL MSUInit
JSL InitRNGPointerTable
JML $00D463 ; The original target of the jump table that we hijacked |
.model small
.data
.code
main proc
MOV AL,10101110b
AND AL,11110110b
endp
end main28 - and_1.asm |
# Paul McKenney's Statistical Counter (PerfBook 5.2) using CAS
#
# Counter thread: increment global variable heap[0] 3 times.
#
# steps: maximum CAS executions = 3 * m * (m + 1) / 2
# = 3 times triangular number for m threads
# * formula = cas * 3 * m * (m + 1) / 2 + 3 * (loop - cas) + total - loop
# * cas = 4
# * loop = 9
# * total = 11
#
# template parameter:
# * 10 = local counter address
#
# initial:
# * heap[0] = 0
# * heap[10] = 3
#
# input:
# * heap[10] = local counter variable
#
inc: MEM 0 # load global | cas | loop
ADDI 1 # increment global | |
CAS 0 # store global | |
JZ inc # retry if case failed _| |
LOAD 10 # load local |
SUBI 1 # decrement local |
STORE 10 # store local (global flushed) |
JNZ inc # repeat if not finished _|
CHECK 0 # start checker thread
HALT
|
; A118610: Start with 1 and repeatedly reverse the digits and add 24 to get the next term.
; 1,25,76,91,43,58,109,925,553,379,997,823,352,277,796,721,151,175,595,619,940,73,61,40,28,106,625,550,79,121,145,565,589,1009,9025,5233,3349,9457,7573,3781,1897,8005,5032,2329,9256,6553,3580,877,802,232,256,676
mov $2,$0
mov $0,1
lpb $2
seq $0,4086 ; Read n backwards (referred to as R(n) in many sequences).
add $0,24
sub $2,1
lpe
|
; A094706: Convolution of Pell(n) and 2^n.
; Submitted by Christian Krause
; 0,1,4,13,38,105,280,729,1866,4717,11812,29365,72590,178641,438064,1071153,2613138,6362965,15470140,37565389,91125206,220864377,534951112,1294960905,3133261530,7578261181,18323338324,44292046693,107041649438,258643781025,624866082400,1509449687649,3645912941346,8805570537637,21265643951212,51354038309245,124008080308070,299438918402121,723023356065784,1745760508440633,4215094128760938,10177048277590285,24571389707197060,59324225738495509,143228637277210286,345799092478960497,834862006607220112
mov $1,4
mov $2,1
lpb $0
sub $0,1
sub $1,2
add $1,$4
mul $1,2
mov $3,$4
mov $4,$2
add $2,$3
add $4,$2
lpe
add $4,$1
mov $0,$4
div $0,2
sub $0,2
|
; A033350: a(n) = floor(30/n).
; 30,15,10,7,6,5,4,3,3,3,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
add $0,1
mov $1,30
div $1,$0
mov $0,$1
|
; uint16_t in_pause_fastcall(uint16_t dur_ms)
SECTION code_clib
SECTION code_input
PUBLIC _in_pause_fastcall
EXTERN asm_in_pause
defc _in_pause_fastcall = asm_in_pause
|
;; Author: Moss Gallagher
;; Data: 13-Oct-21
%ifndef _Mycelium_std_out_
%define _Mycelium_std_out_
%include "std/sys.asm"
; Print the passed string to stdout
; Args
; rax: the string to be printed
; rbx: length of the string
; Returns
; void
out~puts:
push rbp
mov rbp, rsp
push rax ; Perserve the used regiser values
push rbx
push rcx
push rdx
push rsi
push rdi
push r11
mov rdx, rbx
mov rsi, rax
mov rdi, sys~fd~out
mov rax, sys~id~write
syscall
pop r11
pop rdi
pop rsi
pop rdx
pop rcx
pop rbx
pop rax
pop rbp
ret
; Print the passed string to stdout
; Args
; rax: the string to be printed
; rbx: length of the string
; Returns
; void
out~put_err:
push rbp
mov rbp, rsp
push rax ; Perserve the used regiser values
push rbx
push rcx
push rdx
push rsi
push rdi
mov rdx, rbx
mov rsi, rax
mov rdi, sys~fd~err
mov rax, sys~id~write
syscall
pop rdi
pop rsi
pop rdx
pop rcx
pop rbx
pop rax
pop rbp
ret
; Args
; rax: the character to be printed
; Returns
; void
out~putc:
push rcx
push rdx
push rdi
push rsi
push rbx
push r10
push r11
mov [rsp-8], rax
mov rax, sys~id~write
mov rdi, sys~fd~out
lea rsi, [rsp-8] ; Use the stack as a pointer to the character we pushed top it
mov rdx, 1
syscall
pop r11
pop r10
pop rbx
pop rsi
pop rdi
pop rdx
pop rcx
ret
%endif ; ifdef guard
|
// BS_Client.cpp,v 1.9 2000/11/30 06:03:51 pradeep Exp
#include "Options.h"
#include "File_Manager.h"
#include "BS_Client.h"
#include "ace/Log_Msg.h"
BS_Client::BS_Client (void)
{
this->count_ = FILE_MANAGER::instance ()->open_file (Options::friend_file);
if (this->count_ < 0)
ACE_ERROR ((LM_ERROR,
"%p\n",
Options::program_name));
else
{
ACE_NEW (this->protocol_record_,
Protocol_Record[this->count_]);
ACE_NEW (this->sorted_record_,
Protocol_Record *[this->count_]);
for (int i = 0; i < this->count_; i++)
{
Protocol_Record *prp = &this->protocol_record_[i];
this->sorted_record_[i] = prp;
FILE_MANAGER::instance ()->get_login_and_real_name
(prp->key_name1_, prp->key_name2_);
}
ACE_OS::qsort (this->sorted_record_,
this->count_,
sizeof *this->sorted_record_,
(ACE_COMPARE_FUNC)Binary_Search::name_compare);
}
}
// This function is used to merge the KEY_NAME from server HOST_NAME
// into the sorted list of userids kept on the client's side. Since
// we *know* we are going to find the name we use the traditional
// binary search.
Protocol_Record *
BS_Client::insert (const char *key_name, int)
{
#if 0
Protocol_Record *pr = (Protocol_Record *)
ACE_OS::bsearch ((const void *) key_name,
(const void *) this->sorted_record_,
this->count_,
sizeof ...,
int (*compar)(const void *, const void *) ACE_OS::strcmp);
return pr;
#else
int lo = 0;
int hi = this->count_ - 1;
Protocol_Record **sorted_buffer = this->sorted_record_;
while (lo <= hi)
{
int mid = (lo + hi) / 2;
Protocol_Record *prp = sorted_buffer[mid];
int cmp = ACE_OS::strcmp (key_name,
prp->get_login ());
if (cmp == 0)
return prp;
else if (cmp < 0)
hi = mid - 1;
else
lo = mid + 1;
}
return 0;
#endif /* 0 */
}
Protocol_Record *
BS_Client::get_each_entry (void)
{
for (Protocol_Record *prp = Binary_Search::get_each_entry ();
prp != 0;
prp = Binary_Search::get_each_entry ())
if (prp->get_drwho_list () != 0)
return prp;
return 0;
}
|
;Z88 Small C Library functions, linked using the z80 module assembler
;Small C Z88 converted by Dominic Morris <djm@jb.man.ac.uk>
;
;11/3/99 djm Saved two bytes by removing useless ld h,0
;
;
; $Id: getk.asm,v 1.3 2016/03/13 18:14:13 dom Exp $
;
SECTION code_clib
PUBLIC getk ;Read keys
.getk
push ix
ld c,$31 ;SCANKEY
rst $10
pop ix
ld hl,0
ret nz ;no key pressed
ld l,e
ret
|
; A007040: Number of (marked) cyclic n-bit binary strings containing no runs of length > 2.
; 2,2,6,6,10,20,28,46,78,122,198,324,520,842,1366,2206,3570,5780,9348,15126,24478,39602,64078,103684,167760,271442,439206,710646,1149850,1860500,3010348,4870846,7881198,12752042,20633238,33385284,54018520,87403802,141422326,228826126,370248450,599074580,969323028,1568397606,2537720638,4106118242,6643838878,10749957124,17393796000,28143753122,45537549126,73681302246,119218851370,192900153620,312119004988,505019158606,817138163598,1322157322202,2139295485798,3461452808004,5600748293800,9062201101802,14662949395606,23725150497406,38388099893010,62113250390420,100501350283428,162614600673846,263115950957278,425730551631122,688846502588398,1114577054219524,1803423556807920,2918000611027442,4721424167835366,7639424778862806,12360848946698170,20000273725560980,32361122672259148,52361396397820126,84722519070079278,137083915467899402,221806434537978678,358890350005878084,580696784543856760,939587134549734842,1520283919093591606,2459871053643326446,3980154972736918050,6440026026380244500,10420180999117162548,16860207025497407046,27280388024614569598,44140595050111976642,71420983074726546238,115561578124838522884,186982561199565069120,302544139324403592002,489526700523968661126,792070839848372253126
mov $3,2
mov $8,$0
lpb $3
mov $0,$8
sub $3,1
add $0,$3
sub $0,1
mov $4,$0
mov $6,2
lpb $6
mov $0,$4
sub $6,1
add $0,$6
trn $0,1
seq $0,23550 ; Convolution of natural numbers >= 2 and (F(2), F(3), F(4), ...).
div $0,2
mul $0,2
mov $7,$6
mov $9,$0
lpb $7
mov $5,$9
sub $7,1
lpe
lpe
lpb $4
mov $4,0
sub $5,$9
lpe
mov $2,$3
mov $9,$5
lpb $2
mov $1,$9
sub $2,1
lpe
lpe
lpb $8
sub $1,$9
mov $8,0
lpe
mov $0,$1
|
; A269878: Partial sums of the number of active (ON,black) cells in n-th stage of growth of two-dimensional cellular automaton defined by "Rule 43", based on the 5-celled von Neumann neighborhood.
; 1,6,11,48,61,158,183,368,409,710,771,1216,1301,1918,2031,2848,2993,4038,4219,5520,5741,7326,7591,9488,9801,12038,12403,15008,15429,18430,18911,22336,22881,26758,27371,31728,32413,37278,38039,43440,44281,50246,51171
mov $2,$0
mul $2,2
mov $5,$0
mul $0,2
mov $3,3
lpb $3
lpb $2
trn $2,4
add $4,$0
add $0,4
add $1,$4
lpe
mul $1,2
trn $3,$0
lpe
lpb $5
add $1,1
sub $5,1
lpe
add $1,1
|
;-----------------------------------------------------------------------------
; Paul Wasson - 2021
;-----------------------------------------------------------------------------
; inline_print - display following string to COUT
;-----------------------------------------------------------------------------
; Uses stack pointer to find string
; clobbers A,X,Y
;
; Example:
; jsr inline_print
; .byte "HELLO WORLD!",0
; <next instruction>
; Zero page usage
;stringPtr0 := $FE
;stringPtr1 := $FF
.proc inline_print
; Pop return address to find string
pla
sta stringPtr0
pla
sta stringPtr1
ldy #0
; Print characters until 0 (end-of-string)
printLoop:
iny
bne :+ ; Allow strings > 255
inc stringPtr1
:
tya
pha
lda (stringPtr0),y
beq printExit
ora #$80 ; not inverse/flashing
jsr COUT
pla
tay
jmp printLoop
printExit:
pla ; clean up stack
; calculate return address after print string
clc
tya
adc stringPtr0 ; add low-byte first
tax ; save in X
lda stringPtr1 ; carry to high-byte
adc #0
pha ; push return high-byte
txa
pha ; push return low-byte
rts ; return
.endproc ; print
|
ORG 1000
START: ACI 40
XTHL
JMP J1
NOP
ORG 2000
J1:
HLT
END
HLT
|
; A067699: Number of comparisons made in a version of the sorting algorithm QuickSort for an array of size n with n identical elements.
; 0,4,8,14,18,24,30,38,42,48,54,62,68,76,84,94,98,104,110,118,124,132,140,150,156,164,172,182,190,200,210,222,226,232,238,246,252,260,268,278,284,292,300,310,318,328,338,350,356,364,372,382
mov $1,$0
lpb $1
mov $2,$1
sub $1,1
seq $2,120 ; 1's-counting sequence: number of 1's in binary expansion of n (or the binary weight of n).
add $0,$2
lpe
mul $0,2
|
if not defined FDIV
INCLUDE "print_fp.asm"
; HL = BC / HL
DEBUG@FDIV:
FDIV:
CALL @FDIV ; 3:17
PUSH HL ; 1:11
LD HL, '/'+' ' * 256 ; 3:10 "/ "
LD A, COL_BLUE ; 2:7
JP PRINT_XFP ; 3:10
else
if not defined DEBUG@FDIV
.WARNING You must include the file: debug_fdiv.asm before.
endif
endif
|
.init main
.code
check_lsh:
mov i9 @512
mov i0 @2
mov i1 @8
lsh i0 i0 i1
aseq i9 i0
ret
check_rsh:
mov i9 @2
mov i0 @512
mov i1 @8
rsh i0 i0 i1
aseq i9 i0
ret
check_and:
mov i9 @1
mov i0 @9
mov i1 @3
and i0 i0 i1
aseq i9 i0
ret
check_or:
mov i9 @11
mov i0 @9
mov i1 @3
or i0 i0 i1
aseq i9 i0
ret
check_xor:
mov i9 @10
mov i0 @9
mov i1 @3
xor i0 i0 i1
aseq i9 i0
ret
check_not:
mov i0 @0
mov i1 @1
not i0 i0
aseq i0 i1
ret
main:
call check_lsh
call check_rsh
call check_not
call check_and
call check_or
mov i0 @0
exit
|
SECTION code_driver
SECTION code_driver_character_output
PUBLIC _siob_flush_Tx_di
PUBLIC _siob_flush_Tx
EXTERN asm_z80_push_di, asm_z80_pop_ei
EXTERN siobTxCount, siobTxIn, siobTxOut, siobTxBuffer
_siob_flush_Tx_di:
push af
push hl
call asm_z80_push_di ; di
call _siob_flush_Tx
call asm_z80_pop_ei ; ei
pop hl
pop af
ret
_siob_flush_Tx:
xor a
ld (siobTxCount),a ; reset the Tx counter (set 0)
ld hl,siobTxBuffer ; load Tx buffer pointer home
ld (siobTxIn),hl
ld (siobTxOut),hl
ret
EXTERN _sio_need
defc NEED = _sio_need
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "ai_behavior_police.h"
#include "ai_navigator.h"
#include "ai_memory.h"
#include "collisionutils.h"
#include "npc_metropolice.h"
#ifdef MAPBASE
#include "npc_combine.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
BEGIN_DATADESC( CAI_PolicingBehavior )
DEFINE_FIELD( m_bEnabled, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bStartPolicing, FIELD_BOOLEAN ),
DEFINE_FIELD( m_hPoliceGoal, FIELD_EHANDLE ),
DEFINE_FIELD( m_flNextHarassTime, FIELD_TIME ),
DEFINE_FIELD( m_flAggressiveTime, FIELD_TIME ),
DEFINE_FIELD( m_nNumWarnings, FIELD_INTEGER ),
DEFINE_FIELD( m_bTargetIsHostile, FIELD_BOOLEAN ),
DEFINE_FIELD( m_flTargetHostileTime,FIELD_TIME ),
END_DATADESC();
CAI_PolicingBehavior::CAI_PolicingBehavior( void )
{
m_bEnabled = false;
m_nNumWarnings = 0;
m_bTargetIsHostile = false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CAI_PolicingBehavior::TargetIsHostile( void )
{
if ( ( m_flTargetHostileTime < gpGlobals->curtime ) && ( !m_bTargetIsHostile ) )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pGoal -
//-----------------------------------------------------------------------------
void CAI_PolicingBehavior::Enable( CAI_PoliceGoal *pGoal )
{
m_hPoliceGoal = pGoal;
m_bEnabled = true;
m_bStartPolicing = true;
// Update ourselves immediately
GetOuter()->ClearSchedule( "Enable police behavior" );
//NotifyChangeBehaviorStatus( GetOuter()->IsInAScript() );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_PolicingBehavior::Disable( void )
{
m_hPoliceGoal = NULL;
m_bEnabled = false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CAI_PolicingBehavior::CanSelectSchedule( void )
{
// Must be activated and valid
if ( IsEnabled() == false || !m_hPoliceGoal || !m_hPoliceGoal->GetTarget() )
return false;
return true;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : false -
//-----------------------------------------------------------------------------
void CAI_PolicingBehavior::HostSetBatonState( bool state )
{
// If we're a cop, turn the baton on
CNPC_MetroPolice *pCop = dynamic_cast<CNPC_MetroPolice *>(GetOuter());
if ( pCop != NULL )
{
pCop->SetBatonState( state );
pCop->SetTarget( m_hPoliceGoal->GetTarget() );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : false -
//-----------------------------------------------------------------------------
bool CAI_PolicingBehavior::HostBatonIsOn( void )
{
// If we're a cop, turn the baton on
CNPC_MetroPolice *pCop = dynamic_cast<CNPC_MetroPolice *>(GetOuter());
if ( pCop )
return pCop->BatonActive();
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_PolicingBehavior::HostSpeakSentence( const char *pSentence, SentencePriority_t nSoundPriority, SentenceCriteria_t nCriteria )
{
// If we're a cop, turn the baton on
CNPC_MetroPolice *pCop = dynamic_cast<CNPC_MetroPolice *>(GetOuter());
if ( pCop != NULL )
{
#ifdef METROPOLICE_USES_RESPONSE_SYSTEM
pCop->SpeakIfAllowed( pSentence, nSoundPriority, nCriteria );
#else
CAI_Sentence< CNPC_MetroPolice > *pSentences = pCop->GetSentences();
pSentences->Speak( pSentence, nSoundPriority, nCriteria );
#endif
}
#ifdef MAPBASE
else if ( CNPC_Combine *pCombine = dynamic_cast<CNPC_Combine*>(GetOuter()) )
{
pCombine->SpeakIfAllowed( pSentence, nSoundPriority, nCriteria );
}
else if ( GetOuter()->GetExpresser() )
{
GetOuter()->GetExpresser()->Speak( pSentence );
}
#endif
}
#ifdef METROPOLICE_USES_RESPONSE_SYSTEM
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_PolicingBehavior::HostSpeakSentence( const char *pSentence, const char *modifiers, SentencePriority_t nSoundPriority, SentenceCriteria_t nCriteria )
{
// If we're a cop, turn the baton on
CNPC_MetroPolice *pCop = dynamic_cast<CNPC_MetroPolice *>(GetOuter());
if ( pCop != NULL )
{
pCop->SpeakIfAllowed( pSentence, modifiers, nSoundPriority, nCriteria );
}
#ifdef MAPBASE
else if ( CNPC_Combine *pCombine = dynamic_cast<CNPC_Combine*>(GetOuter()) )
{
pCombine->SpeakIfAllowed( pSentence, modifiers, nSoundPriority, nCriteria );
}
else if ( GetOuter()->GetExpresser() )
{
GetOuter()->GetExpresser()->Speak( pSentence, modifiers );
}
#endif
}
#endif
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_PolicingBehavior::BuildScheduleTestBits( void )
{
if ( IsCurSchedule( SCHED_IDLE_STAND ) || IsCurSchedule( SCHED_ALERT_STAND ) )
{
if ( m_flNextHarassTime < gpGlobals->curtime )
{
GetOuter()->SetCustomInterruptCondition( GetClassScheduleIdSpace()->ConditionLocalToGlobal( COND_POLICE_TARGET_TOO_CLOSE_HARASS ) );
}
GetOuter()->SetCustomInterruptCondition( GetClassScheduleIdSpace()->ConditionLocalToGlobal( COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS ) );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_PolicingBehavior::GatherConditions( void )
{
BaseClass::GatherConditions();
// Mapmaker may have removed our goal while we're running our schedule
if ( !m_hPoliceGoal )
{
Disable();
return;
}
ClearCondition( COND_POLICE_TARGET_TOO_CLOSE_HARASS );
ClearCondition( COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS );
CBaseEntity *pTarget = m_hPoliceGoal->GetTarget();
if ( pTarget == NULL )
{
DevMsg( "ai_goal_police with NULL target entity!\n" );
return;
}
// See if we need to knock out our target immediately
if ( ShouldKnockOutTarget( pTarget ) )
{
#ifdef MAPBASE
// If this isn't actually an enemy of ours and we're already warning, don't set this condition
if (GetOuter()->IRelationType( m_hPoliceGoal->GetTarget() ) <= D_FR || !IsCurSchedule(SCHED_POLICE_WARN_TARGET, false))
#endif
SetCondition( COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS );
}
float flDistSqr = ( m_hPoliceGoal->WorldSpaceCenter() - pTarget->WorldSpaceCenter() ).Length2DSqr();
float radius = ( m_hPoliceGoal->GetRadius() * PATROL_RADIUS_RATIO );
float zDiff = fabs( m_hPoliceGoal->WorldSpaceCenter().z - pTarget->WorldSpaceCenter().z );
// If we're too far away, don't bother
if ( flDistSqr < (radius*radius) && zDiff < 32.0f )
{
SetCondition( COND_POLICE_TARGET_TOO_CLOSE_HARASS );
if ( flDistSqr < (m_hPoliceGoal->GetRadius()*m_hPoliceGoal->GetRadius()) )
{
#ifdef MAPBASE
// If this isn't actually an enemy of ours and we're already warning, don't set this condition
if (GetOuter()->IRelationType( m_hPoliceGoal->GetTarget() ) <= D_FR || !IsCurSchedule(SCHED_POLICE_WARN_TARGET, false))
#endif
SetCondition( COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS );
}
}
// If we're supposed to stop chasing (aggression over), return
if ( m_bTargetIsHostile && m_flAggressiveTime < gpGlobals->curtime && IsCurSchedule(SCHED_CHASE_ENEMY) )
{
// Force me to re-evaluate my schedule
GetOuter()->ClearSchedule( "Stopped chasing, aggression over" );
}
}
//-----------------------------------------------------------------------------
// We're taking cover from danger
//-----------------------------------------------------------------------------
void CAI_PolicingBehavior::AnnouncePolicing( void )
{
// We're policing
static const char *pWarnings[3] =
{
"METROPOLICE_MOVE_ALONG_A",
"METROPOLICE_MOVE_ALONG_B",
"METROPOLICE_MOVE_ALONG_C",
};
#ifdef METROPOLICE_USES_RESPONSE_SYSTEM
HostSpeakSentence(TLK_COP_MOVE_ALONG, UTIL_VarArgs("numwarnings:%i", m_nNumWarnings), SENTENCE_PRIORITY_MEDIUM, SENTENCE_CRITERIA_NORMAL);
#else
if ( m_nNumWarnings <= 3 )
{
HostSpeakSentence( pWarnings[ m_nNumWarnings - 1 ], SENTENCE_PRIORITY_MEDIUM, SENTENCE_CRITERIA_NORMAL );
}
else
{
// We loop at m_nNumWarnings == 4 for players who aren't moving
// but still pissing us off, and we're not allowed to do anything about it. (i.e. can't leave post)
// First two sentences sound pretty good, so randomly pick one of them.
int iSentence = RandomInt( 0, 1 );
HostSpeakSentence( pWarnings[ iSentence ], SENTENCE_PRIORITY_MEDIUM, SENTENCE_CRITERIA_NORMAL );
}
#endif
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : scheduleType -
// Output : int
//-----------------------------------------------------------------------------
int CAI_PolicingBehavior::TranslateSchedule( int scheduleType )
{
if ( scheduleType == SCHED_CHASE_ENEMY )
{
if ( m_hPoliceGoal->ShouldRemainAtPost() && !MaintainGoalPosition() )
return BaseClass::TranslateSchedule( SCHED_COMBAT_FACE );
#ifdef MAPBASE
// If this isn't actually an enemy of ours, keep warning
if ( GetOuter()->IRelationType(m_hPoliceGoal->GetTarget()) > D_FR )
return BaseClass::TranslateSchedule( SCHED_POLICE_WARN_TARGET );
#endif
}
return BaseClass::TranslateSchedule( scheduleType );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : newActivity -
// Output : Activity
//-----------------------------------------------------------------------------
Activity CAI_PolicingBehavior::NPC_TranslateActivity( Activity newActivity )
{
// See which harassment to play
if ( newActivity == ACT_POLICE_HARASS1 )
{
switch( m_nNumWarnings )
{
case 1:
return (Activity) ACT_POLICE_HARASS1;
break;
default:
case 2:
return (Activity) ACT_POLICE_HARASS2;
break;
}
}
return BaseClass::NPC_TranslateActivity( newActivity );
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : CBaseEntity
//-----------------------------------------------------------------------------
CBaseEntity *CAI_PolicingBehavior::GetGoalTarget( void )
{
if ( m_hPoliceGoal == NULL )
{
//NOTENOTE: This has been called before the behavior is actually active, or the goal has gone invalid
Assert(0);
return NULL;
}
return m_hPoliceGoal->GetTarget();
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : time -
//-----------------------------------------------------------------------------
void CAI_PolicingBehavior::SetTargetHostileDuration( float time )
{
m_flTargetHostileTime = gpGlobals->curtime + time;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pTask -
//-----------------------------------------------------------------------------
void CAI_PolicingBehavior::StartTask( const Task_t *pTask )
{
switch (pTask->iTask)
{
case TASK_POLICE_GET_PATH_TO_HARASS_GOAL:
{
Vector harassDir = ( m_hPoliceGoal->GetTarget()->WorldSpaceCenter() - WorldSpaceCenter() );
float flDist = VectorNormalize( harassDir );
// See if we're already close enough
if ( flDist < pTask->flTaskData )
{
TaskComplete();
break;
}
float flInter1, flInter2;
Vector harassPos = GetAbsOrigin() + ( harassDir * ( flDist - pTask->flTaskData ) );
// Find a point on our policing radius to stand on
if ( IntersectInfiniteRayWithSphere( GetAbsOrigin(), harassDir, m_hPoliceGoal->GetAbsOrigin(), m_hPoliceGoal->GetRadius(), &flInter1, &flInter2 ) )
{
Vector vPos = m_hPoliceGoal->GetAbsOrigin() + harassDir * ( MAX( flInter1, flInter2 ) );
// See how far away the default one is
float testDist = UTIL_DistApprox2D( m_hPoliceGoal->GetAbsOrigin(), harassPos );
// If our other goal is closer, choose it
if ( testDist > UTIL_DistApprox2D( m_hPoliceGoal->GetAbsOrigin(), vPos ) )
{
harassPos = vPos;
}
}
if ( GetNavigator()->SetGoal( harassPos, pTask->flTaskData ) )
{
#ifdef MAPBASE
GetNavigator()->SetMovementActivity( GetOuter()->TranslateActivity(ACT_WALK_ANGRY) );
#else
GetNavigator()->SetMovementActivity( (Activity) ACT_WALK_ANGRY );
#endif
GetNavigator()->SetArrivalDirection( m_hPoliceGoal->GetTarget() );
TaskComplete();
}
else
{
TaskFail( FAIL_NO_ROUTE );
}
}
break;
case TASK_POLICE_GET_PATH_TO_POLICE_GOAL:
{
if ( GetNavigator()->SetGoal( m_hPoliceGoal->GetAbsOrigin(), pTask->flTaskData ) )
{
GetNavigator()->SetArrivalDirection( m_hPoliceGoal->GetAbsAngles() );
TaskComplete();
}
else
{
TaskFail( FAIL_NO_ROUTE );
}
}
break;
case TASK_POLICE_ANNOUNCE_HARASS:
{
AnnouncePolicing();
// Randomly say this again in the future
m_flNextHarassTime = gpGlobals->curtime + random->RandomInt( 4, 6 );
// Scatter rubber-neckers
CSoundEnt::InsertSound( SOUND_MOVE_AWAY, GetAbsOrigin(), 256.0f, 2.0f, GetOuter() );
}
TaskComplete();
break;
case TASK_POLICE_FACE_ALONG_GOAL:
{
// We may have lost our police goal in the 2 seconds we wait before this task
if ( m_hPoliceGoal )
{
GetMotor()->SetIdealYaw( m_hPoliceGoal->GetAbsAngles().y );
GetOuter()->SetTurnActivity();
}
}
break;
default:
BaseClass::StartTask( pTask );
break;
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CAI_PolicingBehavior::RunTask( const Task_t *pTask )
{
switch ( pTask->iTask )
{
case TASK_POLICE_FACE_ALONG_GOAL:
{
GetMotor()->UpdateYaw();
if ( GetOuter()->FacingIdeal() )
{
TaskComplete();
}
break;
}
default:
BaseClass::RunTask( pTask);
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CAI_PolicingBehavior::MaintainGoalPosition( void )
{
Vector vecOrg = GetAbsOrigin();
Vector vecTarget = m_hPoliceGoal->GetAbsOrigin();
// Allow some slop on Z
if ( fabs(vecOrg.z - vecTarget.z) > 64 )
return true;
// Need to be very close on X/Y
if ( (vecOrg - vecTarget).Length2D() > 16 )
return true;
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool CAI_PolicingBehavior::ShouldKnockOutTarget( CBaseEntity *pTarget )
{
if ( m_hPoliceGoal == NULL )
{
//NOTENOTE: This has been called before the behavior is actually active, or the goal has gone invalid
Assert(0);
return false;
}
bool bVisible = GetOuter()->FVisible( pTarget );
return m_hPoliceGoal->ShouldKnockOutTarget( pTarget->WorldSpaceCenter(), bVisible );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *pTarget -
//-----------------------------------------------------------------------------
void CAI_PolicingBehavior::KnockOutTarget( CBaseEntity *pTarget )
{
if ( m_hPoliceGoal == NULL )
{
//NOTENOTE: This has been called before the behavior is actually active, or the goal has gone invalid
Assert(0);
return;
}
m_hPoliceGoal->KnockOutTarget( pTarget );
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : int
//-----------------------------------------------------------------------------
int CAI_PolicingBehavior::SelectSuppressSchedule( void )
{
CBaseEntity *pTarget = m_hPoliceGoal->GetTarget();
m_flAggressiveTime = gpGlobals->curtime + 4.0f;
if ( m_bTargetIsHostile == false )
{
// Mark this as a valid target
m_bTargetIsHostile = true;
// Attack the target
GetOuter()->SetEnemy( pTarget );
GetOuter()->SetState( NPC_STATE_COMBAT );
GetOuter()->UpdateEnemyMemory( pTarget, pTarget->GetAbsOrigin() );
HostSetBatonState( true );
// Remember that we're angry with the target
m_nNumWarnings = POLICE_MAX_WARNINGS;
// We need to let the system pickup the new enemy and deal with it on the next frame
return SCHED_COMBAT_FACE;
}
// If we're supposed to stand still, then we need to show aggression
if ( m_hPoliceGoal->ShouldRemainAtPost() )
{
// If we're off our mark, fight to it
if ( MaintainGoalPosition() )
{
return SCHED_CHASE_ENEMY;
}
//FIXME: This needs to be a more aggressive warning to the player
if ( m_flNextHarassTime < gpGlobals->curtime )
{
return SCHED_POLICE_WARN_TARGET;
}
else
{
return SCHED_COMBAT_FACE;
}
}
return SCHED_CHASE_ENEMY;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : int
//-----------------------------------------------------------------------------
int CAI_PolicingBehavior::SelectHarassSchedule( void )
{
CBaseEntity *pTarget = m_hPoliceGoal->GetTarget();
m_flAggressiveTime = gpGlobals->curtime + 4.0f;
// If we just started to police, make sure we're on our mark
if ( MaintainGoalPosition() )
return SCHED_POLICE_RETURN_FROM_HARASS;
// Look at the target if they're too close
GetOuter()->AddLookTarget( pTarget, 0.5f, 5.0f );
// Say something if it's been long enough
if ( m_flNextHarassTime < gpGlobals->curtime )
{
// Gesture the player away
GetOuter()->SetTarget( pTarget );
// Send outputs for each level of warning
if ( m_nNumWarnings == 0 )
{
m_hPoliceGoal->FireWarningLevelOutput( 1 );
}
else if ( m_nNumWarnings == 1 )
{
m_hPoliceGoal->FireWarningLevelOutput( 2 );
}
if ( m_nNumWarnings < POLICE_MAX_WARNINGS )
{
m_nNumWarnings++;
}
// If we're over our limit, just suppress the offender
if ( m_nNumWarnings >= POLICE_MAX_WARNINGS )
{
if ( m_bTargetIsHostile == false )
{
// Mark the target as a valid target
m_bTargetIsHostile = true;
GetOuter()->SetEnemy( pTarget );
GetOuter()->SetState( NPC_STATE_COMBAT );
GetOuter()->UpdateEnemyMemory( pTarget, pTarget->GetAbsOrigin() );
HostSetBatonState( true );
m_hPoliceGoal->FireWarningLevelOutput( 4 );
return SCHED_COMBAT_FACE;
}
if ( m_hPoliceGoal->ShouldRemainAtPost() == false )
return SCHED_CHASE_ENEMY;
}
// On our last warning, approach the target
if ( m_nNumWarnings == (POLICE_MAX_WARNINGS-1) )
{
m_hPoliceGoal->FireWarningLevelOutput( 3 );
GetOuter()->SetTarget( pTarget );
HostSetBatonState( true );
if ( m_hPoliceGoal->ShouldRemainAtPost() == false )
return SCHED_POLICE_HARASS_TARGET;
}
// Otherwise just verbally warn him
return SCHED_POLICE_WARN_TARGET;
}
return SCHED_NONE;
}
//-----------------------------------------------------------------------------
// Purpose:
// Output : int
//-----------------------------------------------------------------------------
int CAI_PolicingBehavior::SelectSchedule( void )
{
CBaseEntity *pTarget = m_hPoliceGoal->GetTarget();
// Validate our target
if ( pTarget == NULL )
{
DevMsg( "ai_goal_police with NULL target entity!\n" );
// Turn us off
Disable();
return SCHED_NONE;
}
// Attack if we're supposed to
if ( ( m_flAggressiveTime >= gpGlobals->curtime ) && HasCondition( COND_CAN_MELEE_ATTACK1 ) )
{
return SCHED_MELEE_ATTACK1;
}
// See if we should immediately begin to attack our target
if ( HasCondition( COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS ) )
{
return SelectSuppressSchedule();
}
int newSchedule = SCHED_NONE;
// See if we're harassing
if ( HasCondition( COND_POLICE_TARGET_TOO_CLOSE_HARASS ) )
{
newSchedule = SelectHarassSchedule();
}
// Return that schedule if it was found
if ( newSchedule != SCHED_NONE )
return newSchedule;
// If our enemy is set, fogeda'bout it!
if ( m_flAggressiveTime < gpGlobals->curtime )
{
// Return to your initial spot
if ( GetEnemy() )
{
GetOuter()->SetEnemy( NULL );
GetOuter()->SetState( NPC_STATE_ALERT );
GetOuter()->GetEnemies()->RefreshMemories();
}
HostSetBatonState( false );
m_bTargetIsHostile = false;
}
// If we just started to police, make sure we're on our mark
if ( MaintainGoalPosition() )
return SCHED_POLICE_RETURN_FROM_HARASS;
// If I've got my baton on, keep looking at the target
if ( HostBatonIsOn() )
return SCHED_POLICE_TRACK_TARGET;
// Re-align myself to the goal angles if I've strayed
if ( fabs(UTIL_AngleDiff( GetAbsAngles().y, m_hPoliceGoal->GetAbsAngles().y )) > 15 )
return SCHED_POLICE_FACE_ALONG_GOAL;
return SCHED_IDLE_STAND;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CAI_PolicingBehavior::SelectFailSchedule( int failedSchedule, int failedTask, AI_TaskFailureCode_t taskFailCode )
{
if ( failedSchedule == SCHED_CHASE_ENEMY )
{
// We've failed to chase our enemy, return to where we were came from
if ( MaintainGoalPosition() )
return SCHED_POLICE_RETURN_FROM_HARASS;
return SCHED_POLICE_WARN_TARGET;
}
return BaseClass::SelectFailSchedule( failedSchedule, failedTask, taskFailCode );
}
//-------------------------------------
AI_BEGIN_CUSTOM_SCHEDULE_PROVIDER( CAI_PolicingBehavior )
DECLARE_CONDITION( COND_POLICE_TARGET_TOO_CLOSE_HARASS );
DECLARE_CONDITION( COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS );
DECLARE_TASK( TASK_POLICE_GET_PATH_TO_HARASS_GOAL );
DECLARE_TASK( TASK_POLICE_GET_PATH_TO_POLICE_GOAL );
DECLARE_TASK( TASK_POLICE_ANNOUNCE_HARASS );
DECLARE_TASK( TASK_POLICE_FACE_ALONG_GOAL );
DEFINE_SCHEDULE
(
SCHED_POLICE_WARN_TARGET,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_FACE_TARGET 0"
" TASK_POLICE_ANNOUNCE_HARASS 0"
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_POLICE_HARASS1"
""
" Interrupts"
" COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS"
);
DEFINE_SCHEDULE
(
SCHED_POLICE_HARASS_TARGET,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_FACE_TARGET 0"
" TASK_POLICE_GET_PATH_TO_HARASS_GOAL 64"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_POLICE_ANNOUNCE_HARASS 0"
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_POLICE_HARASS1"
""
" Interrupts"
" COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS"
);
DEFINE_SCHEDULE
(
SCHED_POLICE_SUPPRESS_TARGET,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_FACE_TARGET 0"
" TASK_POLICE_ANNOUNCE_HARASS 0"
" TASK_PLAY_SEQUENCE ACTIVITY:ACT_POLICE_HARASS1"
""
" Interrupts"
);
DEFINE_SCHEDULE
(
SCHED_POLICE_RETURN_FROM_HARASS,
" Tasks"
" TASK_STOP_MOVING 0"
" TASK_POLICE_GET_PATH_TO_POLICE_GOAL 16"
" TASK_WALK_PATH 0"
" TASK_WAIT_FOR_MOVEMENT 0"
" TASK_STOP_MOVING 0"
""
" Interrupts"
" COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS"
);
DEFINE_SCHEDULE
(
SCHED_POLICE_TRACK_TARGET,
" Tasks"
" TASK_FACE_TARGET 0"
""
" Interrupts"
" COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS"
);
DEFINE_SCHEDULE
(
SCHED_POLICE_FACE_ALONG_GOAL,
" Tasks"
" TASK_WAIT_RANDOM 2"
" TASK_POLICE_FACE_ALONG_GOAL 0"
""
" Interrupts"
" COND_POLICE_TARGET_TOO_CLOSE_SUPPRESS"
);
AI_END_CUSTOM_SCHEDULE_PROVIDER()
|
; A037525: Base-8 digits are, in order, the first n terms of the periodic sequence with initial period 2,1,0.
; Submitted by Christian Krause
; 2,17,136,1090,8721,69768,558146,4465169,35721352,285770818,2286166545,18289332360,146314658882,1170517271057,9364138168456,74913105347650,599304842781201,4794438742249608,38355509937996866,306844079503974929,2454752636031799432,19638021088254395458,157104168706035163665,1256833349648281309320,10054666797186250474562,80437334377490003796497,643498675019920030371976,5147989400159360242975810,41183915201274881943806481,329471321610199055550451848,2635770572881592444403614786
mov $2,2
lpb $0
sub $0,1
add $1,$2
mul $1,8
add $2,20
mod $2,3
lpe
add $1,$2
mov $0,$1
|
SECTION UNION "test", WRAM0
Base:
ds $1000
SECTION UNION "test", WRAM0,ALIGN[8]
ds 42
Plus42:
SECTION UNION "test", WRAM0,ALIGN[4]
SECTION UNION "test", WRAM0[$C000]
; Since the section's base address is known, the labels are constant now
ds $1000 ; This shouldn't overflow
End:
SECTION UNION "test", WRAM0,ALIGN[9]
check_label: MACRO
EXPECTED equ \2
IF \1 == EXPECTED
RESULT equs "OK!"
ELSE
RESULT equs "expected {EXPECTED}"
ENDC
PURGE EXPECTED
PRINTT "\1 is at {\1} ({RESULT})\n"
PURGE RESULT
ENDM
check_label Base, $C000
check_label Plus42, $C000 + 42
check_label End, $D000
SECTION "test", WRAM0 ; Don't allow creating a section that's not a union!
|
.global s_prepare_buffers
s_prepare_buffers:
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r13
push %r15
push %r8
push %r9
push %rdx
push %rsi
// Store
lea addresses_RW+0x16f04, %r13
nop
nop
sub $9017, %rdx
mov $0x5152535455565758, %r8
movq %r8, %xmm0
vmovups %ymm0, (%r13)
nop
nop
nop
nop
nop
add $40134, %r15
// Faulty Load
mov $0x6518100000001c4, %r12
nop
nop
nop
nop
nop
sub $21740, %rsi
vmovups (%r12), %ymm3
vextracti128 $0, %ymm3, %xmm3
vpextrq $0, %xmm3, %r13
lea oracles, %r15
and $0xff, %r13
shlq $12, %r13
mov (%r15,%r13,1), %r13
pop %rsi
pop %rdx
pop %r9
pop %r8
pop %r15
pop %r13
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_RW', 'AVXalign': False, 'congruent': 6, 'size': 32, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'AVXalign': False, 'congruent': 0, 'size': 32, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'00': 157}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
; A002808: The composite numbers: numbers n of the form x*y for x > 1 and y > 1.
; 4,6,8,9,10,12,14,15,16,18,20,21,22,24,25,26,27,28,30,32,33,34,35,36,38,39,40,42,44,45,46,48,49,50,51,52,54,55,56,57,58,60,62,63,64,65,66,68,69,70,72,74,75,76,77,78,80,81,82,84,85,86,87,88,90,91,92,93,94,95,96,98,99,100,102,104,105,106,108,110,111,112,114,115,116,117,118,119,120,121,122,123,124,125,126,128,129,130,132,133,134,135,136,138,140,141,142,143,144,145,146,147,148,150,152,153,154,155,156,158,159,160,161,162,164,165,166,168,169,170,171,172,174,175,176,177,178,180,182,183,184,185,186,187,188,189,190,192,194,195,196,198,200,201,202,203,204,205,206,207,208,209,210,212,213,214,215,216,217,218,219,220,221,222,224,225,226,228,230,231,232,234,235,236,237,238,240,242,243,244,245,246,247,248,249,250,252,253,254,255,256,258,259,260,261,262,264,265,266,267,268,270,272,273,274,275,276,278,279,280,282,284,285,286,287,288,289,290,291,292,294,295,296,297,298,299,300,301,302,303,304,305,306,308,309,310,312,314,315,316
add $0,2
cal $0,65090 ; Natural numbers which are not odd primes: composites plus 1 and 2.
mov $1,$0
|
SECTION code_fp_math48
PUBLIC _isless
EXTERN cm48_sdcciy_isless
defc _isless = cm48_sdcciy_isless
|
;
; Sharp OZ family functions
;
; ported from the OZ-7xx SDK by by Alexander R. Pruss
; by Stefano Bodrato - Oct. 2003
;
;
; interrupt driven serial routines
;
;
; ------
; $Id: serial_int.asm,v 1.5 2016-06-27 21:25:36 dom Exp $
;
SECTION code_clib
PUBLIC serial_int
PUBLIC serial_int_check
PUBLIC ozserbufget
PUBLIC ozserbufput
PUBLIC SerialBuffer
PUBLIC ozrxhandshaking
PUBLIC ozrxxoff
EXTERN ozcustomisr
EXTERN rxxoff_hook
EXTERN serial_hook
EXTERN ozintwait
EXTERN serial_check_hook
; Don't exchange the items position !!
rxxoff_handler:
ld a,(ozrxxoff)
or a
;jp z,$rxxoff_hook+2
jp z,rxxoff_hook+3
ld hl,ozserbufput
ld a,(hl)
dec hl ; hl=ozserbufget
sub (hl)
cp 150
jp nc,rxxoff_hook+3
waittop2:
in a,(45h)
and 20h
jr z,waittop2
ld a,17 ; XON
out (40h),a
xor a
ld (ozrxxoff),a
jp rxxoff_hook+3
serial_int_check:
ld a,(ozserbufget)
ld c,a
ld a,(ozserbufput)
cp c
jp z,serial_check_hook+3
ei
ret
serial_int:
in a,(45h)
and 1
jp z,serial_hook+3 ;; no serial data
in a,(40h)
push hl
ld e,a
ld hl,ozserbufput
ld a,(hl)
ld c,a
inc a
dec hl ; hl=ozserbufget
cp (hl)
jp z,BufferFull
inc hl ; hl=ozserbufput
ld (hl),a
ei
ld b,0
inc hl ; hl=SerialBuffer
add hl,bc
ld (hl),e
ld hl,ozserbufget
sub (hl) ; a=buffer size
cp 200
jr c,noXOFF
ld a,(ozrxhandshaking)
or a
jr z,noXOFF
ld a,(ozrxxoff)
or a
jr nz,noXOFF
waittop:
in a,(45h)
and 20h
jr z,waittop
ld a,19 ; XOFF
out (40h),a
ld a,1
ld (ozrxxoff),a
noXOFF:
BufferFull:
pop hl
jp serial_hook+3
SECTION bss_clib
defc BufLen = 256
ozserbufget:
defs 1
ozserbufput:
defs 1
SerialBuffer:
defs BufLen
ozrxhandshaking:
defs 1
ozrxxoff:
defs 1
|
//
// Created by tridu33 on 9/27/2021.
//
#include "quickSortRand.h"
#include <stdlib.h> /* srand, rand */
using namespace std;
#include <bits/stdc++.h>
class Solution {
public:
int partition(vector<int> & nums,int l,int r){
int pivot = nums[r];
int s = l,e = r-1;
while(s<=e){
while(s<=e && nums[s] <= pivot) s++;
while(s<=e && nums[e] >= pivot) e--;
if(s <= e) swap(nums[s],nums[e]);
}
swap(nums[s],nums[r]);
return s;
}
int Random_partition(vector<int> & nums,int l,int r){
srand((unsigned) time(NULL));
int i = rand()%nums.size();
swap(nums[i],nums[r]);
return partition(nums,l,r);
}
void quicksort(vector<int> & nums,int s , int e){
if(s >= e) return;
int pivotindex = Random_partition(nums,s,e);
quicksort(nums,s,pivotindex-1);
quicksort(nums,pivotindex+1,e);
}
vector<int> sortArray(vector<int>& nums) {
int n = nums.size();
quicksort(nums,0,n-1);//快排
return nums;
}
};
int main(){
vector<int> nums = {1,4,3,5,7,9,0,56};
Solution sol;
vector<int> vec = sol.sortArray(nums);
for(auto x: vec){
cout << x << ' ' << endl;
}
return 0;
} |
##############################################################################
# Program : MindReader Programmer: Chaoran Li, Jiaer JIang, Xue Cheng, Pengfei Tong
# Due Date: 12/05/19 Last Modified:11/08/19
# Course: CS3340 Section:501
#############################################################################
# Description:
#
# Topic:
# The topic for the team project this semester is the Mind Reader game.
# For a feel of the game visit
# https://www.mathsisfun.com/games/mind-reader.html
#
# Minimum requirements for the program:
# The game is for a human player and your program is the 'mind reader'. Your program must display the
# cards, get input from the player then correctly display the number that the player has in mind.
# At the end of a game, the program will ask the player if he/she wants to play another game and then
# repeat or end the program.
# The 'cards' MUST be generated and displayed once at a time during a game, i.e. NOT pre-calculated
# and stored in memory. The order of displayed cards MUST be random.
# The player input (keystrokes) should be minimum
# The ASCII based display is the minimum requirement. Creative ways to display the game (e.g. colors)
# will earn the team extra credits.
# If the player gives an invalid input, an error message is displayed to explain why the input was not valid.
#
# Extra credits will be given for:
# Graphic/color display
# Extra features of the programs (e.g. background music, sounds or music to indicate invalid input,
# pleasant display etc...) implemented and documented.
# Any other notable creativity that the team has shown.
# You must document these extra credit features in your report and explain well to unlock these extra
# credits.
#
# Design:
# Print: Two loop to traverse to print
# Calculate: Get higher unit first. Return 0 if out of range.
#
# Log:
# version 1.0 10/04/19 Design the interaction flow
# version 1.1 10/05/19 Print card and calculate result
# version 1.2 10/09/19 If think about number out of 1~63, return 0
# version 1.3 11/08/19 Imply shuffle function
#
#############################################################################
# Register:
# global
# $v0 for I/O
# $a0 for I/O
# $a1 for I/O
# $s0 'y'
# $s1 'n'
# $s2 max digit
# $s3 line feed every x numbers
# $s4 random factor: a random number to decide current digit for card is 0 or 1
# #s5 card length
# $t0 digit left, show result when $t0 is 0
# $t1 result
# $t2 input, 1 for y and 0 for n
# $t3 current digit
# $t4 valid random sequence (last digit)
# $t8 tmp1
# $t9 tmp2
#
# Truth table: current digit(card) answer value result of xor final binary expansion add to result
# 0 0(n) 0 1 1
# 0 1(y) 1 0 0
# 1 0(n) 1 0 0
# 1 1(y) 0 1 1
# if (xor = 0) add to result
#
#############################################################################
.data
# messages
start: .asciiz "\nThink of a number between 1 and 63. Six cards will be displayed and you would tell\nme whether your number is in the card. Once you finish all six cards, I can read your\nmind. Start now?"
hint: .asciiz "\n(input 'y' or 'n'):\n"
question: .asciiz "\nDo you find your number here?"
unvalid: .asciiz "\nThe only valid answer is 'y' or 'n' (lower case). So input correctly.\n"
answer: .asciiz "\nYour number is "
again: .asciiz ". Awesome right?\nDo you wanna another try?"
overflow: .asciiz "\nAll your answer is 'n', which means that your number is not in 1 and 63"
end: .asciiz "\nGLHF!"
sequence: .space 24 # digit sequence
card: .space 128 # at most
#############################################################################
.text
.globl main
# init
main: li $s0, 0x79 # save character 'y'
li $s1, 0x6e # save character 'n'
li $s2, 6 # 6 digits binary for 0 ~ 63
li $s3, 8 # feed back every 8 numbers when print card
li $a1, 64 # random range [0, 64)
li $v0, 42
syscall
move $s4, $a0 # random factor: a random 6-bit 0/1 sequence
li $s5, 1 # set card length
sllv $s5, $s5, $s2 # << 6
srl $s5, $s5, 1 # half of 2^6
# init sequence ( a shuffled sequence to ask question)
li $t8, 1 # start with 000001
move $t9, $s2 # index = max digit
sll $t9, $t9, 2 # index -> address
initSeqL: beq $t9, $zero, initSeqE # break
addi $t9, $t9, -4 # address -= 4
sw $t8, sequence($t9) # save to sequence[index]
sll $t8, $t8, 1 # <<1
j initSeqL
initSeqE: addi $sp, $sp, -8 # save $s0-s1
sw $s0, 0($sp)
sw $s1, 4($sp)
la $s0, sequence
move $s1, $s2
jal shuffle # shuffle sequence (length = 6 (* 4))
lw $s0, 0($sp)
lw $s1, 4($sp)
addi $sp, $sp, 8 # restore
# get start
li $t1, 0 # set result to 0
move $t0, $s2 # digits left
li $v0, 4 # print message start
la $a0, start # load address
syscall
li $v0, 4 # print message hint
la $a0, hint
syscall
jal input # get an input
beq $t2, $zero, exit # input, 1 for y and 0 for n
# main loop: print card and ask question
loop: beq $t0, $zero, show # if 0 digit left, show reslut. Get highter digit first for similicity
sll $t8, $t0, 2
addi $t8, $t8, -4 # index -> address
lw $t3, sequence($t8) # current digit = sequence[index]
move $t4, $s4
srl $s4, $s4, 1 # random sequence >>
andi $t4, $t4, 1 # get valid random sequence (lasr digit)
# write card
addi $sp, $sp, -8 # save $s0-s1
sw $s0, 0($sp)
sw $s1, 4($sp)
move $s0, $t3
move $s1, $t4
jal wCard # write card
lw $s0, 0($sp)
lw $s1, 4($sp)
addi $sp, $sp, 8 # restore
# shuffle card
addi $sp, $sp, -8 # save $s0-s1
sw $s0, 0($sp)
sw $s1, 4($sp) # $s2 is same and const in Callee
la $s0, card
move $s1, $s5 # length -> address
jal shuffle # shuffle card (length = 2^6/2 (* 4) = 2^7)
lw $s0, 0($sp)
lw $s1, 4($sp)
addi $sp, $sp, 8 # restore
# print card
addi $sp, $sp, -12 # save $s0-s2
sw $s0, 0($sp)
sw $s1, 4($sp)
sw $s2, 8($sp)
la $s0, card
move $s1, $s5 # length
move $s2, $s3 # feed back value
jal pCard # print card
lw $s0, 0($sp)
lw $s1, 4($sp)
lw $s2, 8($sp)
addi $sp, $sp, 12 # restore
li $v0, 4 # print question
la $a0, question
syscall
li $v0, 4 # print hint
la $a0, hint
syscall
# get result from input
jal input # get an input
xor $t2, $t2, $t4 # xor
bne $t2, $zero, skipAdd # != 0 skip add
add $t1, $t1, $t3 # result += input
skipAdd: addi $t0, $t0, -1 # digit left--
j loop
show: beq $t1, $zero, overF # if answer is 0, overflow
li $v0, 4 # print answer
la $a0, answer
syscall
li $v0, 1 # print result
addi $a0, $t1, 0 # set $a0 to result
syscall
doAgain: li $v0, 4 # print again
la $a0, again
syscall
li $v0, 4 # print hint
la $a0, hint
syscall
jal input
beq $t2, $zero, exit
j main
overF: li $v0, 4 # print overflow
la $a0, overflow
syscall
j doAgain
input: li $v0, 12 # input a character
syscall
# check input validity
beq $v0, $s0, branchY # input is y
beq $v0, $s1, branchN # input is n
li $v0, 4 # print unvalid
la $a0, unvalid
syscall
j input
branchY: li $t2, 1 # set $t2 to 1 if input is y
jr $ra
branchN: li $t2, 0 # set $t2 to 0 if input is n
jr $ra
# write card
# $s0 current digit (Caller)
# $s1 valid random expansion (Caller)
# $s2 max digit (same as Caller)
# $t0 digit
# $t1 upper count
# $t2 lower count
# $t3 upper end
# $t4 lower end
# $t5 shamt
# $t6 number
# $t7 address in card
# $t8 card length
# $t9 tmp
wCard: addi $sp, $sp, -40 # save $t0-$t9
sw $t0, 0($sp)
sw $t1, 4($sp)
sw $t2, 8($sp)
sw $t3, 12($sp)
sw $t4, 16($sp)
sw $t5, 20($sp)
sw $t6, 24($sp)
sw $t7, 28($sp)
sw $t8, 32($sp)
sw $t9, 36($sp)
li $t0, 0 # get digit
move $t9, $s0
digitL: beq $t9, $zero, digitE
addi $t0, $t0, 1 # digit++
srl $t9, $t9, 1 # $t8 >> 1
j digitL
digitE: li $t1, 0 # upper count
li $t2, 0 # lower count
li $t3, 1 # set upper end
sub $t5, $s2, $t0 # << max digit - current digit
sllv $t3, $t3, $t5
li $t4, 1 # set lower end
addi $t5, $t0, -1 # set shamt for splice number
sllv $t4, $t4, $t5 # set upper end
la $t7, card # get memory address
li $t8, 1 # set card length
sllv $t8, $t8, $s2 # << 6
srl $t8, $t8, 1 # half of 2^6
# traverse
upperL: beq $t1, $t3, upperE # if equal end upper loop
lowerL: beq $t2, $t4, lowerE # if equal end lower loop and start a upper loop
# print number
move $t6, $t1 # number == upper * upper unit + 1 + lower
sll $t6, $t6, 1 # << 1
add $t6, $t6, $s1 # + valid binary expansion
sllv $t6, $t6, $t5 # << until 6 digit
add $t6, $t6, $t2
sw $t6, 0($t7) # save in card
addi $t7, $t7, 4 # addr += 4
addi $t2, $t2, 1 # lower count++
j lowerL
lowerE: addi $t1, $t1, 1 # upper count++
li $t2, 0 # set lower count to 0
j upperL
upperE: lw $t0, 0($sp)
lw $t1, 4($sp)
lw $t2, 8($sp)
lw $t3, 12($sp)
lw $t4, 16($sp)
lw $t5, 20($sp)
lw $t6, 24($sp)
lw $t7, 28($sp)
lw $t8, 32($sp)
lw $t9, 36($sp)
addi $sp, $sp, 40 #restore
jr $ra
# print card
# $s0 start address (Caller)
# $s1 length (Caller)
# $s2 feed back value
# $t0 index
# $t1 address
# $t2 feed back index
# $t3 number
pCard: addi $sp, $sp, -16 # save $t0-t3
sw $t0, 0($sp)
sw $t1, 4($sp)
sw $t2, 8($sp)
sw $t3, 12($sp)
li $t0, 0
move $t1, $s0
li $t2, 0
printL: beq $t0, $s1, printE
lw $t3, 0($t1) # get number from card
beq $t3, $zero, afterPrint # do not print 0
beq $t2, $zero, feedBack
li $v0, 11 # print \t
li $a0, 0x09
syscall
j printNum
feedBack: li $v0, 11 # print \n
li $a0, 0x0a
syscall
printNum: move $a0, $t3
li $v0, 1 # print number
syscall
addi $t2, $t2, 1 # feed back index++
bne $t2, $s2, afterPrint
li $t2, 0 # reset feed back index
afterPrint: addi $t0, $t0, 1 # index++
addi $t1, $t1, 4 # address+=4
j printL
printE: lw $t0, 0($sp)
lw $t1, 4($sp)
lw $t2, 8($sp)
lw $t3, 12($sp)
addi $sp, $sp, 16 # restore
jr $ra
# shuffle
# $s0 start address (Caller)
# $s1 length(Caller)
# $t0 break condition
# $t1 target address
# $t8 tmp1
# $t9 tmp2
shuffle: addi $sp, $sp, -16 # save $t0-t3
sw $t0, 0($sp)
sw $t1, 4($sp)
sw $t8, 8($sp)
sw $t9, 12($sp)
shuffleL: slt $t0, $zero, $s1 # 0 < length? 1: 0
beq $t0, $zero, shuffleE # break condition
move $a1, $s1 # [0, length)
li $v0, 42
syscall
sll $a0, $a0, 2 # * 4
add $t1, $s0, $a0 # target address
lw $t8, 0($s0) # swap
lw $t9, 0($t1)
sw $t9, 0($s0)
sw $t8, 0($t1)
addi $s0, $s0, 4 # addr += 4
addi $s1, $s1, -1 # length--
j shuffleL
shuffleE: lw $t0, 0($sp)
lw $t1, 4($sp)
lw $t8, 8($sp)
lw $t9, 12($sp)
addi $sp, $sp, 16 # restore
jr $ra
# exit
exit: li $v0, 4 # print end
la $a0, end
syscall
|
#include <vector>
#include "DDImage/Writer.h"
#include "DDImage/Thread.h"
#include "DDImage/Row.h"
#include <OpenImageIO/filter.h>
#include <OpenImageIO/imagebuf.h>
#include <OpenImageIO/imagebufalgo.h>
/*
* TODO:
* - Look into using an ImageBuf iterator to fill the source buffer.
* - Support for more than 4 output channels is easy, but we can't currently
* set the output channel names in such a way that OIIO will store them in
* the output file.
* - Could throw Nuke script name and/or tree hash into the metadata
* ( iop->getHashOfInputs() )
*/
using namespace DD::Image;
namespace TxWriterNS
{
using namespace OIIO;
// Limit the available output datatypes (for now, at least).
static const TypeDesc::BASETYPE oiioBitDepths[] = {TypeDesc::INT8,
TypeDesc::INT16,
TypeDesc::INT32,
TypeDesc::FLOAT,
TypeDesc::DOUBLE};
// Knob values for above bit depths (keep them synced!)
static const char* const bitDepthValues[] = {"8-bit integer",
"16-bit integer",
"32-bit integer",
"32-bit float",
"64-bit double",
NULL};
// Knob values for NaN fix modes
static const char* const nanFixValues[] = {"black\tblack",
"box3\tbox3 filter",
NULL};
// Knob values for "preset" modes
static const char* const presetValues[] = {"oiio", "prman", "custom", NULL};
// Knob values for planar configuration
static const char* const planarValues[] = {"contig\tcontiguous",
"separate",
NULL};
// Knob values for texture mode configuration
static const char* const txModeValues[] = {"Ordinary 2D texture",
"Latitude-longitude environment map",
"Latitude-longitude environment map (light probe)",
"Shadow texture",
NULL};
static const ImageBufAlgo::MakeTextureMode oiiotxMode[] = {ImageBufAlgo::MakeTxTexture,
ImageBufAlgo::MakeTxEnvLatl,
ImageBufAlgo::MakeTxEnvLatlFromLightProbe,
ImageBufAlgo::MakeTxShadow};
bool gTxFiltersInitialized = false;
static std::vector<const char*> gFilterNames;
class txWriter : public Writer {
int preset_;
int tileW_, tileH_;
int planarMode_;
int txMode_;
int bitDepth_;
int filter_;
bool fixNan_;
int nanFixType_;
bool checkNan_;
bool verbose_;
bool stats_;
void setChannelNames(ImageSpec& spec, const ChannelSet& channels) {
if (channels == Mask_RGB || channels == Mask_RGBA)
return;
int index = 0;
std::ostringstream buf;
foreach (z, channels) {
if (index > 0)
buf << ",";
switch (z) {
case Chan_Red:
buf << "R";
break;
case Chan_Green:
buf << "G";
break;
case Chan_Blue:
buf << "B";
break;
case Chan_Alpha:
buf << "A";
spec.alpha_channel = index;
break;
case Chan_Z:
buf << "Z";
spec.z_channel = index;
break;
default:
buf << getName(z);
break;
}
index++;
}
spec.attribute("maketx:channelnames", buf.str());
}
public:
txWriter(Write* iop) : Writer(iop),
preset_(0),
tileW_(64), tileH_(64),
planarMode_(0),
txMode_(0), // ordinary 2d texture
bitDepth_(3), // float
filter_(0),
fixNan_(false),
nanFixType_(0),
checkNan_(true),
verbose_(false),
stats_(false)
{
if (!gTxFiltersInitialized) {
for (int i = 0, e = Filter2D::num_filters(); i < e; ++i) {
FilterDesc d;
Filter2D::get_filterdesc (i, &d);
gFilterNames.push_back(d.name);
};
gFilterNames.push_back(NULL);
gTxFiltersInitialized = true;
}
}
void knobs(Knob_Callback cb) {
Enumeration_knob(cb, &preset_, &presetValues[0], "preset");
Tooltip(cb, "Choose a preset for various output parameters.\n"
"<b>oiio</b>: Tile and planar settings optimized for OIIO.\n"
"<b>prman</b>: Tile and planar ettings and metadata safe for "
"use with prman.");
Knob* k;
k = Int_knob(cb, &tileW_, "tile_width", "tile size");
if (cb.makeKnobs())
k->disable();
else if (preset_ == 2)
k->enable();
Tooltip(cb, "Tile width");
k = Int_knob(cb, &tileH_, "tile_height", "x");
if (cb.makeKnobs())
k->disable();
else if (preset_ == 2)
k->enable();
Tooltip(cb, "Tile height");
ClearFlags(cb, Knob::STARTLINE);
k = Enumeration_knob(cb, &planarMode_, &planarValues[0],
"planar_config", "planar config");
if (cb.makeKnobs())
k->disable();
else if (preset_ == 2)
k->enable();
Tooltip(cb, "Planar mode of the image channels.");
SetFlags(cb, Knob::STARTLINE);
Enumeration_knob(cb, &txMode_, &txModeValues[0], "tx_mode",
"mode");
Tooltip(cb, "What type of texture file we are creating.");
Enumeration_knob(cb, &bitDepth_, &bitDepthValues[0], "tx_datatype",
"datatype");
Tooltip(cb, "The datatype of the output image.");
Enumeration_knob(cb, &filter_, &gFilterNames[0], "tx_filter", "filter");
Tooltip(cb, "The filter used to resize the image when generating mip "
"levels.");
Bool_knob(cb, &fixNan_, "fix_nan", "fix NaN/Inf pixels");
Tooltip(cb, "Attempt to fix NaN/Inf pixel values in the image.");
SetFlags(cb, Knob::STARTLINE);
k = Enumeration_knob(cb, &nanFixType_, &nanFixValues[0],
"nan_fix_type", "");
if (cb.makeKnobs())
k->disable();
else if (fixNan_)
k->enable();
Tooltip(cb, "The method to use to fix NaN/Inf pixel values.");
ClearFlags(cb, Knob::STARTLINE);
Bool_knob(cb, &checkNan_, "check_nan", "error on NaN/Inf");
Tooltip(cb, "Check for NaN/Inf pixel values in the output image, and "
"error if any are found. If this is enabled, the check will be "
"run <b>after</b> the NaN fix process.");
SetFlags(cb, Knob::STARTLINE);
Bool_knob(cb, &verbose_, "verbose");
Tooltip(cb, "Toggle verbose OIIO output.");
SetFlags(cb, Knob::STARTLINE);
Bool_knob(cb, &stats_, "oiio_stats", "output stats");
Tooltip(cb, "Toggle output of OIIO runtime statistics.");
ClearFlags(cb, Knob::STARTLINE);
}
int knob_changed(Knob* k) {
if (k->is("fix_nan")) {
iop->knob("nan_fix_type")->enable(fixNan_);
return 1;
}
if (k->is("preset")) {
const bool e = preset_ == 2;
iop->knob("tile_width")->enable(e);
iop->knob("tile_height")->enable(e);
iop->knob("planar_config")->enable(e);
return 1;
}
return Writer::knob_changed(k);
}
void execute() {
const int chanCount = num_channels();
ChannelSet channels = channel_mask(chanCount);
const bool doAlpha = channels.contains(Chan_Alpha);
iop->progressMessage("Preparing image");
input0().request(0, 0, width(), height(), channels, 1);
if (aborted())
return;
ImageSpec srcSpec(width(), height(), chanCount, TypeDesc::FLOAT);
ImageBuf srcBuffer(srcSpec);
Row row(0, width());
// Buffer for a channel-interleaved row after output LUT processing
std::vector<float> lutBuffer(width() * chanCount);
for (int y = 0; y < height(); y++) {
iop->progressFraction(double(y) / height() * 0.85);
get(height() - y - 1, 0, width(), channels, row);
if (aborted())
return;
const float* alpha = doAlpha ? row[Chan_Alpha] : NULL;
for (int i = 0; i < chanCount; i++)
to_float(i, &lutBuffer[i], row[channel(i)], alpha, width(),
chanCount);
for (int x = 0; x < width(); x++)
srcBuffer.setpixel(x, y, &lutBuffer[x * chanCount]);
}
ImageSpec destSpec(width(), height(), chanCount, oiioBitDepths[bitDepth_]);
setChannelNames(destSpec, channels);
destSpec.attribute("maketx:filtername", gFilterNames[filter_]);
switch (preset_) {
case 0:
destSpec.attribute("maketx:oiio_options", 1);
break;
case 1:
destSpec.attribute("maketx:prman_options", 1);
break;
default:
destSpec.tile_width = tileW_;
destSpec.tile_height = tileH_;
destSpec.attribute("planarconfig",
planarMode_ ? "separate" : "contig");
break;
}
if (fixNan_) {
if (nanFixType_)
destSpec.attribute("maketx:fixnan", "box3");
else
destSpec.attribute("maketx:fixnan", "black");
}
else
destSpec.attribute("maketx:fixnan", "none");
destSpec.attribute("maketx:checknan", checkNan_);
destSpec.attribute("maketx:verbose", verbose_);
destSpec.attribute("maketx:stats", stats_);
OIIO::attribute("threads", (int)Thread::numCPUs);
if (aborted())
return;
iop->progressMessage("Writing %s", filename());
if (!ImageBufAlgo::make_texture(oiiotxMode[txMode_], srcBuffer,
filename(), destSpec, &std::cout))
iop->critical("ImageBufAlgo::make_texture failed to write file %s",
filename());
}
const char* help() { return "Tiled, mipmapped texture format"; }
static const Writer::Description d;
};
} // ~TxWriterNS
static Writer* build(Write* iop) { return new TxWriterNS::txWriter(iop); }
const Writer::Description TxWriterNS::txWriter::d("tx\0TX\0", build);
|
; A037141: Convolution of natural numbers n >= 1 with Fibonacci numbers F(k), for k >= -5, with F(-n)=(-1)^(n+1)*F(n);.
; 5,7,11,14,18,22,27,33,41,52,68,92,129,187,279,426,662,1042,1655,2645,4245,6832,11016,17784,28733,46447,75107,121478,196506,317902,514323,832137,1346369,2178412,3524684,5702996,9227577,14930467,24157935,39088290
mov $5,$0
add $0,4
mov $1,21
mov $2,5
mov $3,5
lpb $0
sub $0,1
add $3,1
sub $1,$3
mov $4,$2
mov $2,$1
add $1,$4
sub $1,5
add $2,4
lpe
lpb $5
add $1,1
sub $5,1
lpe
sub $1,20
|
/****************************************************************************
** Meta object code from reading C++ file 'EditorDescripttionSetup.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.14.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <memory>
#include "../../EditorDescripttionSetup.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'EditorDescripttionSetup.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.14.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_FastCAEDesigner__EditorDescripttionSetup_t {
QByteArrayData data[38];
char stringdata0[895];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_FastCAEDesigner__EditorDescripttionSetup_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_FastCAEDesigner__EditorDescripttionSetup_t qt_meta_stringdata_FastCAEDesigner__EditorDescripttionSetup = {
{
QT_MOC_LITERAL(0, 0, 40), // "FastCAEDesigner::EditorDescri..."
QT_MOC_LITERAL(1, 41, 30), // "dispalyParameterLinkageManager"
QT_MOC_LITERAL(2, 72, 0), // ""
QT_MOC_LITERAL(3, 73, 14), // "OnBtnOkClicked"
QT_MOC_LITERAL(4, 88, 20), // "OnBtnLoadIconClicked"
QT_MOC_LITERAL(5, 109, 19), // "OnBtnAddParaClicked"
QT_MOC_LITERAL(6, 129, 20), // "OnBtnEditParaClicked"
QT_MOC_LITERAL(7, 150, 19), // "OnBtnDelParaClicked"
QT_MOC_LITERAL(8, 170, 24), // "OnBtnClearAllParaClicked"
QT_MOC_LITERAL(9, 195, 28), // "TableWidgetParaDoubleClicked"
QT_MOC_LITERAL(10, 224, 11), // "QModelIndex"
QT_MOC_LITERAL(11, 236, 10), // "modelIndex"
QT_MOC_LITERAL(12, 247, 22), // "TableWidgetParaClicked"
QT_MOC_LITERAL(13, 270, 33), // "TableWidgetParaCurrentCellCha..."
QT_MOC_LITERAL(14, 304, 20), // "OnBtnAddGroupClicked"
QT_MOC_LITERAL(15, 325, 20), // "OnBtnDelGroupClicked"
QT_MOC_LITERAL(16, 346, 21), // "OnBtnEditGroupClicked"
QT_MOC_LITERAL(17, 368, 25), // "OnBtnClearAllGroupClicked"
QT_MOC_LITERAL(18, 394, 28), // "TableWidgetGoupDoubleClicked"
QT_MOC_LITERAL(19, 423, 23), // "TableWidgetGroupClicked"
QT_MOC_LITERAL(20, 447, 34), // "TableWidgetGroupCurrentCellCh..."
QT_MOC_LITERAL(21, 482, 24), // "OnBtnAddGroupParaClicked"
QT_MOC_LITERAL(22, 507, 25), // "OnBtnEditGroupParaClicked"
QT_MOC_LITERAL(23, 533, 24), // "OnBtnDelGroupParaClicked"
QT_MOC_LITERAL(24, 558, 29), // "OnBtnClearAllGroupParaClicked"
QT_MOC_LITERAL(25, 588, 33), // "TableWidgetGroupParaDoubleCli..."
QT_MOC_LITERAL(26, 622, 27), // "TableWidgetGroupParaClicked"
QT_MOC_LITERAL(27, 650, 38), // "TableWidgetGroupParaCurrentCe..."
QT_MOC_LITERAL(28, 689, 18), // "OnCreateIntClicked"
QT_MOC_LITERAL(29, 708, 19), // "OnCreateBoolClicked"
QT_MOC_LITERAL(30, 728, 21), // "OnCreateDoubleClicked"
QT_MOC_LITERAL(31, 750, 21), // "OnCreateStringClicked"
QT_MOC_LITERAL(32, 772, 19), // "OnCreateEnumClicked"
QT_MOC_LITERAL(33, 792, 20), // "OnCreateTableClicked"
QT_MOC_LITERAL(34, 813, 19), // "OnCreatePathClicked"
QT_MOC_LITERAL(35, 833, 9), // "OnTimeout"
QT_MOC_LITERAL(36, 843, 21), // "OnBtnShowGroupClicked"
QT_MOC_LITERAL(37, 865, 29) // "OnParameterLinkagePBtnClicked"
},
"FastCAEDesigner::EditorDescripttionSetup\0"
"dispalyParameterLinkageManager\0\0"
"OnBtnOkClicked\0OnBtnLoadIconClicked\0"
"OnBtnAddParaClicked\0OnBtnEditParaClicked\0"
"OnBtnDelParaClicked\0OnBtnClearAllParaClicked\0"
"TableWidgetParaDoubleClicked\0QModelIndex\0"
"modelIndex\0TableWidgetParaClicked\0"
"TableWidgetParaCurrentCellChanged\0"
"OnBtnAddGroupClicked\0OnBtnDelGroupClicked\0"
"OnBtnEditGroupClicked\0OnBtnClearAllGroupClicked\0"
"TableWidgetGoupDoubleClicked\0"
"TableWidgetGroupClicked\0"
"TableWidgetGroupCurrentCellChanged\0"
"OnBtnAddGroupParaClicked\0"
"OnBtnEditGroupParaClicked\0"
"OnBtnDelGroupParaClicked\0"
"OnBtnClearAllGroupParaClicked\0"
"TableWidgetGroupParaDoubleClicked\0"
"TableWidgetGroupParaClicked\0"
"TableWidgetGroupParaCurrentCellChanged\0"
"OnCreateIntClicked\0OnCreateBoolClicked\0"
"OnCreateDoubleClicked\0OnCreateStringClicked\0"
"OnCreateEnumClicked\0OnCreateTableClicked\0"
"OnCreatePathClicked\0OnTimeout\0"
"OnBtnShowGroupClicked\0"
"OnParameterLinkagePBtnClicked"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_FastCAEDesigner__EditorDescripttionSetup[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
34, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 184, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
3, 0, 185, 2, 0x08 /* Private */,
4, 0, 186, 2, 0x08 /* Private */,
5, 0, 187, 2, 0x08 /* Private */,
6, 0, 188, 2, 0x08 /* Private */,
7, 0, 189, 2, 0x08 /* Private */,
8, 0, 190, 2, 0x08 /* Private */,
9, 1, 191, 2, 0x08 /* Private */,
12, 1, 194, 2, 0x08 /* Private */,
13, 0, 197, 2, 0x08 /* Private */,
14, 0, 198, 2, 0x08 /* Private */,
15, 0, 199, 2, 0x08 /* Private */,
16, 0, 200, 2, 0x08 /* Private */,
17, 0, 201, 2, 0x08 /* Private */,
18, 1, 202, 2, 0x08 /* Private */,
19, 1, 205, 2, 0x08 /* Private */,
20, 0, 208, 2, 0x08 /* Private */,
21, 0, 209, 2, 0x08 /* Private */,
22, 0, 210, 2, 0x08 /* Private */,
23, 0, 211, 2, 0x08 /* Private */,
24, 0, 212, 2, 0x08 /* Private */,
25, 1, 213, 2, 0x08 /* Private */,
26, 1, 216, 2, 0x08 /* Private */,
27, 0, 219, 2, 0x08 /* Private */,
28, 0, 220, 2, 0x08 /* Private */,
29, 0, 221, 2, 0x08 /* Private */,
30, 0, 222, 2, 0x08 /* Private */,
31, 0, 223, 2, 0x08 /* Private */,
32, 0, 224, 2, 0x08 /* Private */,
33, 0, 225, 2, 0x08 /* Private */,
34, 0, 226, 2, 0x08 /* Private */,
35, 0, 227, 2, 0x08 /* Private */,
36, 0, 228, 2, 0x08 /* Private */,
37, 0, 229, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, 0x80000000 | 10, 11,
QMetaType::Void, 0x80000000 | 10, 11,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, 0x80000000 | 10, 11,
QMetaType::Void, 0x80000000 | 10, 11,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, 0x80000000 | 10, 11,
QMetaType::Void, 0x80000000 | 10, 11,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void FastCAEDesigner::EditorDescripttionSetup::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<EditorDescripttionSetup *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->dispalyParameterLinkageManager(); break;
case 1: _t->OnBtnOkClicked(); break;
case 2: _t->OnBtnLoadIconClicked(); break;
case 3: _t->OnBtnAddParaClicked(); break;
case 4: _t->OnBtnEditParaClicked(); break;
case 5: _t->OnBtnDelParaClicked(); break;
case 6: _t->OnBtnClearAllParaClicked(); break;
case 7: _t->TableWidgetParaDoubleClicked((*reinterpret_cast< QModelIndex(*)>(_a[1]))); break;
case 8: _t->TableWidgetParaClicked((*reinterpret_cast< QModelIndex(*)>(_a[1]))); break;
case 9: _t->TableWidgetParaCurrentCellChanged(); break;
case 10: _t->OnBtnAddGroupClicked(); break;
case 11: _t->OnBtnDelGroupClicked(); break;
case 12: _t->OnBtnEditGroupClicked(); break;
case 13: _t->OnBtnClearAllGroupClicked(); break;
case 14: _t->TableWidgetGoupDoubleClicked((*reinterpret_cast< QModelIndex(*)>(_a[1]))); break;
case 15: _t->TableWidgetGroupClicked((*reinterpret_cast< QModelIndex(*)>(_a[1]))); break;
case 16: _t->TableWidgetGroupCurrentCellChanged(); break;
case 17: _t->OnBtnAddGroupParaClicked(); break;
case 18: _t->OnBtnEditGroupParaClicked(); break;
case 19: _t->OnBtnDelGroupParaClicked(); break;
case 20: _t->OnBtnClearAllGroupParaClicked(); break;
case 21: _t->TableWidgetGroupParaDoubleClicked((*reinterpret_cast< QModelIndex(*)>(_a[1]))); break;
case 22: _t->TableWidgetGroupParaClicked((*reinterpret_cast< QModelIndex(*)>(_a[1]))); break;
case 23: _t->TableWidgetGroupParaCurrentCellChanged(); break;
case 24: _t->OnCreateIntClicked(); break;
case 25: _t->OnCreateBoolClicked(); break;
case 26: _t->OnCreateDoubleClicked(); break;
case 27: _t->OnCreateStringClicked(); break;
case 28: _t->OnCreateEnumClicked(); break;
case 29: _t->OnCreateTableClicked(); break;
case 30: _t->OnCreatePathClicked(); break;
case 31: _t->OnTimeout(); break;
case 32: _t->OnBtnShowGroupClicked(); break;
case 33: _t->OnParameterLinkagePBtnClicked(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
using _t = void (EditorDescripttionSetup::*)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&EditorDescripttionSetup::dispalyParameterLinkageManager)) {
*result = 0;
return;
}
}
}
}
QT_INIT_METAOBJECT const QMetaObject FastCAEDesigner::EditorDescripttionSetup::staticMetaObject = { {
QMetaObject::SuperData::link<QDialog::staticMetaObject>(),
qt_meta_stringdata_FastCAEDesigner__EditorDescripttionSetup.data,
qt_meta_data_FastCAEDesigner__EditorDescripttionSetup,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *FastCAEDesigner::EditorDescripttionSetup::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *FastCAEDesigner::EditorDescripttionSetup::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_FastCAEDesigner__EditorDescripttionSetup.stringdata0))
return static_cast<void*>(this);
return QDialog::qt_metacast(_clname);
}
int FastCAEDesigner::EditorDescripttionSetup::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 34)
qt_static_metacall(this, _c, _id, _a);
_id -= 34;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 34)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 34;
}
return _id;
}
// SIGNAL 0
void FastCAEDesigner::EditorDescripttionSetup::dispalyParameterLinkageManager()
{
QMetaObject::activate(this, &staticMetaObject, 0, nullptr);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
|
; Windows intro skeleton by TomCat/Abaddon
; Flashdance/MIDI music by ern0
RESX EQU 256
RESY EQU 160
BASE EQU 00400000H
ORG BASE
USE32
FORMAT BINARY AS 'exe'
DW 'MZ' ; 00.e_magic
DW ? ; 02.e_cblp
DD 'PE' ; 04.Signature
DW 014CH ; 08.Machine
DW 0 ; 0A.NumberOfSections
DD ? ; 0C.TimeDateStamp
DD ? ; 10.PointerToSymbolTable
DD ? ; 14.NumberOfSymbols
DW 0 ; 18.SizeOfOptionalHeader
DW 2 ; 1A.Characteristics IMAGE_FILE_EXECUTABLE_IMAGE&!IMAGE_FILE_DLL
DW 010BH ; 1C.Magic
DB ? ; 1E.MajorLinkerVersion
DB ? ; 1F.MinorLinkerVersion
DD ? ; 20.SizeOfCode
DD ? ; 24.SizeOfInitializedData
DD ? ; 28.SizeOfUninitializedData
DD start-BASE ; 2C.AddressOfEntryPoint
DD ? ; 30.BaseOfCode
DD ? ; 34.BaseOfData
DD BASE ; 38.ImageBase
DD 4 ; 3C.SectionAlignment (.e_lfanew)
DD 4 ; 40.FileAlignment
DW ? ; 44.MajorOperatingSystemVersion
DW ? ; 46.MinorOperatingSystemVersion
DW ? ; 48.MajorImageVersion
DW ? ; 4A.MinorImageVersion
DW 4 ; 4C.MajorSubsystemVersion
DW ? ; 4E.MinorSubsystemVersion
DD 0 ; 50.Win32VersionValue
DD 00100000H ; 54.SizeOfImage
DD 2CH ; 58.SizeOfHeaders
DD ? ; 5C.CheckSum
DW 2 ; 60.Subsystem 2->gui
DW 0 ; 62.DllCharacteristics
DB ?,?,?,0 ; 64.SizeOfStackReserve
DD ? ; 68.SizeOfStackCommit
DB ?,?,?,0 ; 6C.SizeOfHeapReserve
DD ? ; 70.SizeOfHeapCommit
DD ? ; 74.LoaderFlags
DD 13 ; 78.NumberOfRvaAndSizes
DD ? ; 7C.Export.RVA
DD ? ; 80.Export.Size
DD IMPORT-BASE; 84.Import.RVA
DD ? ; 88.Import.Size
DD 0 ; 8C.Resource.RVA
DD ? ; 90.Resource.Size
DD ? ; 94.Exception.RVA
DD ? ; 98.Exception.Size
DD ? ; 9C.Security.RVA
DD ? ; A0.Security.Size
DD ? ; A4.Basereloc.RVA
DD ? ; A8.Basereloc.Size
DD ? ; AC.Debug.RVA
DD 0 ; B0.Debug.Size
DD ? ; B4.Copyright.RVA
DD ? ; B8.Copyright.Size
DD ? ; BC.Globalptr.RVA
DD ? ; C0.Globalptr.Size
DD 0 ; C4.TLS.RVA
DD ? ; C8.TLS.Size
DD ? ; CC.LoadConfig.RVA
DD ? ; D0.LoadConfig.Size
DD ? ; D4.BoundImport.RVA
DD ? ; D8.BoundImport.Size
DD IAT-BASE ; DC.IAT.RVA
DD IATend-IAT ; E0.IAT.Size
IMPORT:
DD 0
DD ?
DD ?
DD gdi32-BASE
DD g32-BASE
DD 0
DD ?
DD ?
DD user32-BASE
DD u32-BASE
DD 0
DD ?
DD ?
DD kern32-BASE
DD k32-BASE
DD 0
DD ?
DD ?
DD midi32-BASE
DD m32-BASE
DD ?
DD ?
DD ?
DD 0 ; TERMINATOR
DB ?,?,?
_check:
DB 0,0,'GetAsyncKeyState',0
_moutm:
DB 0,0,'midiOutShortMsg',0
_creat:
DB 0,0,'CreateWindowExA',0
_stret:
DB 0,0,'StretchDIBits',0
_getwr:
DB 0,0,'GetWindowRect',0
_gtick:
DB 0,0,'GetTickCount',0
_exitp:
DB 0,0,'ExitProcess',0
_mopen:
DB 0,0,'midiOutOpen',0
_showc:
DB 0,0,'ShowCursor',0
_getdc:
DB 0,0,'GetDC',0
kern32:
DB 'kernel32',0
user32:
DB 'user32',0
gdi32:
DB 'gdi32',0
midi32:
DB 'winmm',0
edit:
DB 'edit',0
;bit mirror table
;0123456789ABCDEF
;084C2A6E195D3B7F
score:
DB 32H,3DH,32H,3DH,0D4H,0D5H,0D4H,0D5H,0D4H,0D5H,0D4H,0D5H
DB 94H,91H,94H,91H,90H,91H,90H,91H,0E0H,0E6H,0E0H,0E6H
DB 24H,0E6H,0D9H,93H,62H,91H,03DH
last:
DB 0F7H ; XOR 0D7H
adder:
DB 60 ; XOR 72
IAT:;--------------------------
m32:
midiOutOpen:
DD _mopen-BASE; .AddressOfData
midiOutShortMsg:
DD _moutm-BASE; .AddressOfData
DD 0 ; .Terminator
k32:
ExitProcess:
DD _exitp-BASE; .AddressOfData
GetTickCount:
DD _gtick-BASE; .AddressOfData
DD 0 ; .Terminator
g32:
StretchDIBits:
DD _stret-BASE; .AddressOfData
DD 0 ; .Terminator
u32:
ShowCursor:
DD _showc-BASE; .AddressOfData
CreateWindowExA:
DD _creat-BASE; .AddressOfData
GetWindowRect:
DD _getwr-BASE; .AddressOfData
GetDC:
DD _getdc-BASE; .AddressOfData
GetAsyncKeyState:
DD _check-BASE; .AddressOfData
DD 0 ; .Terminator
IATend:;-----------------------
start:
MOV EDI,EDX ; EDI:start
SUB EBX,EBX ; EBX:0
MUL EBX ; EAX:0,EDX:0
MOV AH,RESX/256;EAX:RESX
MOV DL,RESY ; EDX:RESY
LEA ECX,[EBX+6]
@@:
PUSH EBX
LOOP @B
PUSH 00200001H; .biPlanes+.biBitCount
PUSH EDX ; .biHeight (negative value->vertical flip)
PUSH EAX ; .biWidth
PUSH 40 ; .biSize
MOV EBP,ESP ; BITMAPINFOHEADER
PUSH 00CC0020H; SRCCOPY
PUSH EBX ; DIB_RGB_COLORS
PUSH EBP ; BITMAPINFOHEADER
PUSH start+RESX*RESY
PUSH EDX ; RESY
PUSH EAX ; RESX
MOV CL,2+4+1+8+4; 2:StretchDIBits, 4:midiOutOpen, 1:ShowCursor, 8:CreateWindowEx, 4:RECT
@@:
PUSH EBX ; fill by zero
LOOP @B
;midiOutOpen(&handle, 0, 0, 0, CALLBACK_NULL);
PUSH EDI ; lphmo
CALL DWORD [EDI-start+midiOutOpen]
;ShowCursor(FALSE);
CALL DWORD [EDI-start+ShowCursor]
LEA EAX,[EDI-start+edit]
PUSH 91000000H; WS_POPUP|WS_MAXIMIZE|WS_VISIBLE
PUSH EBX
PUSH EAX
PUSH EBX
;CreateWindowEx(0,"edit",0,WS_POPUP|WS_MAXIMIZE|WS_VISIBLE,0,0,0,0,0,0,0,0);
CALL DWORD [EDI-start+CreateWindowExA]
MOV EDX,ESP
PUSH EAX ; hwnd
PUSH EDX ; RECT
PUSH EAX ; hwnd
CALL DWORD [EDI-start+GetWindowRect]
;GetDC(hwnd);
CALL DWORD [EDI-start+GetDC]
PUSH EAX ; hdc
music:
MOV EDX,007F1090H
@@:
BT [EDI-start+score],EBX
RCL DH,1
INC BL
JNC @B
ADD DH,[EDI-start+adder]
TEST BL,BL
JNZ @F
XOR WORD [EDI-start+last],7420H
@@:
;midiOutShortMsg(handle, 0x007f4090);
PUSH EDX ; send note on channel 0
PUSH DWORD [EDI]
CALL DWORD [EDI-start+midiOutShortMsg]
PUSH 29 ; tempo of the music
POP EBP
main:
CALL DWORD [EDI-start+GetTickCount]
CMP EAX,ESI
JE main
XCHG ESI,EAX ; time counter
DEC EBP
JZ music
visual:
PUSHAD
SHR ESI,6 ; speed of the visual
SUB ECX,ECX
MOV CH,RESX*RESY/256
ADD EDI,ECX
@loop:
LEA EAX,[ESI+ECX]
PUSH EAX
MOV DL,CH
ADD EDX,ESI
PUSH EDX
ADD EAX,EDX
PUSH EAX
SUB EDX,EDX
@@:
POP EAX
CBW
XOR AL,AH
ADD AL,AL
STOSB
INC EDX
JPO @B
INC EDI
LOOP @loop
POPAD
;StretchDIBits(hdc,rc.left,rc.top,rc.right,rc.bottom,0,0,ResX,ResY,pixels,bmpnfo,0,SRCCOPY);
CALL DWORD [EDI-start+StretchDIBits]
SUB ESP,13*4 ; repair the stack frame (preserves StretchDIBits arguments)
PUSH 1BH ; VK_ESCAPE
CALL DWORD [EDI-start+GetAsyncKeyState]
TEST EAX,EAX
JZ main
quit:
JMP DWORD [EDI-start+ExitProcess]
|
; A139280: a(n) = 90*n - 81.
; 9,99,189,279,369,459,549,639,729,819,909,999,1089,1179,1269,1359,1449,1539,1629,1719,1809,1899,1989,2079,2169,2259,2349,2439,2529,2619,2709,2799,2889,2979,3069,3159,3249,3339,3429,3519,3609,3699,3789,3879,3969,4059,4149,4239,4329,4419,4509,4599,4689,4779,4869,4959,5049,5139,5229,5319,5409,5499,5589,5679,5769,5859,5949,6039,6129,6219,6309,6399,6489,6579,6669,6759,6849,6939,7029,7119,7209,7299,7389,7479,7569,7659,7749,7839,7929,8019,8109,8199,8289,8379,8469,8559,8649,8739,8829,8919
mul $0,90
add $0,9
|
.global s_prepare_buffers
s_prepare_buffers:
push %r12
push %r13
push %r14
push %r9
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_WT_ht+0x1a7d5, %r13
nop
nop
xor $49099, %r12
mov (%r13), %r14w
nop
nop
nop
nop
inc %r9
lea addresses_normal_ht+0xb815, %rdx
nop
nop
cmp $9625, %r9
mov $0x6162636465666768, %rsi
movq %rsi, %xmm6
movups %xmm6, (%rdx)
cmp $65193, %r13
lea addresses_UC_ht+0x1e875, %rsi
lea addresses_WC_ht+0xdd55, %rdi
nop
nop
xor $36139, %r12
mov $14, %rcx
rep movsq
nop
nop
nop
nop
nop
cmp $20010, %rsi
lea addresses_UC_ht+0xb555, %rdx
nop
nop
sub $64727, %r12
mov $0x6162636465666768, %rdi
movq %rdi, %xmm5
movups %xmm5, (%rdx)
nop
nop
nop
nop
xor $13727, %rsi
lea addresses_UC_ht+0x4955, %rsi
clflush (%rsi)
nop
nop
nop
and $63581, %r13
mov $0x6162636465666768, %rdi
movq %rdi, %xmm0
and $0xffffffffffffffc0, %rsi
movntdq %xmm0, (%rsi)
nop
nop
cmp %rsi, %rsi
lea addresses_UC_ht+0x19de5, %rdx
and $15966, %rsi
and $0xffffffffffffffc0, %rdx
movaps (%rdx), %xmm5
vpextrq $0, %xmm5, %r9
nop
nop
nop
nop
nop
inc %r12
lea addresses_normal_ht+0x12365, %rdi
nop
add $53992, %rcx
movb (%rdi), %r14b
nop
nop
nop
and %r14, %r14
lea addresses_D_ht+0x15c15, %rcx
nop
nop
nop
add %r9, %r9
mov $0x6162636465666768, %r12
movq %r12, %xmm3
movups %xmm3, (%rcx)
nop
nop
nop
cmp %rsi, %rsi
lea addresses_WC_ht+0x6ed5, %rcx
clflush (%rcx)
nop
nop
nop
nop
and $49965, %r14
mov $0x6162636465666768, %rdx
movq %rdx, %xmm5
movups %xmm5, (%rcx)
and %r14, %r14
lea addresses_UC_ht+0x10a0b, %rdi
nop
nop
nop
xor %rdx, %rdx
movb (%rdi), %r12b
nop
nop
nop
and $44757, %r13
lea addresses_D_ht+0x104f, %rsi
lea addresses_WT_ht+0x4c65, %rdi
nop
nop
nop
nop
xor %r9, %r9
mov $115, %rcx
rep movsb
nop
nop
and $41107, %rcx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r9
pop %r14
pop %r13
pop %r12
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r13
push %r14
push %r15
push %r8
push %rbx
// Faulty Load
lea addresses_RW+0x1bd55, %r13
sub %r8, %r8
movb (%r13), %r14b
lea oracles, %r15
and $0xff, %r14
shlq $12, %r14
mov (%r15,%r14,1), %r14
pop %rbx
pop %r8
pop %r15
pop %r14
pop %r13
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_RW', 'same': False, 'AVXalign': False, 'congruent': 0}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'size': 1, 'NT': True, 'type': 'addresses_RW', 'same': True, 'AVXalign': False, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'LOAD', 'src': {'size': 2, 'NT': True, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 6}}
{'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 6}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 4}, 'dst': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 11}}
{'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_UC_ht', 'same': True, 'AVXalign': False, 'congruent': 9}}
{'OP': 'STOR', 'dst': {'size': 16, 'NT': True, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 10}}
{'OP': 'LOAD', 'src': {'size': 16, 'NT': True, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': True, 'congruent': 3}}
{'OP': 'LOAD', 'src': {'size': 1, 'NT': True, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 4}}
{'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 5}}
{'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 6}}
{'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 1}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_D_ht', 'congruent': 1}, 'dst': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 4}}
{'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
*/
|
; A183624: Number of (n+1) X 2 0..2 arrays with every 2 x 2 subblock summing to 4.
; 19,45,115,309,859,2445,7075,20709,61099,181245,539635,1610709,4815739,14414445,43177795,129402309,387944779,1163310045,3488881555,10464547509,31389448219,94159956045,282463090915,847355718309,2542000046059,7625865920445,22877329325875,68631451106709,205893279578299,617677691251245,1853028778786435,5559077746424709
add $0,3
mov $1,1
mov $2,1
mov $3,1
lpb $0,1
sub $0,1
add $2,$1
mul $3,2
add $3,$1
add $1,$2
sub $3,$2
mov $2,$3
mul $3,2
lpe
add $1,2
|
;
; ZX IF1 & Microdrive functions
;
; Get Microdrive status
;
; int if1_mdv_status (int drive);
;
; Returns:
; 0: Microdrive Ready, cartridge inserted, no write protection
; 1: Cartridge is write protected
; 2: Microdrive not present
;
; $Id: if1_mdv_status.asm,v 1.3 2016/07/01 22:08:20 dom Exp $
;
SECTION code_clib
PUBLIC if1_mdv_status
PUBLIC _if1_mdv_status
EXTERN if1_rommap
EXTERN MOTOR
if1_mdv_status:
_if1_mdv_status:
pop hl
pop bc
push bc
push hl
ld a,c
ld hl,-1
and a ; drive no. = 0 ?
ret z ; yes, return -1
dec a
cp 8 ; drive no. >8 ?
ret nc ; yes, return -1
inc a
push af
call if1_rommap
pop af
call MOTOR ; select drive motor
ld hl,retcode+1
ld a,2
ld (hl),a
jr nz,estatus ; microdrive not present
in a,($ef)
and 1 ; test the write-protect tab
;;ret z ; drive 'write' protected
xor 1 ; invert result (now 1=protected)
ld (hl),a
estatus:
xor a
call MOTOR ; Switch microdrive motor off (a=0)
call 1 ; unpage
ei
retcode: ld hl,0
ret
|
#ifndef LM_BINARY_FORMAT_H
#define LM_BINARY_FORMAT_H
#include "lm/config.hh"
#include "lm/model_type.hh"
#include "lm/read_arpa.hh"
#include "util/file_piece.hh"
#include "util/mmap.hh"
#include "util/scoped.hh"
#include <cstddef>
#include <vector>
#include <stdint.h>
namespace lm {
namespace ngram {
extern const char *kModelNames[6];
/*Inspect a file to determine if it is a binary lm. If not, return false.
* If so, return true and set recognized to the type. This is the only API in
* this header designed for use by decoder authors.
*/
bool RecognizeBinary(const char *file, ModelType &recognized);
struct FixedWidthParameters {
unsigned char order;
float probing_multiplier;
// What type of model is this?
ModelType model_type;
// Does the end of the file have the actual strings in the vocabulary?
bool has_vocabulary;
unsigned int search_version;
};
// This is a macro instead of an inline function so constants can be assigned using it.
#define ALIGN8(a) ((std::ptrdiff_t(((a)-1)/8)+1)*8)
// Parameters stored in the header of a binary file.
struct Parameters {
FixedWidthParameters fixed;
std::vector<uint64_t> counts;
};
class BinaryFormat {
public:
explicit BinaryFormat(const Config &config);
// Reading a binary file:
// Takes ownership of fd
void InitializeBinary(int fd, ModelType model_type, unsigned int search_version, Parameters ¶ms);
// Used to read parts of the file to update the config object before figuring out full size.
void ReadForConfig(void *to, std::size_t amount, uint64_t offset_excluding_header) const;
// Actually load the binary file and return a pointer to the beginning of the search area.
void *LoadBinary(std::size_t size);
uint64_t VocabStringReadingOffset() const {
assert(vocab_string_offset_ != kInvalidOffset);
return vocab_string_offset_;
}
// Writing a binary file or initializing in RAM from ARPA:
// Size for vocabulary.
void *SetupJustVocab(std::size_t memory_size, uint8_t order);
// Warning: can change the vocaulary base pointer.
void *GrowForSearch(std::size_t memory_size, std::size_t vocab_pad, void *&vocab_base);
// Warning: can change vocabulary and search base addresses.
void WriteVocabWords(const std::string &buffer, void *&vocab_base, void *&search_base);
// Write the header at the beginning of the file.
void FinishFile(const Config &config, ModelType model_type, unsigned int search_version, const std::vector<uint64_t> &counts);
private:
void MapFile(void *&vocab_base, void *&search_base);
// Copied from configuration.
const Config::WriteMethod write_method_;
const char *write_mmap_;
util::LoadMethod load_method_;
// File behind memory, if any.
util::scoped_fd file_;
// If there is a file involved, a single mapping.
util::scoped_memory mapping_;
// If the data is only in memory, separately allocate each because the trie
// knows vocab's size before it knows search's size (because SRILM might
// have pruned).
util::scoped_memory memory_vocab_, memory_search_;
// Memory ranges. Note that these may not be contiguous and may not all
// exist.
std::size_t header_size_, vocab_size_, vocab_pad_;
// aka end of search.
uint64_t vocab_string_offset_;
static const uint64_t kInvalidOffset = (uint64_t)-1;
};
bool IsBinaryFormat(int fd);
} // namespace ngram
} // namespace lm
#endif // LM_BINARY_FORMAT_H
|
; /**
; * syscall.asm
; */
%include "sconst.inc"
_NR_get_ticks equ 0 ; 要跟 global.c 中 sys_call_table 的定义相对应!
_NR_ipc_send equ 1
INT_VECTOR_SYS_CALL equ 0x36
; 导出符号
global get_ticks ; 0
global ipc_send ; 1
bits 32
[section .text]
; ====================================================================
; get_ticks(void)
; ====================================================================
get_ticks:
mov eax, _NR_get_ticks
int INT_VECTOR_SYS_CALL
ret
; ====================================================================
; ipc_send
; ====================================================================
; ipc_send(message* m)
ipc_send:
mov eax, _NR_ipc_send
mov ebx, [esp + 4]
int INT_VECTOR_SYS_CALL
ret
; ====================================================================
;
;
|
format PE64 Console 5.0
entry main
include 'C:\Program Files (x86)\fasmw17322\INCLUDE\win64a.inc'
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
section '.text' code readable executable
main:
; for printf, scanf etc. we use cinvoke (__cdecl), invoke is used for __stdcall functions
cinvoke printf, msg_enter_x
cinvoke scanf, x_read_fmt, x
mov rax, 0.0 ; for double values we must write .0 always.
movq xmm5, rax ; xmm5 is s
mov rax, 1.0 ; 64bit mode allows only signed 32bit immediates. Only instruction that can take 64bit immediate is "mov rax, imm64"
movq xmm6, rax ; xmm6 is p
mov ecx, 0 ; ecx is n
movq xmm7, [x] ; xmm7 is x
while_1:
; check if abs(p) >= eps. if false break
movq xmm0, xmm6
pslld xmm0, 1
psrld xmm0, 1
comisd xmm0, [eps]
jc while_1_end ; if abs(p) < eps then break
movq xmm1, xmm5
addsd xmm1, xmm6
movq xmm5, xmm1
inc ecx
cvtsi2sd xmm1, ecx ; convert int to double. ~ xmm1 = (double)n;
mulsd xmm1, xmm1 ; now xmm1 = n^2
mov rax, 4.0
movq xmm4, rax
mulsd xmm1, xmm4 ; now xmm1 = 4*(n^2)
movq xmm0, xmm7
mulsd xmm0, xmm0 ; now xmm0 = x^2
mov rax, -1.0
movq xmm4, rax
mulsd xmm0, xmm4 ; now xmm0 = -(x^2)
movq xmm3, xmm6
mulsd xmm3, xmm0
divsd xmm3, xmm1
movq xmm6, xmm3
jmp while_1
while_1_end:
movq [s], xmm5
cinvoke printf, <"J0(%f) = %f", 13, 10, 13, 10>, [x], [s]
;cinvoke getchar ; first getchar will read \n
;cinvoke getchar
jmp main
Exit: ; exit from program
invoke ExitProcess, 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
section '.data' data readable writeable
; db - reserve byte, dw - reserve word, dd - reserve dword, dq - reserve qword
eps dq 0.000001 ; double eps = 0.000001; // epsilon
x dq ? ; double x; // x value
n dd ? ; int n; // step counter
s dq ? ; double s; // current sum
p dq ? ; double p; // current member of series
msg_enter_x db 'Enter x: ', 13, 10, 0
x_read_fmt db '%lf', 0
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;section '.bss' readable writeable ; statically-allocated variables that are not explicitly initialized to any value
; readBuf db ?
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
section '.idata' import data readable
library msvcrt,'MSVCRT.DLL',\
kernel,'KERNEL32.DLL'
import kernel,\
ExitProcess, 'ExitProcess'
;SetConsoleTitleA, 'SetConsoleTitleA',\
;GetStdHandle, 'GetStdHandle',\
;WriteConsoleA, 'WriteConsoleA',\
;ReadConsoleA, 'ReadConsoleA'
import msvcrt,\
puts,'puts',\
scanf,'scanf',\
printf,'printf',\
getchar,'getchar',\
system,'system',\
exit,'exit' |
; A292611: Skip 3 triangle numbers, take 1 triangle number, skip 4 triangle numbers, take 2 triangle numbers, skip 5 triangle numbers, take 3 triangle numbers, ...
; 10,45,55,136,153,171,325,351,378,406,666,703,741,780,820,1225,1275,1326,1378,1431,1485,2080,2145,2211,2278,2346,2415,2485,3321,3403,3486,3570,3655,3741,3828,3916,5050,5151,5253,5356,5460,5565,5671,5778,5886,7381,7503,7626,7750,7875,8001,8128,8256,8385,8515,10440,10585,10731,10878,11026,11175,11325,11476,11628,11781,11935,14365,14535,14706,14878,15051,15225,15400,15576,15753,15931,16110,16290,19306,19503,19701,19900,20100,20301,20503,20706,20910,21115,21321,21528,21736,25425,25651,25878,26106
seq $0,189151 ; Numbers n such that n < floor(sqrt(n)) * ceiling(sqrt(n)).
bin $0,2
|
; A001814: Coefficient of H_2 when expressing x^{2n} in terms of Hermite polynomials H_m.
; 1,12,180,3360,75600,1995840,60540480,2075673600,79394515200,3352212864000,154872234316800,7771770303897600,420970891461120000,24481076457277440000,1521324036987955200000,100610229646136770560000,7055292353935341035520000,522921668585795864985600000,40845992557312721453875200000,3353670967863570814107648000000,288751070333053447094668492800000,26015096431911291519195847065600000,2447784073366198792942518337536000000,240095689978875846820796581281792000000
add $0,1
mov $1,$0
mov $2,$0
lpb $1
mul $0,$2
sub $1,1
add $2,1
lpe
|
; A111802: n^2-n-1 for n>3; a(1)=1; a(2)=2; a(3)=3.
; 1,2,3,11,19,29,41,55,71,89,109,131,155,181,209,239,271,305,341,379,419,461,505,551,599,649,701,755,811,869,929,991,1055,1121,1189,1259,1331,1405,1481,1559,1639,1721,1805,1891,1979,2069,2161,2255,2351,2449,2549
mov $1,$0
add $1,2
lpb $0,1
mul $1,$0
sub $1,$0
mod $0,3
lpe
sub $1,1
|
; QPC 16 bit palette
;
section driver
;
xdef qpc16_palette
xdef qpc16_palend
;
qpc16_palette
dc.w $0000,$1f00,$00f8,$1ff8,$c007,$df07,$c0ff,$dfff
;
dc.w $0000,$DFFF,$00F8,$C007,$1F00,$1FF8,$C0FF,$DF07
dc.w $0421,$494A,$4D6B,$9294,$96B5,$DBDE,$0090,$D6B7
dc.w $8094,$8004,$9204,$1200,$1290,$12F8,$80FC,$C097
dc.w $D207,$9F04,$1F90,$96FD,$D6FF,$DFB7,$9FB5,$9FFD
dc.w $9BFD,$D6FE,$DBFE,$DBFF,$DBDF,$DFDF,$DFDE,$DFFE
dc.w $4DB3,$8DB5,$8D6D,$966D,$566B,$56B3,$0469,$446B
dc.w $4423,$4D23,$0D21,$0D69,$52B2,$89B4,$8995,$924D
dc.w $964C,$5692,$0990,$4092,$804C,$8904,$5202,$1248
dc.w $0900,$0420,$0D20,$1620,$1F20,$0048,$0948,$1B48
dc.w $0468,$0D68,$1668,$1F68,$04B0,$0DB0,$16B0,$1FB0
dc.w $00D8,$09D8,$12D8,$1BD8,$0DF8,$0001,$0901,$1201
dc.w $1B01,$1621,$1F21,$0049,$0949,$1249,$1B49,$1669
dc.w $1F69,$0091,$0991,$1291,$1B91,$04B1,$0DB1,$16B1
dc.w $1FB1,$00D9,$09D9,$12D9,$1BD9,$04F9,$0DF9,$16F9
dc.w $1FF9,$4002,$4902,$5B02,$4422,$4D22,$5622,$5F22
dc.w $404A,$524A,$5B4A,$446A,$4D6A,$566A,$5F6A,$4992
dc.w $5B92,$44B2,$4DB2,$5FB2,$40DA,$49DA,$52DA,$5BDA
dc.w $44FA,$4DFA,$56FA,$5FFA,$4003,$4903,$5203,$5B03
dc.w $5623,$5F23,$404B,$494B,$524B,$5B4B,$5F6B,$4093
dc.w $4993,$5293,$5B93,$44B3,$5FB3,$40DB,$49DB,$52DB
dc.w $5BDB,$44FB,$4DFB,$56FB,$5FFB,$8424,$8D24,$9624
dc.w $9F24,$894C,$9B4C,$846C,$8D6C,$966C,$9F6C,$8994
dc.w $9B94,$84B4,$96B4,$9FB4,$80DC,$89DC,$92DC,$9BDC
dc.w $8DFC,$96FC,$9FFC,$8005,$8905,$9205,$9B05,$8425
dc.w $8D25,$9625,$9F25,$804D,$894D,$9B4D,$846D,$9F6D
dc.w $8095,$9295,$9B95,$84B5,$80DD,$89DD,$92DD,$9BDD
dc.w $84FD,$8DFD,$C006,$C906,$D206,$DB06,$C426,$CD26
dc.w $D626,$DF26,$C04E,$C94E,$D24E,$DB4E,$C46E,$CD6E
dc.w $D66E,$DF6E,$C096,$C996,$D296,$DB96,$C4B6,$CDB6
dc.w $D6B6,$DFB6,$C9DE,$D2DE,$CDFE,$C907,$CD27,$D627
dc.w $C04F,$C94F,$D24F,$DB4F,$C46F,$CD6F,$D66F,$DF6F
dc.w $C997,$D297,$DB97,$C4B7,$CDB7,$C9DF,$D2DF,$CDFF
qpc16_palend
;
end
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r12
push %r13
push %r14
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0x2c33, %r10
nop
nop
nop
nop
nop
and %r12, %r12
movw $0x6162, (%r10)
sub $16926, %r14
lea addresses_normal_ht+0x10f77, %r10
nop
nop
nop
and %rdi, %rdi
mov (%r10), %r13w
nop
lfence
lea addresses_D_ht+0x3457, %r11
nop
nop
nop
sub $31721, %r14
movb (%r11), %r12b
nop
nop
nop
nop
cmp $301, %r13
lea addresses_WC_ht+0x1af57, %rsi
lea addresses_WC_ht+0x167d7, %rdi
clflush (%rdi)
nop
nop
cmp $5624, %r12
mov $88, %rcx
rep movsb
nop
nop
sub $57304, %r13
lea addresses_A_ht+0x9c17, %r12
nop
nop
and %r10, %r10
movb $0x61, (%r12)
nop
add %r11, %r11
lea addresses_WC_ht+0x191eb, %rdi
clflush (%rdi)
nop
nop
and $27533, %r12
mov (%rdi), %rcx
nop
xor %r13, %r13
lea addresses_normal_ht+0x11937, %rsi
lea addresses_A_ht+0x8ed, %rdi
nop
nop
nop
nop
and %r12, %r12
mov $87, %rcx
rep movsq
nop
nop
nop
inc %r13
lea addresses_normal_ht+0xc57, %rcx
nop
nop
nop
nop
nop
and %r13, %r13
mov (%rcx), %r12w
add $53614, %rdi
lea addresses_WC_ht+0x633e, %r13
add $12132, %r11
mov (%r13), %rsi
nop
nop
xor $25574, %r14
lea addresses_normal_ht+0xa4d7, %r10
nop
sub %rcx, %rcx
mov (%r10), %di
nop
nop
nop
nop
and %r11, %r11
lea addresses_A_ht+0x157f7, %rdi
nop
nop
cmp $219, %rcx
movb $0x61, (%rdi)
nop
nop
nop
sub %r13, %r13
pop %rsi
pop %rdi
pop %rcx
pop %r14
pop %r13
pop %r12
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r13
push %r15
push %rcx
push %rdi
push %rsi
// REPMOV
lea addresses_A+0x15657, %rsi
lea addresses_WC+0x34b7, %rdi
nop
nop
nop
cmp $26721, %r15
mov $46, %rcx
rep movsq
nop
nop
nop
nop
xor $42950, %r10
// Faulty Load
lea addresses_normal+0xc457, %r11
xor %rcx, %rcx
mov (%r11), %r10
lea oracles, %rcx
and $0xff, %r10
shlq $12, %r10
mov (%rcx,%r10,1), %r10
pop %rsi
pop %rdi
pop %rcx
pop %r15
pop %r13
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 0, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_A', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_WC', 'congruent': 5, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': True, 'NT': True}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 1, 'size': 2, 'same': False, 'NT': True}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 3, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 11, 'size': 1, 'same': False, 'NT': True}}
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 6, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 6, 'size': 1, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 2, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 1, 'same': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 11, 'size': 2, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 7, 'size': 2, 'same': False, 'NT': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'congruent': 5, 'size': 1, 'same': False, 'NT': True}}
{'34': 9}
34 34 34 34 34 34 34 34 34
*/
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2019 The PIVX developers
// Copyright (c) 2019-2020 The Altbet developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/abet-config.h"
#endif
#include "init.h"
#include "zpiv/accumulators.h"
#include "activemasternode.h"
#include "addrman.h"
#include "amount.h"
#include "checkpoints.h"
#include "compat/sanity.h"
#include "httpserver.h"
#include "httprpc.h"
#include "invalid.h"
#include "key.h"
#include "main.h"
#include "masternode-budget.h"
#include "masternode-payments.h"
#include "masternodeconfig.h"
#include "masternodeman.h"
#include "miner.h"
#include "net.h"
#include "rpc/server.h"
#include "script/standard.h"
#include "scheduler.h"
#include "spork.h"
#include "sporkdb.h"
#include "txdb.h"
#include "torcontrol.h"
#include "guiinterface.h"
#include "util.h"
#include "utilmoneystr.h"
#include "validationinterface.h"
#include "zpiv/accumulatorcheckpoints.h"
#include "zpivchain.h"
#ifdef ENABLE_WALLET
#include "wallet/db.h"
#include "wallet/wallet.h"
#include "wallet/walletdb.h"
#endif
#include <fstream>
#include <stdint.h>
#include <stdio.h>
#ifndef WIN32
#include <signal.h>
#endif
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/interprocess/sync/file_lock.hpp>
#include <boost/thread.hpp>
#include <boost/foreach.hpp>
#include <openssl/crypto.h>
#if ENABLE_ZMQ
#include "zmq/zmqnotificationinterface.h"
#endif
#ifdef ENABLE_WALLET
CWallet* pwalletMain = NULL;
CzPIVWallet* zwalletMain = NULL;
int nWalletBackups = 10;
#endif
volatile bool fFeeEstimatesInitialized = false;
volatile bool fRestartRequested = false; // true: restart false: shutdown
extern std::list<uint256> listAccCheckpointsNoDB;
#if ENABLE_ZMQ
static CZMQNotificationInterface* pzmqNotificationInterface = NULL;
#endif
#ifdef WIN32
// Win32 LevelDB doesn't use filedescriptors, and the ones used for
// accessing block files, don't count towards to fd_set size limit
// anyway.
#define MIN_CORE_FILEDESCRIPTORS 0
#else
#define MIN_CORE_FILEDESCRIPTORS 150
#endif
/** Used to pass flags to the Bind() function */
enum BindFlags {
BF_NONE = 0,
BF_EXPLICIT = (1U << 0),
BF_REPORT_ERROR = (1U << 1),
BF_WHITELIST = (1U << 2),
};
static const char* FEE_ESTIMATES_FILENAME = "fee_estimates.dat";
CClientUIInterface uiInterface;
//////////////////////////////////////////////////////////////////////////////
//
// Shutdown
//
//
// Thread management and startup/shutdown:
//
// The network-processing threads are all part of a thread group
// created by AppInit() or the Qt main() function.
//
// A clean exit happens when StartShutdown() or the SIGTERM
// signal handler sets fRequestShutdown, which triggers
// the DetectShutdownThread(), which interrupts the main thread group.
// DetectShutdownThread() then exits, which causes AppInit() to
// continue (it .joins the shutdown thread).
// Shutdown() is then
// called to clean up database connections, and stop other
// threads that should only be stopped after the main network-processing
// threads have exited.
//
// Note that if running -daemon the parent process returns from AppInit2
// before adding any threads to the threadGroup, so .join_all() returns
// immediately and the parent exits from main().
//
// Shutdown for Qt is very similar, only it uses a QTimer to detect
// fRequestShutdown getting set, and then does the normal Qt
// shutdown thing.
//
volatile bool fRequestShutdown = false;
void StartShutdown()
{
fRequestShutdown = true;
}
bool ShutdownRequested()
{
return fRequestShutdown || fRestartRequested;
}
class CCoinsViewErrorCatcher : public CCoinsViewBacked
{
public:
CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {}
bool GetCoins(const uint256& txid, CCoins& coins) const
{
try {
return CCoinsViewBacked::GetCoins(txid, coins);
} catch (const std::runtime_error& e) {
uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR);
LogPrintf("Error reading from database: %s\n", e.what());
// Starting the shutdown sequence and returning false to the caller would be
// interpreted as 'entry not found' (as opposed to unable to read data), and
// could lead to invalid interpration. Just exit immediately, as we can't
// continue anyway, and all writes should be atomic.
abort();
}
}
// Writes do not need similar protection, as failure to write is handled by the caller.
};
static CCoinsViewDB* pcoinsdbview = NULL;
static CCoinsViewErrorCatcher* pcoinscatcher = NULL;
static boost::scoped_ptr<ECCVerifyHandle> globalVerifyHandle;
static boost::thread_group threadGroup;
static CScheduler scheduler;
void Interrupt()
{
InterruptHTTPServer();
InterruptHTTPRPC();
InterruptRPC();
InterruptREST();
InterruptTorControl();
}
/** Preparing steps before shutting down or restarting the wallet */
void PrepareShutdown()
{
fRequestShutdown = true; // Needed when we shutdown the wallet
fRestartRequested = true; // Needed when we restart the wallet
LogPrintf("%s: In progress...\n", __func__);
static CCriticalSection cs_Shutdown;
TRY_LOCK(cs_Shutdown, lockShutdown);
if (!lockShutdown)
return;
/// Note: Shutdown() must be able to handle cases in which AppInit2() failed part of the way,
/// for example if the data directory was found to be locked.
/// Be sure that anything that writes files or flushes caches only does this if the respective
/// module was initialized.
RenameThread("abet-shutoff");
mempool.AddTransactionsUpdated(1);
StopHTTPRPC();
StopREST();
StopRPC();
StopHTTPServer();
#ifdef ENABLE_WALLET
if (pwalletMain)
bitdb.Flush(false);
GenerateBitcoins(false, NULL, 0);
#endif
StopNode();
DumpMasternodes();
DumpBudgets();
DumpMasternodePayments();
UnregisterNodeSignals(GetNodeSignals());
// After everything has been shut down, but before things get flushed, stop the
// CScheduler/checkqueue threadGroup
threadGroup.interrupt_all();
threadGroup.join_all();
if (fFeeEstimatesInitialized) {
boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION);
if (!est_fileout.IsNull())
mempool.WriteFeeEstimates(est_fileout);
else
LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string());
fFeeEstimatesInitialized = false;
}
{
LOCK(cs_main);
if (pcoinsTip != NULL) {
FlushStateToDisk();
//record that client took the proper shutdown procedure
pblocktree->WriteFlag("shutdown", true);
}
delete pcoinsTip;
pcoinsTip = NULL;
delete pcoinscatcher;
pcoinscatcher = NULL;
delete pcoinsdbview;
pcoinsdbview = NULL;
delete pblocktree;
pblocktree = NULL;
delete zerocoinDB;
zerocoinDB = NULL;
delete pSporkDB;
pSporkDB = NULL;
}
#ifdef ENABLE_WALLET
if (pwalletMain)
bitdb.Flush(true);
#endif
#if ENABLE_ZMQ
if (pzmqNotificationInterface) {
UnregisterValidationInterface(pzmqNotificationInterface);
delete pzmqNotificationInterface;
pzmqNotificationInterface = NULL;
}
#endif
#ifndef WIN32
try {
boost::filesystem::remove(GetPidFile());
} catch (const boost::filesystem::filesystem_error& e) {
LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what());
}
#endif
UnregisterAllValidationInterfaces();
}
/**
* Shutdown is split into 2 parts:
* Part 1: shut down everything but the main wallet instance (done in PrepareShutdown() )
* Part 2: delete wallet instance
*
* In case of a restart PrepareShutdown() was already called before, but this method here gets
* called implicitly when the parent object is deleted. In this case we have to skip the
* PrepareShutdown() part because it was already executed and just delete the wallet instance.
*/
void Shutdown()
{
// Shutdown part 1: prepare shutdown
if (!fRestartRequested) {
PrepareShutdown();
}
// Shutdown part 2: Stop TOR thread and delete wallet instance
StopTorControl();
// Shutdown witness thread if it's enabled
if (nLocalServices == NODE_BLOOM_LIGHT_ZC) {
lightWorker.StopLightZpivThread();
}
#ifdef ENABLE_WALLET
delete pwalletMain;
pwalletMain = NULL;
delete zwalletMain;
zwalletMain = NULL;
#endif
globalVerifyHandle.reset();
ECC_Stop();
LogPrintf("%s: done\n", __func__);
}
/**
* Signal handlers are very limited in what they are allowed to do, so:
*/
void HandleSIGTERM(int)
{
fRequestShutdown = true;
}
void HandleSIGHUP(int)
{
fReopenDebugLog = true;
}
bool static InitError(const std::string& str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR);
return false;
}
bool static InitWarning(const std::string& str)
{
uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING);
return true;
}
bool static Bind(const CService& addr, unsigned int flags)
{
if (!(flags & BF_EXPLICIT) && IsLimited(addr))
return false;
std::string strError;
if (!BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) {
if (flags & BF_REPORT_ERROR)
return InitError(strError);
return false;
}
return true;
}
void OnRPCStarted()
{
uiInterface.NotifyBlockTip.connect(RPCNotifyBlockChange);
}
void OnRPCStopped()
{
uiInterface.NotifyBlockTip.disconnect(RPCNotifyBlockChange);
//RPCNotifyBlockChange(0);
cvBlockChange.notify_all();
LogPrint("rpc", "RPC stopped.\n");
}
void OnRPCPreCommand(const CRPCCommand& cmd)
{
#ifdef ENABLE_WALLET
if (cmd.reqWallet && !pwalletMain)
throw JSONRPCError(RPC_METHOD_NOT_FOUND, "Method not found (disabled)");
#endif
// Observe safe mode
std::string strWarning = GetWarnings("rpc");
if (strWarning != "" && !GetBoolArg("-disablesafemode", false) &&
!cmd.okSafeMode)
throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning);
}
std::string HelpMessage(HelpMessageMode mode)
{
// When adding new options to the categories, please keep and ensure alphabetical ordering.
std::string strUsage = HelpMessageGroup(_("Options:"));
strUsage += HelpMessageOpt("-?", _("This help message"));
strUsage += HelpMessageOpt("-version", _("Print version and exit"));
strUsage += HelpMessageOpt("-alertnotify=<cmd>", _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)"));
strUsage += HelpMessageOpt("-alerts", strprintf(_("Receive and display P2P network alerts (default: %u)"), DEFAULT_ALERTS));
strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)"));
strUsage += HelpMessageOpt("-blocksizenotify=<cmd>", _("Execute command when the best block changes and its size is over (%s in cmd is replaced by block hash, %d with the block size)"));
strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), 500));
strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), "abet.conf"));
if (mode == HMM_BITCOIND) {
#if !defined(WIN32)
strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands"));
#endif
}
strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory"));
strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache));
strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file") + " " + _("on startup"));
strUsage += HelpMessageOpt("-maxreorg=<n>", strprintf(_("Set the Maximum reorg depth (default: %u)"), Params(CBaseChainParams::MAIN).MaxReorganizationDepth()));
strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS));
strUsage += HelpMessageOpt("-par=<n>", strprintf(_("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"), -(int)boost::thread::hardware_concurrency(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS));
#ifndef WIN32
strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), "abetd.pid"));
#endif
strUsage += HelpMessageOpt("-reindex", _("Rebuild block chain index from current blk000??.dat files") + " " + _("on startup"));
strUsage += HelpMessageOpt("-reindexaccumulators", _("Reindex the accumulator database") + " " + _("on startup"));
strUsage += HelpMessageOpt("-reindexmoneysupply", _("Reindex the ABET and zABET money supply statistics") + " " + _("on startup"));
strUsage += HelpMessageOpt("-resync", _("Delete blockchain folders and resync from scratch") + " " + _("on startup"));
#if !defined(WIN32)
strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)"));
#endif
strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), 0));
strUsage += HelpMessageOpt("-forcestart", _("Attempt to force blockchain corruption recovery") + " " + _("on startup"));
strUsage += HelpMessageGroup(_("Connection options:"));
strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open"));
strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), 100));
strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), 86400));
strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6"));
strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s)"));
strUsage += HelpMessageOpt("-discover", _("Discover own IP address (default: 1 when listening and no -externalip)"));
strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + _("(default: 1)"));
strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)"));
strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address"));
strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), 0));
strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect)"));
strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION));
strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), 125));
strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), 5000));
strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), 1000));
strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy"));
strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)"));
strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), 1));
strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS));
strUsage += HelpMessageOpt("-peerbloomfilterszc", strprintf(_("Support the zerocoin light node protocol (default: %u)"), DEFAULT_PEERBLOOMFILTERS_ZC));
strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), 8322, 51474));
strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy"));
strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), 1));
strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect"));
strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT));
strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL));
strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)"));
#ifdef USE_UPNP
#if USE_UPNP
strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening)"));
#else
strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0));
#endif
#endif
strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6"));
strUsage += HelpMessageOpt("-whitelist=<netmask>", _("Whitelist peers connecting from the given netmask or IP address. Can be specified multiple times.") +
" " + _("Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway"));
#ifdef ENABLE_WALLET
strUsage += HelpMessageGroup(_("Wallet options:"));
strUsage += HelpMessageOpt("-backuppath=<dir|file>", _("Specify custom backup path to add a copy of any wallet backup. If set as dir, every backup generates a timestamped file. If set as file, will rewrite to that file every backup."));
strUsage += HelpMessageOpt("-createwalletbackups=<n>", _("Number of automatic wallet backups (default: 10)"));
strUsage += HelpMessageOpt("-custombackupthreshold=<n>", strprintf(_("Number of custom location backups to retain (default: %d)"), DEFAULT_CUSTOMBACKUPTHRESHOLD));
strUsage += HelpMessageOpt("-disablewallet", _("Do not load the wallet and disable wallet RPC calls"));
strUsage += HelpMessageOpt("-keypool=<n>", strprintf(_("Set key pool size to <n> (default: %u)"), 100));
if (GetBoolArg("-help-debug", false))
strUsage += HelpMessageOpt("-mintxfee=<amt>", strprintf(_("Fees (in PIV/Kb) smaller than this are considered zero fee for transaction creation (default: %s)"),
FormatMoney(CWallet::minTxFee.GetFeePerK())));
strUsage += HelpMessageOpt("-paytxfee=<amt>", strprintf(_("Fee (in PIV/kB) to add to transactions you send (default: %s)"), FormatMoney(payTxFee.GetFeePerK())));
strUsage += HelpMessageOpt("-rescan", _("Rescan the block chain for missing wallet transactions") + " " + _("on startup"));
strUsage += HelpMessageOpt("-salvagewallet", _("Attempt to recover private keys from a corrupt wallet.dat") + " " + _("on startup"));
strUsage += HelpMessageOpt("-sendfreetransactions", strprintf(_("Send transactions as zero-fee transactions if possible (default: %u)"), 0));
strUsage += HelpMessageOpt("-spendzeroconfchange", strprintf(_("Spend unconfirmed change when sending transactions (default: %u)"), 1));
strUsage += HelpMessageOpt("-disablesystemnotifications", strprintf(_("Disable OS notifications for incoming transactions (default: %u)"), 0));
strUsage += HelpMessageOpt("-txconfirmtarget=<n>", strprintf(_("If paytxfee is not set, include enough fee so transactions begin confirmation on average within n blocks (default: %u)"), 1));
strUsage += HelpMessageOpt("-maxtxfee=<amt>", strprintf(_("Maximum total fees to use in a single wallet transaction, setting too low may abort large transactions (default: %s)"),
FormatMoney(maxTxFee)));
strUsage += HelpMessageOpt("-upgradewallet", _("Upgrade wallet to latest format") + " " + _("on startup"));
strUsage += HelpMessageOpt("-wallet=<file>", _("Specify wallet file (within data directory)") + " " + strprintf(_("(default: %s)"), "wallet.dat"));
strUsage += HelpMessageOpt("-walletnotify=<cmd>", _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)"));
if (mode == HMM_BITCOIN_QT)
strUsage += HelpMessageOpt("-windowtitle=<name>", _("Wallet window title"));
strUsage += HelpMessageOpt("-zapwallettxes=<mode>", _("Delete all wallet transactions and only recover those parts of the blockchain through -rescan on startup") +
" " + _("(1 = keep tx meta data e.g. account owner and payment request information, 2 = drop tx meta data)"));
#endif
#if ENABLE_ZMQ
strUsage += HelpMessageGroup(_("ZeroMQ notification options:"));
strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>"));
strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>"));
strUsage += HelpMessageOpt("-zmqpubhashtxlock=<address>", _("Enable publish hash transaction (locked via SwiftX) in <address>"));
strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>"));
strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>"));
strUsage += HelpMessageOpt("-zmqpubrawtxlock=<address>", _("Enable publish raw transaction (locked via SwiftX) in <address>"));
#endif
strUsage += HelpMessageGroup(_("Debugging/Testing options:"));
strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string"));
if (GetBoolArg("-help-debug", false)) {
strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks()));
strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks()));
strUsage += HelpMessageOpt("-checkpoints", strprintf(_("Only accept block chain matching built-in checkpoints (default: %u)"), 1));
strUsage += HelpMessageOpt("-dblogsize=<n>", strprintf(_("Flush database activity from memory pool to disk log every <n> megabytes (default: %u)"), 100));
strUsage += HelpMessageOpt("-disablesafemode", strprintf(_("Disable safemode, override a real safe mode event (default: %u)"), 0));
strUsage += HelpMessageOpt("-testsafemode", strprintf(_("Force safe mode (default: %u)"), 0));
strUsage += HelpMessageOpt("-dropmessagestest=<n>", _("Randomly drop 1 of every <n> network messages"));
strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", _("Randomly fuzz 1 of every <n> network messages"));
strUsage += HelpMessageOpt("-flushwallet", strprintf(_("Run a thread to flush wallet periodically (default: %u)"), 1));
strUsage += HelpMessageOpt("-maxreorg", strprintf(_("Use a custom max chain reorganization depth (default: %u)"), 100));
strUsage += HelpMessageOpt("-stopafterblockimport", strprintf(_("Stop running after importing blocks from disk (default: %u)"), 0));
strUsage += HelpMessageOpt("-sporkkey=<privkey>", _("Enable spork administration functionality with the appropriate private key."));
}
std::string debugCategories = "addrman, alert, bench, coindb, db, lock, rand, rpc, selectcoins, tor, mempool, net, proxy, http, libevent, abet, (obfuscation, swiftx, masternode, mnpayments, mnbudget, zero, precompute, staking)"; // Don't translate these and qt below
if (mode == HMM_BITCOIN_QT)
debugCategories += ", qt";
strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " +
_("If <category> is not supplied, output all debugging information.") + _("<category> can be:") + " " + debugCategories + ".");
if (GetBoolArg("-help-debug", false))
strUsage += HelpMessageOpt("-nodebug", "Turn off debugging messages, same as -debug=0");
#ifdef ENABLE_WALLET
strUsage += HelpMessageOpt("-gen", strprintf(_("Generate coins (default: %u)"), 0));
strUsage += HelpMessageOpt("-genproclimit=<n>", strprintf(_("Set the number of threads for coin generation if enabled (-1 = all cores, default: %d)"), 1));
#endif
strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)"));
strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), 0));
strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), 1));
if (GetBoolArg("-help-debug", false)) {
strUsage += HelpMessageOpt("-limitfreerelay=<n>", strprintf(_("Continuously rate-limit free transactions to <n>*1000 bytes per minute (default:%u)"), 15));
strUsage += HelpMessageOpt("-relaypriority", strprintf(_("Require high priority for relaying free or low-fee transactions (default:%u)"), 1));
strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf(_("Limit size of signature cache to <n> entries (default: %u)"), 50000));
}
strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE));
strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in PIV/Kb) smaller than this are considered zero fee for relaying (default: %s)"), FormatMoney(::minRelayTxFee.GetFeePerK())));
strUsage += HelpMessageOpt("-printtoconsole", strprintf(_("Send trace/debug info to console instead of debug.log file (default: %u)"), 0));
if (GetBoolArg("-help-debug", false)) {
strUsage += HelpMessageOpt("-printpriority", strprintf(_("Log transaction priority and fee per kB when mining blocks (default: %u)"), 0));
strUsage += HelpMessageOpt("-privdb", strprintf(_("Sets the DB_PRIVATE flag in the wallet db environment (default: %u)"), 1));
strUsage += HelpMessageOpt("-regtest", _("Enter regression test mode, which uses a special chain in which blocks can be solved instantly.") + " " +
_("This is intended for regression testing tools and app development.") + " " +
_("In this mode -genproclimit controls how many blocks are generated immediately."));
}
strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)"));
strUsage += HelpMessageOpt("-testnet", _("Use the test network"));
strUsage += HelpMessageOpt("-litemode=<n>", strprintf(_("Disable all ABET specific functionality (Masternodes, Zerocoin, SwiftX, Budgeting) (0-1, default: %u)"), 0));
#ifdef ENABLE_WALLET
strUsage += HelpMessageGroup(_("Staking options:"));
strUsage += HelpMessageOpt("-staking=<n>", strprintf(_("Enable staking functionality (0-1, default: %u)"), 1));
strUsage += HelpMessageOpt("-pivstake=<n>", strprintf(_("Enable or disable staking functionality for ABET inputs (0-1, default: %u)"), 1));
strUsage += HelpMessageOpt("-zpivstake=<n>", strprintf(_("Enable or disable staking functionality for zABET inputs (0-1, default: %u)"), 1));
strUsage += HelpMessageOpt("-reservebalance=<amt>", _("Keep the specified amount available for spending at all times (default: 0)"));
if (GetBoolArg("-help-debug", false)) {
strUsage += HelpMessageOpt("-printstakemodifier", _("Display the stake modifier calculations in the debug.log file."));
strUsage += HelpMessageOpt("-printcoinstake", _("Display verbose coin stake messages in the debug.log file."));
}
#endif
strUsage += HelpMessageGroup(_("Masternode options:"));
strUsage += HelpMessageOpt("-masternode=<n>", strprintf(_("Enable the client to act as a masternode (0-1, default: %u)"), 0));
strUsage += HelpMessageOpt("-mnconf=<file>", strprintf(_("Specify masternode configuration file (default: %s)"), "masternode.conf"));
strUsage += HelpMessageOpt("-mnconflock=<n>", strprintf(_("Lock masternodes from masternode configuration file (default: %u)"), 1));
strUsage += HelpMessageOpt("-masternodeprivkey=<n>", _("Set the masternode private key"));
strUsage += HelpMessageOpt("-masternodeaddr=<n>", strprintf(_("Set external address:port to get to this masternode (example: %s)"), "128.127.106.235:8322"));
strUsage += HelpMessageOpt("-budgetvotemode=<mode>", _("Change automatic finalized budget voting behavior. mode=auto: Vote for only exact finalized budget match to my generated budget. (string, default: auto)"));
strUsage += HelpMessageGroup(_("Zerocoin options:"));
#ifdef ENABLE_WALLET
strUsage += HelpMessageOpt("-enablezeromint=<n>", strprintf(_("Enable automatic Zerocoin minting (0-1, default: %u)"), 1));
strUsage += HelpMessageOpt("-enableautoconvertaddress=<n>", strprintf(_("Enable automatic Zerocoin minting from specific addresses (0-1, default: %u)"), DEFAULT_AUTOCONVERTADDRESS));
strUsage += HelpMessageOpt("-zeromintpercentage=<n>", strprintf(_("Percentage of automatically minted Zerocoin (1-100, default: %u)"), 10));
strUsage += HelpMessageOpt("-preferredDenom=<n>", strprintf(_("Preferred Denomination for automatically minted Zerocoin (1/5/10/50/100/500/1000/5000), 0 for no preference. default: %u)"), 0));
strUsage += HelpMessageOpt("-backupzpiv=<n>", strprintf(_("Enable automatic wallet backups triggered after each zABET minting (0-1, default: %u)"), 1));
strUsage += HelpMessageOpt("-precompute=<n>", strprintf(_("Enable precomputation of zABET spends and stakes (0-1, default %u)"), 1));
strUsage += HelpMessageOpt("-precomputecachelength=<n>", strprintf(_("Set the number of included blocks to precompute per cycle. (minimum: %d) (maximum: %d) (default: %d)"), MIN_PRECOMPUTE_LENGTH, MAX_PRECOMPUTE_LENGTH, DEFAULT_PRECOMPUTE_LENGTH));
strUsage += HelpMessageOpt("-zpivbackuppath=<dir|file>", _("Specify custom backup path to add a copy of any automatic zABET backup. If set as dir, every backup generates a timestamped file. If set as file, will rewrite to that file every backup. If backuppath is set as well, 4 backups will happen"));
#endif // ENABLE_WALLET
strUsage += HelpMessageOpt("-reindexzerocoin=<n>", strprintf(_("Delete all zerocoin spends and mints that have been recorded to the blockchain database and reindex them (0-1, default: %u)"), 0));
strUsage += HelpMessageGroup(_("SwiftX options:"));
strUsage += HelpMessageOpt("-enableswifttx=<n>", strprintf(_("Enable SwiftX, show confirmations for locked transactions (bool, default: %s)"), "true"));
strUsage += HelpMessageOpt("-swifttxdepth=<n>", strprintf(_("Show N confirmations for a successfully locked transaction (0-9999, default: %u)"), nSwiftTXDepth));
strUsage += HelpMessageGroup(_("Node relay options:"));
strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), 1));
strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY));
if (GetBoolArg("-help-debug", false)) {
strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios");
}
strUsage += HelpMessageGroup(_("Block creation options:"));
strUsage += HelpMessageOpt("-blockminsize=<n>", strprintf(_("Set minimum block size in bytes (default: %u)"), 0));
strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE));
strUsage += HelpMessageOpt("-blockprioritysize=<n>", strprintf(_("Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), DEFAULT_BLOCK_PRIORITY_SIZE));
strUsage += HelpMessageGroup(_("RPC server options:"));
strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands"));
strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), 0));
strUsage += HelpMessageOpt("-rpcbind=<addr>", _("Bind to given address to listen for JSON-RPC connections. Use [host]:port notation for IPv6. This option can be specified multiple times (default: bind to all interfaces)"));
strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)"));
strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections"));
strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), 8322, 51475));
strUsage += HelpMessageOpt("-rpcallowip=<ip>", _("Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"));
strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS));
if (GetBoolArg("-help-debug", false)) {
strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE));
strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT));
}
strUsage += HelpMessageOpt("-blockspamfilter=<n>", strprintf(_("Use block spam filter (default: %u)"), DEFAULT_BLOCK_SPAM_FILTER));
strUsage += HelpMessageOpt("-blockspamfiltermaxsize=<n>", strprintf(_("Maximum size of the list of indexes in the block spam filter (default: %u)"), DEFAULT_BLOCK_SPAM_FILTER_MAX_SIZE));
strUsage += HelpMessageOpt("-blockspamfiltermaxavg=<n>", strprintf(_("Maximum average size of an index occurrence in the block spam filter (default: %u)"), DEFAULT_BLOCK_SPAM_FILTER_MAX_AVG));
return strUsage;
}
std::string LicenseInfo()
{
return FormatParagraph(strprintf(_("Copyright (C) 2009-%i The Bitcoin Core Developers"), COPYRIGHT_YEAR)) + "\n" +
"\n" +
FormatParagraph(strprintf(_("Copyright (C) 2014-%i The Dash Core Developers"), COPYRIGHT_YEAR)) + "\n" +
"\n" +
FormatParagraph(strprintf(_("Copyright (C) 2015-%i The ABET Core Developers"), COPYRIGHT_YEAR)) + "\n" +
"\n" +
FormatParagraph(_("This is experimental software.")) + "\n" +
"\n" +
FormatParagraph(_("Distributed under the MIT software license, see the accompanying file COPYING or <http://www.opensource.org/licenses/mit-license.php>.")) + "\n" +
"\n" +
FormatParagraph(_("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard.")) +
"\n";
}
static void BlockNotifyCallback(const uint256& hashNewTip)
{
std::string strCmd = GetArg("-blocknotify", "");
boost::replace_all(strCmd, "%s", hashNewTip.GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
static void BlockSizeNotifyCallback(int size, const uint256& hashNewTip)
{
std::string strCmd = GetArg("-blocksizenotify", "");
boost::replace_all(strCmd, "%s", hashNewTip.GetHex());
boost::replace_all(strCmd, "%d", std::to_string(size));
boost::thread t(runCommand, strCmd); // thread runs free
}
struct CImportingNow {
CImportingNow()
{
assert(fImporting == false);
fImporting = true;
}
~CImportingNow()
{
assert(fImporting == true);
fImporting = false;
}
};
void ThreadImport(std::vector<boost::filesystem::path> vImportFiles)
{
RenameThread("abet-loadblk");
// -reindex
if (fReindex) {
CImportingNow imp;
int nFile = 0;
while (true) {
CDiskBlockPos pos(nFile, 0);
if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk")))
break; // No block files left to reindex
FILE* file = OpenBlockFile(pos, true);
if (!file)
break; // This error is logged in OpenBlockFile
LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile);
LoadExternalBlockFile(file, &pos);
nFile++;
}
pblocktree->WriteReindexing(false);
fReindex = false;
LogPrintf("Reindexing finished\n");
// To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked):
InitBlockIndex();
}
// hardcoded $DATADIR/bootstrap.dat
boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat";
if (boost::filesystem::exists(pathBootstrap)) {
FILE* file = fopen(pathBootstrap.string().c_str(), "rb");
if (file) {
CImportingNow imp;
boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old";
LogPrintf("Importing bootstrap.dat...\n");
LoadExternalBlockFile(file);
RenameOver(pathBootstrap, pathBootstrapOld);
} else {
LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string());
}
}
// -loadblock=
for (boost::filesystem::path& path : vImportFiles) {
FILE* file = fopen(path.string().c_str(), "rb");
if (file) {
CImportingNow imp;
LogPrintf("Importing blocks file %s...\n", path.string());
LoadExternalBlockFile(file);
} else {
LogPrintf("Warning: Could not open blocks file %s\n", path.string());
}
}
if (GetBoolArg("-stopafterblockimport", false)) {
LogPrintf("Stopping after block import\n");
StartShutdown();
}
}
/** Sanity checks
* Ensure that ABET is running in a usable environment with all
* necessary library support.
*/
bool InitSanityCheck(void)
{
if (!ECC_InitSanityCheck()) {
InitError("Elliptic curve cryptography sanity check failure. Aborting.");
return false;
}
if (!glibc_sanity_test() || !glibcxx_sanity_test())
return false;
return true;
}
bool AppInitServers()
{
RPCServer::OnStarted(&OnRPCStarted);
RPCServer::OnStopped(&OnRPCStopped);
RPCServer::OnPreCommand(&OnRPCPreCommand);
if (!InitHTTPServer())
return false;
if (!StartRPC())
return false;
if (!StartHTTPRPC())
return false;
if (GetBoolArg("-rest", false) && !StartREST())
return false;
if (!StartHTTPServer())
return false;
return true;
}
/** Initialize abet.
* @pre Parameters should be parsed and config file should be read.
*/
bool AppInit2()
{
// ********************************************************* Step 1: setup
#ifdef _MSC_VER
// Turn off Microsoft heap dump noise
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
_CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0));
#endif
#if _MSC_VER >= 1400
// Disable confusing "helpful" text message on abort, Ctrl-C
_set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
#endif
#ifdef WIN32
// Enable Data Execution Prevention (DEP)
// Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008
// A failure is non-critical and needs no further attention!
#ifndef PROCESS_DEP_ENABLE
// We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7),
// which is not correct. Can be removed, when GCCs winbase.h is fixed!
#define PROCESS_DEP_ENABLE 0x00000001
#endif
typedef BOOL(WINAPI * PSETPROCDEPPOL)(DWORD);
PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy");
if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE);
#endif
if (!SetupNetworking())
return InitError("Error: Initializing networking failed");
#ifndef WIN32
if (GetBoolArg("-sysperms", false)) {
#ifdef ENABLE_WALLET
if (!GetBoolArg("-disablewallet", false))
return InitError("Error: -sysperms is not allowed in combination with enabled wallet functionality");
#endif
} else {
umask(077);
}
// Clean shutdown on SIGTERM
struct sigaction sa;
sa.sa_handler = HandleSIGTERM;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sigaction(SIGTERM, &sa, NULL);
sigaction(SIGINT, &sa, NULL);
// Reopen debug.log on SIGHUP
struct sigaction sa_hup;
sa_hup.sa_handler = HandleSIGHUP;
sigemptyset(&sa_hup.sa_mask);
sa_hup.sa_flags = 0;
sigaction(SIGHUP, &sa_hup, NULL);
// Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly
signal(SIGPIPE, SIG_IGN);
#endif
// ********************************************************* Step 2: parameter interactions
// Set this early so that parameter interactions go to console
fPrintToConsole = GetBoolArg("-printtoconsole", false);
fLogTimestamps = GetBoolArg("-logtimestamps", true);
fLogIPs = GetBoolArg("-logips", false);
if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
// when specifying an explicit binding address, you want to listen on it
// even when -connect or -proxy is specified
if (SoftSetBoolArg("-listen", true))
LogPrintf("AppInit2 : parameter interaction: -bind or -whitebind set -> setting -listen=1\n");
}
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
// when only connecting to trusted nodes, do not seed via DNS, or listen by default
if (SoftSetBoolArg("-dnsseed", false))
LogPrintf("AppInit2 : parameter interaction: -connect set -> setting -dnsseed=0\n");
if (SoftSetBoolArg("-listen", false))
LogPrintf("AppInit2 : parameter interaction: -connect set -> setting -listen=0\n");
}
if (mapArgs.count("-proxy")) {
// to protect privacy, do not listen by default if a default proxy server is specified
if (SoftSetBoolArg("-listen", false))
LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__);
// to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1
// to listen locally, so don't rely on this happening through -listen below.
if (SoftSetBoolArg("-upnp", false))
LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__);
// to protect privacy, do not discover addresses by default
if (SoftSetBoolArg("-discover", false))
LogPrintf("AppInit2 : parameter interaction: -proxy set -> setting -discover=0\n");
}
if (!GetBoolArg("-listen", true)) {
// do not map ports or try to retrieve public IP when not listening (pointless)
if (SoftSetBoolArg("-upnp", false))
LogPrintf("AppInit2 : parameter interaction: -listen=0 -> setting -upnp=0\n");
if (SoftSetBoolArg("-discover", false))
LogPrintf("AppInit2 : parameter interaction: -listen=0 -> setting -discover=0\n");
if (SoftSetBoolArg("-listenonion", false))
LogPrintf("AppInit2 : parameter interaction: -listen=0 -> setting -listenonion=0\n");
}
if (mapArgs.count("-externalip")) {
// if an explicit public IP is specified, do not try to find others
if (SoftSetBoolArg("-discover", false))
LogPrintf("AppInit2 : parameter interaction: -externalip set -> setting -discover=0\n");
}
if (GetBoolArg("-salvagewallet", false)) {
// Rewrite just private keys: rescan to find transactions
if (SoftSetBoolArg("-rescan", true))
LogPrintf("AppInit2 : parameter interaction: -salvagewallet=1 -> setting -rescan=1\n");
}
// -zapwallettx implies a rescan
if (GetBoolArg("-zapwallettxes", false)) {
if (SoftSetBoolArg("-rescan", true))
LogPrintf("AppInit2 : parameter interaction: -zapwallettxes=<mode> -> setting -rescan=1\n");
}
if (!GetBoolArg("-enableswifttx", fEnableSwiftTX)) {
if (SoftSetArg("-swifttxdepth", "0"))
LogPrintf("AppInit2 : parameter interaction: -enableswifttx=false -> setting -nSwiftTXDepth=0\n");
}
if (mapArgs.count("-reservebalance")) {
if (!ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) {
InitError(_("Invalid amount for -reservebalance=<amount>"));
return false;
}
}
// Make sure enough file descriptors are available
int nBind = std::max((int)mapArgs.count("-bind") + (int)mapArgs.count("-whitebind"), 1);
nMaxConnections = GetArg("-maxconnections", 125);
nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0);
int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS);
if (nFD < MIN_CORE_FILEDESCRIPTORS)
return InitError(_("Not enough file descriptors available."));
if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections)
nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS;
// ********************************************************* Step 3: parameter-to-internal-flags
fDebug = !mapMultiArgs["-debug"].empty();
// Special-case: if -debug=0/-nodebug is set, turn off debugging messages
const std::vector<std::string>& categories = mapMultiArgs["-debug"];
if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), std::string("0")) != categories.end())
fDebug = false;
// Check for -debugnet
if (GetBoolArg("-debugnet", false))
InitWarning(_("Warning: Unsupported argument -debugnet ignored, use -debug=net."));
// Check for -socks - as this is a privacy risk to continue, exit here
if (mapArgs.count("-socks"))
return InitError(_("Error: Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported."));
// Check for -tor - as this is a privacy risk to continue, exit here
if (GetBoolArg("-tor", false))
return InitError(_("Error: Unsupported argument -tor found, use -onion."));
// Check level must be 4 for zerocoin checks
if (mapArgs.count("-checklevel"))
return InitError(_("Error: Unsupported argument -checklevel found. Checklevel must be level 4."));
if (GetBoolArg("-benchmark", false))
InitWarning(_("Warning: Unsupported argument -benchmark ignored, use -debug=bench."));
// Checkmempool and checkblockindex default to true in regtest mode
mempool.setSanityCheck(GetBoolArg("-checkmempool", Params().DefaultConsistencyChecks()));
fCheckBlockIndex = GetBoolArg("-checkblockindex", Params().DefaultConsistencyChecks());
Checkpoints::fEnabled = GetBoolArg("-checkpoints", true);
// -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency
nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS);
if (nScriptCheckThreads <= 0)
nScriptCheckThreads += boost::thread::hardware_concurrency();
if (nScriptCheckThreads <= 1)
nScriptCheckThreads = 0;
else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS)
nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS;
fServer = GetBoolArg("-server", false);
setvbuf(stdout, NULL, _IOLBF, 0); /// ***TODO*** do we still need this after -printtoconsole is gone?
// Staking needs a CWallet instance, so make sure wallet is enabled
#ifdef ENABLE_WALLET
bool fDisableWallet = GetBoolArg("-disablewallet", false);
if (fDisableWallet) {
#endif
if (SoftSetBoolArg("-staking", false))
LogPrintf("AppInit2 : parameter interaction: wallet functionality not enabled -> setting -staking=0\n");
#ifdef ENABLE_WALLET
}
#endif
nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT);
if (nConnectTimeout <= 0)
nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
// Fee-per-kilobyte amount considered the same as "free"
// If you are mining, be careful setting this:
// if you set it to zero then
// a transaction spammer can cheaply fill blocks using
// 1-satoshi-fee transactions. It should be set above the real
// cost to you of processing a transaction.
if (mapArgs.count("-minrelaytxfee")) {
CAmount n = 0;
if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0)
::minRelayTxFee = CFeeRate(n);
else
return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"]));
}
#ifdef ENABLE_WALLET
if (mapArgs.count("-mintxfee")) {
CAmount n = 0;
if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0)
CWallet::minTxFee = CFeeRate(n);
else
return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"]));
}
if (mapArgs.count("-paytxfee")) {
CAmount nFeePerK = 0;
if (!ParseMoney(mapArgs["-paytxfee"], nFeePerK))
return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"]));
if (nFeePerK > nHighTransactionFeeWarning)
InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction."));
payTxFee = CFeeRate(nFeePerK, 1000);
if (payTxFee < ::minRelayTxFee) {
return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"),
mapArgs["-paytxfee"], ::minRelayTxFee.ToString()));
}
}
if (mapArgs.count("-maxtxfee")) {
CAmount nMaxFee = 0;
if (!ParseMoney(mapArgs["-maxtxfee"], nMaxFee))
return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s'"), mapArgs["-maxtxfee"]));
if (nMaxFee > nHighTransactionMaxFeeWarning)
InitWarning(_("Warning: -maxtxfee is set very high! Fees this large could be paid on a single transaction."));
maxTxFee = nMaxFee;
if (CFeeRate(maxTxFee, 1000) < ::minRelayTxFee) {
return InitError(strprintf(_("Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay fee of %s to prevent stuck transactions)"),
mapArgs["-maxtxfee"], ::minRelayTxFee.ToString()));
}
}
nTxConfirmTarget = GetArg("-txconfirmtarget", 1);
bSpendZeroConfChange = GetBoolArg("-spendzeroconfchange", false);
bdisableSystemnotifications = GetBoolArg("-disablesystemnotifications", false);
fSendFreeTransactions = GetBoolArg("-sendfreetransactions", false);
fEnableAutoConvert = GetBoolArg("-enableautoconvertaddress", DEFAULT_AUTOCONVERTADDRESS);
std::string strWalletFile = GetArg("-wallet", "wallet.dat");
#endif // ENABLE_WALLET
fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", true) != 0;
nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes);
fAlerts = GetBoolArg("-alerts", DEFAULT_ALERTS);
if (GetBoolArg("-peerbloomfilterszc", DEFAULT_PEERBLOOMFILTERS_ZC))
nLocalServices |= NODE_BLOOM_LIGHT_ZC;
if (nLocalServices != NODE_BLOOM_LIGHT_ZC) {
if (GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS))
nLocalServices |= NODE_BLOOM;
}
nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE);
// ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log
// Initialize elliptic curve code
ECC_Start();
globalVerifyHandle.reset(new ECCVerifyHandle());
// Sanity check
if (!InitSanityCheck())
return InitError(_("Initialization sanity check failed. ABET Core is shutting down."));
std::string strDataDir = GetDataDir().string();
#ifdef ENABLE_WALLET
// Wallet file must be a plain filename without a directory
if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile))
return InitError(strprintf(_("Wallet %s resides outside data directory %s"), strWalletFile, strDataDir));
#endif
// Make sure only a single ABET process is using the data directory.
boost::filesystem::path pathLockFile = GetDataDir() / ".lock";
FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist.
if (file) fclose(file);
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
// Wait maximum 10 seconds if an old wallet is still running. Avoids lockup during restart
if (!lock.timed_lock(boost::get_system_time() + boost::posix_time::seconds(10)))
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. ABET Core is probably already running."), strDataDir));
#ifndef WIN32
CreatePidFile(GetPidFile(), getpid());
#endif
if (GetBoolArg("-shrinkdebugfile", !fDebug))
ShrinkDebugFile();
LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
LogPrintf("Abet version %s (%s)\n", FormatFullVersion(), CLIENT_DATE);
LogPrintf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
#ifdef ENABLE_WALLET
LogPrintf("Using BerkeleyDB version %s\n", DbEnv::version(0, 0, 0));
#endif
if (!fLogTimestamps)
LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()));
LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
LogPrintf("Using data directory %s\n", strDataDir);
LogPrintf("Using config file %s\n", GetConfigFile().string());
LogPrintf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD);
std::ostringstream strErrors;
LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads);
if (nScriptCheckThreads) {
for (int i = 0; i < nScriptCheckThreads - 1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
}
if (mapArgs.count("-sporkkey")) // spork priv key
{
if (!sporkManager.SetPrivKey(GetArg("-sporkkey", "")))
return InitError(_("Unable to sign spork message, wrong key?"));
}
// Start the lightweight task scheduler thread
CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler);
threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop));
/* Start the RPC server already. It will be started in "warmup" mode
* and not really process calls already (but it will signify connections
* that the server is there and will be ready later). Warmup mode will
* be disabled when initialisation is finished.
*/
if (fServer) {
uiInterface.InitMessage.connect(SetRPCWarmupStatus);
if (!AppInitServers())
return InitError(_("Unable to start HTTP server. See debug log for details."));
}
int64_t nStart;
// ********************************************************* Step 5: Backup wallet and verify wallet database integrity
#ifdef ENABLE_WALLET
if (!fDisableWallet) {
boost::filesystem::path backupDir = GetDataDir() / "backups";
if (!boost::filesystem::exists(backupDir)) {
// Always create backup folder to not confuse the operating system's file browser
boost::filesystem::create_directories(backupDir);
}
nWalletBackups = GetArg("-createwalletbackups", 10);
nWalletBackups = std::max(0, std::min(10, nWalletBackups));
if (nWalletBackups > 0) {
if (boost::filesystem::exists(backupDir)) {
// Create backup of the wallet
std::string dateTimeStr = DateTimeStrFormat(".%Y-%m-%d-%H-%M", GetTime());
std::string backupPathStr = backupDir.string();
backupPathStr += "/" + strWalletFile;
std::string sourcePathStr = GetDataDir().string();
sourcePathStr += "/" + strWalletFile;
boost::filesystem::path sourceFile = sourcePathStr;
boost::filesystem::path backupFile = backupPathStr + dateTimeStr;
sourceFile.make_preferred();
backupFile.make_preferred();
if (boost::filesystem::exists(sourceFile)) {
#if BOOST_VERSION >= 105800
try {
boost::filesystem::copy_file(sourceFile, backupFile);
LogPrintf("Creating backup of %s -> %s\n", sourceFile, backupFile);
} catch (boost::filesystem::filesystem_error& error) {
LogPrintf("Failed to create backup %s\n", error.what());
}
#else
std::ifstream src(sourceFile.string(), std::ios::binary);
std::ofstream dst(backupFile.string(), std::ios::binary);
dst << src.rdbuf();
#endif
}
// Keep only the last 10 backups, including the new one of course
typedef std::multimap<std::time_t, boost::filesystem::path> folder_set_t;
folder_set_t folder_set;
boost::filesystem::directory_iterator end_iter;
boost::filesystem::path backupFolder = backupDir.string();
backupFolder.make_preferred();
// Build map of backup files for current(!) wallet sorted by last write time
boost::filesystem::path currentFile;
for (boost::filesystem::directory_iterator dir_iter(backupFolder); dir_iter != end_iter; ++dir_iter) {
// Only check regular files
if (boost::filesystem::is_regular_file(dir_iter->status())) {
currentFile = dir_iter->path().filename();
// Only add the backups for the current wallet, e.g. wallet.dat.*
if (dir_iter->path().stem().string() == strWalletFile) {
folder_set.insert(folder_set_t::value_type(boost::filesystem::last_write_time(dir_iter->path()), *dir_iter));
}
}
}
// Loop backward through backup files and keep the N newest ones (1 <= N <= 10)
int counter = 0;
BOOST_REVERSE_FOREACH (PAIRTYPE(const std::time_t, boost::filesystem::path) file, folder_set) {
counter++;
if (counter > nWalletBackups) {
// More than nWalletBackups backups: delete oldest one(s)
try {
boost::filesystem::remove(file.second);
LogPrintf("Old backup deleted: %s\n", file.second);
} catch (boost::filesystem::filesystem_error& error) {
LogPrintf("Failed to delete backup %s\n", error.what());
}
}
}
}
}
if (GetBoolArg("-resync", false)) {
uiInterface.InitMessage(_("Preparing for resync..."));
// Delete the local blockchain folders to force a resync from scratch to get a consitent blockchain-state
boost::filesystem::path blocksDir = GetDataDir() / "blocks";
boost::filesystem::path chainstateDir = GetDataDir() / "chainstate";
boost::filesystem::path sporksDir = GetDataDir() / "sporks";
boost::filesystem::path zerocoinDir = GetDataDir() / "zerocoin";
LogPrintf("Deleting blockchain folders blocks, chainstate, sporks and zerocoin\n");
// We delete in 4 individual steps in case one of the folder is missing already
try {
if (boost::filesystem::exists(blocksDir)){
boost::filesystem::remove_all(blocksDir);
LogPrintf("-resync: folder deleted: %s\n", blocksDir.string().c_str());
}
if (boost::filesystem::exists(chainstateDir)){
boost::filesystem::remove_all(chainstateDir);
LogPrintf("-resync: folder deleted: %s\n", chainstateDir.string().c_str());
}
if (boost::filesystem::exists(sporksDir)){
boost::filesystem::remove_all(sporksDir);
LogPrintf("-resync: folder deleted: %s\n", sporksDir.string().c_str());
}
if (boost::filesystem::exists(zerocoinDir)){
boost::filesystem::remove_all(zerocoinDir);
LogPrintf("-resync: folder deleted: %s\n", zerocoinDir.string().c_str());
}
} catch (boost::filesystem::filesystem_error& error) {
LogPrintf("Failed to delete blockchain folders %s\n", error.what());
}
}
LogPrintf("Using wallet %s\n", strWalletFile);
uiInterface.InitMessage(_("Verifying wallet..."));
if (!bitdb.Open(GetDataDir())) {
// try moving the database env out of the way
boost::filesystem::path pathDatabase = GetDataDir() / "database";
boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%d.bak", GetTime());
try {
boost::filesystem::rename(pathDatabase, pathDatabaseBak);
LogPrintf("Moved old %s to %s. Retrying.\n", pathDatabase.string(), pathDatabaseBak.string());
} catch (boost::filesystem::filesystem_error& error) {
// failure is ok (well, not really, but it's not worse than what we started with)
}
// try again
if (!bitdb.Open(GetDataDir())) {
// if it still fails, it probably means we can't even create the database env
std::string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir);
return InitError(msg);
}
}
if (GetBoolArg("-salvagewallet", false)) {
// Recover readable keypairs:
if (!CWalletDB::Recover(bitdb, strWalletFile, true))
return false;
}
if (boost::filesystem::exists(GetDataDir() / strWalletFile)) {
CDBEnv::VerifyResult r = bitdb.Verify(strWalletFile, CWalletDB::Recover);
if (r == CDBEnv::RECOVER_OK) {
std::string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!"
" Original wallet.dat saved as wallet.{timestamp}.bak in %s; if"
" your balance or transactions are incorrect you should"
" restore from a backup."),
strDataDir);
InitWarning(msg);
}
if (r == CDBEnv::RECOVER_FAIL)
return InitError(_("wallet.dat corrupt, salvage failed"));
}
} // (!fDisableWallet)
#endif // ENABLE_WALLET
// ********************************************************* Step 6: network initialization
RegisterNodeSignals(GetNodeSignals());
// sanitize comments per BIP-0014, format user agent and check total size
std::vector<std::string> uacomments;
for (const std::string& cmt : mapMultiArgs["-uacomment"]) {
if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT))
return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt));
uacomments.push_back(cmt);
}
// format user agent, check total size
strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments);
if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) {
return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."),
strSubVersion.size(), MAX_SUBVERSION_LENGTH));
}
if (mapArgs.count("-onlynet")) {
std::set<enum Network> nets;
for (std::string snet : mapMultiArgs["-onlynet"]) {
enum Network net = ParseNetwork(snet);
if (net == NET_UNROUTABLE)
return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet));
nets.insert(net);
}
for (int n = 0; n < NET_MAX; n++) {
enum Network net = (enum Network)n;
if (!nets.count(net))
SetLimited(net);
}
}
if (mapArgs.count("-whitelist")) {
for (const std::string& net : mapMultiArgs["-whitelist"]) {
CSubNet subnet(net);
if (!subnet.IsValid())
return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net));
CNode::AddWhitelistedRange(subnet);
}
}
// Check for host lookup allowed before parsing any network related parameters
fNameLookup = GetBoolArg("-dns", DEFAULT_NAME_LOOKUP);
bool proxyRandomize = GetBoolArg("-proxyrandomize", true);
// -proxy sets a proxy for all outgoing network traffic
// -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default
std::string proxyArg = GetArg("-proxy", "");
SetLimited(NET_TOR);
if (proxyArg != "" && proxyArg != "0") {
CService proxyAddr;
if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) {
return InitError(strprintf(_("Lookup(): Invalid -proxy address or hostname: '%s'"), proxyArg));
}
proxyType addrProxy = proxyType(proxyAddr, proxyRandomize);
if (!addrProxy.IsValid())
return InitError(strprintf(_("isValid(): Invalid -proxy address or hostname: '%s'"), proxyArg));
SetProxy(NET_IPV4, addrProxy);
SetProxy(NET_IPV6, addrProxy);
SetProxy(NET_TOR, addrProxy);
SetNameProxy(addrProxy);
SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later
}
// -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses
// -noonion (or -onion=0) disables connecting to .onion entirely
// An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none)
std::string onionArg = GetArg("-onion", "");
if (onionArg != "") {
if (onionArg == "0") { // Handle -noonion/-onion=0
SetLimited(NET_TOR); // set onions as unreachable
} else {
CService onionProxy;
if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) {
return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
}
proxyType addrOnion = proxyType(onionProxy, proxyRandomize);
if (!addrOnion.IsValid())
return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg));
SetProxy(NET_TOR, addrOnion);
SetLimited(NET_TOR, false);
}
}
// see Step 2: parameter interactions for more information about these
fListen = GetBoolArg("-listen", DEFAULT_LISTEN);
fDiscover = GetBoolArg("-discover", true);
bool fBound = false;
if (fListen) {
if (mapArgs.count("-bind") || mapArgs.count("-whitebind")) {
for (std::string strBind : mapMultiArgs["-bind"]) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false))
return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind));
fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR));
}
for (std::string strBind : mapMultiArgs["-whitebind"]) {
CService addrBind;
if (!Lookup(strBind.c_str(), addrBind, 0, false))
return InitError(strprintf(_("Cannot resolve -whitebind address: '%s'"), strBind));
if (addrBind.GetPort() == 0)
return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind));
fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST));
}
} else {
struct in_addr inaddr_any;
inaddr_any.s_addr = INADDR_ANY;
fBound |= Bind(CService((in6_addr)IN6ADDR_ANY_INIT, GetListenPort()), BF_NONE);
fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE);
}
if (!fBound)
return InitError(_("Failed to listen on any port. Use -listen=0 if you want this."));
}
if (mapArgs.count("-externalip")) {
for (std::string strAddr : mapMultiArgs["-externalip"]) {
CService addrLocal(strAddr, GetListenPort(), fNameLookup);
if (!addrLocal.IsValid())
return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr));
AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL);
}
}
for (std::string strDest : mapMultiArgs["-seednode"])
AddOneShot(strDest);
#if ENABLE_ZMQ
pzmqNotificationInterface = CZMQNotificationInterface::CreateWithArguments(mapArgs);
if (pzmqNotificationInterface) {
RegisterValidationInterface(pzmqNotificationInterface);
}
#endif
// ********************************************************* Step 7: load block chain
//ABET: Load Accumulator Checkpoints according to network (main/test/regtest)
assert(AccumulatorCheckpoints::LoadCheckpoints(Params().NetworkIDString()));
fReindex = GetBoolArg("-reindex", false);
// Create blocks directory if it doesn't already exist
boost::filesystem::create_directories(GetDataDir() / "blocks");
// cache size calculations
size_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20);
if (nTotalCache < (nMinDbCache << 20))
nTotalCache = (nMinDbCache << 20); // total cache cannot be less than nMinDbCache
else if (nTotalCache > (nMaxDbCache << 20))
nTotalCache = (nMaxDbCache << 20); // total cache cannot be greater than nMaxDbCache
size_t nBlockTreeDBCache = nTotalCache / 8;
if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", true))
nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB
nTotalCache -= nBlockTreeDBCache;
size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache
nTotalCache -= nCoinDBCache;
nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes
bool fLoaded = false;
while (!fLoaded) {
bool fReset = fReindex;
std::string strLoadError;
uiInterface.InitMessage(_("Loading block index..."));
nStart = GetTimeMillis();
do {
try {
UnloadBlockIndex();
delete pcoinsTip;
delete pcoinsdbview;
delete pcoinscatcher;
delete pblocktree;
delete zerocoinDB;
delete pSporkDB;
//ABET specific: zerocoin and spork DB's
zerocoinDB = new CZerocoinDB(0, false, fReindex);
pSporkDB = new CSporkDB(0, false, false);
pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex);
pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex);
pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview);
pcoinsTip = new CCoinsViewCache(pcoinscatcher);
if (fReindex)
pblocktree->WriteReindexing(true);
// ABET: load previous sessions sporks if we have them.
uiInterface.InitMessage(_("Loading sporks..."));
LoadSporksFromDB();
uiInterface.InitMessage(_("Loading block index..."));
std::string strBlockIndexError = "";
if (!LoadBlockIndex(strBlockIndexError)) {
strLoadError = _("Error loading block database");
strLoadError = strprintf("%s : %s", strLoadError, strBlockIndexError);
break;
}
// If the loaded chain has a wrong genesis, bail out immediately
// (we're likely using a testnet datadir, or the other way around).
if (!mapBlockIndex.empty() && mapBlockIndex.count(Params().HashGenesisBlock()) == 0)
return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?"));
// Initialize the block index (no-op if non-empty database was already loaded)
if (!InitBlockIndex()) {
strLoadError = _("Error initializing block database");
break;
}
// Check for changed -txindex state
if (fTxIndex != GetBoolArg("-txindex", true)) {
strLoadError = _("You need to rebuild the database using -reindex to change -txindex");
break;
}
// Populate list of invalid/fraudulent outpoints that are banned from the chain
invalid_out::LoadOutpoints();
invalid_out::LoadSerials();
// Drop all information from the zerocoinDB and repopulate
if (GetBoolArg("-reindexzerocoin", false)) {
if (chainActive.Height() > Params().Zerocoin_StartHeight()) {
uiInterface.InitMessage(_("Reindexing zerocoin database..."));
std::string strError = ReindexZerocoinDB();
if (strError != "") {
strLoadError = strError;
break;
}
}
}
// Wrapped serials inflation check
bool reindexDueWrappedSerials = false;
bool reindexZerocoin = false;
int chainHeight = chainActive.Height();
if(Params().NetworkID() == CBaseChainParams::MAIN && chainHeight > Params().Zerocoin_Block_EndFakeSerial()) {
// Supply needs to be exactly GetSupplyBeforeFakeSerial + GetWrapppedSerialInflationAmount
CBlockIndex* pblockindex = chainActive[Params().Zerocoin_Block_EndFakeSerial() + 1];
CAmount zpivSupplyCheckpoint = Params().GetSupplyBeforeFakeSerial() + GetWrapppedSerialInflationAmount();
if (pblockindex->GetZerocoinSupply() < zpivSupplyCheckpoint) {
// Trigger reindex due wrapping serials
LogPrintf("Current GetZerocoinSupply: %d vs %d\n", pblockindex->GetZerocoinSupply()/COIN , zpivSupplyCheckpoint/COIN);
reindexDueWrappedSerials = true;
} else if (pblockindex->GetZerocoinSupply() > zpivSupplyCheckpoint) {
// Trigger global zABET reindex
reindexZerocoin = true;
LogPrintf("Current GetZerocoinSupply: %d vs %d\n", pblockindex->GetZerocoinSupply()/COIN , zpivSupplyCheckpoint/COIN);
}
}
// Reindex only for wrapped serials inflation.
if (reindexDueWrappedSerials)
AddWrappedSerialsInflation();
// Recalculate money supply for blocks that are impacted by accounting issue after zerocoin activation
if (GetBoolArg("-reindexmoneysupply", false) || reindexZerocoin) {
if (chainHeight > Params().Zerocoin_StartHeight()) {
RecalculateZPIVMinted();
RecalculateZPIVSpent();
}
// Recalculate from the zerocoin activation or from scratch.
RecalculatePIVSupply(reindexZerocoin ? Params().Zerocoin_StartHeight() : 1);
}
// Check Recalculation result
if(Params().NetworkID() == CBaseChainParams::MAIN && chainHeight > Params().Zerocoin_Block_EndFakeSerial()) {
CBlockIndex* pblockindex = chainActive[Params().Zerocoin_Block_EndFakeSerial() + 1];
CAmount zpivSupplyCheckpoint = Params().GetSupplyBeforeFakeSerial() + GetWrapppedSerialInflationAmount();
if (pblockindex->GetZerocoinSupply() != zpivSupplyCheckpoint)
return InitError(strprintf("ZerocoinSupply Recalculation failed: %d vs %d", pblockindex->GetZerocoinSupply()/COIN , zpivSupplyCheckpoint/COIN));
}
// Force recalculation of accumulators.
if (GetBoolArg("-reindexaccumulators", false)) {
if (chainHeight > Params().Zerocoin_Block_V2_Start()) {
CBlockIndex *pindex = chainActive[Params().Zerocoin_Block_V2_Start()];
while (pindex->nHeight < chainActive.Height()) {
if (!count(listAccCheckpointsNoDB.begin(), listAccCheckpointsNoDB.end(),
pindex->nAccumulatorCheckpoint))
listAccCheckpointsNoDB.emplace_back(pindex->nAccumulatorCheckpoint);
pindex = chainActive.Next(pindex);
}
// ABET: recalculate Accumulator Checkpoints that failed to database properly
if (!listAccCheckpointsNoDB.empty()) {
uiInterface.InitMessage(_("Calculating missing accumulators..."));
LogPrintf("%s : finding missing checkpoints\n", __func__);
std::string strError;
if (!ReindexAccumulators(listAccCheckpointsNoDB, strError))
return InitError(strError);
}
}
}
if (!fReindex) {
uiInterface.InitMessage(_("Verifying blocks..."));
// Flag sent to validation code to let it know it can skip certain checks
fVerifyingBlocks = true;
{
LOCK(cs_main);
CBlockIndex *tip = chainActive[chainActive.Height()];
RPCNotifyBlockChange(tip->GetBlockHash());
if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) {
strLoadError = _("The block database contains a block which appears to be from the future. "
"This may be due to your computer's date and time being set incorrectly. "
"Only rebuild the block database if you are sure that your computer's date and time are correct");
break;
}
}
// Zerocoin must check at level 4
if (!CVerifyDB().VerifyDB(pcoinsdbview, 4, GetArg("-checkblocks", 100))) {
strLoadError = _("Corrupted block database detected");
fVerifyingBlocks = false;
break;
}
}
} catch (std::exception& e) {
if (fDebug) LogPrintf("%s\n", e.what());
strLoadError = _("Error opening block database");
fVerifyingBlocks = false;
break;
}
fVerifyingBlocks = false;
fLoaded = true;
} while (false);
if (!fLoaded) {
// first suggest a reindex
if (!fReset) {
bool fRet = uiInterface.ThreadSafeMessageBox(
strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"),
"", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT);
if (fRet) {
fReindex = true;
fRequestShutdown = false;
} else {
LogPrintf("Aborted block database rebuild. Exiting.\n");
return false;
}
} else {
return InitError(strLoadError);
}
}
}
// As LoadBlockIndex can take several minutes, it's possible the user
// requested to kill the GUI during the last operation. If so, exit.
// As the program has not fully started yet, Shutdown() is possibly overkill.
if (fRequestShutdown) {
LogPrintf("Shutdown requested. Exiting.\n");
return false;
}
LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart);
boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME;
CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION);
// Allowed to fail as this file IS missing on first startup.
if (!est_filein.IsNull())
mempool.ReadFeeEstimates(est_filein);
fFeeEstimatesInitialized = true;
// ********************************************************* Step 8: load wallet
#ifdef ENABLE_WALLET
if (fDisableWallet) {
pwalletMain = NULL;
zwalletMain = NULL;
LogPrintf("Wallet disabled!\n");
} else {
// needed to restore wallet transaction meta data after -zapwallettxes
std::vector<CWalletTx> vWtx;
if (GetBoolArg("-zapwallettxes", false)) {
uiInterface.InitMessage(_("Zapping all transactions from wallet..."));
pwalletMain = new CWallet(strWalletFile);
DBErrors nZapWalletRet = pwalletMain->ZapWalletTx(vWtx);
if (nZapWalletRet != DB_LOAD_OK) {
uiInterface.InitMessage(_("Error loading wallet.dat: Wallet corrupted"));
return false;
}
delete pwalletMain;
pwalletMain = NULL;
}
uiInterface.InitMessage(_("Loading wallet..."));
fVerifyingBlocks = true;
nStart = GetTimeMillis();
bool fFirstRun = true;
pwalletMain = new CWallet(strWalletFile);
DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun);
if (nLoadWalletRet != DB_LOAD_OK) {
if (nLoadWalletRet == DB_CORRUPT)
strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n";
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR) {
std::string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect."));
InitWarning(msg);
} else if (nLoadWalletRet == DB_TOO_NEW)
strErrors << _("Error loading wallet.dat: Wallet requires newer version of ABET Core") << "\n";
else if (nLoadWalletRet == DB_NEED_REWRITE) {
strErrors << _("Wallet needed to be rewritten: restart ABET Core to complete") << "\n";
LogPrintf("%s", strErrors.str());
return InitError(strErrors.str());
} else
strErrors << _("Error loading wallet.dat") << "\n";
}
if (GetBoolArg("-upgradewallet", fFirstRun)) {
int nMaxVersion = GetArg("-upgradewallet", 0);
if (nMaxVersion == 0) // the -upgradewallet without argument case
{
LogPrintf("Performing wallet upgrade to %i\n", FEATURE_LATEST);
nMaxVersion = CLIENT_VERSION;
pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately
} else
LogPrintf("Allowing wallet upgrade up to %i\n", nMaxVersion);
if (nMaxVersion < pwalletMain->GetVersion())
strErrors << _("Cannot downgrade wallet") << "\n";
pwalletMain->SetMaxVersion(nMaxVersion);
}
if (fFirstRun) {
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (pwalletMain->GetKeyFromPool(newDefaultKey)) {
pwalletMain->SetDefaultKey(newDefaultKey);
if (!pwalletMain->SetAddressBook(pwalletMain->vchDefaultKey.GetID(), "", "receive"))
strErrors << _("Cannot write default address") << "\n";
}
pwalletMain->SetBestChain(chainActive.GetLocator());
}
LogPrintf("%s", strErrors.str());
LogPrintf(" wallet %15dms\n", GetTimeMillis() - nStart);
zwalletMain = new CzPIVWallet(pwalletMain->strWalletFile);
pwalletMain->setZWallet(zwalletMain);
RegisterValidationInterface(pwalletMain);
CBlockIndex* pindexRescan = chainActive.Tip();
if (GetBoolArg("-rescan", false))
pindexRescan = chainActive.Genesis();
else {
CWalletDB walletdb(strWalletFile);
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = FindForkInGlobalIndex(chainActive, locator);
else
pindexRescan = chainActive.Genesis();
}
if (chainActive.Tip() && chainActive.Tip() != pindexRescan) {
uiInterface.InitMessage(_("Rescanning..."));
LogPrintf("Rescanning last %i blocks (from block %i)...\n", chainActive.Height() - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
LogPrintf(" rescan %15dms\n", GetTimeMillis() - nStart);
pwalletMain->SetBestChain(chainActive.GetLocator());
nWalletDBUpdated++;
// Restore wallet transaction metadata after -zapwallettxes=1
if (GetBoolArg("-zapwallettxes", false) && GetArg("-zapwallettxes", "1") != "2") {
for (const CWalletTx& wtxOld : vWtx) {
uint256 hash = wtxOld.GetHash();
std::map<uint256, CWalletTx>::iterator mi = pwalletMain->mapWallet.find(hash);
if (mi != pwalletMain->mapWallet.end()) {
const CWalletTx* copyFrom = &wtxOld;
CWalletTx* copyTo = &mi->second;
copyTo->mapValue = copyFrom->mapValue;
copyTo->vOrderForm = copyFrom->vOrderForm;
copyTo->nTimeReceived = copyFrom->nTimeReceived;
copyTo->nTimeSmart = copyFrom->nTimeSmart;
copyTo->fFromMe = copyFrom->fFromMe;
copyTo->strFromAccount = copyFrom->strFromAccount;
copyTo->nOrderPos = copyFrom->nOrderPos;
copyTo->WriteToDisk();
}
}
}
}
fVerifyingBlocks = false;
//Inititalize zPIVWallet
uiInterface.InitMessage(_("Syncing zABET wallet..."));
pwalletMain->InitAutoConvertAddresses();
bool fEnableZPivBackups = GetBoolArg("-backupzpiv", true);
pwalletMain->setZPivAutoBackups(fEnableZPivBackups);
//Load zerocoin mint hashes to memory
pwalletMain->zpivTracker->Init();
zwalletMain->LoadMintPoolFromDB();
zwalletMain->SyncWithChain();
} // (!fDisableWallet)
#else // ENABLE_WALLET
LogPrintf("No wallet compiled in!\n");
#endif // !ENABLE_WALLET
// ********************************************************* Step 9: import blocks
if (mapArgs.count("-blocknotify"))
uiInterface.NotifyBlockTip.connect(BlockNotifyCallback);
if (mapArgs.count("-blocksizenotify"))
uiInterface.NotifyBlockSize.connect(BlockSizeNotifyCallback);
// scan for better chains in the block chain database, that are not yet connected in the active best chain
CValidationState state;
if (!ActivateBestChain(state))
strErrors << "Failed to connect best block";
std::vector<boost::filesystem::path> vImportFiles;
if (mapArgs.count("-loadblock")) {
for (std::string strFile : mapMultiArgs["-loadblock"])
vImportFiles.push_back(strFile);
}
threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles));
if (chainActive.Tip() == NULL) {
LogPrintf("Waiting for genesis block to be imported...\n");
while (!fRequestShutdown && chainActive.Tip() == NULL)
MilliSleep(10);
}
// ********************************************************* Step 10: setup ObfuScation
uiInterface.InitMessage(_("Loading masternode cache..."));
CMasternodeDB mndb;
CMasternodeDB::ReadResult readResult = mndb.Read(mnodeman);
if (readResult == CMasternodeDB::FileError)
LogPrintf("Missing masternode cache file - mncache.dat, will try to recreate\n");
else if (readResult != CMasternodeDB::Ok) {
LogPrintf("Error reading mncache.dat: ");
if (readResult == CMasternodeDB::IncorrectFormat)
LogPrintf("magic is ok but data has invalid format, will try to recreate\n");
else
LogPrintf("file format is unknown or invalid, please fix it manually\n");
}
uiInterface.InitMessage(_("Loading budget cache..."));
CBudgetDB budgetdb;
CBudgetDB::ReadResult readResult2 = budgetdb.Read(budget);
if (readResult2 == CBudgetDB::FileError)
LogPrintf("Missing budget cache - budget.dat, will try to recreate\n");
else if (readResult2 != CBudgetDB::Ok) {
LogPrintf("Error reading budget.dat: ");
if (readResult2 == CBudgetDB::IncorrectFormat)
LogPrintf("magic is ok but data has invalid format, will try to recreate\n");
else
LogPrintf("file format is unknown or invalid, please fix it manually\n");
}
//flag our cached items so we send them to our peers
budget.ResetSync();
budget.ClearSeen();
uiInterface.InitMessage(_("Loading masternode payment cache..."));
CMasternodePaymentDB mnpayments;
CMasternodePaymentDB::ReadResult readResult3 = mnpayments.Read(masternodePayments);
if (readResult3 == CMasternodePaymentDB::FileError)
LogPrintf("Missing masternode payment cache - mnpayments.dat, will try to recreate\n");
else if (readResult3 != CMasternodePaymentDB::Ok) {
LogPrintf("Error reading mnpayments.dat: ");
if (readResult3 == CMasternodePaymentDB::IncorrectFormat)
LogPrintf("magic is ok but data has invalid format, will try to recreate\n");
else
LogPrintf("file format is unknown or invalid, please fix it manually\n");
}
fMasterNode = GetBoolArg("-masternode", false);
if ((fMasterNode || masternodeConfig.getCount() > -1) && fTxIndex == false) {
return InitError("Enabling Masternode support requires turning on transaction indexing."
"Please add txindex=1 to your configuration and start with -reindex");
}
if (fMasterNode) {
LogPrintf("IS MASTER NODE\n");
strMasterNodeAddr = GetArg("-masternodeaddr", "");
LogPrintf(" addr %s\n", strMasterNodeAddr.c_str());
if (!strMasterNodeAddr.empty()) {
CService addrTest = CService(strMasterNodeAddr);
if (!addrTest.IsValid()) {
return InitError("Invalid -masternodeaddr address: " + strMasterNodeAddr);
}
}
strMasterNodePrivKey = GetArg("-masternodeprivkey", "");
if (!strMasterNodePrivKey.empty()) {
std::string errorMessage;
CKey key;
CPubKey pubkey;
if (!obfuScationSigner.SetKey(strMasterNodePrivKey, errorMessage, key, pubkey)) {
return InitError(_("Invalid masternodeprivkey. Please see documenation."));
}
activeMasternode.pubKeyMasternode = pubkey;
} else {
return InitError(_("You must specify a masternodeprivkey in the configuration. Please see documentation for help."));
}
}
//get the mode of budget voting for this masternode
strBudgetMode = GetArg("-budgetvotemode", "auto");
if (GetBoolArg("-mnconflock", true) && pwalletMain) {
LOCK(pwalletMain->cs_wallet);
LogPrintf("Locking Masternodes:\n");
uint256 mnTxHash;
for (CMasternodeConfig::CMasternodeEntry mne : masternodeConfig.getEntries()) {
LogPrintf(" %s %s\n", mne.getTxHash(), mne.getOutputIndex());
mnTxHash.SetHex(mne.getTxHash());
COutPoint outpoint = COutPoint(mnTxHash, (unsigned int) std::stoul(mne.getOutputIndex().c_str()));
pwalletMain->LockCoin(outpoint);
}
}
fEnableZeromint = GetBoolArg("-enablezeromint", true);
nZeromintPercentage = GetArg("-zeromintpercentage", 10);
if (nZeromintPercentage > 100) nZeromintPercentage = 100;
if (nZeromintPercentage < 1) nZeromintPercentage = 1;
nPreferredDenom = GetArg("-preferredDenom", 0);
if (nPreferredDenom != 0 && nPreferredDenom != 1 && nPreferredDenom != 5 && nPreferredDenom != 10 && nPreferredDenom != 50 &&
nPreferredDenom != 100 && nPreferredDenom != 500 && nPreferredDenom != 1000 && nPreferredDenom != 5000){
LogPrintf("-preferredDenom: invalid denomination parameter %d. Default value used\n", nPreferredDenom);
nPreferredDenom = 0;
}
fEnableSwiftTX = GetBoolArg("-enableswifttx", fEnableSwiftTX);
nSwiftTXDepth = GetArg("-swifttxdepth", nSwiftTXDepth);
nSwiftTXDepth = std::min(std::max(nSwiftTXDepth, 0), 60);
//lite mode disables all Masternode and Obfuscation related functionality
fLiteMode = GetBoolArg("-litemode", false);
if (fMasterNode && fLiteMode) {
return InitError("You can not start a masternode in litemode");
}
LogPrintf("fLiteMode %d\n", fLiteMode);
LogPrintf("nSwiftTXDepth %d\n", nSwiftTXDepth);
LogPrintf("Budget Mode %s\n", strBudgetMode.c_str());
/* Denominations
A note about convertability. Within Obfuscation pools, each denomination
is convertable to another.
For example:
1PIV+1000 == (.1PIV+100)*10
10PIV+10000 == (1PIV+1000)*10
*/
obfuScationDenominations.push_back((10000 * COIN) + 10000000);
obfuScationDenominations.push_back((1000 * COIN) + 1000000);
obfuScationDenominations.push_back((100 * COIN) + 100000);
obfuScationDenominations.push_back((10 * COIN) + 10000);
obfuScationDenominations.push_back((1 * COIN) + 1000);
obfuScationDenominations.push_back((.1 * COIN) + 100);
obfuScationPool.InitCollateralAddress();
threadGroup.create_thread(boost::bind(&ThreadCheckObfuScationPool));
// ********************************************************* Step 11: start node
if (!CheckDiskSpace())
return false;
if (!strErrors.str().empty())
return InitError(strErrors.str());
RandAddSeedPerfmon();
//// debug print
LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size());
LogPrintf("chainActive.Height() = %d\n", chainActive.Height());
#ifdef ENABLE_WALLET
LogPrintf("setKeyPool.size() = %u\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
LogPrintf("mapWallet.size() = %u\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
LogPrintf("mapAddressBook.size() = %u\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
#endif
if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION))
StartTorControl(threadGroup);
StartNode(threadGroup, scheduler);
if (nLocalServices & NODE_BLOOM_LIGHT_ZC) {
// Run a thread to compute witnesses
lightWorker.StartLightZpivThread(threadGroup);
}
#ifdef ENABLE_WALLET
// Generate coins in the background
if (pwalletMain)
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain, GetArg("-genproclimit", 1));
#endif
// ********************************************************* Step 12: finished
SetRPCWarmupFinished();
uiInterface.InitMessage(_("Done loading"));
#ifdef ENABLE_WALLET
if (pwalletMain) {
// Add wallet transactions that aren't already in a block to mapTransactions
pwalletMain->ReacceptWalletTransactions();
// Run a thread to flush wallet periodically
threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile)));
if (GetBoolArg("-precompute", false)) {
// Run a thread to precompute any zABET spends
threadGroup.create_thread(boost::bind(&ThreadPrecomputeSpends));
}
if (GetBoolArg("-staking", true)) {
// ppcoin:mint proof-of-stake blocks in the background
threadGroup.create_thread(boost::bind(&ThreadStakeMinter));
}
}
#endif
return !fRequestShutdown;
}
|
; ICS 331
; Tetris
; Alex Watanabe
; Using DLX architecture
; Contains anything to do with shifting so I don't have to
; scroll through many things while working on the program
; Function that shifts pieces from the current shift to the desired shift
; Arguments Taken-
; R4 | Sublocation pointer to current shift (0xC)
; R5 | Address of the piece rotation block (0x1300)
; R6 | The direction to shift (normally from x input)
; If 0 is passed in, assume default.
: R7 | The sublocation pointer for the piece set (the _0 in R5)
; Arguments Passed-
; Calls no functions
; Temporaries-
; R8 | pieceRow counter
; R9 | Current row temp
; R10 |
; R11 | Temporary holder for new shift
; R12 |
; R13 |
; R14 | subtraciton result temp2
; R15 | subtraction result temp
;
; R16 | Address of piece block (0x1300 + piece designation)
; R17 | Address of current shift for piece & upper bound of orientations
; R18 | Current shift
; R19 | Default shift
; R20 | Desired shift
; R21 |
; R22 |
; R23 |
;
; R24 | Logical temporary
; R25 | Logical temporary 2
; Returns-
; N/A
;
; Function start, calculate needed address from arguments
pshift: add R16 R5 R7
add R17 R16 R4
; Now load current shift and default shift
lw R18 R17 0x0
lw R19 R17 0x1
; Is R6 0 (setup/new piece) or 1-3 (controller)
; If 0, we're resetting to default so
; R20 should be set to R19
; Otherwise, R20 should be adjusted from R18 accordingly
beqz R6 todeflt
bnez R6 tonrml
todeflt: addi R20 R19 0x0
beqz R0 endtodn
tonrml: addi R20 R18 0x0
; Calculate if R6 is 1 2 or 3
; SL for negative, SR for positive
addi R15 R6 -2
beqz R15 endtodn
slti R24 R16 0x0
bnez R24 ifSL
sgti R24 R16 0x0
bnez R24 ifSR
; For these if statements we first check if above/below bounds
; (note that we count shift from right corner)
ifSL: addi R11 R20 1
sgei R24 R11 0xFF
bnez R24 endtodn
addi R20 R11 0x0
beqz R0 endtodn
ifSR: addi R11 R20 -1
slti R24 R11 0x00
bnez R24 endtodn
addi R20 R11 0x0
beqz R0 endtodn
; At this point we have the current shift
; R18 and the desired shift R20
; Now we iterate over every orientation for that piece
endtodn: addi R8 R16 0x0
; Here's the outer while loop.
; Go until R18 = R20
shifting: sub R14 R20 R18
; if >0 shift left, if <0 shift right else end
slti R24 R14 0x0
sgti R25 R14 0x0
beqz R14 enshift
; Here's the inner while loop. R17 has the upper bound of iteration
; Go until pointer on 0x13_C
sh1: sub R15 R17 R8
beqz R15 endsh1
bnez R25 shftL
bnez R24 shftR
beqz R0 retsft
; Shifts
shftL: lw R9 R8 0x0
sll R9 R9
sw R9 R8 0x0
beqz R0 retsft
shftR: lw R9 R8 0x0
srl R9 R9
sw R9 R8 0x0
beqz R0 retsft
retsft: addi R8 R8 1
beqz R0 sh1
endsh1: addi R8 R16 0x0
; Adjust currentshift accordingly
bnez R25 eshftL
bnez R24 eshftR
beqz R0 ensh2
eshftL: addi R18 R18 1
beqz R0 ensh2
eshftR: addi R18 R18 -1
beqz R0 ensh2
ensh2: beqz R0 shifting
enshift: sw R18 R16 0xC
; current shift stored and all piecerows have been shifted
jr R31
|
;====================== comments ===================
; first operand - address bufer result (string symbols)
; second operand - address of number
; third operand - count bits of number (should be multiple 8)
;===================================================
;======================= code ======================
section .code
;===================================================
;====================== StrDec =====================
StrHex_MY:
;===================================================
push ebp ; write EBP to STACK
mov ebp, esp ; write pointer on STACK to EBP
mov ecx, [ebp+8] ; count bits of number
cmp ecx, 0 ; compare ECX with 0
jle .exitp ; ability for jump on { .exitp }
shr ecx, 3 ; count bytes of number
mov esi, [ebp+12] ; address of number
mov ebx, [ebp+16] ; address of bufer result
.cycle:
mov dl, byte [esi+ecx-1] ; byte of number - its two hex numbers
mov al, dl ; move DL to AL
shr al, 4 ; oldest number
call HexSymbol_MY ; call procedure { HexSymbol_MY }
mov byte [ebx], al ; move one byte from AL to EBX
mov al, dl ; younger number
call HexSymbol_MY ; call procedure { HexSymbol_MY }
mov byte [ebx+1], al ; move one byte from AL to EBX
mov eax, ecx ; move ECX to EAX
cmp eax, 4 ; compare EAX with 4
jle .next ; ability for jump on { .next }
dec eax ; EAX--
and eax, 3 ; interval that separated groups by 8 bit
cmp al, 0 ; compare AL with 0
jne .next ; ability for jump on { .next }
mov byte [ebx+2], 32 ; code of symbol from interval
inc ebx ; EBX++
.next:
add ebx, 2 ; addition { EBX = EBX + 2 }
dec ecx ; ECX--
jnz .cycle ; ability for jump on { .cycle }
mov byte [ebx], 0 ; string has end as null
.exitp:
pop ebp ; remove pointer on the STACK
ret 12 ; return parametrs from STACK
; this procedure calculating code of hex-number
; parametr it's value of AL
; result will be written to AL
HexSymbol_MY:
and al, 0Fh ; cut younger 4 bits
add al, 48 ; we can do this only for numbers 0-9
cmp al, 58 ; compare AL with 58
jl .exitp ; ability for jump on { .exitp }
add al, 7 ; only for numbers A,B,C,D,E,F
ret ; exit from procedure
.exitp:
ret ; alternative exit from procedure
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %r13
push %r14
push %r9
push %rbp
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0x1d074, %rbp
clflush (%rbp)
nop
nop
nop
nop
nop
xor %r13, %r13
mov $0x6162636465666768, %r12
movq %r12, %xmm5
vmovups %ymm5, (%rbp)
nop
nop
nop
and $140, %r11
lea addresses_A_ht+0xe79c, %rbx
nop
nop
nop
nop
nop
sub %r14, %r14
movups (%rbx), %xmm6
vpextrq $0, %xmm6, %r9
cmp %r14, %r14
lea addresses_UC_ht+0x6564, %rsi
lea addresses_WC_ht+0x1d79c, %rdi
nop
nop
nop
nop
xor %r12, %r12
mov $64, %rcx
rep movsq
nop
nop
and $5486, %rbx
lea addresses_D_ht+0x10664, %r9
nop
nop
nop
nop
nop
cmp %rdi, %rdi
mov (%r9), %bx
nop
and $63498, %r11
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r9
pop %r14
pop %r13
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r13
push %r14
push %r15
push %r8
push %rbp
// Faulty Load
lea addresses_A+0x1664, %r8
nop
nop
nop
and %r12, %r12
mov (%r8), %r13d
lea oracles, %r14
and $0xff, %r13
shlq $12, %r13
mov (%r14,%r13,1), %r13
pop %rbp
pop %r8
pop %r15
pop %r14
pop %r13
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_A', 'congruent': 0}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 4, 'type': 'addresses_A', 'congruent': 0}}
<gen_prepare_buffer>
{'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_WT_ht', 'congruent': 4}, 'OP': 'STOR'}
{'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_A_ht', 'congruent': 3}}
{'dst': {'same': False, 'congruent': 1, 'type': 'addresses_WC_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 6, 'type': 'addresses_UC_ht'}}
{'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_D_ht', 'congruent': 11}}
{'35': 21829}
35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35
*/
|
; A017510: a(n) = (11*n + 10)^2.
; 100,441,1024,1849,2916,4225,5776,7569,9604,11881,14400,17161,20164,23409,26896,30625,34596,38809,43264,47961,52900,58081,63504,69169,75076,81225,87616,94249,101124,108241,115600,123201,131044,139129,147456,156025,164836,173889,183184,192721,202500,212521,222784,233289,244036,255025,266256,277729,289444,301401,313600,326041,338724,351649,364816,378225,391876,405769,419904,434281,448900,463761,478864,494209,509796,525625,541696,558009,574564,591361,608400,625681,643204,660969,678976,697225,715716
mul $0,11
add $0,10
pow $0,2
|
/*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
| Copyright (c) 1997-2010 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/base/util/request_local.h"
#include "hphp/runtime/ext/thrift/transport.h"
#include "hphp/runtime/ext/ext_reflection.h"
#include "hphp/runtime/ext/ext_thrift.h"
#include <stack>
#include <utility>
namespace HPHP {
static const uint8_t VERSION_MASK = 0x1f;
static const uint8_t VERSION = 2;
static const uint8_t VERSION_LOW = 1;
static const uint8_t VERSION_DOUBLE_BE = 2;
static const uint8_t PROTOCOL_ID = 0x82;
static const uint8_t TYPE_MASK = 0xe0;
static const uint8_t TYPE_SHIFT_AMOUNT = 5;
enum CState {
STATE_CLEAR,
STATE_FIELD_WRITE,
STATE_VALUE_WRITE,
STATE_CONTAINER_WRITE,
STATE_BOOL_WRITE,
STATE_FIELD_READ,
STATE_CONTAINER_READ,
STATE_VALUE_READ,
STATE_BOOL_READ
};
enum CType {
C_STOP = 0x00,
C_TRUE = 0x01,
C_FALSE = 0x02,
C_BYTE = 0x03,
C_I16 = 0x04,
C_I32 = 0x05,
C_I64 = 0x06,
C_DOUBLE = 0x07,
C_BINARY = 0x08,
C_LIST = 0x09,
C_SET = 0x0A,
C_MAP = 0x0B,
C_STRUCT = 0x0C
};
enum CListType {
C_LIST_LIST,
C_LIST_SET
};
enum TResponseType {
T_REPLY = 2,
T_EXCEPTION = 3
};
static CType ttype_to_ctype(TType x) {
switch (x) {
case T_STOP:
return C_STOP;
case T_BOOL:
return C_TRUE;
case T_BYTE:
return C_BYTE;
case T_I16:
return C_I16;
case T_I32:
return C_I32;
case T_I64:
return C_I64;
case T_DOUBLE:
return C_DOUBLE;
case T_STRING:
return C_BINARY;
case T_STRUCT:
return C_STRUCT;
case T_LIST:
return C_LIST;
case T_SET:
return C_SET;
case T_MAP:
return C_MAP;
default:
throw InvalidArgumentException("unknown TType", x);
}
}
static TType ctype_to_ttype(CType x) {
switch (x) {
case C_STOP:
return T_STOP;
case C_TRUE:
case C_FALSE:
return T_BOOL;
case C_BYTE:
return T_BYTE;
case C_I16:
return T_I16;
case C_I32:
return T_I32;
case C_I64:
return T_I64;
case C_DOUBLE:
return T_DOUBLE;
case C_BINARY:
return T_STRING;
case C_STRUCT:
return T_STRUCT;
case C_LIST:
return T_LIST;
case C_SET:
return T_SET;
case C_MAP:
return T_MAP;
default:
throw InvalidArgumentException("unknown CType", x);
}
}
enum TError {
ERR_UNKNOWN = 0,
ERR_INVALID_DATA = 1,
ERR_BAD_VERSION = 4
};
class CompactRequestData : public RequestEventHandler {
public:
CompactRequestData() : version(VERSION) { }
void clear() { version = VERSION; }
virtual void requestInit() {
clear();
}
virtual void requestShutdown() {
clear();
}
uint8_t version;
};
IMPLEMENT_STATIC_REQUEST_LOCAL(CompactRequestData, s_compact_request_data);
static void thrift_error(CStrRef what, TError why) ATTRIBUTE_NORETURN;
static void thrift_error(CStrRef what, TError why) {
throw create_object("TProtocolException", CREATE_VECTOR2(what, why));
}
class CompactWriter {
public:
explicit CompactWriter(PHPOutputTransport *transport) :
transport(transport),
version(VERSION),
state(STATE_CLEAR),
lastFieldNum(0),
boolFieldNum(0),
structHistory(),
containerHistory() {
}
void setWriteVersion(uint8_t _version) {
version = _version;
}
void writeHeader(CStrRef name, uint8_t msgtype, uint32_t seqid) {
writeUByte(PROTOCOL_ID);
writeUByte(version | (msgtype << TYPE_SHIFT_AMOUNT));
writeVarint(seqid);
writeString(name);
state = STATE_VALUE_WRITE;
}
void write(CObjRef obj) {
writeStruct(obj);
}
private:
PHPOutputTransport* transport;
uint8_t version;
CState state;
uint16_t lastFieldNum;
uint16_t boolFieldNum;
std::stack<std::pair<CState, uint16_t> > structHistory;
std::stack<CState> containerHistory;
void writeStruct(CObjRef obj) {
// Save state
structHistory.push(std::make_pair(state, lastFieldNum));
state = STATE_FIELD_WRITE;
lastFieldNum = 0;
// Get field specification
CArrRef spec = f_hphp_get_static_property(obj->o_getClassName(), "_TSPEC")
.toArray();
// Write each member
for (ArrayIter specIter = spec.begin(); !specIter.end(); ++specIter) {
Variant key = specIter.first();
if (!key.isInteger()) {
thrift_error("Bad keytype in TSPEC (expected 'long')",
ERR_INVALID_DATA);
}
uint16_t fieldNo = key.toInt16();
Array fieldSpec = specIter.second().toArray();
String fieldName = fieldSpec
.rvalAt(PHPTransport::s_var, AccessFlags::Error_Key).toString();
TType fieldType = (TType)fieldSpec
.rvalAt(PHPTransport::s_type, AccessFlags::Error_Key).toByte();
Variant fieldVal = obj->o_get(fieldName, true, obj->o_getClassName());
if (!fieldVal.isNull()) {
writeFieldBegin(fieldNo, fieldType);
writeField(fieldVal, fieldSpec, fieldType);
writeFieldEnd();
}
}
// Write stop
writeUByte(0);
// Restore state
std::pair<CState, uint16_t> prev = structHistory.top();
state = prev.first;
lastFieldNum = prev.second;
structHistory.pop();
}
void writeFieldBegin(uint16_t fieldNum, TType fieldType) {
if (fieldType == T_BOOL) {
state = STATE_BOOL_WRITE;
boolFieldNum = fieldNum;
// the value and header are written together in writeField
} else {
state = STATE_VALUE_WRITE;
writeFieldHeader(fieldNum, ttype_to_ctype(fieldType));
}
}
void writeFieldEnd(void) {
state = STATE_FIELD_WRITE;
}
void writeFieldHeader(uint16_t fieldNum, CType fieldType) {
int delta = fieldNum - lastFieldNum;
if (0 < delta && delta <= 15) {
writeUByte((delta << 4) | fieldType);
} else {
writeUByte(fieldType);
writeI(fieldNum);
}
lastFieldNum = fieldNum;
}
void writeField(CVarRef value,
CArrRef valueSpec,
TType type) {
switch (type) {
case T_STOP:
case T_VOID:
break;
case T_STRUCT:
if (!value.is(KindOfObject)) {
thrift_error("Attempt to send non-object type as T_STRUCT",
ERR_INVALID_DATA);
}
writeStruct(value);
break;
case T_BOOL: {
bool b = value.toBoolean();
if (state == STATE_BOOL_WRITE) {
CType t = b ? C_TRUE : C_FALSE;
writeFieldHeader(boolFieldNum, t);
} else if (state == STATE_CONTAINER_WRITE) {
writeUByte(b ? C_TRUE : C_FALSE);
} else {
thrift_error("Invalid state in compact protocol", ERR_UNKNOWN);
}
}
break;
case T_BYTE:
writeUByte(value.toByte());
break;
case T_I16:
case T_I32:
case T_I64:
case T_U64:
writeI(value.toInt64());
break;
case T_DOUBLE: {
union {
uint64_t i;
double d;
} u;
u.d = value.toDouble();
uint64_t bits;
if (version >= VERSION_DOUBLE_BE) {
bits = htonll(u.i);
} else {
bits = htolell(u.i);
}
transport->write((char*)&bits, 8);
}
break;
case T_UTF8:
case T_UTF16:
case T_STRING: {
String s = value.toString();
auto slice = s.slice();
writeVarint(slice.len);
transport->write(slice.ptr, slice.len);
break;
}
case T_MAP:
writeMap(value.toArray(), valueSpec);
break;
case T_LIST:
writeList(value.toArray(), valueSpec, C_LIST_LIST);
break;
case T_SET:
writeList(value.toArray(), valueSpec, C_LIST_SET);
break;
default:
throw InvalidArgumentException("unknown TType", type);
}
}
void writeMap(Array arr, CArrRef spec) {
TType keyType = (TType)spec
.rvalAt(PHPTransport::s_ktype, AccessFlags::Error_Key).toByte();
TType valueType = (TType)spec
.rvalAt(PHPTransport::s_vtype, AccessFlags::Error_Key).toByte();
Array keySpec = spec.rvalAt(PHPTransport::s_key, AccessFlags::Error_Key)
.toArray();
Array valueSpec = spec.rvalAt(PHPTransport::s_val, AccessFlags::Error_Key)
.toArray();
writeMapBegin(keyType, valueType, arr.size());
for (ArrayIter arrIter = arr.begin(); !arrIter.end(); ++arrIter) {
writeField(arrIter.first(), keySpec, keyType);
writeField(arrIter.second(), valueSpec, valueType);
}
writeCollectionEnd();
}
void writeList(Array arr, CArrRef spec, CListType listType) {
TType valueType = (TType)spec
.rvalAt(PHPTransport::s_etype, AccessFlags::Error_Key).toByte();
Array valueSpec = spec
.rvalAt(PHPTransport::s_elem, AccessFlags::Error_Key).toArray();
writeListBegin(valueType, arr.size());
for (ArrayIter arrIter = arr.begin(); !arrIter.end(); ++arrIter) {
Variant x;
if (listType == C_LIST_LIST) {
x = arrIter.second();
} else if (listType == C_LIST_SET) {
x = arrIter.first();
}
writeField(x, valueSpec, valueType);
}
writeCollectionEnd();
}
void writeMapBegin(TType keyType, TType valueType, uint32_t size) {
if (size == 0) {
writeUByte(0);
} else {
writeVarint(size);
CType keyCType = ttype_to_ctype(keyType);
CType valueCType = ttype_to_ctype(valueType);
writeUByte((keyCType << 4) | valueCType);
}
containerHistory.push(state);
state = STATE_CONTAINER_WRITE;
}
void writeListBegin(TType elemType, uint32_t size) {
if (size <= 14) {
writeUByte((size << 4) | ttype_to_ctype(elemType));
} else {
writeUByte(0xf0 | ttype_to_ctype(elemType));
writeVarint(size);
}
containerHistory.push(state);
state = STATE_CONTAINER_WRITE;
}
void writeCollectionEnd(void) {
state = containerHistory.top();
containerHistory.pop();
}
void writeUByte(uint8_t n) {
transport->writeI8(n);
}
void writeI(int64_t n) {
writeVarint(i64ToZigzag(n));
}
void writeVarint(uint64_t n) {
uint8_t buf[10];
uint8_t wsize = 0;
while (true) {
if ((n & ~0x7FL) == 0) {
buf[wsize++] = (int8_t)n;
break;
} else {
buf[wsize++] = (int8_t)((n & 0x7F) | 0x80);
n >>= 7;
}
}
transport->write((char*)buf, wsize);
}
void writeString(CStrRef s) {
auto slice = s.slice();
writeVarint(slice.len);
transport->write(slice.ptr, slice.len);
}
uint64_t i64ToZigzag(int64_t n) {
return (n << 1) ^ (n >> 63);
}
};
class CompactReader {
public:
explicit CompactReader(CObjRef _transportobj) :
transport(_transportobj),
version(VERSION),
state(STATE_CLEAR),
lastFieldNum(0),
boolValue(true),
structHistory(),
containerHistory() {
}
Variant read(CStrRef resultClassName) {
uint8_t protoId = readUByte();
if (protoId != PROTOCOL_ID) {
thrift_error("Bad protocol id in TCompact message", ERR_BAD_VERSION);
}
uint8_t versionAndType = readUByte();
uint8_t type = (versionAndType & TYPE_MASK) >> TYPE_SHIFT_AMOUNT;
version = versionAndType & VERSION_MASK;
if (version < VERSION_LOW || version > VERSION) {
thrift_error("Bad version in TCompact message", ERR_BAD_VERSION);
}
// TODO: we eventually want to return seqid to the caller
/*uint32_t seqid =*/ readVarint(); // unused
/*Variant name =*/ readString(); // unused
if (type == T_REPLY) {
Object ret = create_object(resultClassName, Array());
Variant spec = f_hphp_get_static_property(resultClassName, "_TSPEC");
readStruct(ret, spec);
return ret;
} else if (type == T_EXCEPTION) {
Object exn = create_object("TApplicationException", Array());
Variant spec = f_hphp_get_static_property("TApplicationException", "_TSPEC");
readStruct(exn, spec);
throw exn;
} else {
thrift_error("Invalid response type", ERR_INVALID_DATA);
}
}
private:
PHPInputTransport transport;
uint8_t version;
CState state;
uint16_t lastFieldNum;
bool boolValue;
std::stack<std::pair<CState, uint16_t> > structHistory;
std::stack<CState> containerHistory;
void readStruct(CObjRef dest, CArrRef spec) {
readStructBegin();
while (true) {
int16_t fieldNum;
TType fieldType;
readFieldBegin(fieldNum, fieldType);
if (fieldType == T_STOP) {
break;
}
bool readComplete = false;
Variant fieldSpecVariant = spec.rvalAt(fieldNum);
if (!fieldSpecVariant.isNull()) {
Array fieldSpec = fieldSpecVariant.toArray();
String fieldName = fieldSpec.rvalAt(PHPTransport::s_var).toString();
auto expectedType = (TType)fieldSpec.rvalAt(PHPTransport::s_type)
.toInt64();
if (typesAreCompatible(fieldType, expectedType)) {
readComplete = true;
Variant fieldValue = readField(fieldSpec, fieldType);
dest->o_set(fieldName, fieldValue, dest->o_getClassName());
}
}
if (!readComplete) {
skip(fieldType);
}
readFieldEnd();
}
readStructEnd();
}
void readStructBegin(void) {
structHistory.push(std::make_pair(state, lastFieldNum));
state = STATE_FIELD_READ;
lastFieldNum = 0;
}
void readStructEnd(void) {
std::pair<CState, uint16_t> prev = structHistory.top();
state = prev.first;
lastFieldNum = prev.second;
structHistory.pop();
}
void readFieldBegin(int16_t &fieldNum, TType &fieldType) {
uint8_t fieldTypeAndDelta = readUByte();
int delta = fieldTypeAndDelta >> 4;
CType fieldCType = (CType)(fieldTypeAndDelta & 0x0f);
fieldType = ctype_to_ttype(fieldCType);
if (fieldCType == C_STOP) {
fieldNum = 0;
return;
}
if (delta == 0) {
fieldNum = readI();
} else {
fieldNum = lastFieldNum + delta;
}
lastFieldNum = fieldNum;
if (fieldCType == C_TRUE) {
state = STATE_BOOL_READ;
boolValue = true;
} else if (fieldCType == C_FALSE) {
state = STATE_BOOL_READ;
boolValue = false;
} else {
state = STATE_VALUE_READ;
}
}
void readFieldEnd(void) {
state = STATE_FIELD_READ;
}
Variant readField(CArrRef spec, TType type) {
switch (type) {
case T_STOP:
case T_VOID:
return uninit_null();
case T_STRUCT: {
Variant className = spec.rvalAt(PHPTransport::s_class);
if (className.isNull()) {
thrift_error("no class type in spec", ERR_INVALID_DATA);
}
String classNameString = className.toString();
Variant newStruct = create_object(classNameString, Array());
if (newStruct.isNull()) {
thrift_error("invalid class type in spec", ERR_INVALID_DATA);
}
Variant newStructSpec =
f_hphp_get_static_property(classNameString, "_TSPEC");
if (!newStructSpec.is(KindOfArray)) {
thrift_error("invalid type of spec", ERR_INVALID_DATA);
}
readStruct(newStruct, newStructSpec);
return newStruct;
}
case T_BOOL:
if (state == STATE_BOOL_READ) {
return boolValue;
} else if (state == STATE_CONTAINER_READ) {
return (readUByte() == C_TRUE);
} else {
thrift_error("Invalid state in compact protocol", ERR_UNKNOWN);
}
case T_BYTE:
return readUByte();
case T_I16:
case T_I32:
case T_I64:
case T_U64:
return readI();
case T_DOUBLE: {
union {
uint64_t i;
double d;
} u;
transport.readBytes(&(u.i), 8);
if (version >= VERSION_DOUBLE_BE) {
u.i = ntohll(u.i);
} else {
u.i = letohll(u.i);
}
return u.d;
}
case T_UTF8:
case T_UTF16:
case T_STRING:
return readString();
case T_MAP:
return readMap(spec);
case T_LIST:
return readList(spec, C_LIST_LIST);
case T_SET:
return readList(spec, C_LIST_SET);
default:
throw InvalidArgumentException("unknown TType", type);
}
}
void skip(TType type) {
switch (type) {
case T_STOP:
case T_VOID:
break;
case T_STRUCT: {
readStructBegin();
while (true) {
int16_t fieldNum;
TType fieldType;
readFieldBegin(fieldNum, fieldType);
if (fieldType == T_STOP) {
break;
}
skip(fieldType);
readFieldEnd();
}
readStructEnd();
}
break;
case T_BOOL:
if (state == STATE_BOOL_READ) {
// don't need to do anything
} else if (state == STATE_CONTAINER_READ) {
readUByte();
} else {
thrift_error("Invalid state in compact protocol", ERR_UNKNOWN);
}
break;
case T_BYTE:
readUByte();
break;
case T_I16:
case T_I32:
case T_I64:
case T_U64:
readI();
break;
case T_DOUBLE:
transport.skip(8);
break;
case T_UTF8:
case T_UTF16:
case T_STRING:
transport.skip(readVarint());
break;
case T_MAP: {
TType keyType, valueType;
uint32_t size;
readMapBegin(keyType, valueType, size);
for (uint32_t i = 0; i < size; i++) {
skip(keyType);
skip(valueType);
}
readCollectionEnd();
}
break;
case T_LIST:
case T_SET: {
TType valueType;
uint32_t size;
readListBegin(valueType, size);
for (uint32_t i = 0; i < size; i++) {
skip(valueType);
}
readCollectionEnd();
}
break;
default:
throw InvalidArgumentException("unknown TType", type);
}
}
Variant readMap(CArrRef spec) {
TType keyType, valueType;
uint32_t size;
readMapBegin(keyType, valueType, size);
Array keySpec = spec.rvalAt(PHPTransport::s_key, AccessFlags::Error);
Array valueSpec = spec.rvalAt(PHPTransport::s_val, AccessFlags::Error);
Variant ret = Array::Create();
for (uint32_t i = 0; i < size; i++) {
Variant key = readField(keySpec, keyType);
Variant value = readField(valueSpec, valueType);
ret.set(key, value);
}
readCollectionEnd();
return ret;
}
Variant readList(CArrRef spec, CListType listType) {
TType valueType;
uint32_t size;
readListBegin(valueType, size);
Array valueSpec = spec.rvalAt(PHPTransport::s_elem,
AccessFlags::Error_Key);
Variant ret = Array::Create();
for (uint32_t i = 0; i < size; i++) {
Variant value = readField(valueSpec, valueType);
if (listType == C_LIST_LIST) {
ret.append(value);
} else {
ret.set(value, true);
}
}
readCollectionEnd();
return ret;
}
void readMapBegin(TType &keyType, TType &valueType, uint32_t &size) {
size = readVarint();
uint8_t types = 0;
if (size > 0) {
types = readUByte();
}
valueType = ctype_to_ttype((CType)(types & 0x0f));
keyType = ctype_to_ttype((CType)(types >> 4));
containerHistory.push(state);
state = STATE_CONTAINER_READ;
}
void readListBegin(TType &elemType, uint32_t &size) {
uint8_t sizeAndType = readUByte();
size = sizeAndType >> 4;
elemType = ctype_to_ttype((CType)(sizeAndType & 0x0f));
if (size == 15) {
size = readVarint();
}
containerHistory.push(state);
state = STATE_CONTAINER_READ;
}
void readCollectionEnd(void) {
state = containerHistory.top();
containerHistory.pop();
}
uint8_t readUByte(void) {
return transport.readI8();
}
int64_t readI(void) {
return zigzagToI64(readVarint());
}
uint64_t readVarint(void) {
uint64_t result = 0;
uint8_t shift = 0;
while (true) {
uint8_t byte = readUByte();
result |= (uint64_t)(byte & 0x7f) << shift;
shift += 7;
if (!(byte & 0x80)) {
return result;
}
// Should never read more than 10 bytes, which is the max for a 64-bit
// int
if (shift >= 10 * 7) {
thrift_error("Variable-length int over 10 bytes", ERR_INVALID_DATA);
}
}
}
Variant readString(void) {
uint32_t size = readVarint();
if (size && (size + 1)) {
String s = String(size, ReserveString);
char* buf = s.mutableSlice().ptr;
transport.readBytes(buf, size);
return s.setSize(size);
} else {
transport.skip(size);
return "";
}
}
int64_t zigzagToI64(uint64_t n) {
return (n >> 1) ^ -(n & 1);
}
bool typeIsInt(TType t) {
return (t == T_BYTE) || ((t >= T_I16) && (t <= T_I64));
}
bool typesAreCompatible(TType t1, TType t2) {
return (t1 == t2) || (typeIsInt(t1) && (typeIsInt(t2)));
}
};
int f_thrift_protocol_set_compact_version(int version) {
int result = s_compact_request_data->version;
s_compact_request_data->version = (uint8_t)version;
return result;
}
void f_thrift_protocol_write_compact(CObjRef transportobj,
CStrRef method_name,
int64_t msgtype,
CObjRef request_struct,
int seqid) {
PHPOutputTransport transport(transportobj);
CompactWriter writer(&transport);
writer.setWriteVersion(s_compact_request_data->version);
writer.writeHeader(method_name, (uint8_t)msgtype, (uint32_t)seqid);
writer.write(request_struct);
transport.flush();
}
Variant f_thrift_protocol_read_compact(CObjRef transportobj,
CStrRef obj_typename) {
CompactReader reader(transportobj);
return reader.read(obj_typename);
}
}
|
; A073548: Number of Fibonacci numbers F(k), k <= 10^n, which end in 2.
; 1,6,66,666,6666,66666,666666,6666666,66666666,666666666,6666666666,66666666666,666666666666,6666666666666,66666666666666,666666666666666,6666666666666666
lpb $0,1
add $1,$0
add $2,$1
add $2,1
sub $2,$0
add $2,2
mov $1,0
mul $2,2
sub $0,1
add $1,$2
add $2,$1
mul $2,2
lpe
sub $1,1
add $1,1
|
.org OC1Baddr
; Back up registers we will be clobbering to the stack.
push r28
push r29
push r30
push r31
in r31, SREG
push r31
; Skip past this logic if this is not a VSYNC line.
cpi interrupt_state, INTERRUPT_STATE_PRE_BLANK_START
brsh interrupt_non_vsync
; If this isn't the last VSYNC line, skip colorburst and active video without any other actions being taken.
cpi interrupt_state, INTERRUPT_STATE_VSYNC_END
brne interrupt_increment_state_and_exit_near
; Otherwise, convert the VSYNC pulse into a HSYNC pulse.
store_immediate_16 OCR1AL, r31, HSYNC_PULSE_CYCLES
; Skip colorburst and active video.
rjmp interrupt_increment_state_and_exit_near
interrupt_non_vsync:
.include "engine/interrupt/implementation/handler/colorburst/index.asm"
; If this is a pre-blank line...
cpi interrupt_state, INTERRUPT_STATE_ACTIVE_A
brsh interrupt_non_pre_blank
; If this is not the last pre-blank line, don't do anything beyond skipping active video.
cpi interrupt_state, INTERRUPT_STATE_PRE_BLANK_END
brne interrupt_increment_state_and_exit_near
; Otherwise, get the main loop to start preparing the second line.
inc video_next_row
.include "engine/pads/implementation/start-poll.asm"
; And then skip active video
rjmp interrupt_increment_state_and_exit_near
interrupt_non_pre_blank:
; Skip past this logic if this is not a post-blank line.
cpi interrupt_state, INTERRUPT_STATE_POST_BLANK_START
brlo interrupt_non_blank
; If this isn't the last post-blank line, skip colorburst and active video without any other actions being taken.
cpi interrupt_state, INTERRUPT_STATE_POST_BLANK_END
brne interrupt_increment_state_and_exit_near
; Otherwise, convert the HSYNC pulse into a VSYNC pulse.
store_immediate_16 OCR1AL, r31, VSYNC_PULSE_CYCLES
; Start from the top.
ldi interrupt_state, INTERRUPT_STATE_VSYNC_START
.include "engine/pads/implementation/end-poll.asm"
; Skip colorburst and active video.
rjmp interrupt_handler_skip_to_end
interrupt_increment_state_and_exit_near:
rjmp interrupt_increment_state_and_exit
interrupt_non_blank:
; Pads are polled once per button.
; The first repetition of each line is used to read the input while the second is used to adjust the clock line.
cpi video_next_row, NUMBER_OF_BUTTONS_PER_PAD + 1
brsh interrupt_after_pads
; Use line repeat flag to determine whether this is the first or second line covering this button.
cpi interrupt_state, INTERRUPT_STATE_ACTIVE_A
brne interrupt_odd
.include "engine/pads/implementation/poll-even.asm"
rjmp interrupt_after_pads
interrupt_odd:
.include "engine/pads/implementation/poll-odd.asm"
interrupt_after_pads:
.include "engine/interrupt/implementation/handler/active-video/index.asm"
; If we've just finished the first repetition of this line, skip to code which increments to the next state.
cpi interrupt_state, INTERRUPT_STATE_ACTIVE_A
breq interrupt_increment_state_and_exit
; Otherwise, we've just finished the second repetition of this line.
; If this is the last active line, skip to code which handles that scenario.
cpi video_next_row, VIDEO_ROWS
breq interrupt_last_row
; This is not the last active line. Move onto the next row.
inc video_next_row
; The next line is its first repetition.
ldi interrupt_state, INTERRUPT_STATE_ACTIVE_A
rjmp interrupt_handler_skip_to_end
interrupt_last_row:
; Tell the main loop to start work on the first row again.
clr video_next_row
interrupt_increment_state_and_exit:
; Move to the next state.
inc interrupt_state
interrupt_handler_skip_to_end:
.include "game/implementation/sample.asm"
.ifdef PAL_60
ldi r31, 1 << INTERRUPT_FLAG_ALTERNATE_LINE
eor interrupt_flags, r31
.endif
; Restore clobbered registers from the stack.
pop r31
out SREG, r31
pop r31
pop r30
pop r29
pop r28
reti
|
; Compiling command: nasm core.asm -f bin -o os.bin
[BITS 16] ; 16-bit mode
[ORG 0x7C00] ; easy
; Switching mode
mov ah, 0
mov al, 0x13 ; VGA mode (320x200x8bit)
int 0x10
mov ax, 0A000h ; Video offset
mov es, ax
mov cx, 0
start:
mov ah, 0
int 0x16
cmp ah, 72 ; UP key code
je key_up_pressed ; Jump if equal
cmp ah, 80 ; DOWN key code
je key_down_pressed ; Jump if equal
jne key_other_pressed ; Very important to do negative check
key_up_pressed:
mov di, cx
mov byte [es:di], 14 ; Yellow
inc cx
jmp start
key_down_pressed:
mov di, cx
mov byte [es:di], 12 ; Red
inc cx
jmp start
key_other_pressed:
mov di, cx
mov byte [es:di], 10 ; Green
inc cx
jmp start
jmp start
JMP $
TIMES 510 - ($ - $$) db 0
DW 0xAA55 |
/***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
#include "../ReverseTranslator.hpp"
#include "../../model/OutputMeter.hpp"
#include "../../model/OutputMeter_Impl.hpp"
#include <utilities/idd/Output_Meter_Cumulative_FieldEnums.hxx>
#include "../../utilities/idd/IddEnums.hpp"
using namespace openstudio::model;
namespace openstudio {
namespace energyplus {
OptionalModelObject ReverseTranslator::translateOutputMeterCumulative(const WorkspaceObject& workspaceObject) {
openstudio::model::OutputMeter meter(m_model);
OptionalString s = workspaceObject.getString(Output_Meter_CumulativeFields::KeyName);
if (s) {
meter.setName(*s);
}
s = workspaceObject.getString(Output_Meter_CumulativeFields::ReportingFrequency);
if (s) {
meter.setReportingFrequency(*s);
}
meter.setMeterFileOnly(false);
meter.setCumulative(true);
return meter;
}
} // namespace energyplus
} // namespace openstudio
|
#include "state_impl.hpp"
#include "bitvector.hpp"
#include "globals.hpp"
#include "number/random.hpp"
#include "script/lisp.hpp"
void State::enter(Platform&, Game&, State&)
{
}
void State::exit(Platform&, Game&, State&)
{
}
StatePtr State::update(Platform&, Game&, Microseconds)
{
return null_state();
}
static void lethargy_update(Platform& pfrm, Game& game)
{
if (auto lethargy = get_powerup(game, Powerup::Type::lethargy)) {
lethargy->dirty_ = true;
if (lethargy->parameter_.get() > 0) {
lethargy->parameter_.set(lethargy->parameter_.get() - seconds(1));
if (not game.on_timeout(pfrm, seconds(1), lethargy_update)) {
// Because, if we fail to enqueue the timeout, I believe that
// the powerup would get stuck.
lethargy->parameter_.set(0);
}
} else {
lethargy->parameter_.set(0);
}
}
}
static void add_lethargy_powerup(Platform& pfrm, Game& game)
{
add_powerup(game,
Powerup::Type::lethargy,
seconds(18),
Powerup::DisplayMode::timestamp);
// For simplicity, I've implemented lethargy with timeouts. Easier to keep
// behavior consistent across multiplayer games this way. Otherwise, each
// game state would need to remember to update the powerup countdown timer
// on each update step.
game.on_timeout(pfrm, seconds(1), [](Platform& pfrm, Game& game) {
lethargy_update(pfrm, game);
});
}
void CommonNetworkListener::receive(const net_event::LethargyActivated&,
Platform& pfrm,
Game& game)
{
add_lethargy_powerup(pfrm, game);
push_notification(
pfrm,
game.state(),
locale_string(pfrm, LocaleString::peer_used_lethargy)->c_str());
}
void CommonNetworkListener::receive(const net_event::ProgramVersion& vn,
Platform& pfrm,
Game& game)
{
const auto major = vn.info_.major_.get();
const auto minor = vn.info_.minor_.get();
const auto subminor = vn.info_.subminor_.get();
const auto revision = vn.info_.revision_.get();
auto local_vn = std::make_tuple(PROGRAM_MAJOR_VERSION,
PROGRAM_MINOR_VERSION,
PROGRAM_SUBMINOR_VERSION,
PROGRAM_VERSION_REVISION);
auto peer_vn = std::tie(major, minor, subminor, revision);
if (peer_vn not_eq local_vn) {
game.peer().reset();
if (peer_vn > local_vn) {
push_notification(
pfrm,
game.state(),
locale_string(pfrm, LocaleString::update_required)->c_str());
} else {
auto str = locale_string(pfrm, LocaleString::peer_requires_update);
push_notification(pfrm, game.state(), str->c_str());
}
safe_disconnect(pfrm);
} else {
info(pfrm, "received valid program version");
}
}
void CommonNetworkListener::receive(const net_event::PlayerEnteredGate&,
Platform& pfrm,
Game& game)
{
if (game.peer()) {
game.peer()->warping() = true;
}
push_notification(
pfrm,
game.state(),
locale_string(pfrm, LocaleString::peer_transport_waiting)->c_str());
}
void CommonNetworkListener::receive(const net_event::Disconnect&,
Platform& pfrm,
Game& game)
{
pfrm.network_peer().disconnect();
}
bool within_view_frustum(const Platform::Screen& screen,
const Vec2<Float>& pos);
void show_boss_health(Platform& pfrm, Game& game, int bar, Float percentage)
{
if (bar >= ActiveState::boss_health_bar_count) {
return;
}
if (auto state = dynamic_cast<ActiveState*>(game.state())) {
if (not state->boss_health_bar_[bar]) {
state->boss_health_bar_[bar].emplace(
pfrm,
6,
OverlayCoord{u8(pfrm.screen().size().x / 8 - (2 + bar)), 1});
}
state->boss_health_bar_[bar]->set_health(percentage);
}
}
void hide_boss_health(Game& game)
{
if (auto state = dynamic_cast<ActiveState*>(game.state())) {
for (auto& bar : state->boss_health_bar_) {
bar.reset();
}
}
}
void push_notification(Platform& pfrm,
State* state,
const NotificationStr& string)
{
pfrm.sleep(3);
if (auto os = dynamic_cast<OverworldState*>(state)) {
os->notification_status = OverworldState::NotificationStatus::flash;
os->notification_str = string;
}
}
void repaint_health_score(Platform& pfrm,
Game& game,
std::optional<UIMetric>* health,
std::optional<UIMetric>* score,
std::optional<MediumIcon>* dodge,
UIMetric::Align align)
{
auto screen_tiles = calc_screen_tiles(pfrm);
const u8 x = align == UIMetric::Align::right ? screen_tiles.x - 2 : 1;
health->emplace(
pfrm,
OverlayCoord{x, u8(screen_tiles.y - (3 + game.powerups().size()))},
145,
(int)game.player().get_health(),
align);
score->emplace(
pfrm,
OverlayCoord{x, u8(screen_tiles.y - (2 + game.powerups().size()))},
146,
game.score(),
align);
}
void repaint_powerups(Platform& pfrm,
Game& game,
bool clean,
std::optional<UIMetric>* health,
std::optional<UIMetric>* score,
std::optional<MediumIcon>* dodge,
Buffer<UIMetric, Powerup::max_>* powerups,
UIMetric::Align align)
{
auto screen_tiles = calc_screen_tiles(pfrm);
auto get_normalized_param = [](Powerup& powerup) {
switch (powerup.display_mode_) {
case Powerup::DisplayMode::integer:
return powerup.parameter_.get();
case Powerup::DisplayMode::timestamp:
return powerup.parameter_.get() / 1000000;
}
return s32(0);
};
if (clean) {
repaint_health_score(pfrm, game, health, score, dodge, align);
powerups->clear();
u8 write_pos = screen_tiles.y - 2;
for (auto& powerup : game.powerups()) {
powerups->emplace_back(
pfrm,
OverlayCoord{(*health)->position().x, write_pos},
powerup.icon_index(),
get_normalized_param(powerup),
align);
powerup.dirty_ = false;
--write_pos;
}
} else {
for (u32 i = 0; i < game.powerups().size(); ++i) {
if (game.powerups()[i].dirty_) {
const auto p = get_normalized_param(game.powerups()[i]);
(*powerups)[i].set_value(p);
game.powerups()[i].dirty_ = false;
}
}
}
}
void update_powerups(Platform& pfrm,
Game& game,
std::optional<UIMetric>* health,
std::optional<UIMetric>* score,
std::optional<MediumIcon>* dodge,
Buffer<UIMetric, Powerup::max_>* powerups,
UIMetric::Align align)
{
bool update_powerups = false;
bool update_all = false;
for (auto it = game.powerups().begin(); it not_eq game.powerups().end();) {
if (it->parameter_.get() <= 0) {
it = game.powerups().erase(it);
update_powerups = true;
update_all = true;
} else {
if (it->dirty_) {
update_powerups = true;
}
++it;
}
}
if (game.powerups().size() not_eq powerups->size()) {
update_powerups = true;
update_all = true;
}
if (update_powerups) {
repaint_powerups(
pfrm, game, update_all, health, score, dodge, powerups, align);
}
}
void update_ui_metrics(Platform& pfrm,
Game& game,
Microseconds delta,
std::optional<UIMetric>* health,
std::optional<UIMetric>* score,
std::optional<MediumIcon>* dodge,
Buffer<UIMetric, Powerup::max_>* powerups,
Entity::Health last_health,
Score last_score,
bool dodge_was_ready,
UIMetric::Align align)
{
update_powerups(pfrm, game, health, score, dodge, powerups, align);
const auto screen_tiles = calc_screen_tiles(pfrm);
if (dodge and
static_cast<bool>(game.player().dodges()) not_eq dodge_was_ready) {
dodge->emplace(
pfrm,
game.player().dodges() ? 383 : 387,
OverlayCoord{1, u8(screen_tiles.y - (5 + game.powerups().size()))});
}
if (dodge and static_cast<bool>(game.player().dodges()) == 0) {
if (pfrm.keyboard().pressed(game.action1_key())) {
dodge->emplace(
pfrm,
379,
OverlayCoord{
1, u8(screen_tiles.y - (5 + game.powerups().size()))});
}
if (pfrm.keyboard().up_transition(game.action1_key())) {
dodge->emplace(
pfrm,
387,
OverlayCoord{
1, u8(screen_tiles.y - (5 + game.powerups().size()))});
}
}
if (last_health not_eq game.player().get_health()) {
net_event::PlayerHealthChanged hc;
hc.new_health_.set(game.player().get_health());
net_event::transmit(pfrm, hc);
(*health)->set_value(game.player().get_health());
}
if (last_score not_eq game.score()) {
(*score)->set_value(game.score());
}
(*health)->update(pfrm, delta);
(*score)->update(pfrm, delta);
for (auto& powerup : *powerups) {
powerup.update(pfrm, delta);
}
}
// FIXME: this shouldn't be global...
std::optional<Platform::Keyboard::RestoreState> restore_keystates;
int PauseScreenState::cursor_loc_ = 0;
static StatePoolInst state_pool_;
StatePtr null_state()
{
return {nullptr, state_deleter};
}
void state_deleter(State* s)
{
if (s) {
s->~State();
state_pool_.pool_.post(reinterpret_cast<byte*>(s));
}
}
StatePoolInst& state_pool()
{
return state_pool_;
}
constexpr int item_icon(Item::Type item)
{
int icon_base = 177;
return icon_base +
(static_cast<int>(item) - (static_cast<int>(Item::Type::coin) + 1)) *
4;
}
// Just so we don't have to type so much stuff. Some items will invariably use
// icons from existing items, so we still want the flexibility of setting icon
// values manually.
#define STANDARD_ITEM_HANDLER(TYPE) \
Item::Type::TYPE, item_icon(Item::Type::TYPE)
constexpr static const InventoryItemHandler inventory_handlers[] = {
{Item::Type::null,
0,
[](Platform&, Game&) { return null_state(); },
LocaleString::empty_inventory_str},
{STANDARD_ITEM_HANDLER(old_poster_1),
[](Platform& pfrm, Game&) {
StringBuffer<48> seed_packet_texture = "old_poster_";
seed_packet_texture += locale_language_name(locale_get_language());
seed_packet_texture += "_flattened";
if (not pfrm.overlay_texture_exists(seed_packet_texture.c_str())) {
seed_packet_texture = "old_poster_flattened";
}
return state_pool().create<ImageViewState>(seed_packet_texture.c_str(),
ColorConstant::steel_blue);
},
LocaleString::old_poster_title},
{Item::Type::postal_advert,
item_icon(Item::Type::old_poster_1),
[](Platform&, Game&) {
// static const auto str = "postal_advert_flattened";
// return state_pool().create<ImageViewState>(str,
// ColorConstant::steel_blue);
return null_state();
},
LocaleString::postal_advert_title},
{Item::Type::long_jump_z2,
item_icon(Item::Type::long_jump_z2),
[](Platform& pfrm, Game& game) {
const auto c = current_zone(game).energy_glow_color_;
pfrm.speaker().play_sound("bell", 5);
game.persistent_data().level_.set(boss_0_level);
game.score() = 0; // Otherwise, people could exploit the jump packs to
// keep replaying a zone, in order to get a really
// high score.
return state_pool().create<PreFadePauseState>(game, c);
},
LocaleString::long_jump_z2_title,
{LocaleString::sc_dialog_jumpdrive, LocaleString::empty},
InventoryItemHandler::yes},
{Item::Type::long_jump_z3,
item_icon(Item::Type::long_jump_z2),
[](Platform& pfrm, Game& game) {
const auto c = current_zone(game).energy_glow_color_;
pfrm.speaker().play_sound("bell", 5);
game.persistent_data().level_.set(boss_1_level);
game.score() = 0;
return state_pool().create<PreFadePauseState>(game, c);
},
LocaleString::long_jump_z3_title,
{LocaleString::sc_dialog_jumpdrive, LocaleString::empty},
InventoryItemHandler::yes},
{Item::Type::long_jump_z4,
item_icon(Item::Type::long_jump_z2),
[](Platform& pfrm, Game& game) {
const auto c = current_zone(game).energy_glow_color_;
pfrm.speaker().play_sound("bell", 5);
game.persistent_data().level_.set(boss_2_level);
game.score() = 0;
return state_pool().create<PreFadePauseState>(game, c);
},
LocaleString::long_jump_z4_title,
{LocaleString::sc_dialog_jumpdrive, LocaleString::empty},
InventoryItemHandler::yes},
{Item::Type::long_jump_home,
item_icon(Item::Type::long_jump_z2),
[](Platform& pfrm, Game& game) {
const auto c = current_zone(game).energy_glow_color_;
pfrm.speaker().play_sound("bell", 5);
game.persistent_data().level_.set(boss_max_level);
return state_pool().create<PreFadePauseState>(game, c);
},
LocaleString::long_jump_home_title,
{LocaleString::sc_dialog_jumpdrive, LocaleString::empty},
InventoryItemHandler::yes},
{STANDARD_ITEM_HANDLER(worker_notebook_1),
[](Platform& pfrm, Game&) {
return state_pool().create<NotebookState>(
locale_string(pfrm, LocaleString::worker_notebook_1_str));
},
LocaleString::worker_notebook_1_title},
{Item::Type::worker_notebook_2,
item_icon(Item::Type::worker_notebook_1),
[](Platform& pfrm, Game&) {
return state_pool().create<NotebookState>(
locale_string(pfrm, LocaleString::worker_notebook_2_str));
},
LocaleString::worker_notebook_2_title},
{STANDARD_ITEM_HANDLER(blaster),
[](Platform&, Game&) { return null_state(); },
LocaleString::blaster_title},
{STANDARD_ITEM_HANDLER(accelerator),
[](Platform&, Game& game) {
add_powerup(game, Powerup::Type::accelerator, 60);
return null_state();
},
LocaleString::accelerator_title,
{LocaleString::sc_dialog_accelerator, LocaleString::empty},
InventoryItemHandler::yes},
{STANDARD_ITEM_HANDLER(lethargy),
[](Platform& pfrm, Game& game) {
add_lethargy_powerup(pfrm, game);
net_event::LethargyActivated event;
net_event::transmit(pfrm, event);
return null_state();
},
LocaleString::lethargy_title,
{LocaleString::sc_dialog_lethargy, LocaleString::empty},
InventoryItemHandler::yes},
{STANDARD_ITEM_HANDLER(map_system),
[](Platform&, Game&) { return state_pool().create<MapSystemState>(); },
LocaleString::map_system_title,
{LocaleString::sc_dialog_map_system, LocaleString::empty}},
{STANDARD_ITEM_HANDLER(explosive_rounds_2),
[](Platform&, Game& game) {
add_powerup(game, Powerup::Type::explosive_rounds, 2);
return null_state();
},
LocaleString::explosive_rounds_title,
{LocaleString::sc_dialog_explosive_rounds, LocaleString::empty},
InventoryItemHandler::yes},
{STANDARD_ITEM_HANDLER(seed_packet),
[](Platform& pfrm, Game&) {
StringBuffer<48> seed_packet_texture = "seed_packet_";
seed_packet_texture += locale_language_name(locale_get_language());
seed_packet_texture += "_flattened";
if (not pfrm.overlay_texture_exists(seed_packet_texture.c_str())) {
seed_packet_texture = "seed_packet_flattened";
}
return state_pool().create<ImageViewState>(seed_packet_texture.c_str(),
ColorConstant::steel_blue);
},
LocaleString::seed_packet_title},
{STANDARD_ITEM_HANDLER(engineer_notebook_2),
[](Platform& pfrm, Game&) {
return state_pool().create<NotebookState>(
locale_string(pfrm, LocaleString::engineer_notebook_2_str));
},
LocaleString::engineer_notebook_2_title},
{Item::Type::engineer_notebook_1,
item_icon(Item::Type::engineer_notebook_2),
[](Platform& pfrm, Game&) {
return state_pool().create<NotebookState>(
locale_string(pfrm, LocaleString::engineer_notebook_1_str));
},
LocaleString::engineer_notebook_1_title},
{STANDARD_ITEM_HANDLER(signal_jammer),
[](Platform&, Game&) {
return state_pool().create<SignalJammerSelectorState>();
},
LocaleString::signal_jammer_title,
{LocaleString::sc_dialog_skip, LocaleString::empty},
InventoryItemHandler::custom},
{STANDARD_ITEM_HANDLER(navigation_pamphlet),
[](Platform& pfrm, Game&) {
return state_pool().create<NotebookState>(
locale_string(pfrm, LocaleString::navigation_pamphlet));
},
LocaleString::navigation_pamphlet_title},
{STANDARD_ITEM_HANDLER(orange),
[](Platform& pfrm, Game& game) {
game.player().heal(pfrm, game, 1);
if (game.inventory().item_count(Item::Type::orange_seeds) == 0) {
game.inventory().push_item(pfrm, game, Item::Type::orange_seeds);
}
return null_state();
},
LocaleString::orange_title,
{LocaleString::sc_dialog_orange, LocaleString::empty},
InventoryItemHandler::yes},
{STANDARD_ITEM_HANDLER(orange_seeds),
[](Platform&, Game&) { return null_state(); },
LocaleString::orange_seeds_title}};
const InventoryItemHandler* inventory_item_handler(Item::Type type)
{
for (auto& handler : inventory_handlers) {
if (handler.type_ == type) {
return &handler;
}
}
return nullptr;
}
Vec2<s8> get_constrained_player_tile_coord(Game& game)
{
auto player_tile = to_tile_coord(game.player().get_position().cast<s32>());
//u32 integer_text_length(int n);
if (not is_walkable(game.tiles().get_tile(player_tile.x, player_tile.y))) {
// Player movement isn't constrained to tiles exactly, and sometimes the
// player's map icon displays as inside of a wall.
if (is_walkable(
game.tiles().get_tile(player_tile.x + 1, player_tile.y))) {
player_tile.x += 1;
} else if (is_walkable(game.tiles().get_tile(player_tile.x,
player_tile.y + 1))) {
player_tile.y += 1;
}
}
return player_tile;
}
bool draw_minimap(Platform& pfrm,
Game& game,
Float percentage,
int& last_column,
int x_start,
int y_start,
int y_skip_top,
int y_skip_bot,
bool force_icons,
PathBuffer* path)
{
auto set_tile = [&](s8 x, s8 y, int icon, bool dodge = true) {
if (y < y_skip_top or y >= TileMap::height - y_skip_bot) {
return;
}
const auto tile =
pfrm.get_tile(Layer::overlay, x + x_start, y + y_start);
if (dodge and (tile == 133 or tile == 132)) {
// ...
} else {
pfrm.set_tile(Layer::overlay, x + x_start, y + y_start, icon);
}
};
auto render_map_icon = [&](Entity& entity, s16 icon) {
auto t = to_tile_coord(entity.get_position().cast<s32>());
if (is_walkable(game.tiles().get_tile(t.x, t.y))) {
set_tile(t.x, t.y, icon);
}
};
const auto current_column = std::min(
TileMap::width,
interpolate(TileMap::width, (decltype(TileMap::width))0, percentage));
game.tiles().for_each([&](u8 t, s8 x, s8 y) {
if (x > current_column or x <= last_column) {
return;
}
bool visited_nearby = false;
static const int offset = 3;
for (int x2 = std::max(0, x - (offset + 1));
x2 < std::min((int)TileMap::width, x + offset + 1);
++x2) {
for (int y2 = std::max(0, y - offset);
y2 < std::min((int)TileMap::height, y + offset);
++y2) {
if (std::get<BlindJumpGlobalData>(globals()).visited_.get(x2,
y2)) {
visited_nearby = true;
}
}
}
if (not visited_nearby) {
set_tile(x, y, is_walkable(t) ? 132 : 133, false);
} else if (is_walkable(t)) {
set_tile(x, y, 143, false);
} else {
if (is_walkable(game.tiles().get_tile(x, y - 1))) {
set_tile(x, y, 140);
} else {
set_tile(x, y, 144, false);
}
}
});
last_column = current_column;
if (force_icons or current_column == TileMap::width) {
if (path) {
for (u32 i = 0; i < path->size(); ++i) {
if (i > 0 and i < path->size() - 1) {
set_tile((*path)[i].x, (*path)[i].y, 131);
}
}
}
game.enemies().transform([&](auto& buf) {
for (auto& entity : buf) {
render_map_icon(*entity, 139);
}
});
render_map_icon(game.transporter(), 141);
for (auto& chest : game.details().get<ItemChest>()) {
if (chest->state() not_eq ItemChest::State::opened) {
render_map_icon(*chest, 138);
}
}
if (game.scavenger()) {
render_map_icon(*game.scavenger(), 392);
}
const auto player_tile = get_constrained_player_tile_coord(game);
set_tile(player_tile.x, player_tile.y, 142);
return true;
}
return false;
}
StatePtr State::initial(Platform& pfrm, Game& game)
{
pfrm.keyboard().poll();
if (game.persistent_data().settings_.initial_lang_selected_ and
not pfrm.keyboard().pressed<Key::select>()) {
return state_pool().create<TitleScreenState>();
} else {
if (not(lisp::length(lisp::get_var("languages")) == 1)) {
return state_pool().create<LanguageSelectionState>();
} else {
return state_pool().create<TitleScreenState>();
}
}
}
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <iostream>
#include <sstream>
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"
#include "rapidjson/prettywriter.h"
#include "../testeventloop.h"
using namespace apl;
class SerializeTest : public DocumentWrapper {
protected:
static void checkCommonProperties(const ComponentPtr& component, rapidjson::Value& json) {
ASSERT_EQ(component->getUniqueId(), json["id"].GetString());
ASSERT_EQ(component->getType(), json["type"].GetInt());
ASSERT_EQ(component->getCalculated(kPropertyAccessibilityLabel), json["accessibilityLabel"].GetString());
auto bounds = component->getCalculated(kPropertyBounds).getRect();
ASSERT_EQ(bounds.getX(), json["_bounds"][0].GetFloat());
ASSERT_EQ(bounds.getY(), json["_bounds"][1].GetFloat());
ASSERT_EQ(bounds.getWidth(), json["_bounds"][2].GetFloat());
ASSERT_EQ(bounds.getHeight(), json["_bounds"][3].GetFloat());
ASSERT_EQ(component->getCalculated(kPropertyChecked), json["checked"].GetBool());
ASSERT_EQ(component->getCalculated(kPropertyDisabled), json["disabled"].GetBool());
ASSERT_EQ(component->getCalculated(kPropertyDisplay), json["display"].GetDouble());
auto innerBounds = component->getCalculated(kPropertyInnerBounds).getRect();
ASSERT_EQ(innerBounds.getX(), json["_innerBounds"][0].GetFloat());
ASSERT_EQ(innerBounds.getY(), json["_innerBounds"][1].GetFloat());
ASSERT_EQ(innerBounds.getWidth(), json["_innerBounds"][2].GetFloat());
ASSERT_EQ(innerBounds.getHeight(), json["_innerBounds"][3].GetFloat());
ASSERT_EQ(component->getCalculated(kPropertyOpacity), json["opacity"].GetDouble());
auto transform = component->getCalculated(kPropertyTransform).getTransform2D();
ASSERT_EQ(transform.get().at(0), json["_transform"][0].GetFloat());
ASSERT_EQ(transform.get().at(1), json["_transform"][1].GetFloat());
ASSERT_EQ(transform.get().at(2), json["_transform"][2].GetFloat());
ASSERT_EQ(transform.get().at(3), json["_transform"][3].GetFloat());
ASSERT_EQ(transform.get().at(4), json["_transform"][4].GetFloat());
ASSERT_EQ(transform.get().at(5), json["_transform"][5].GetFloat());
ASSERT_EQ(component->getCalculated(kPropertyUser).size(), json["_user"].MemberCount());
ASSERT_EQ(component->getCalculated(kPropertyFocusable), json["_focusable"].GetBool());
}
};
static const char *SERIALIZE_COMPONENTS = R"({
"type": "APL",
"version": "1.1",
"mainTemplate": {
"items": {
"type": "Container",
"width": "100%",
"height": "100%",
"numbered": true,
"items": [
{
"type": "Image",
"id": "image",
"source": "http://images.amazon.com/image/foo.png",
"overlayColor": "red",
"overlayGradient": {
"colorRange": [
"blue",
"red"
]
},
"filters": {
"type": "Blur",
"radius": 22
}
},
{
"type": "Text",
"id": "text",
"text": "<span color='red'>colorful</span> <b>Styled</b> <i>text</i>"
},
{
"type": "ScrollView",
"id": "scroll"
},
{
"type": "Frame",
"id": "frame",
"backgroundColor": "red",
"borderColor": "blue",
"borderBottomLeftRadius": "1dp",
"borderBottomRightRadius": "2dp",
"borderTopLeftRadius": "3dp",
"borderTopRightRadius": "4dp",
"actions": {
"name": "green",
"label": "Change the border to green",
"commands": {
"type": "SetValue",
"property": "borderColor",
"value": "green"
}
}
},
{
"type": "Sequence",
"id": "sequence",
"data": [
1,
2,
3,
4,
5
],
"items": [
{
"type": "Text",
"id": "text",
"width": 100,
"height": 100,
"text": "${data}"
}
]
},
{
"type": "TouchWrapper",
"id": "touch",
"height": 50,
"onPress": {
"type": "SendEvent",
"arguments": [
"${event.source.handler}",
"${event.source.value}",
"${event.target.opacity}"
],
"components": [
"text"
]
}
},
{
"type": "Pager",
"id": "pager",
"data": [
1,
2,
3,
4,
5
],
"items": [
{
"type": "Text",
"id": "text",
"width": 100,
"height": 100,
"text": "${data}"
}
]
},
{
"type": "VectorGraphic",
"id": "vector",
"source": "iconWifi3"
},
{
"type": "Video",
"id": "video",
"source": [
"URL1",
{
"url": "URL2"
},
{
"description": "Sample video.",
"duration": 1000,
"url": "URL3",
"repeatCount": 2,
"offset": 100
}
]
}
]
}
}
})";
TEST_F(SerializeTest, Components)
{
loadDocument(SERIALIZE_COMPONENTS);
ASSERT_TRUE(component);
rapidjson::Document doc;
auto json = component->serialize(doc.GetAllocator());
ASSERT_EQ(kComponentTypeContainer, component->getType());
checkCommonProperties(component, json);
auto image = context->findComponentById("image");
ASSERT_TRUE(image);
auto& imageJson = json["children"][0];
checkCommonProperties(image, imageJson);
ASSERT_EQ(image->getCalculated(kPropertyAlign), imageJson["align"].GetDouble());
ASSERT_EQ(image->getCalculated(kPropertyBorderRadius).getAbsoluteDimension(), imageJson["borderRadius"].GetDouble());
auto filter = image->getCalculated(kPropertyFilters).getArray().at(0).getFilter();
ASSERT_EQ(filter.getType(), imageJson["filters"][0]["type"]);
ASSERT_EQ(filter.getValue(FilterProperty::kFilterPropertyRadius).getAbsoluteDimension(), imageJson["filters"][0]["radius"].GetDouble());
ASSERT_EQ(image->getCalculated(kPropertyOverlayColor).getColor(), Color(session, imageJson["overlayColor"].GetString()));
auto gradient = image->getCalculated(kPropertyOverlayGradient).getGradient();
ASSERT_EQ(gradient.getType(), imageJson["overlayGradient"]["type"].GetDouble());
ASSERT_EQ(gradient.getAngle(), imageJson["overlayGradient"]["angle"].GetDouble());
ASSERT_EQ(gradient.getColorRange().size(), imageJson["overlayGradient"]["colorRange"].Size());
ASSERT_EQ(gradient.getInputRange().size(), imageJson["overlayGradient"]["inputRange"].Size());
ASSERT_EQ(image->getCalculated(kPropertyScale), imageJson["scale"].GetDouble());
ASSERT_EQ(image->getCalculated(kPropertySource), imageJson["source"].GetString());
auto text = context->findComponentById("text");
ASSERT_TRUE(text);
auto& textJson = json["children"][1];
checkCommonProperties(text, textJson);
ASSERT_EQ(text->getCalculated(kPropertyColor).getColor(), Color(session, textJson["color"].GetString()));
ASSERT_EQ(text->getCalculated(kPropertyColorKaraokeTarget).getColor(), Color(session, textJson["_colorKaraokeTarget"].GetString()));
ASSERT_EQ(text->getCalculated(kPropertyFontFamily), textJson["fontFamily"].GetString());
ASSERT_EQ(text->getCalculated(kPropertyFontSize).getAbsoluteDimension(), textJson["fontSize"].GetDouble());
ASSERT_EQ(text->getCalculated(kPropertyFontStyle), textJson["fontStyle"].GetDouble());
ASSERT_EQ(text->getCalculated(kPropertyFontWeight), textJson["fontWeight"].GetDouble());
ASSERT_EQ(text->getCalculated(kPropertyLetterSpacing).getAbsoluteDimension(), textJson["letterSpacing"].GetDouble());
ASSERT_EQ(text->getCalculated(kPropertyLineHeight), textJson["lineHeight"].GetDouble());
ASSERT_EQ(text->getCalculated(kPropertyMaxLines), textJson["maxLines"].GetDouble());
auto styledText = text->getCalculated(kPropertyText).getStyledText();
ASSERT_EQ(styledText.getText(), textJson["text"]["text"].GetString());
ASSERT_EQ(styledText.getSpans().size(), textJson["text"]["spans"].Size());
ASSERT_EQ(styledText.getSpans()[0].attributes.size(), textJson["text"]["spans"][0][3].Size());
ASSERT_EQ(text->getCalculated(kPropertyTextAlignAssigned), textJson["_textAlign"].GetDouble());
ASSERT_EQ(text->getCalculated(kPropertyTextAlignVertical), textJson["textAlignVertical"].GetDouble());
auto scroll = context->findComponentById("scroll");
ASSERT_TRUE(scroll);
auto& scrollJson = json["children"][2];
checkCommonProperties(scroll, scrollJson);
ASSERT_EQ(scroll->getCalculated(kPropertyScrollPosition).asNumber(), scrollJson["_scrollPosition"].GetDouble());
auto frame = context->findComponentById("frame");
ASSERT_TRUE(frame);
auto& frameJson = json["children"][3];
checkCommonProperties(frame, frameJson);
ASSERT_EQ(frame->getCalculated(kPropertyBackgroundColor).getColor(), Color(session, frameJson["backgroundColor"].GetString()));
auto radii = frame->getCalculated(kPropertyBorderRadii).getRadii();
ASSERT_EQ(radii.get().at(0), frameJson["_borderRadii"][0].GetFloat());
ASSERT_EQ(radii.get().at(1), frameJson["_borderRadii"][1].GetFloat());
ASSERT_EQ(radii.get().at(2), frameJson["_borderRadii"][2].GetFloat());
ASSERT_EQ(radii.get().at(3), frameJson["_borderRadii"][3].GetFloat());
ASSERT_EQ(frame->getCalculated(kPropertyBorderColor).getColor(), Color(session, frameJson["borderColor"].GetString()));
ASSERT_EQ(frame->getCalculated(kPropertyBorderWidth).getAbsoluteDimension(), frameJson["borderWidth"].GetDouble());
auto action = frame->getCalculated(kPropertyAccessibilityActions).at(0).getAccessibilityAction();
ASSERT_EQ(action->getName(), frameJson["action"][0]["name"].GetString());
ASSERT_EQ(action->getLabel(), frameJson["action"][0]["label"].GetString());
ASSERT_EQ(action->enabled(), frameJson["action"][0]["enabled"].GetBool());
ASSERT_FALSE(frameJson["action"][0].HasMember("commands")); // Commands don't get serialized
auto sequence = context->findComponentById("sequence");
ASSERT_TRUE(sequence);
auto& sequenceJson = json["children"][4];
checkCommonProperties(sequence, sequenceJson);
ASSERT_EQ(sequence->getCalculated(kPropertyScrollDirection), sequenceJson["scrollDirection"].GetDouble());
ASSERT_EQ(sequence->getCalculated(kPropertyScrollPosition).asNumber(), sequenceJson["_scrollPosition"].GetDouble());
auto touch = context->findComponentById("touch");
ASSERT_TRUE(touch);
auto& touchJson = json["children"][5];
checkCommonProperties(touch, touchJson);
auto pager = context->findComponentById("pager");
ASSERT_TRUE(pager);
auto& pagerJson = json["children"][6];
checkCommonProperties(pager, pagerJson);
ASSERT_EQ(pager->getCalculated(kPropertyNavigation), pagerJson["navigation"].GetDouble());
ASSERT_EQ(pager->getCalculated(kPropertyCurrentPage), pagerJson["_currentPage"].GetDouble());
auto vector = context->findComponentById("vector");
ASSERT_TRUE(vector);
auto& vectorJson = json["children"][7];
checkCommonProperties(vector, vectorJson);
ASSERT_EQ(vector->getCalculated(kPropertyAlign), vectorJson["align"].GetDouble());
ASSERT_TRUE(vectorJson["graphic"].IsNull());
ASSERT_TRUE(vectorJson["mediaBounds"].IsNull());
ASSERT_EQ(vector->getCalculated(kPropertyScale), vectorJson["scale"].GetDouble());
ASSERT_EQ(vector->getCalculated(kPropertySource), vectorJson["source"].GetString());
auto video = context->findComponentById("video");
ASSERT_TRUE(video);
auto& videoJson = json["children"][8];
checkCommonProperties(video, videoJson);
ASSERT_EQ(video->getCalculated(kPropertyAudioTrack), videoJson["audioTrack"].GetDouble());
ASSERT_EQ(video->getCalculated(kPropertyAutoplay), videoJson["autoplay"].GetBool());
ASSERT_EQ(video->getCalculated(kPropertyScale), videoJson["scale"].GetDouble());
auto videoSource = video->getCalculated(kPropertySource).getArray();
ASSERT_EQ(3, videoSource.size());
ASSERT_EQ(videoSource.size(), videoJson["source"].Size());
auto source3 = videoSource.at(2).getMediaSource();
ASSERT_EQ(source3.getUrl(), videoJson["source"][2]["url"].GetString());
ASSERT_EQ(source3.getDescription(), videoJson["source"][2]["description"].GetString());
ASSERT_EQ(source3.getDuration(), videoJson["source"][2]["duration"].GetInt());
ASSERT_EQ(source3.getRepeatCount(), videoJson["source"][2]["repeatCount"].GetInt());
ASSERT_EQ(source3.getOffset(), videoJson["source"][2]["offset"].GetInt());
}
TEST_F(SerializeTest, Dirty)
{
loadDocument(SERIALIZE_COMPONENTS);
ASSERT_EQ(kComponentTypeContainer, component->getType());
auto text = std::static_pointer_cast<CoreComponent>(context->findComponentById("text"));
ASSERT_TRUE(text);
text->setProperty(kPropertyText, "Not very styled text.");
rapidjson::Document doc;
auto json = text->serializeDirty(doc.GetAllocator());
ASSERT_EQ(2, json.MemberCount());
ASSERT_STREQ("Not very styled text.", json["text"]["text"].GetString());
ASSERT_TRUE(json["text"]["spans"].Empty());
}
TEST_F(SerializeTest, Event)
{
loadDocument(SERIALIZE_COMPONENTS);
ASSERT_EQ(kComponentTypeContainer, component->getType());
auto text = std::static_pointer_cast<CoreComponent>(context->findComponentById("text"));
ASSERT_TRUE(text);
auto touch = context->findComponentById("touch");
ASSERT_TRUE(touch);
auto touchBounds = touch->getGlobalBounds();
ASSERT_EQ(Rect(0, 310, 1024, 50), touchBounds);
root->handlePointerEvent(PointerEvent(kPointerDown, Point(1,311)));
root->handlePointerEvent(PointerEvent(kPointerUp, Point(1,311)));
ASSERT_TRUE(root->hasEvent());
auto event = root->popEvent();
rapidjson::Document doc;
auto json = event.serialize(doc.GetAllocator());
//TODO: Unclear what we should do with actionRef in terms of serialization.
ASSERT_EQ(4, json.MemberCount());
ASSERT_EQ(kEventTypeSendEvent, json["type"].GetInt());
ASSERT_STREQ("Press", json["arguments"][0].GetString());
ASSERT_EQ(false, json["arguments"][1].GetBool());
ASSERT_EQ(1.0, json["arguments"][2].GetDouble());
ASSERT_TRUE(json["components"].HasMember("text"));
ASSERT_STREQ("<span color='red'>colorful</span> <b>Styled</b> <i>text</i>", json["components"]["text"].GetString());
ASSERT_STREQ("Press", json["source"]["handler"].GetString());
ASSERT_STREQ("touch", json["source"]["id"].GetString());
ASSERT_STREQ("TouchWrapper", json["source"]["source"].GetString());
ASSERT_EQ(touch->getUniqueId(), json["source"]["uid"].GetString());
ASSERT_EQ(false, json["source"]["value"].GetBool());
}
const static char * SERIALIZE_ALL = R"({
"type": "APL",
"version": "1.1",
"layouts": {
"MyLayout": {
"parameters": "MyText",
"items": {
"type": "Text",
"text": "${MyText}",
"width": "100%",
"textAlign": "center"
}
}
},
"mainTemplate": {
"items": {
"type": "MyLayout",
"MyText": "Hello",
"width": "100%",
"height": "50%"
}
}
})";
const static char *SERIALIZE_ALL_RESULT = R"({
"type": "Text",
"__id": "",
"__inheritParentState": false,
"__style": "",
"__path": "_main/layouts/MyLayout/items",
"accessibilityLabel": "",
"action": [],
"_bounds": [
0,
0,
1280,
400
],
"checked": false,
"color": "#fafafaff",
"_colorKaraokeTarget": "#fafafaff",
"_colorNonKaraoke": "#fafafaff",
"description": "",
"disabled": false,
"display": "normal",
"entities": [],
"_focusable": false,
"fontFamily": "sans-serif",
"fontSize": 40,
"fontStyle": "normal",
"fontWeight": "normal",
"handleTick": [],
"height": "50%",
"_innerBounds": [
0,
0,
1280,
400
],
"lang": "",
"layoutDirection": "inherit",
"_layoutDirection": "LTR",
"letterSpacing": 0,
"lineHeight": 1.25,
"maxHeight": null,
"maxLines": 0,
"maxWidth": null,
"minHeight": 0,
"minWidth": 0,
"onMount": [],
"opacity": 1,
"padding": [],
"paddingBottom": null,
"paddingEnd": null,
"paddingLeft": null,
"paddingRight": null,
"paddingTop": null,
"paddingStart": null,
"preserve": [],
"role": "none",
"shadowColor": "#00000000",
"shadowHorizontalOffset": 0,
"shadowRadius": 0,
"shadowVerticalOffset": 0,
"speech": "",
"text": {
"text": "Hello",
"spans": []
},
"textAlign": "center",
"_textAlign": "center",
"textAlignVertical": "auto",
"_transform": [
1,
0,
0,
1,
0,
0
],
"transform": null,
"_user": {},
"width": "100%",
"onCursorEnter": [],
"onCursorExit": [],
"_laidOut": true,
"_visualHash": "[HASH]"
})";
TEST_F(SerializeTest, SerializeAll)
{
metrics.size(1280, 800);
loadDocument(SERIALIZE_ALL);
ASSERT_TRUE(component);
auto visualHash = component->getCalculated(kPropertyVisualHash).getString();
rapidjson::Document doc;
auto json = component->serializeAll(doc.GetAllocator());
// Need to remove the "id" element - it changes depending on the number of unit tests executed.
json.RemoveMember("id");
// Load the JSON result above
rapidjson::Document result;
rapidjson::ParseResult ok = result.Parse(SERIALIZE_ALL_RESULT);
ASSERT_TRUE(ok);
result["_visualHash"].SetString(visualHash.c_str(), doc.GetAllocator());
// Compare the output - they should be the same
ASSERT_TRUE(json == result);
}
static const char *CHILDREN_UPDATE = R"({
"type": "APL",
"version": "1.0",
"mainTemplate": {
"item": {
"type": "Container",
"data": "${TestArray}",
"item": {
"type": "Text",
"text": "${data} ${index} ${dataIndex} ${length}"
}
}
}
})";
TEST_F(SerializeTest, ChildrenUpdateNotification)
{
auto myArray = LiveArray::create(ObjectArray{"A", "B"});
config->liveData("TestArray", myArray);
loadDocument(CHILDREN_UPDATE);
ASSERT_TRUE(component);
ASSERT_EQ(2, component->getChildCount());
auto removedId = component->getChildAt(1)->getUniqueId();
myArray->insert(0, "Z"); // Z, A, B
myArray->push_back("C"); // Z, A, B, C
myArray->remove(2); // Z, A, C
root->clearPending();
ASSERT_EQ(3, component->getChildCount());
rapidjson::Document doc;
auto json = component->serializeDirty(doc.GetAllocator());
ASSERT_EQ(2, json.MemberCount());
auto& notify = json["_notify_childrenChanged"];
ASSERT_EQ(3, notify.Size());
ASSERT_EQ(0.0, notify[0]["index"].GetDouble());
ASSERT_EQ(component->getChildAt(0)->getUniqueId(), notify[0]["uid"].GetString());
ASSERT_STREQ("insert", notify[0]["action"].GetString());
ASSERT_EQ(2.0, notify[1]["index"].GetDouble());
ASSERT_EQ(component->getChildAt(2)->getUniqueId(), notify[1]["uid"].GetString());
ASSERT_STREQ("insert", notify[1]["action"].GetString());
ASSERT_EQ(3.0, notify[2]["index"].GetDouble());
ASSERT_EQ(removedId, notify[2]["uid"].GetString());
ASSERT_STREQ("remove", notify[2]["action"].GetString());
}
static const char *SEQUENCE_CHILDREN_UPDATE = R"({
"type": "APL",
"version": "1.0",
"mainTemplate": {
"item": {
"type": "Sequence",
"data": "${TestArray}",
"item": {
"type": "Text",
"height": 100,
"width": "100%",
"text": "${data} ${index} ${dataIndex} ${length}"
}
}
}
})";
TEST_F(SerializeTest, SequencePositionChildrenUpdate)
{
auto myArray = LiveArray::create(ObjectArray{"A", "B"});
config->liveData("TestArray", myArray);
loadDocument(SEQUENCE_CHILDREN_UPDATE);
ASSERT_TRUE(component);
ASSERT_EQ(2, component->getChildCount());
myArray->insert(0, "Z"); // Z, A, B
myArray->remove(2); // Z, A
root->clearPending();
ASSERT_EQ(2, component->getChildCount());
ASSERT_EQ(100, component->getCalculated(kPropertyScrollPosition).asNumber());
rapidjson::Document doc;
auto json = component->serializeDirty(doc.GetAllocator());
ASSERT_EQ(3, json.MemberCount());
ASSERT_EQ(2, json["_notify_childrenChanged"].Size());
ASSERT_EQ(component->getCalculated(kPropertyScrollPosition).asNumber(), json["_scrollPosition"].GetDouble());
}
static const char *PAGER_CHILDREN_UPDATE = R"({
"type": "APL",
"version": "1.0",
"mainTemplate": {
"item": {
"type": "Pager",
"data": "${TestArray}",
"item": {
"type": "Text",
"height": 100,
"width": "100%",
"text": "${data} ${index} ${dataIndex} ${length}"
}
}
}
})";
TEST_F(SerializeTest, PagerPositionChildrenUpdate)
{
auto myArray = LiveArray::create(ObjectArray{"A", "B"});
config->liveData("TestArray", myArray);
loadDocument(PAGER_CHILDREN_UPDATE);
ASSERT_TRUE(component);
ASSERT_EQ(2, component->getChildCount());
ASSERT_EQ(0, component->getCalculated(kPropertyCurrentPage).getInteger());
myArray->insert(0, "Z"); // Z, A, B
myArray->remove(2); // Z, A
root->clearPending();
ASSERT_EQ(2, component->getChildCount());
rapidjson::Document doc;
auto json = component->serializeDirty(doc.GetAllocator());
ASSERT_EQ(3, json.MemberCount());
ASSERT_EQ(2, json["_notify_childrenChanged"].Size());
ASSERT_EQ(1, component->getCalculated(kPropertyCurrentPage).getInteger());
ASSERT_EQ(component->getCalculated(kPropertyCurrentPage).getInteger(), json["_currentPage"].GetDouble());
}
static const char *SERIALIE_VG = R"({
"type": "APL",
"version": "1.4",
"mainTemplate": {
"items": {
"type": "VectorGraphic",
"height": 100,
"width": 100,
"source": "box"
}
},
"graphics": {
"box": {
"type": "AVG",
"version": "1.1",
"height": 100,
"width": 100,
"resources": [
{
"gradients": {
"strokeGradient": {
"type": "linear",
"colorRange": [ "blue", "white" ],
"inputRange": [0, 1],
"x1": 0.1,
"y1": 0.2,
"x2": 0.3,
"y2": 0.4
}
},
"patterns": {
"fillPattern": {
"height": 18,
"width": 18,
"item": {
"type": "path",
"pathData": "M0,9 a9,9 0 1 1 18,0 a9,9 0 1 1 -18,0",
"fill": "red"
}
}
}
}
],
"items": {
"type": "group",
"clipPath": "M 0,0",
"opacity": 0.7,
"transform": "translate(1 1) ",
"items": [
{
"type": "path",
"fill": "@fillPattern",
"fillOpacity": 0.1,
"fillTransform": "skewX(7) ",
"pathData": "M 1,1",
"pathLength": 5,
"stroke": "@strokeGradient",
"strokeDashArray": [1, 2, 3],
"strokeDashOffset": 1,
"strokeLineCap": "butt",
"strokeLineJoin": "bevel",
"strokeMiterLimit": 2,
"strokeOpacity": 0.9,
"strokeTransform": "skewY(8) ",
"strokeWidth": 2
},
{
"type": "text",
"fill": "red",
"fillOpacity": 0.1,
"fillTransform": "skewX(7) ",
"fontFamily": "Violet",
"fontSize": 50,
"fontStyle": "italic",
"fontWeight": "bold",
"letterSpacing": 3,
"stroke": "green",
"strokeOpacity": 0.9,
"strokeTransform": "skewY(8) ",
"strokeWidth": 2,
"text": "Text",
"textAnchor": "middle",
"x": 5,
"y": 6
}
]
}
}
}
})";
TEST_F(SerializeTest, AVG)
{
loadDocument(SERIALIE_VG);
ASSERT_TRUE(component);
ASSERT_EQ(kComponentTypeVectorGraphic, component->getType());
rapidjson::Document doc;
auto json = component->serialize(doc.GetAllocator());
checkCommonProperties(component, json);
auto graphic = component->getCalculated(kPropertyGraphic).getGraphic();
auto& graphicJson = json["graphic"];
ASSERT_EQ(graphicJson["isValid"].GetBool(), true);
ASSERT_EQ(graphicJson["intrinsicWidth"].GetDouble(), graphic->getIntrinsicWidth());
ASSERT_EQ(graphicJson["intrinsicHeight"].GetDouble(), graphic->getIntrinsicHeight());
ASSERT_EQ(graphicJson["viewportWidth"].GetDouble(), graphic->getViewportWidth());
ASSERT_EQ(graphicJson["viewportHeight"].GetDouble(), graphic->getViewportHeight());
auto graphicRoot = graphic->getRoot();
auto& graphicRootJson = graphicJson["root"];
ASSERT_EQ(graphicRootJson["id"].GetInt(), graphicRoot->getId());
ASSERT_EQ(graphicRootJson["props"]["height_actual"].GetDouble(), graphicRoot->getValue(kGraphicPropertyHeightActual).getAbsoluteDimension());
ASSERT_EQ(graphicRootJson["props"]["width_actual"].GetDouble(), graphicRoot->getValue(kGraphicPropertyWidthActual).getAbsoluteDimension());
ASSERT_EQ(graphicRootJson["props"]["viewportHeight_actual"].GetDouble(), graphicRoot->getValue(kGraphicPropertyViewportHeightActual).getDouble());
ASSERT_EQ(graphicRootJson["props"]["viewportWidth_actual"].GetDouble(), graphicRoot->getValue(kGraphicPropertyViewportWidthActual).getDouble());
auto group = graphicRoot->getChildAt(0);
auto& groupJson = graphicRootJson["children"][0];
ASSERT_EQ(groupJson["id"].GetInt(), group->getId());
ASSERT_EQ(groupJson["type"].GetInt(), group->getType());
ASSERT_EQ(groupJson["props"]["clipPath"].GetString(), group->getValue(kGraphicPropertyClipPath).getString());
ASSERT_EQ(groupJson["props"]["opacity"].GetDouble(), group->getValue(kGraphicPropertyOpacity).getDouble());
ASSERT_TRUE(groupJson["props"]["_transform"].IsArray());
auto path = group->getChildAt(0);
auto& pathJson = groupJson["children"][0];
ASSERT_EQ(pathJson["id"].GetInt(), path->getId());
ASSERT_EQ(pathJson["type"].GetInt(), path->getType());
ASSERT_EQ(pathJson["props"]["fillOpacity"].GetDouble(), path->getValue(kGraphicPropertyFillOpacity).getDouble());
ASSERT_TRUE(pathJson["props"]["_fillTransform"].IsArray());
ASSERT_EQ(pathJson["props"]["pathData"].GetString(), path->getValue(kGraphicPropertyPathData).getString());
ASSERT_EQ(pathJson["props"]["pathLength"].GetDouble(), path->getValue(kGraphicPropertyPathLength).getDouble());
ASSERT_TRUE(pathJson["props"]["strokeDashArray"].IsArray());
ASSERT_EQ(pathJson["props"]["strokeDashOffset"].GetDouble(), path->getValue(kGraphicPropertyStrokeDashOffset).getDouble());
ASSERT_EQ(pathJson["props"]["strokeLineCap"].GetDouble(), path->getValue(kGraphicPropertyStrokeLineCap).getInteger());
ASSERT_EQ(pathJson["props"]["strokeLineJoin"].GetDouble(), path->getValue(kGraphicPropertyStrokeLineJoin).getInteger());
ASSERT_EQ(pathJson["props"]["strokeMiterLimit"].GetDouble(), path->getValue(kGraphicPropertyStrokeMiterLimit).getInteger());
ASSERT_EQ(pathJson["props"]["strokeOpacity"].GetDouble(), path->getValue(kGraphicPropertyStrokeOpacity).getDouble());
ASSERT_TRUE(pathJson["props"]["_strokeTransform"].IsArray());
ASSERT_EQ(pathJson["props"]["strokeWidth"].GetDouble(), path->getValue(kGraphicPropertyStrokeWidth).getDouble());
auto gradient = path->getValue(kGraphicPropertyStroke).getGradient();
auto& gradientJson = pathJson["props"]["stroke"];
ASSERT_EQ(gradientJson["type"].GetDouble(), gradient.getType());
ASSERT_TRUE(gradientJson["colorRange"].IsArray());
ASSERT_TRUE(gradientJson["inputRange"].IsArray());
ASSERT_EQ(gradientJson["spreadMethod"].GetDouble(), gradient.getProperty(kGradientPropertySpreadMethod).getInteger());
ASSERT_EQ(gradientJson["x1"].GetDouble(), gradient.getProperty(kGradientPropertyX1).getDouble());
ASSERT_EQ(gradientJson["y1"].GetDouble(), gradient.getProperty(kGradientPropertyY1).getDouble());
ASSERT_EQ(gradientJson["x2"].GetDouble(), gradient.getProperty(kGradientPropertyX2).getDouble());
ASSERT_EQ(gradientJson["y2"].GetDouble(), gradient.getProperty(kGradientPropertyY2).getDouble());
auto pattern = path->getValue(kGraphicPropertyFill).getGraphicPattern();
auto& patternJson = pathJson["props"]["fill"];
ASSERT_EQ(patternJson["id"].GetString(), pattern->getId());
ASSERT_EQ(patternJson["description"].GetString(), pattern->getDescription());
ASSERT_EQ(patternJson["width"].GetDouble(), pattern->getWidth());
ASSERT_EQ(patternJson["height"].GetDouble(), pattern->getHeight());
auto patternPath = pattern->getItems().at(0);
auto& patternPathJson = patternJson["items"][0];
// Just check type and ID. It's just regular Path.
ASSERT_EQ(patternPathJson["id"].GetInt(), patternPath->getId());
ASSERT_EQ(patternPathJson["type"].GetInt(), patternPath->getType());
auto text = group->getChildAt(1);
auto& textJson = groupJson["children"][1];
ASSERT_EQ(textJson["id"].GetInt(), text->getId());
ASSERT_EQ(textJson["type"].GetInt(), text->getType());
ASSERT_EQ(textJson["props"]["x"].GetDouble(), text->getValue(kGraphicPropertyCoordinateX).getDouble());
ASSERT_EQ(textJson["props"]["y"].GetDouble(), text->getValue(kGraphicPropertyCoordinateY).getDouble());
ASSERT_EQ(textJson["props"]["fill"].GetString(), text->getValue(kGraphicPropertyFill).asString());
ASSERT_EQ(textJson["props"]["fillOpacity"].GetDouble(), text->getValue(kGraphicPropertyFillOpacity).getDouble());
ASSERT_EQ(textJson["props"]["fontFamily"].GetString(), text->getValue(kGraphicPropertyFontFamily).getString());
ASSERT_EQ(textJson["props"]["fontSize"].GetDouble(), text->getValue(kGraphicPropertyFontSize).getDouble());
ASSERT_EQ(textJson["props"]["fontStyle"].GetDouble(), text->getValue(kGraphicPropertyFontStyle).getInteger());
ASSERT_EQ(textJson["props"]["fontWeight"].GetDouble(), text->getValue(kGraphicPropertyFontWeight).getDouble());
ASSERT_EQ(textJson["props"]["letterSpacing"].GetDouble(), text->getValue(kGraphicPropertyLetterSpacing).getDouble());
ASSERT_EQ(textJson["props"]["stroke"].GetString(), text->getValue(kGraphicPropertyStroke).asString());
ASSERT_EQ(textJson["props"]["strokeOpacity"].GetDouble(), text->getValue(kGraphicPropertyStrokeOpacity).getDouble());
ASSERT_EQ(textJson["props"]["strokeWidth"].GetDouble(), text->getValue(kGraphicPropertyStrokeWidth).getDouble());
ASSERT_EQ(textJson["props"]["text"].GetString(), text->getValue(kGraphicPropertyText).getString());
ASSERT_EQ(textJson["props"]["textAnchor"].GetDouble(), text->getValue(kGraphicPropertyTextAnchor).getInteger());
}
static const char *MUSIC_DOC = R"({
"type": "APL",
"version": "1.5",
"mainTemplate": {
"items": [
{
"type": "Container",
"height": "100%",
"width": "100%",
"id": "document",
"items": [
{
"type": "Container",
"position": "relative",
"id": "view",
"height": "16vh",
"display": "none",
"grow": 1,
"items": [
{
"type": "Sequence",
"height": "16vh",
"alignSelf": "center",
"position": "absolute",
"id": "sequence",
"numbered": true,
"data": [
"first",
"second"
],
"grow": 1,
"item": {
"type": "VectorGraphic",
"source": "diamond",
"scale": "best-fit",
"width": "100%",
"align": "center",
"Tick": "${elapsedTime}"
}
}
]
}
]
}
]
},
"graphics": {
"diamond": {
"type": "AVG",
"version": "1.1",
"parameters": [
{
"name": "Tick",
"type": "number",
"default": 0
},
{
"name": "Colors",
"type": "array",
"default": ["yellow", "orange", "red"]
}
],
"width": 48,
"height": 48,
"items": {
"type": "path",
"fill": "${Colors[Tick % Colors.length]}",
"stroke": "${Colors[(Tick+1) % Colors.length]}",
"strokeWidth": 3,
"pathData": "M 24 0 L 48 24 L 24 48 L 0 24 z"
}
}
}
})";
TEST_F(SerializeTest, AVGInSequence) {
loadDocument(MUSIC_DOC);
ASSERT_TRUE(component);
advanceTime(5);
ASSERT_TRUE(root->isDirty());
ASSERT_EQ(2, root->getDirty().size());
for (auto& c : root->getDirty()) {
rapidjson::Document doc;
auto json = c->serializeDirty(doc.GetAllocator());
ASSERT_TRUE(json.HasMember("graphic"));
ASSERT_TRUE(json["graphic"]["isValid"].GetBool());
ASSERT_EQ(json["graphic"]["intrinsicWidth"].GetDouble(), 48.0);
ASSERT_EQ(json["graphic"]["intrinsicHeight"].GetDouble(), 48.0);
ASSERT_EQ(json["graphic"]["viewportWidth"].GetDouble(), 48.0);
ASSERT_EQ(json["graphic"]["viewportHeight"].GetDouble(), 48.0);
ASSERT_EQ(json["graphic"]["root"]["props"]["width_actual"].GetDouble(), 48.0);
ASSERT_EQ(json["graphic"]["root"]["props"]["height_actual"].GetDouble(), 48.0);
ASSERT_EQ(json["graphic"]["root"]["props"]["viewportWidth_actual"].GetDouble(), 48.0);
ASSERT_EQ(json["graphic"]["root"]["props"]["viewportHeight_actual"].GetDouble(), 48.0);
ASSERT_STREQ(json["graphic"]["root"]["children"][0]["props"]["fill"].GetString(), "#ff0000ff");
ASSERT_STREQ(json["graphic"]["root"]["children"][0]["props"]["stroke"].GetString(), "#ffff00ff");
ASSERT_EQ(json["graphic"]["root"]["children"][0]["props"]["strokeWidth"].GetDouble(), 3.0);
}
}
static const char *SINGULAR_TRANSFORM = R"({
"type": "APL",
"version": "1.5",
"mainTemplate": {
"items": [
{
"type": "Container",
"height": "100%",
"width": "100%",
"id": "document",
"items": [
{
"type": "Text",
"id": "text",
"transform": [
{"scale": "${1/0}"}
],
"text": "Lorem Ipsum"
}
]
}
]
}
})";
TEST_F(SerializeTest, SingularTransform) {
loadDocument(SINGULAR_TRANSFORM);
ASSERT_TRUE(component);
rapidjson::Document doc;
auto json = component->serialize(doc.GetAllocator());
auto &transformJson = json["children"][0]["_transform"];
ASSERT_EQ(0.0f, transformJson[0].GetFloat());
ASSERT_EQ(0.0f, transformJson[1].GetFloat());
ASSERT_EQ(0.0f, transformJson[2].GetFloat());
ASSERT_EQ(0.0f, transformJson[3].GetFloat());
ASSERT_EQ(0.0f, transformJson[4].GetFloat());
ASSERT_EQ(0.0f, transformJson[5].GetFloat());
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.