text
stringlengths
1
1.05M
.globl main .text main: li $v0,4 la $a0,str syscall li $v0,4 la $a0,strn syscall li $v0,1 la $t0,b0 lb $a0,0($t0) syscall lh $a0,0($t0) syscall lw $a0,0($t0) syscall la $t0,$h0 lh $a0,0($t0) syscall lw $a0,0($t0) syscall la $t0,w0 lw $a0,0($t0) syscall li $v0,10 syscall
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Geoworks 1995 -- All Rights Reserved PROJECT: Tiramisu MODULE: Preferences FILE: preffax2ItemGroupSpecial.asm AUTHOR: Peter Trinh, Mar 15, 1995 ROUTINES: Name Description ---- ----------- PrefItemGroupSpecialSaveOptions Will save options to two seperate ini keys. PIGSCopyToGOP Copies a string to GenOptionsParams. PIGSWriteClassInfo Write class info of chosen fax class. PIGSWriteT30Response Write T30Response struct to faxin and faxout. PIGSWriteFaxDriverName Writes driver name to both faxin and faxout. PrefItemGroupSpecialCheckPort Checks com port for viable faxmodem. PIGSCheckIfViableInputModem Checks for viable input-faxmodem. PIGSCheckIfViableOutputModem Checks for viable output-faxmodem. PIGSLoadInputDriver Loads input fax driver. PIGSLoadOutputDriver Loads output fax driver. PIGSInstantiateWarningDB Instantiates a warning DB. PIGSPopUpRetryDialogBox Displays a "retry" dialog box ECPIGSVerifyCategories Verifies categories str matches fax class REVISION HISTORY: Name Date Description ---- ---- ----------- PT 3/15/95 Initial revision DESCRIPTION: Contains methods for the PrefItemGroupSpecial class. $Id: preffax2ItemGroupSpecial.asm,v 1.1 97/04/05 01:43:34 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PrefFaxCode segment resource; ; ; Constants ; if ERROR_CHECK class1InputDriverName char "EC Class 1 Fax Input Driver",0 class2InputDriverName char "EC Class 2 Fax Input Driver",0 class1OutputDriverName char "EC Class 1 Fax Output Driver",0 class2OutputDriverName char "EC Class 2 Fax Output Driver",0 else class1InputDriverName char "Class 1 Fax Input Driver",0 class2InputDriverName char "Class 2 Fax Input Driver",0 class1OutputDriverName char "Class 1 Fax Output Driver",0 class2OutputDriverName char "Class 2 Fax Output Driver",0 endif ; ; For now, class 1 and class 2 are identical. ; class1Capabilities T30Response < FVR_NORMAL, FBPS_14400, FPW_215, FPL_297, FDCF_2D_MODIFIED_READ, FEC_DISABLE_ECM, FBFT_DISABLE_XFER, FSTPL_ZERO > .assert size(class1Capabilities) eq size(T30Response) class2Capabilities T30Response < FVR_NORMAL, FBPS_14400, FPW_215, FPL_297, FDCF_2D_MODIFIED_READ, FEC_DISABLE_ECM, FBFT_DISABLE_XFER, FSTPL_ZERO > .assert size(class1Capabilities) eq size(T30Response) faxinCapabilitiesStr char FAX_INI_FAXIN_CAPABILITIES_KEY, 0 faxoutCapabilitiesStr char FAX_INI_FAXOUT_CAPABILITIES_KEY, 0 faxinDriverNameStr char FAX_INI_FAXIN_DRIVER_KEY, 0 faxoutDriverNameStr char FAX_INI_FAXOUT_DRIVER_KEY, 0 if ERROR_CHECK EC_faxinStr char FAX_INI_FAXIN_CATEGORY,0 EC_faxoutStr char FAX_INI_FAXOUT_CATEGORY,0 endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PrefItemGroupSpecialSaveOptions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Save options to both ini keys. CALLED BY: MSG_GEN_SAVE_OPTIONS PASS: *ds:si = PrefItemGroupSpecialClass object ds:di = PrefItemGroupSpecialClass instance data ds:bx = PrefItemGroupSpecialClass object (same as *ds:si) es = segment of PrefItemGroupSpecialClass ax = message # ss:bp = GenOptionsParams RETURN: nothing DESTROYED: none SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- PT 3/15/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PrefItemGroupSpecialSaveOptions method dynamic PrefItemGroupSpecialClass, MSG_GEN_SAVE_OPTIONS uses ax, cx, dx, bp .enter mov ax, MSG_GEN_ITEM_GROUP_GET_SELECTION push bp ; ss:bp - GenOptionsParams call ObjCallInstanceNoLock pop bp ; ss:bp - GenOptionsParams jc done DerefInstanceDataDSDI PrefItemGroupSpecial_offset mov ax, ds:[di].PIGSI_categoryOne call PIGSCopyToGOP mov di, offset PrefItemGroupSpecialClass mov ax, MSG_GEN_SAVE_OPTIONS call ObjCallSuperNoLock DerefInstanceDataDSDI PrefItemGroupSpecial_offset mov ax, ds:[di].PIGSI_categoryTwo call PIGSCopyToGOP mov di, offset PrefItemGroupSpecialClass mov ax, MSG_GEN_SAVE_OPTIONS call ObjCallSuperNoLock DerefInstanceDataDSDI PrefItemGroupSpecial_offset test ds:[di].PIGSI_itemGroupSpecialflags, mask PIGSF_FAX_CLASS jz done call PIGSWriteClassInfo done: .leave ret PrefItemGroupSpecialSaveOptions endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PIGSCopyToGOP %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Given the lptr to the src string, will copy it to the GenOptionsParams category buffer. CALLED BY: PrefItemGroupSpecialSaveOptions PASS: *ds:ax - src string ss:bp - GenOptionsParams RETURN: copied strings DESTROYED: nothing SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- PT 3/15/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PIGSCopyToGOP proc near uses ax,si,di,es .enter Assert chunk ax, ds mov si, ax ; lptr to src str mov si, ds:[si] ; ds:si - ptr to src str segmov es, ss, di lea di, ss:[bp].GOP_category ; es:di - ptr to dst buf LocalCopyString .leave ret PIGSCopyToGOP endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PIGSWriteClassInfo %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Write out a hardcoded class information to the designated key and category. CALLED BY: PrefItemGroupSpecialSaveOptions PASS: *ds:si - PrefItemGroupSpecialClass object ss:bp - GenOptionsParams RETURN: nothing DESTROYED: nothing SIDE EFFECTS: Driver name and capabilities written out to the ini file. PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- PT 3/15/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PIGSWriteClassInfo proc near class PrefItemGroupSpecialClass uses ax,cx,dx,di,bp,es .enter Assert objectPtr dssi, PrefItemGroupSpecialClass mov ax, MSG_GEN_ITEM_GROUP_GET_SELECTION push bp ; GenOptionsParams call ObjCallInstanceNoLock ; ax - item selected pop bp ; GenOptionsParams jc done ; none selected EC < call ECPIGSVerifyCategories > cmp ax, FAX_CLASS_1 jne writeClass2Info ; ; Write out class 1 capabilities ; segmov es, cs, di mov di, offset class1Capabilities call PIGSWriteT30Response ; ; Write out driver name ; mov di, offset class1InputDriverName mov bp, offset class1OutputDriverName call PIGSWriteFaxDriverName done: .leave ret writeClass2Info: ; ; Write out class 2 capabilities ; segmov es, cs, di mov di, offset class2Capabilities call PIGSWriteT30Response ; ; Write out driver name ; mov di, offset class2InputDriverName mov bp, offset class2OutputDriverName call PIGSWriteFaxDriverName jmp done PIGSWriteClassInfo endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PIGSWriteT30Response %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Will write out the given capabilities to the capabilities key of both faxin and faxout. CALLED BY: PIGSWriteClassInfo PASS: *ds:si - PrefItemGroupSpecialClass object es:di - offset of T30Response structure RETURN: nothing DESTROYED: nothing SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- PT 3/15/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PIGSWriteT30Response proc near class PrefItemGroupSpecialClass uses cx,dx,bx,si .enter Assert objectPtr dssi, PrefItemGroupSpecialClass Assert fptr esdi push si ; self lptr DerefInstanceDataDSBX PrefItemGroupSpecial_offset mov si, ds:[bx].PIGSI_categoryOne mov si, ds:[si] ; ds:si - category str segmov cx, cs, dx mov dx, offset faxinCapabilitiesStr ; cx:dx - key str call FaxInitFileWriteT30 pop si ; self lptr DerefInstanceDataDSBX PrefItemGroupSpecial_offset mov si, ds:[bx].PIGSI_categoryTwo mov si, ds:[si] ; ds:si - category str mov dx, offset faxoutCapabilitiesStr ; cx:dx - key str call FaxInitFileWriteT30 .leave ret PIGSWriteT30Response endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PIGSWriteFaxDriverName %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Will write out the given capabilities to the capabilities key of both faxin and faxout. CALLED BY: PIGSWriteClassInfo PASS: *ds:si - PrefItemGroupSpecialClass es:di - input driver name es:bp - output driver name RETURN: nothing DESTROYED: nothing SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- PT 3/15/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PIGSWriteFaxDriverName proc near class PrefItemGroupSpecialClass uses cx,dx,bx,si,di,ds .enter Assert objectPtr dssi, PrefItemGroupSpecialClass Assert nullTerminatedAscii esdi Assert nullTerminatedAscii esbp ; ; Write the input driver name ; push si ; self lptr DerefInstanceDataDSBX PrefItemGroupSpecial_offset mov si, ds:[bx].PIGSI_categoryOne mov si, ds:[si] ; ds:si - category str segmov cx, cs, dx mov dx, offset faxinDriverNameStr ; cx:dx - key str call InitFileWriteString ; ; Write the output driver name ; pop si ; self lptr DerefInstanceDataDSBX PrefItemGroupSpecial_offset mov si, ds:[bx].PIGSI_categoryTwo mov si, ds:[si] ; ds:si - category str mov dx, offset faxoutDriverNameStr ; cx:dx - key str mov di, bp call InitFileWriteString .leave ret PIGSWriteFaxDriverName endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PrefItemGroupSpecialCheckPort %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Checks the selected port to see if a viable faxmodem is connected. If not, then display a warning dialog box. CALLED BY: MSG_PREF_ITEM_GROUP_SPECIAL_CHECK_PORT PASS: *ds:si = PrefItemGroupSpecialClass object ds:di = PrefItemGroupSpecialClass instance data ds:bx = PrefItemGroupSpecialClass object (same as *ds:si) es = segment of PrefItemGroupSpecialClass ax = message # cx = current selection, or first selection in item group, if more than one selection, or GIGS_NONE if no selection bp = number of selections dl = GenItemGroupStateFlags GIGSF_MODIFIED will be set if a user activation has just changed the status of the group. Will be clear if a redundant user activation has occurred, such as the re-selection of the singly selected exclusive item. If message is a result of MSG_GEN_ITEM_GROUP_SEND_STATUS_MSG being sent, then this bit will hold the value passed in that message. RETURN: nothing DESTROYED: nothing SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- PT 3/24/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PrefItemGroupSpecialCheckPort method dynamic PrefItemGroupSpecialClass, MSG_PREF_ITEM_GROUP_SPECIAL_CHECK_PORT uses ax, cx, dx, bp .enter cmp cx, GIGS_NONE je done tst bp jz done test dl, mask GIGSF_MODIFIED jz done ; user didn't modify ; ; Determine which fax driver was chosen. ; push si, cx ; self lptr, ; selected comport mov ax, MSG_GEN_ITEM_GROUP_GET_SELECTION mov si, offset PrefFaxDriversSelector call ObjCallInstanceNoLock ; ax - driver pop si, cx ; self lptr ; selected comport jc done ; ; Now call the driver with the selected port number and see if ; a viable modem is attached. ; retry: call PIGSCheckIfViableInputModem cmp ax, IC_YES je retry call PIGSCheckIfViableOutputModem cmp ax, IC_YES je retry done: .leave ret PrefItemGroupSpecialCheckPort endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PIGSCheckIfViableInputModem %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Checks to see if there's a viable input faxmodem of the given class, connected to the given port. CALLED BY: PrefItemGroupSpecialCheckPort PASS: ax - FAX_CLASS_# cx - FAX_COMPORT_# RETURN: CF - SET if NO viable input faxmodem ax - IC_YES for RETRY - IC_NO for CANCEL DESTROYED: nothing SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- PT 3/24/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PIGSCheckIfViableInputModem proc near uses bx,cx,di,si,ds .enter call PIGSLoadInputDriver jc warning call GeodeInfoDriver ; dssi - ; DriverInfoStruct push ax ; driver class mov ss:[TPD_dataAX], cx ; port num movdw bxax, ds:[si].DIS_strategy mov di, DR_FAXIN_CHECK_FOR_MODEM call ProcCallFixedOrMovable pop ax ; driver class jc warning mov ax, IC_NO ; found valid modem done: .leave ret warning: ; ; Put up a warning/retry dialog box ; mov cx, FAX_INPUT_DRIVER call PIGSInstantiateWarningDB stc jmp done PIGSCheckIfViableInputModem endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PIGSCheckIfViableOutputModem %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Checks to see if there's a viable output faxmodem of the given class, connected to the given port. CALLED BY: PrefItemGroupSpecialCheckPort PASS: ax - FAX_CLASS_# cx - FAX_COMPORT_# RETURN: CF - SET if NO viable output faxmodem ax - IC_YES for RETRY - IC_NO for CANCEL DESTROYED: nothing SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- PT 3/24/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PIGSCheckIfViableOutputModem proc near uses bx,cx,di,si,ds .enter call PIGSLoadOutputDriver ; bx - driver handle jc warning call GeodeInfoDriver ; dssi - ; DriverInfoStruct push ax ; driver class mov ss:[TPD_dataAX], cx ; port num movdw bxax, ds:[si].DIS_strategy mov di, DR_FAXOUT_CHECK_FOR_MODEM call ProcCallFixedOrMovable pop ax ; driver class jc warning mov ax, IC_NO ; found valid modem done: .leave ret warning: ; ; Put up a warning/retry dialog box ; mov cx, FAX_OUTPUT_DRIVER call PIGSInstantiateWarningDB stc jmp done PIGSCheckIfViableOutputModem endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PIGSLoadInputDriver %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Loads up the appropriate input fax driver. CALLED BY: PIGSCheckIfViableInputModem PASS: ax - FAX_CLASS_# RETURN: CF - SET on error else bx - driver handle DESTROYED: nothing SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- PT 3/24/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PIGSLoadInputDriver proc near driverName local FileLongName uses ax,si,di,ds,es .enter ; ; Move to the fax driver directory. ; call FilePushDir call PutThreadInFaxDriverDir jc error ; jump if no dir ; ; Copy the driver's name to the stack for XIP purposes ; segmov ds, cs, si mov si, offset class1InputDriverName cmp ax, FAX_CLASS_1 je copyName mov si, offset class2InputDriverName copyName: segmov es, ss, di lea di, ss:[driverName] LocalCopyString ; ; Load the driver. ; segmov ds, es, si lea si, ss:[driverName] ; ds:si - filename mov ax, FAXIN_PROTO_MAJOR mov bx, FAXIN_PROTO_MINOR call GeodeUseDriver ; carry set on error ; ax = GeodeLoadError ; bx = driver handle error: call FilePopDir ; (preserves flags) .leave ret PIGSLoadInputDriver endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PIGSLoadOutputDriver %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Loads up the appropriate output fax driver. CALLED BY: PIGSCheckIfViableOutputModem PASS: ax - FAX_CLASS_# RETURN: CF - SET on error else bx - driver handle DESTROYED: nothing SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- PT 3/24/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PIGSLoadOutputDriver proc near driverName local FileLongName uses ax,si,di,ds,es .enter ; ; Move to the fax driver directory. ; call FilePushDir call PutThreadInFaxDriverDir jc error ; jump if no dir ; ; Copy the driver's name to the stack for XIP purposes ; segmov ds, cs, si mov si, offset class1OutputDriverName cmp ax, FAX_CLASS_1 je copyName mov si, offset class2OutputDriverName copyName: segmov es, ss, di lea di, ss:[driverName] LocalCopyString ; ; Load the driver. ; segmov ds, es, si lea si, ss:[driverName] ; ds:si - filename mov ax, FAXOUT_PROTO_MAJOR mov bx, FAXOUT_PROTO_MINOR call GeodeUseDriver ; carry set on error ; ax = GeodeLoadError ; bx = driver handle error: call FilePopDir ; (preserves flags) .leave ret PIGSLoadOutputDriver endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PIGSInstantiateWarningDB %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Will load in the DB strings from the Strings resource, and call PIGSPopUpRetryDialogBox to dynamically create a standard dialog box. CALLED BY: PIGSCheckIfViableInputModem, PIGSCheckIfViableOutputModem PASS: ax - FAX_CLASS_# cx - FAX_INPUT_DRIVER or FAX_OUTPUT_DRIVER RETURN: ax - IC_YES for RETRY - IC_NO for CANCEL DESTROYED: nothing SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- PT 3/29/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PIGSInstantiateWarningDB proc near uses bx,cx,dx,si,di,bp,es .enter push ax ; driver class mov bx, handle Strings call MemLock mov_tr es, ax ; Strings segment pop ax ; driver class mov di, offset noViableModemChunk mov si, offset oneChunk cmp ax, FAX_CLASS_1 je getIOString mov si, offset twoChunk getIOString: mov bx, offset inputChunk cmp cx, FAX_INPUT_DRIVER je popUpDB mov bx, offset outputChunk popUpDB: call PIGSPopUpRetryDialogBox mov bx, handle Strings call MemUnlock .leave ret PIGSInstantiateWarningDB endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PIGSPopUpRetryDialogBox %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Puts up a dialog box with the RETRY and CANCEL triggers. CALLED BY: PIGSInstantiateWarningDB PASS: *es:di - message string *es:si - string arg1 *es:bx - string arg3 RETURN: ax - IC_YES for RETRY - IC_NO for CANCEL DESTROYED: nothing SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- PT 3/24/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ responseTriggers StandardDialogResponseTriggerTable <2> retryTrigger StandardDialogResponseTriggerEntry <retryChunk, IC_YES> cancelTrigger StandardDialogResponseTriggerEntry <cancelChunk, IC_NO> ForceRef retryTrigger ForceRef cancelTrigger PIGSPopUpRetryDialogBox proc near uses bx,bp,di,si,es .enter ; Allocate parameters buffer sub sp, size StandardDialogParams mov bp, sp mov ss:[bp].SDP_customFlags, CustomDialogBoxFlags <0, CDT_QUESTION, GIT_MULTIPLE_RESPONSE, 0> mov di, es:[di] ; es:di - msg str movdw ss:[bp].SDP_customString, esdi mov si, es:[si] ; es:si - arg1 str movdw ss:[bp].SDP_stringArg1, essi mov bx, es:[bx] ; es:bx - arg2 str movdw ss:[bp].SDP_stringArg2, esbx clr ss:[bp].SDP_helpContext.segment mov ss:[bp].SDP_customTriggers.segment, cs mov ss:[bp].SDP_customTriggers.offset, offset responseTriggers call UserStandardDialog ; No need to deAllocate parameters because UserStandardDialog ; does it for us. .leave ret PIGSPopUpRetryDialogBox endp if ERROR_CHECK COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ECPIGSVerifyCategories %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Verifies that the categories are correct for writing out the class information. Ie. categoryOne = FAX_INI_FAXIN_CATEGORY categoryTwo = FAX_INI_FAXOUT_CATEGORY CALLED BY: PIGSWriteClassInfo PASS: *ds:si - PrefItemGroupSpecialClass object RETURN: nothing DESTROYED: nothing SIDE EFFECTS: none PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- PT 3/15/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ECPIGSVerifyCategories proc near class PrefItemGroupSpecialClass uses es,di,si,cx .enter Assert objectPtr dssi, PrefItemGroupSpecialClass pushf push si ; self lptr, DerefInstanceDataDSDI PrefItemGroupSpecial_offset mov si, ds:[di].PIGSI_categoryOne mov si, ds:[si] ; str offset segmov es, cs, di mov di, offset EC_faxinStr clr cx ; 0-terminated ; ; ds:si - category string, es:di - EC string ; call LocalCmpStrings ERROR_NE< PREF_ITEM_GROUP_SPECIAL_CATEGORY_ERROR > pop si ; self lptr, DerefInstanceDataDSDI PrefItemGroupSpecial_offset mov si, ds:[di].PIGSI_categoryTwo mov si, ds:[si] ; str offset mov di, offset EC_faxoutStr ; ; ds:si - category string, es:di - EC string ; call LocalCmpStrings ERROR_NE< PREF_ITEM_GROUP_SPECIAL_CATEGORY_ERROR > popf .leave ret ECPIGSVerifyCategories endp endif PrefFaxCode ends
; Executable name : args ; Version : 0.1 ; Created date : 07/02/2012 ; Last update : 07/02/2012 ; Author : helq ; Description : A simple program in assembly for Linux, using NASM 2.10, ; printing the second argv. ; ; Build using these commands: ; nasm -f elf -g -F stabs args.asm -l args.lst ; ld -m elf_i386 -o args args.o ; ; Use -dDEBUG option %macro nopDebug 0 %ifdef DEBUG nop %endif %endmacro ; ================== PRINT ================== %macro PutStr 2 mov eax,0x4 ; Specify sys_write call mov ebx,0x1 ; Specify File Descriptor 1: Standard Output mov ecx,%1 ; Pass offset of the message mov edx,%2 ; Pass the length of the message int 0x80 ; Make kernel call %endmacro ; ================== INPUT ================== %macro GetStr 2 mov eax,0x3 ; Specify sys_read call mov ebx,0x0 ; Specify File Descriptor 0: Standard Input mov ecx,%1 ; Pass offset of the message mov edx,%2 ; Pass the length of the message int 0x80 ; Make kernel call %endmacro SECTION .data space: db " ",0h SECTION .bss SECTION .text global _start _start: nopDebug pop esi ; argc dec esi ; argc-- pop edi ; argv[0] loop1: ; Trough argv (except the last argv) mov ecx,edi ; argv[n] to ecx ; offset of the message pop edi ; argv[n+1] mov edx,edi ; copy edi to edx sub edx,ecx ; length(argv[n]) ; length of the message mov eax,0x4 ; Specify sys_write call mov ebx,0x1 ; Specify File Descriptor 1: Standard Output int 0x80 ; Make kernel call PutStr space,0x1 ; printing an space dec esi ; argc-- jnz loop1 pop esi ; empty, api linux pop esi ; next value on the stack sub esi,edi ; length of argv[n] PutStr edi,esi ; ================== EXIT ================== mov eax,0x1 ; Code for Exit Syscall mov ebx,0x0 ; Return a code of zero int 0x80 ; Make kernel call
; A033487: a(n) = n*(n+1)*(n+2)*(n+3)/4. ; 0,6,30,90,210,420,756,1260,1980,2970,4290,6006,8190,10920,14280,18360,23256,29070,35910,43890,53130,63756,75900,89700,105300,122850,142506,164430,188790,215760,245520,278256,314160,353430,396270,442890,493506,548340,607620,671580,740460,814506,893970,979110,1070190,1167480,1271256,1381800,1499400,1624350,1756950,1897506,2046330,2203740,2370060,2545620,2730756,2925810,3131130,3347070,3573990,3812256,4062240,4324320,4598880,4886310,5187006,5501370,5829810,6172740,6530580,6903756,7292700,7697850,8119650,8558550,9015006,9489480,9982440,10494360,11025720,11577006,12148710,12741330,13355370,13991340,14649756,15331140,16036020,16764930,17518410,18297006,19101270,19931760,20789040,21673680,22586256,23527350,24497550,25497450,26527650,27588756,28681380,29806140,30963660,32154570,33379506,34639110,35934030,37264920,38632440,40037256,41480040,42961470,44482230,46043010,47644506,49287420,50972460,52700340,54471780,56287506,58148250,60054750,62007750,64008000,66056256,68153280,70299840,72496710,74744670,77044506,79397010,81802980,84263220,86778540,89349756,91977690,94663170,97407030,100210110,103073256,105997320,108983160,112031640,115143630,118320006,121561650,124869450,128244300,131687100,135198756,138780180,142432290,146156010,149952270,153822006,157766160,161785680,165881520,170054640,174306006,178636590,183047370,187539330,192113460,196770756,201512220,206338860,211251690,216251730,221340006,226517550,231785400,237144600,242596200,248141256,253780830,259515990,265347810,271277370,277305756,283434060,289663380,295994820,302429490,308968506,315612990,322364070,329222880,336190560,343268256,350457120,357758310,365172990,372702330,380347506,388109700,395990100,403989900,412110300,420352506,428717730,437207190,445822110,454563720,463433256,472431960,481561080,490821870,500215590,509743506,519406890,529207020,539145180,549222660,559440756,569800770,580304010,590951790,601745430,612686256,623775600,635014800,646405200,657948150,669645006,681497130,693505890,705672660,717998820,730485756,743134860,755947530,768925170,782069190,795381006,808862040,822513720,836337480,850334760,864507006,878855670,893382210,908088090,922974780,938043756,953296500,968734500,984359250 sub $1,$0 bin $1,4 mul $1,6
#include "Tag.h" #include <cmath> // For trig functions using namespace std; using namespace boost::math; // Extend ostream. // Output stream operator. Allows easy writing of tag data to an output stream. ostream& operator<<(ostream& output_stream, const Tag& tag) { tuple<float, float, float> position = tag.getPosition(); tuple<float, float, float> orientation = tag.calcRollPitchYaw(); output_stream << "Tag ID:" << tag.getID() << ", Position (XYZ): <" << get<0>(position) << ", " << get<1>(position) << ", " << get<2>(position) << ", " << ">, " << " Orientation (RPY): <" << get<0>(orientation) << ", " << get<1>(orientation) << ", " << get<2>(orientation) << ", " << ">" << endl; return output_stream; } // Constructors Tag::Tag() { // Initialize orientation and position orientation = ::boost::math::quaternion<float>(0,0,0,0); position = make_tuple(0,0,0); } Tag::Tag(const Tag &that) { this->setPosition( that.position ); this->setOrientation( that.orientation ); this->setID( that.id ); } int Tag::getID() const { return id; } void Tag::setID( int id) { this->id = id; } tuple<float, float, float> Tag::getPosition() const { return position; } void Tag::setPosition( tuple<float, float, float> position ) { this->position = position; } quaternion<float> Tag::getOrientation() const { return orientation; } void Tag::setOrientation( quaternion<float> orientation ) { this->orientation = orientation; } // convenience accessor functions float Tag::getPositionX() const { return std::get<0>(position); } float Tag::getPositionY() const { return std::get<1>(position); } float Tag::getPositionZ() const { return std::get<2>(position); } float Tag::getOrientationX() const { return orientation.R_component_1(); } float Tag::getOrientationY() const { orientation.R_component_2(); } float Tag::getOrientationZ() const { orientation.R_component_3(); } float Tag::getOrientationW() const { orientation.R_component_4(); } void Tag::setPositionX( float x ) { std::get<0>(position) = x; } void Tag::setPositionY( float y ) { std::get<1>(position) = y; } void Tag::setPositionZ( float z ) { std::get<2>(position) = z; } // The following functions recreate the entire quaternion each time a value is changed // becuase you cannot change quaternion components without rebuilding the whole quaternion. // This is a limitation of the boost quaternion. void Tag::setOrientationX( float x ){ orientation = quaternion<float>( x, getOrientationY(), getOrientationZ(), getOrientationW() ); } void Tag::setOrientationY( float y ){ orientation = quaternion<float>( getOrientationX(), y, getOrientationZ(), getOrientationW() ); } void Tag::setOrientationZ( float z ){ orientation = quaternion<float>( getOrientationX(), getOrientationY(), z, getOrientationW() ); } void Tag::setOrientationW( float w ){ orientation = quaternion<float>( getOrientationX(), getOrientationY(), getOrientationZ(), w ); } // *** // Consider whether to memoise the "calc" functions for performace // *** // Returns orientation as Roll-Pitch-Yaw tuple<float, float, float> Tag::calcRollPitchYaw() const { float yaw = calcYaw(); float pitch = calcPitch(); float roll = calcRoll(); return make_tuple(roll, pitch, yaw); } float Tag::calcYaw() const { float x = getOrientationX(); float y = getOrientationY(); float z = getOrientationZ(); float w = getOrientationW(); return atan2(2.0f*(y*z + w*x), w*w - x*x - y*y + z*z); } float Tag::calcPitch() const { float x = getOrientationX(); float y = getOrientationY(); float z = getOrientationZ(); float w = getOrientationW(); return asin(-2.0f*(x*z - w*y)); } float Tag::calcRoll() const { float x = getOrientationX(); float y = getOrientationY(); float z = getOrientationZ(); float w = getOrientationW(); return atan2(2.0f*(y + w*z), w*w + x*x - y*y - z*z); }
; A158764: 38*(38*n^2-1). ; 1406,5738,12958,23066,36062,51946,70718,92378,116926,144362,174686,207898,243998,282986,324862,369626,417278,467818,521246,577562,636766,698858,763838,831706,902462,976106,1052638,1132058,1214366,1299562,1387646,1478618,1572478,1669226,1768862,1871386,1976798,2085098,2196286,2310362,2427326,2547178,2669918,2795546,2924062,3055466,3189758,3326938,3467006,3609962,3755806,3904538,4056158,4210666,4368062,4528346,4691518,4857578,5026526,5198362,5373086,5550698,5731198,5914586,6100862,6290026,6482078,6677018,6874846,7075562,7279166,7485658,7695038,7907306,8122462,8340506,8561438,8785258,9011966,9241562,9474046,9709418,9947678,10188826,10432862,10679786,10929598,11182298,11437886,11696362,11957726,12221978,12489118,12759146,13032062,13307866,13586558,13868138,14152606,14439962,14730206,15023338,15319358,15618266,15920062,16224746,16532318,16842778,17156126,17472362,17791486,18113498,18438398,18766186,19096862,19430426,19766878,20106218,20448446,20793562,21141566,21492458,21846238,22202906,22562462,22924906,23290238,23658458,24029566,24403562,24780446,25160218,25542878,25928426,26316862,26708186,27102398,27499498,27899486,28302362,28708126,29116778,29528318,29942746,30360062,30780266,31203358,31629338,32058206,32489962,32924606,33362138,33802558,34245866,34692062,35141146,35593118,36047978,36505726,36966362,37429886,37896298,38365598,38837786,39312862,39790826,40271678,40755418,41242046,41731562,42223966,42719258,43217438,43718506,44222462,44729306,45239038,45751658,46267166,46785562,47306846,47831018,48358078,48888026,49420862,49956586,50495198,51036698,51581086,52128362,52678526,53231578,53787518,54346346,54908062,55472666,56040158,56610538,57183806,57759962,58339006,58920938,59505758,60093466,60684062,61277546,61873918,62473178,63075326,63680362,64288286,64899098,65512798,66129386,66748862,67371226,67996478,68624618,69255646,69889562,70526366,71166058,71808638,72454106,73102462,73753706,74407838,75064858,75724766,76387562,77053246,77721818,78393278,79067626,79744862,80424986,81107998,81793898,82482686,83174362,83868926,84566378,85266718,85969946,86676062,87385066,88096958,88811738,89529406,90249962 mov $1,2 add $1,$0 mul $1,$0 mul $1,1444 add $1,1406
db 0 ; species ID placeholder db 75, 90, 50, 95, 110, 80 ; hp atk def spd sat sdf db DARK, FIRE ; type db 45 ; catch rate db 204 ; base exp db NO_ITEM, NO_ITEM ; items db GENDER_F0 ; gender ratio db 100 ; unknown 1 db 20 ; step cycles to hatch db 5 ; unknown 2 INCBIN "gfx/pokemon/houndoom/front.dimensions" db 0, 0, 0, 0 ; padding db GROWTH_SLOW ; growth rate dn EGG_GROUND, EGG_GROUND ; egg groups ; tm/hm learnset tmhm HEADBUTT, CURSE, ROAR, TOXIC, ROCK_SMASH, HIDDEN_POWER, SUNNY_DAY, SNORE, HYPER_BEAM, PROTECT, ENDURE, FRUSTRATION, SOLARBEAM, IRON_TAIL, RETURN, SHADOW_BALL, MUD_SLAP, DOUBLE_TEAM, SWAGGER, SLEEP_TALK, SLUDGE_BOMB, FIRE_BLAST, SWIFT, DREAM_EATER, DETECT, REST, ATTRACT, THIEF, NIGHTMARE, STRENGTH, FLAMETHROWER ; end
.model small ; el tamanio del programa .stack 0h ; donde iniciara .data ; declara variables hor db ? min db ? sec db ? .code mov ax,@data mov ds,ax INICIO : MOV AH,06H ;LIMPIEZA 1 MOV AL,00H MOV BH,100D ;COLOR AMARILLO MOV CX,0000H ;PUNTO DE INICIO MOV DX,244fH ;PUNTO DE FINAL INT 10H PLOP: mov ah,02h mov dh,0ch mov dl,28h int 10h mov ah, 2ch int 21h mov hor,ch mov min,cl mov sec,dh ;one sec delay MOV CX, 0FH MOV DX, 4240H MOV AH, 86H ;wait INT 15H ;pases the ; end of on sec delay jmp PLOP mov ah,0eh mov bx,007h mov al,2ah mov al,50h mov bl,5h mov cx,3 mov ah,09h int 10h end ; finaliza directiva
; A047357: Numbers that are congruent to {0, 1, 3} mod 7. ; Submitted by Christian Krause ; 0,1,3,7,8,10,14,15,17,21,22,24,28,29,31,35,36,38,42,43,45,49,50,52,56,57,59,63,64,66,70,71,73,77,78,80,84,85,87,91,92,94,98,99,101,105,106,108,112,113,115,119,120,122,126,127,129,133,134,136,140 mul $0,36 div $0,27 mul $0,6 div $0,4 mul $0,7 div $0,6
; A026200: a(n) = (s(n) + 2)/3, where s(n) is the n-th number congruent to 1 mod 3 in A026166. ; Submitted by Jon Maiga ; 1,2,4,6,3,8,10,12,5,14,16,18,7,20,22,24,9,26,28,30,11,32,34,36,13,38,40,42,15,44,46,48,17,50,52,54,19,56,58,60,21,62,64,66,23,68,70,72,25,74,76,78,27,80,82,84,29,86,88,90,31,92,94,96,33,98,100,102,35,104,106,108,37,110,112,114,39,116,118,120,41,122,124,126,43,128,130,132,45,134,136,138,47,140,142,144,49,146,148,150 mov $1,$0 mul $0,3 add $1,23 mod $1,4 add $0,$1 dif $0,$1 div $0,2 add $0,1
global test_case extern path.filename extern std.outsln %include "String.inc" section .text test_case: mov rax, fullpath_str ; argument call path.filename ; extract filename call std.outsln ; print filename ret section .data fullpath: db "/path/to/filename.ext" fullpath_len: equ $-fullpath fullpath_str: istruc String at String.pdata, dq fullpath at String.length, dq fullpath_len iend
.size 8000 .text@48 jp lstatint .text@100 jp lbegin .data@143 c0 .text@150 lbegin: ld a, 00 ldff(ff), a ld a, 30 ldff(00), a ld a, 01 ldff(4d), a stop, 00 ld a, ff ldff(45), a ld b, 96 call lwaitly_b ld a, 80 ldff(68), a ld a, ff ld c, 69 ldff(c), a ldff(c), a ldff(c), a ldff(c), a ldff(c), a ldff(c), a xor a, a ldff(c), a ldff(c), a ld a, 40 ldff(41), a ld a, 02 ldff(ff), a xor a, a ldff(0f), a ei ld a, b inc a inc a ldff(45), a ld c, 0f .text@1000 lstatint: xor a, a ldff(41), a ld a, 99 ldff(45), a .text@10d9 ld a, 40 ldff(41), a nop nop nop nop nop nop nop nop nop ldff a, (c) jp lprint_a .text@7000 lprint_a: push af ld b, 91 call lwaitly_b xor a, a ldff(40), a ld bc, 7a00 ld hl, 8000 ld d, 00 lprint_copytiles: ld a, (bc) inc bc ld(hl++), a dec d jrnz lprint_copytiles pop af ld b, a srl a srl a srl a srl a ld(9800), a ld a, b and a, 0f ld(9801), a ld a, c0 ldff(47), a ld a, 80 ldff(68), a ld a, ff ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a xor a, a ldff(69), a ldff(69), a ldff(43), a ld a, 91 ldff(40), a lprint_limbo: jr lprint_limbo .text@7400 lwaitly_b: ld c, 44 lwaitly_b_loop: ldff a, (c) cmp a, b jrnz lwaitly_b_loop ret .data@7a00 00 00 7f 7f 41 41 41 41 41 41 41 41 41 41 7f 7f 00 00 08 08 08 08 08 08 08 08 08 08 08 08 08 08 00 00 7f 7f 01 01 01 01 7f 7f 40 40 40 40 7f 7f 00 00 7f 7f 01 01 01 01 3f 3f 01 01 01 01 7f 7f 00 00 41 41 41 41 41 41 7f 7f 01 01 01 01 01 01 00 00 7f 7f 40 40 40 40 7e 7e 01 01 01 01 7e 7e 00 00 7f 7f 40 40 40 40 7f 7f 41 41 41 41 7f 7f 00 00 7f 7f 01 01 02 02 04 04 08 08 10 10 10 10 00 00 3e 3e 41 41 41 41 3e 3e 41 41 41 41 3e 3e 00 00 7f 7f 41 41 41 41 7f 7f 01 01 01 01 7f 7f 00 00 08 08 22 22 41 41 7f 7f 41 41 41 41 41 41 00 00 7e 7e 41 41 41 41 7e 7e 41 41 41 41 7e 7e 00 00 3e 3e 41 41 40 40 40 40 40 40 41 41 3e 3e 00 00 7e 7e 41 41 41 41 41 41 41 41 41 41 7e 7e 00 00 7f 7f 40 40 40 40 7f 7f 40 40 40 40 7f 7f 00 00 7f 7f 40 40 40 40 7f 7f 40 40 40 40 40 40
; VideoPrint.asm ; Commodore 64 ;------------------------------------------------------------------ !zone SetPrintYPosition SetPrintYPosition pha ; Set character pointer to beginning of row Y. lda SCREEN_LINE_OFFSET_TABLE_LO,y sta PrintCharacterPointer lda SCREEN_LINE_OFFSET_TABLE_HI,y sta PrintCharacterPointer+1 ; Set color pointer to beginning of row Y. lda SCREEN_COLOR_LINE_OFFSET_TABLE_LO,y sta PrintColorPointer lda SCREEN_COLOR_LINE_OFFSET_TABLE_HI,y sta PrintColorPointer+1 pla rts ;------------------------------------------------------------------ !zone PrintChar PrintChar pha sty PARAM2 ldy PrintXPosition sta (PrintCharacterPointer),y lda PrintColor sta (PrintColorPointer),y ldy PARAM2 pla rts ;------------------------------------------------------------------ !zone PrintString PrintString pha tya pha ldy #0 .printStringLoop ; Load character byte from input string. lda (ZEROPAGE_POINTER_1),y ; End on null terminator. cmp #0 beq .printStringDone sty PARAM1 ldy PrintXPosition sta (PrintCharacterPointer),y lda PrintColor sta (PrintColorPointer),y inc PrintXPosition ldy PARAM1 iny jmp .printStringLoop .printStringDone pla tay pla rts ;------------------------------------------------------------------ !zone FillScreen FillScreen sta PARAM1 txa pha tya pha ; Fill character memory. ; Algorithm assumes even pages, thus -1 to high byte and zeroing of low byte of address. lda #>SCREEN_CHAR+SCREEN_CHAR_SIZE-1 sta ZEROPAGE_POINTER_1+1 tax ; Set up X to be part of loop as a secondary decrementer. ldy #0 ; Also, setting Y's starting value in loop. sty ZEROPAGE_POINTER_1 lda PARAM1 .fillScreenCharacterLoop dey sta (ZEROPAGE_POINTER_1),y bne .fillScreenCharacterLoop dex cpx #>SCREEN_CHAR-1 beq .endFillScreenCharacter stx ZEROPAGE_POINTER_1+1 bne .fillScreenCharacterLoop .endFillScreenCharacter ; Fill color memory. lda #>SCREEN_COLOR+SCREEN_CHAR_SIZE-1 sta ZEROPAGE_POINTER_1+1 tax lda #0 sta ZEROPAGE_POINTER_1 tay lda PrintColor .fillScreenColorLoop dey sta (ZEROPAGE_POINTER_1),y bne .fillScreenColorLoop dex cpx #>SCREEN_COLOR-1 beq .endFillScreenColor stx ZEROPAGE_POINTER_1+1 bne .fillScreenColorLoop .endFillScreenColor pla tay pla tax lda PARAM1 ; lda #<SCREEN_COLOR ; sta ZEROPAGE_POINTER_2 ; lda #>SCREEN_COLOR ; sta ZEROPAGE_POINTER_2+1 ; ldx #0 ; .FillRow ; ldy #0 ; .FillRowColumn ; lda PARAM1 ; sta (ZEROPAGE_POINTER_1),y ; ; lda PARAM2 ; sta (ZEROPAGE_POINTER_2),y ; ; iny ; cpy #SCREEN_CHAR_WIDTH ; bcs .AdvanceToNextRow ; jmp .FillRowColumn ; .AdvanceToNextRow ; inx ; cpx #SCREEN_CHAR_HEIGHT ; bcs .FillScreenDone ; ; clc ; lda ZEROPAGE_POINTER_1 ; adc #SCREEN_CHAR_WIDTH ; sta ZEROPAGE_POINTER_1 ; lda #0 ; adc ZEROPAGE_POINTER_1+1 ; sta ZEROPAGE_POINTER_1+1 ; ; clc ; lda ZEROPAGE_POINTER_2 ; adc #SCREEN_CHAR_WIDTH ; sta ZEROPAGE_POINTER_2 ; lda #0 ; adc ZEROPAGE_POINTER_2+1 ; sta ZEROPAGE_POINTER_2+1 ; ; jmp .FillRow ; ; .FillScreenDone rts
SFX_Battle_20_Ch7: unknownnoise0x20 12, 241, 84 unknownnoise0x20 8, 241, 100 endchannel
VermilionDockScript: call EnableAutoTextBoxDrawing CheckEventHL EVENT_STARTED_WALKING_OUT_OF_DOCK jr nz, .asm_1db8d CheckEventReuseHL EVENT_GOT_HM01 ret z ld a, [wDestinationWarpID] cp $1 ret nz CheckEventReuseHL EVENT_SS_ANNE_LEFT jp z, VermilionDock_1db9b SetEventReuseHL EVENT_STARTED_WALKING_OUT_OF_DOCK call Delay3 ld hl, wd730 set 7, [hl] ld hl, wSimulatedJoypadStatesEnd ld a, D_UP ld [hli], a ld [hli], a ld [hl], a ld a, $3 ld [wSimulatedJoypadStatesIndex], a xor a ld [wSpriteStateData2 + $06], a ld [wOverrideSimulatedJoypadStatesMask], a dec a ld [wJoyIgnore], a ret .asm_1db8d CheckEventAfterBranchReuseHL EVENT_WALKED_OUT_OF_DOCK, EVENT_STARTED_WALKING_OUT_OF_DOCK ret nz ld a, [wSimulatedJoypadStatesIndex] and a ret nz ld [wJoyIgnore], a SetEventReuseHL EVENT_WALKED_OUT_OF_DOCK ret VermilionDock_1db9b: SetEventForceReuseHL EVENT_SS_ANNE_LEFT ld a, $ff ld [wJoyIgnore], a call StopAllMusic ld c, BANK(Music_Surfing) ld a, MUSIC_SURFING call PlayMusic callba LoadSmokeTileFourTimes xor a ld [wSpriteStateData1 + 2], a ld c, 120 call DelayFrames ld b, $9c call CopyScreenTileBufferToVRAM coord hl, 0, 10 ld bc, SCREEN_WIDTH * 6 ld a, $14 ; water tile call FillMemory ld a, 1 ld [H_AUTOBGTRANSFERENABLED], a call Delay3 xor a ld [H_AUTOBGTRANSFERENABLED], a ld [wSSAnneSmokeDriftAmount], a ld [rOBP1], a call UpdateGBCPal_OBP1 ld a, 88 ld [wSSAnneSmokeX], a ld hl, wMapViewVRAMPointer ld c, [hl] inc hl ld b, [hl] push bc push hl ld a, SFX_SS_ANNE_HORN call PlaySoundWaitForCurrent ld a, $ff ld [wUpdateSpritesEnabled], a ld d, $0 ld e, $8 .asm_1dbfa ld hl, $0002 add hl, bc ld a, l ld [wMapViewVRAMPointer], a ld a, h ld [wMapViewVRAMPointer + 1], a push hl push de call ScheduleEastColumnRedraw call VermilionDock_EmitSmokePuff pop de ld b, $10 .asm_1dc11 call VermilionDock_AnimSmokePuffDriftRight ld c, $8 .asm_1dc16 call VermilionDock_1dc7c dec c jr nz, .asm_1dc16 inc d dec b jr nz, .asm_1dc11 pop bc dec e jr nz, .asm_1dbfa xor a ld [rWY], a ld [hWY], a call VermilionDock_EraseSSAnne ld a, $90 ld [hWY], a ld a, $1 ld [wUpdateSpritesEnabled], a pop hl pop bc ld [hl], b dec hl ld [hl], c call LoadPlayerSpriteGraphics ld hl, wNumberOfWarps dec [hl] ret VermilionDock_AnimSmokePuffDriftRight: push bc push de ld hl, wOAMBuffer + 4 * $4 + 1 ; x coord ld a, [wSSAnneSmokeDriftAmount] swap a ld c, a ld de, 4 .loop inc [hl] inc [hl] add hl, de dec c jr nz, .loop pop de pop bc ret VermilionDock_EmitSmokePuff: ; new smoke puff above the S.S. Anne's front smokestack ld a, [wSSAnneSmokeX] sub 16 ld [wSSAnneSmokeX], a ld c, a ld b, 100 ; Y ld a, [wSSAnneSmokeDriftAmount] inc a ld [wSSAnneSmokeDriftAmount], a ld a, $1 ld de, VermilionDockOAMBlock call WriteOAMBlock ret VermilionDockOAMBlock: db $fc, $10 db $fd, $10 db $fe, $10 db $ff, $10 VermilionDock_1dc7c: ld h, d ld l, $50 call .asm_1dc86 ld h, $0 ld l, $80 .asm_1dc86 ld a, [rLY] cp l jr nz, .asm_1dc86 ld a, h ld [rSCX], a .asm_1dc8e ld a, [rLY] cp h jr z, .asm_1dc8e ret VermilionDock_EraseSSAnne: ; Fill the area the S.S. Anne occupies in BG map 0 with water tiles. ld hl, wVermilionDockTileMapBuffer ld bc, (5 * BG_MAP_WIDTH) + SCREEN_WIDTH ld a, $14 ; water tile call FillMemory ld hl, vBGMap0 + 10 * BG_MAP_WIDTH ld de, wVermilionDockTileMapBuffer ld bc, (6 * BG_MAP_WIDTH) / 16 call CopyVideoData ; Replace the blocks of the lower half of the ship with water blocks. This ; leaves the upper half alone, but that doesn't matter because replacing any of ; the blocks is unnecessary because the blocks the ship occupies are south of ; the player and won't be redrawn when the player automatically walks north and ; exits the map. This code could be removed without affecting anything. overworldMapCoord hl, 5, 2, VERMILION_DOCK_WIDTH ld a, $d ; water block ld [hli], a ld [hli], a ld [hli], a ld [hl], a ld a, SFX_SS_ANNE_HORN call PlaySound ld c, 120 call DelayFrames ret VermilionDockTextPointers: dw VermilionDockText1 VermilionDockText1: TX_FAR _VermilionDockText1 db "@"
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2018 BSG Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bitcoinunits.h" #include "chainparams.h" #include "primitives/transaction.h" #include <QSettings> #include <QStringList> BitcoinUnits::BitcoinUnits(QObject* parent) : QAbstractListModel(parent), unitlist(availableUnits()) { } QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits() { QList<BitcoinUnits::Unit> unitlist; unitlist.append(BSG); unitlist.append(mBSG); unitlist.append(uBSG); return unitlist; } bool BitcoinUnits::valid(int unit) { switch (unit) { case BSG: case mBSG: case uBSG: return true; default: return false; } } QString BitcoinUnits::id(int unit) { switch (unit) { case BSG: return QString("blowsbig"); case mBSG: return QString("mblowsbig"); case uBSG: return QString::fromUtf8("ublowsbig"); default: return QString("???"); } } QString BitcoinUnits::name(int unit) { if (Params().NetworkID() == CBaseChainParams::MAIN) { switch (unit) { case BSG: return QString("BSG"); case mBSG: return QString("mBSG"); case uBSG: return QString::fromUtf8("μBSG"); default: return QString("???"); } } else { switch (unit) { case BSG: return QString("tBSG"); case mBSG: return QString("mtBSG"); case uBSG: return QString::fromUtf8("μtBSG"); default: return QString("???"); } } } QString BitcoinUnits::description(int unit) { if (Params().NetworkID() == CBaseChainParams::MAIN) { switch (unit) { case BSG: return QString("BSG"); case mBSG: return QString("Milli-BSG (1 / 1" THIN_SP_UTF8 "000)"); case uBSG: return QString("Micro-BSG (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)"); default: return QString("???"); } } else { switch (unit) { case BSG: return QString("TestBSGs"); case mBSG: return QString("Milli-TestBSG (1 / 1" THIN_SP_UTF8 "000)"); case uBSG: return QString("Micro-TestBSG (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)"); default: return QString("???"); } } } qint64 BitcoinUnits::factor(int unit) { switch (unit) { case BSG: return 100000000; case mBSG: return 100000; case uBSG: return 100; default: return 100000000; } } int BitcoinUnits::decimals(int unit) { switch (unit) { case BSG: return 8; case mBSG: return 5; case uBSG: return 2; default: return 0; } } QString BitcoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. if (!valid(unit)) return QString(); // Refuse to format invalid unit qint64 n = (qint64)nIn; qint64 coin = factor(unit); int num_decimals = decimals(unit); qint64 n_abs = (n > 0 ? n : -n); qint64 quotient = n_abs / coin; qint64 remainder = n_abs % coin; QString quotient_str = QString::number(quotient); QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0'); // Use SI-style thin space separators as these are locale independent and can't be // confused with the decimal marker. QChar thin_sp(THIN_SP_CP); int q_size = quotient_str.size(); if (separators == separatorAlways || (separators == separatorStandard && q_size > 4)) for (int i = 3; i < q_size; i += 3) quotient_str.insert(q_size - i, thin_sp); if (n < 0) quotient_str.insert(0, '-'); else if (fPlus && n > 0) quotient_str.insert(0, '+'); if (num_decimals <= 0) return quotient_str; return quotient_str + QString(".") + remainder_str; } // TODO: Review all remaining calls to BitcoinUnits::formatWithUnit to // TODO: determine whether the output is used in a plain text context // TODO: or an HTML context (and replace with // TODO: BtcoinUnits::formatHtmlWithUnit in the latter case). Hopefully // TODO: there aren't instances where the result could be used in // TODO: either context. // NOTE: Using formatWithUnit in an HTML context risks wrapping // quantities at the thousands separator. More subtly, it also results // in a standard space rather than a thin space, due to a bug in Qt's // XML whitespace canonicalisation // // Please take care to use formatHtmlWithUnit instead, when // appropriate. QString BitcoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { return format(unit, amount, plussign, separators) + QString(" ") + name(unit); } QString BitcoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { QString str(formatWithUnit(unit, amount, plussign, separators)); str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML)); return QString("<span style='white-space: nowrap;'>%1</span>").arg(str); } QString BitcoinUnits::floorWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { QSettings settings; int digits = settings.value("digits").toInt(); QString result = format(unit, amount, plussign, separators); if (decimals(unit) > digits) result.chop(decimals(unit) - digits); return result + QString(" ") + name(unit); } QString BitcoinUnits::floorHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { QString str(floorWithUnit(unit, amount, plussign, separators)); str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML)); return QString("<span style='white-space: nowrap;'>%1</span>").arg(str); } bool BitcoinUnits::parse(int unit, const QString& value, CAmount* val_out) { if (!valid(unit) || value.isEmpty()) return false; // Refuse to parse invalid unit or empty string int num_decimals = decimals(unit); // Ignore spaces and thin spaces when parsing QStringList parts = removeSpaces(value).split("."); if (parts.size() > 2) { return false; // More than one dot } QString whole = parts[0]; QString decimals; if (parts.size() > 1) { decimals = parts[1]; } if (decimals.size() > num_decimals) { return false; // Exceeds max precision } bool ok = false; QString str = whole + decimals.leftJustified(num_decimals, '0'); if (str.size() > 18) { return false; // Longer numbers will exceed 63 bits } CAmount retvalue(str.toLongLong(&ok)); if (val_out) { *val_out = retvalue; } return ok; } QString BitcoinUnits::getAmountColumnTitle(int unit) { QString amountTitle = QObject::tr("Amount"); if (BitcoinUnits::valid(unit)) { amountTitle += " (" + BitcoinUnits::name(unit) + ")"; } return amountTitle; } int BitcoinUnits::rowCount(const QModelIndex& parent) const { Q_UNUSED(parent); return unitlist.size(); } QVariant BitcoinUnits::data(const QModelIndex& index, int role) const { int row = index.row(); if (row >= 0 && row < unitlist.size()) { Unit unit = unitlist.at(row); switch (role) { case Qt::EditRole: case Qt::DisplayRole: return QVariant(name(unit)); case Qt::ToolTipRole: return QVariant(description(unit)); case UnitRole: return QVariant(static_cast<int>(unit)); } } return QVariant(); } CAmount BitcoinUnits::maxMoney() { return Params().MaxMoneyOut(); }
;------------------------------------------------------------------------------ ; ; Copyright (c) 2016, Intel Corporation. All rights reserved.<BR> ; This program and the accompanying materials ; are licensed and made available under the terms and conditions of the BSD License ; which accompanies this distribution. The full text of the license may be found at ; http://opensource.org/licenses/bsd-license.php. ; ; THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, ; WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. ; ; Abstract: ; ; FSP Debug functions ; ;------------------------------------------------------------------------------ SECTION .text ;------------------------------------------------------------------------------ ; UINT32 * ; EFIAPI ; GetStackFramePointer ( ; VOID ; ); ;------------------------------------------------------------------------------ global ASM_PFX(GetStackFramePointer) ASM_PFX(GetStackFramePointer): mov eax, ebp ret
DEVICE ZXSPECTRUM1024 ORG $8000 regular: equClassic: EQU $4000 ; actually in current v1.17.0 this will still receive "page 5" page based ; on the current memory mapping and the address value, but in docs it's ; described as "irrelevant". This test is documenting the behaviour for ; the sake of the test, not making it official/guaranteed, avoid using it equWithPage: EQU $4001 , 1 ASSERT $8000 == regular && 2 == $$regular ASSERT $4000 == equClassic && 5 == $$equClassic ASSERT $4001 == equWithPage && 1 == $$equWithPage errorEqu1 EQU $4002 , errorEqu2 EQU $4003 , @
MENU_CONFIG_ANIMS_BANK_NUMBER = CURRENT_BANK_NUMBER menu_config_anim_cursor: ; Frame 1 ANIM_FRAME_BEGIN(8) ANIM_SPRITE($fe, TILE_MENU_CONFIG_SPRITES_CORNER, $00, $fd) ANIM_SPRITE($fe, TILE_MENU_CONFIG_SPRITES_CORNER, $40, $42) ANIM_SPRITE($0a, TILE_MENU_CONFIG_SPRITES_CORNER, $80, $fd) ANIM_SPRITE($0a, TILE_MENU_CONFIG_SPRITES_CORNER, $c0, $42) ANIM_SPRITE($09, TILE_MENU_CONFIG_SPRITES_ARROW_HORIZONTAL, $40, $01) ANIM_SPRITE($09, TILE_MENU_CONFIG_SPRITES_ARROW_HORIZONTAL, $00, $3d) ANIM_FRAME_END ; Frame 2 ANIM_FRAME_BEGIN(8) ANIM_SPRITE($fd, TILE_MENU_CONFIG_SPRITES_CORNER, $00, $fc) ANIM_SPRITE($fd, TILE_MENU_CONFIG_SPRITES_CORNER, $40, $43) ANIM_SPRITE($0b, TILE_MENU_CONFIG_SPRITES_CORNER, $80, $fc) ANIM_SPRITE($0b, TILE_MENU_CONFIG_SPRITES_CORNER, $c0, $43) ANIM_SPRITE($09, TILE_MENU_CONFIG_SPRITES_ARROW_HORIZONTAL, $40, $00) ANIM_SPRITE($09, TILE_MENU_CONFIG_SPRITES_ARROW_HORIZONTAL, $00, $3e) ANIM_FRAME_END ; Frame 3 ANIM_FRAME_BEGIN(8) ANIM_SPRITE($fe, TILE_MENU_CONFIG_SPRITES_CORNER, $00, $fd) ANIM_SPRITE($fe, TILE_MENU_CONFIG_SPRITES_CORNER, $40, $42) ANIM_SPRITE($0a, TILE_MENU_CONFIG_SPRITES_CORNER, $80, $fd) ANIM_SPRITE($0a, TILE_MENU_CONFIG_SPRITES_CORNER, $c0, $42) ANIM_SPRITE($09, TILE_MENU_CONFIG_SPRITES_ARROW_HORIZONTAL, $40, $01) ANIM_SPRITE($09, TILE_MENU_CONFIG_SPRITES_ARROW_HORIZONTAL, $00, $3d) ANIM_FRAME_END ; Frame 4 ANIM_FRAME_BEGIN(8) ANIM_SPRITE($fd, TILE_MENU_CONFIG_SPRITES_CORNER, $00, $fc) ANIM_SPRITE($fd, TILE_MENU_CONFIG_SPRITES_CORNER, $40, $43) ANIM_SPRITE($0b, TILE_MENU_CONFIG_SPRITES_CORNER, $80, $fc) ANIM_SPRITE($0b, TILE_MENU_CONFIG_SPRITES_CORNER, $c0, $43) ANIM_SPRITE($09, TILE_MENU_CONFIG_SPRITES_ARROW_HORIZONTAL, $40, $02) ANIM_SPRITE($09, TILE_MENU_CONFIG_SPRITES_ARROW_HORIZONTAL, $00, $3c) ANIM_FRAME_END ; End of animation ANIM_ANIMATION_END
cpy #0 beq !e+ !: lsr {m1}+3 ror {m1}+2 ror {m1}+1 ror {m1} dey bne !- !e:
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_D3D9_DEVICEFUNCS_SET_SCISSOR_RECT_HPP_INCLUDED #define SGE_D3D9_DEVICEFUNCS_SET_SCISSOR_RECT_HPP_INCLUDED #include <sge/d3d9/d3dinclude.hpp> #include <sge/renderer/target/scissor_area_fwd.hpp> namespace sge { namespace d3d9 { namespace devicefuncs { void set_scissor_rect(IDirect3DDevice9 &, sge::renderer::target::scissor_area const &); } } } #endif
; A097039: a(n) = Sum_{i=0..n} i*L(i), where L = A000032. ; 0,1,7,19,47,102,210,413,789,1473,2703,4892,8756,15529,27331,47791,83103,143810,247814,425445,727985,1241981,2113247,3587064,6075432,10269457,17326975,29185483,49083599,82429278,138244218,231565037 lpb $0 add $2,$0 add $3,$0 sub $0,1 add $4,$2 mov $1,$4 sub $1,$3 add $1,$4 mov $2,$3 mov $3,$4 lpe
SFX_Snare8_1_Ch7: unknownnoise0x20 0, 130, 37 endchannel
; A309337: a(n) = n^3 if n odd, 3*n^3/4 if n even. ; 0,1,6,27,48,125,162,343,384,729,750,1331,1296,2197,2058,3375,3072,4913,4374,6859,6000,9261,7986,12167,10368,15625,13182,19683,16464,24389,20250,29791,24576,35937,29478,42875,34992,50653,41154,59319,48000,68921,55566,79507,63888,91125,73002,103823,82944,117649,93750,132651,105456,148877,118098,166375,131712,185193,146334,205379,162000,226981,178746,250047,196608,274625,215622,300763,235824,328509,257250,357911,279936,389017,303918,421875,329232,456533,355914,493039,384000,531441,413526,571787,444528,614125,477042,658503,511104,704969,546750,753571,584016,804357,622938,857375,663552,912673,705894,970299 pow $0,3 mov $1,$0 dif $0,2 add $0,$1 div $0,2
_ln: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { 0: 55 push %ebp 1: 89 e5 mov %esp,%ebp 3: 83 e4 f0 and $0xfffffff0,%esp 6: 83 ec 10 sub $0x10,%esp if(argc != 3){ 9: 83 7d 08 03 cmpl $0x3,0x8(%ebp) d: 74 19 je 28 <main+0x28> printf(2, "Usage: ln old new\n"); f: c7 44 24 04 3d 08 00 movl $0x83d,0x4(%esp) 16: 00 17: c7 04 24 02 00 00 00 movl $0x2,(%esp) 1e: e8 4e 04 00 00 call 471 <printf> exit(); 23: e8 b9 02 00 00 call 2e1 <exit> } if(link(argv[1], argv[2]) < 0) 28: 8b 45 0c mov 0xc(%ebp),%eax 2b: 83 c0 08 add $0x8,%eax 2e: 8b 10 mov (%eax),%edx 30: 8b 45 0c mov 0xc(%ebp),%eax 33: 83 c0 04 add $0x4,%eax 36: 8b 00 mov (%eax),%eax 38: 89 54 24 04 mov %edx,0x4(%esp) 3c: 89 04 24 mov %eax,(%esp) 3f: e8 fd 02 00 00 call 341 <link> 44: 85 c0 test %eax,%eax 46: 79 2c jns 74 <main+0x74> printf(2, "link %s %s: failed\n", argv[1], argv[2]); 48: 8b 45 0c mov 0xc(%ebp),%eax 4b: 83 c0 08 add $0x8,%eax 4e: 8b 10 mov (%eax),%edx 50: 8b 45 0c mov 0xc(%ebp),%eax 53: 83 c0 04 add $0x4,%eax 56: 8b 00 mov (%eax),%eax 58: 89 54 24 0c mov %edx,0xc(%esp) 5c: 89 44 24 08 mov %eax,0x8(%esp) 60: c7 44 24 04 50 08 00 movl $0x850,0x4(%esp) 67: 00 68: c7 04 24 02 00 00 00 movl $0x2,(%esp) 6f: e8 fd 03 00 00 call 471 <printf> exit(); 74: e8 68 02 00 00 call 2e1 <exit> 00000079 <stosb>: "cc"); } static inline void stosb(void *addr, int data, int cnt) { 79: 55 push %ebp 7a: 89 e5 mov %esp,%ebp 7c: 57 push %edi 7d: 53 push %ebx asm volatile("cld; rep stosb" : 7e: 8b 4d 08 mov 0x8(%ebp),%ecx 81: 8b 55 10 mov 0x10(%ebp),%edx 84: 8b 45 0c mov 0xc(%ebp),%eax 87: 89 cb mov %ecx,%ebx 89: 89 df mov %ebx,%edi 8b: 89 d1 mov %edx,%ecx 8d: fc cld 8e: f3 aa rep stos %al,%es:(%edi) 90: 89 ca mov %ecx,%edx 92: 89 fb mov %edi,%ebx 94: 89 5d 08 mov %ebx,0x8(%ebp) 97: 89 55 10 mov %edx,0x10(%ebp) "=D" (addr), "=c" (cnt) : "0" (addr), "1" (cnt), "a" (data) : "memory", "cc"); } 9a: 5b pop %ebx 9b: 5f pop %edi 9c: 5d pop %ebp 9d: c3 ret 0000009e <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 9e: 55 push %ebp 9f: 89 e5 mov %esp,%ebp a1: 83 ec 10 sub $0x10,%esp char *os; os = s; a4: 8b 45 08 mov 0x8(%ebp),%eax a7: 89 45 fc mov %eax,-0x4(%ebp) while((*s++ = *t++) != 0) aa: 90 nop ab: 8b 45 08 mov 0x8(%ebp),%eax ae: 8d 50 01 lea 0x1(%eax),%edx b1: 89 55 08 mov %edx,0x8(%ebp) b4: 8b 55 0c mov 0xc(%ebp),%edx b7: 8d 4a 01 lea 0x1(%edx),%ecx ba: 89 4d 0c mov %ecx,0xc(%ebp) bd: 0f b6 12 movzbl (%edx),%edx c0: 88 10 mov %dl,(%eax) c2: 0f b6 00 movzbl (%eax),%eax c5: 84 c0 test %al,%al c7: 75 e2 jne ab <strcpy+0xd> ; return os; c9: 8b 45 fc mov -0x4(%ebp),%eax } cc: c9 leave cd: c3 ret 000000ce <strcmp>: int strcmp(const char *p, const char *q) { ce: 55 push %ebp cf: 89 e5 mov %esp,%ebp while(*p && *p == *q) d1: eb 08 jmp db <strcmp+0xd> p++, q++; d3: 83 45 08 01 addl $0x1,0x8(%ebp) d7: 83 45 0c 01 addl $0x1,0xc(%ebp) } int strcmp(const char *p, const char *q) { while(*p && *p == *q) db: 8b 45 08 mov 0x8(%ebp),%eax de: 0f b6 00 movzbl (%eax),%eax e1: 84 c0 test %al,%al e3: 74 10 je f5 <strcmp+0x27> e5: 8b 45 08 mov 0x8(%ebp),%eax e8: 0f b6 10 movzbl (%eax),%edx eb: 8b 45 0c mov 0xc(%ebp),%eax ee: 0f b6 00 movzbl (%eax),%eax f1: 38 c2 cmp %al,%dl f3: 74 de je d3 <strcmp+0x5> p++, q++; return (uchar)*p - (uchar)*q; f5: 8b 45 08 mov 0x8(%ebp),%eax f8: 0f b6 00 movzbl (%eax),%eax fb: 0f b6 d0 movzbl %al,%edx fe: 8b 45 0c mov 0xc(%ebp),%eax 101: 0f b6 00 movzbl (%eax),%eax 104: 0f b6 c0 movzbl %al,%eax 107: 29 c2 sub %eax,%edx 109: 89 d0 mov %edx,%eax } 10b: 5d pop %ebp 10c: c3 ret 0000010d <strlen>: uint strlen(char *s) { 10d: 55 push %ebp 10e: 89 e5 mov %esp,%ebp 110: 83 ec 10 sub $0x10,%esp int n; for(n = 0; s[n]; n++) 113: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) 11a: eb 04 jmp 120 <strlen+0x13> 11c: 83 45 fc 01 addl $0x1,-0x4(%ebp) 120: 8b 55 fc mov -0x4(%ebp),%edx 123: 8b 45 08 mov 0x8(%ebp),%eax 126: 01 d0 add %edx,%eax 128: 0f b6 00 movzbl (%eax),%eax 12b: 84 c0 test %al,%al 12d: 75 ed jne 11c <strlen+0xf> ; return n; 12f: 8b 45 fc mov -0x4(%ebp),%eax } 132: c9 leave 133: c3 ret 00000134 <memset>: void* memset(void *dst, int c, uint n) { 134: 55 push %ebp 135: 89 e5 mov %esp,%ebp 137: 83 ec 0c sub $0xc,%esp stosb(dst, c, n); 13a: 8b 45 10 mov 0x10(%ebp),%eax 13d: 89 44 24 08 mov %eax,0x8(%esp) 141: 8b 45 0c mov 0xc(%ebp),%eax 144: 89 44 24 04 mov %eax,0x4(%esp) 148: 8b 45 08 mov 0x8(%ebp),%eax 14b: 89 04 24 mov %eax,(%esp) 14e: e8 26 ff ff ff call 79 <stosb> return dst; 153: 8b 45 08 mov 0x8(%ebp),%eax } 156: c9 leave 157: c3 ret 00000158 <strchr>: char* strchr(const char *s, char c) { 158: 55 push %ebp 159: 89 e5 mov %esp,%ebp 15b: 83 ec 04 sub $0x4,%esp 15e: 8b 45 0c mov 0xc(%ebp),%eax 161: 88 45 fc mov %al,-0x4(%ebp) for(; *s; s++) 164: eb 14 jmp 17a <strchr+0x22> if(*s == c) 166: 8b 45 08 mov 0x8(%ebp),%eax 169: 0f b6 00 movzbl (%eax),%eax 16c: 3a 45 fc cmp -0x4(%ebp),%al 16f: 75 05 jne 176 <strchr+0x1e> return (char*)s; 171: 8b 45 08 mov 0x8(%ebp),%eax 174: eb 13 jmp 189 <strchr+0x31> } char* strchr(const char *s, char c) { for(; *s; s++) 176: 83 45 08 01 addl $0x1,0x8(%ebp) 17a: 8b 45 08 mov 0x8(%ebp),%eax 17d: 0f b6 00 movzbl (%eax),%eax 180: 84 c0 test %al,%al 182: 75 e2 jne 166 <strchr+0xe> if(*s == c) return (char*)s; return 0; 184: b8 00 00 00 00 mov $0x0,%eax } 189: c9 leave 18a: c3 ret 0000018b <gets>: char* gets(char *buf, int max) { 18b: 55 push %ebp 18c: 89 e5 mov %esp,%ebp 18e: 83 ec 28 sub $0x28,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 191: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 198: eb 4c jmp 1e6 <gets+0x5b> cc = read(0, &c, 1); 19a: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 1a1: 00 1a2: 8d 45 ef lea -0x11(%ebp),%eax 1a5: 89 44 24 04 mov %eax,0x4(%esp) 1a9: c7 04 24 00 00 00 00 movl $0x0,(%esp) 1b0: e8 44 01 00 00 call 2f9 <read> 1b5: 89 45 f0 mov %eax,-0x10(%ebp) if(cc < 1) 1b8: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 1bc: 7f 02 jg 1c0 <gets+0x35> break; 1be: eb 31 jmp 1f1 <gets+0x66> buf[i++] = c; 1c0: 8b 45 f4 mov -0xc(%ebp),%eax 1c3: 8d 50 01 lea 0x1(%eax),%edx 1c6: 89 55 f4 mov %edx,-0xc(%ebp) 1c9: 89 c2 mov %eax,%edx 1cb: 8b 45 08 mov 0x8(%ebp),%eax 1ce: 01 c2 add %eax,%edx 1d0: 0f b6 45 ef movzbl -0x11(%ebp),%eax 1d4: 88 02 mov %al,(%edx) if(c == '\n' || c == '\r') 1d6: 0f b6 45 ef movzbl -0x11(%ebp),%eax 1da: 3c 0a cmp $0xa,%al 1dc: 74 13 je 1f1 <gets+0x66> 1de: 0f b6 45 ef movzbl -0x11(%ebp),%eax 1e2: 3c 0d cmp $0xd,%al 1e4: 74 0b je 1f1 <gets+0x66> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 1e6: 8b 45 f4 mov -0xc(%ebp),%eax 1e9: 83 c0 01 add $0x1,%eax 1ec: 3b 45 0c cmp 0xc(%ebp),%eax 1ef: 7c a9 jl 19a <gets+0xf> break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 1f1: 8b 55 f4 mov -0xc(%ebp),%edx 1f4: 8b 45 08 mov 0x8(%ebp),%eax 1f7: 01 d0 add %edx,%eax 1f9: c6 00 00 movb $0x0,(%eax) return buf; 1fc: 8b 45 08 mov 0x8(%ebp),%eax } 1ff: c9 leave 200: c3 ret 00000201 <stat>: int stat(char *n, struct stat *st) { 201: 55 push %ebp 202: 89 e5 mov %esp,%ebp 204: 83 ec 28 sub $0x28,%esp int fd; int r; fd = open(n, O_RDONLY); 207: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp) 20e: 00 20f: 8b 45 08 mov 0x8(%ebp),%eax 212: 89 04 24 mov %eax,(%esp) 215: e8 07 01 00 00 call 321 <open> 21a: 89 45 f4 mov %eax,-0xc(%ebp) if(fd < 0) 21d: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 221: 79 07 jns 22a <stat+0x29> return -1; 223: b8 ff ff ff ff mov $0xffffffff,%eax 228: eb 23 jmp 24d <stat+0x4c> r = fstat(fd, st); 22a: 8b 45 0c mov 0xc(%ebp),%eax 22d: 89 44 24 04 mov %eax,0x4(%esp) 231: 8b 45 f4 mov -0xc(%ebp),%eax 234: 89 04 24 mov %eax,(%esp) 237: e8 fd 00 00 00 call 339 <fstat> 23c: 89 45 f0 mov %eax,-0x10(%ebp) close(fd); 23f: 8b 45 f4 mov -0xc(%ebp),%eax 242: 89 04 24 mov %eax,(%esp) 245: e8 bf 00 00 00 call 309 <close> return r; 24a: 8b 45 f0 mov -0x10(%ebp),%eax } 24d: c9 leave 24e: c3 ret 0000024f <atoi>: int atoi(const char *s) { 24f: 55 push %ebp 250: 89 e5 mov %esp,%ebp 252: 83 ec 10 sub $0x10,%esp int n; n = 0; 255: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) while('0' <= *s && *s <= '9') 25c: eb 25 jmp 283 <atoi+0x34> n = n*10 + *s++ - '0'; 25e: 8b 55 fc mov -0x4(%ebp),%edx 261: 89 d0 mov %edx,%eax 263: c1 e0 02 shl $0x2,%eax 266: 01 d0 add %edx,%eax 268: 01 c0 add %eax,%eax 26a: 89 c1 mov %eax,%ecx 26c: 8b 45 08 mov 0x8(%ebp),%eax 26f: 8d 50 01 lea 0x1(%eax),%edx 272: 89 55 08 mov %edx,0x8(%ebp) 275: 0f b6 00 movzbl (%eax),%eax 278: 0f be c0 movsbl %al,%eax 27b: 01 c8 add %ecx,%eax 27d: 83 e8 30 sub $0x30,%eax 280: 89 45 fc mov %eax,-0x4(%ebp) atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') 283: 8b 45 08 mov 0x8(%ebp),%eax 286: 0f b6 00 movzbl (%eax),%eax 289: 3c 2f cmp $0x2f,%al 28b: 7e 0a jle 297 <atoi+0x48> 28d: 8b 45 08 mov 0x8(%ebp),%eax 290: 0f b6 00 movzbl (%eax),%eax 293: 3c 39 cmp $0x39,%al 295: 7e c7 jle 25e <atoi+0xf> n = n*10 + *s++ - '0'; return n; 297: 8b 45 fc mov -0x4(%ebp),%eax } 29a: c9 leave 29b: c3 ret 0000029c <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 29c: 55 push %ebp 29d: 89 e5 mov %esp,%ebp 29f: 83 ec 10 sub $0x10,%esp char *dst, *src; dst = vdst; 2a2: 8b 45 08 mov 0x8(%ebp),%eax 2a5: 89 45 fc mov %eax,-0x4(%ebp) src = vsrc; 2a8: 8b 45 0c mov 0xc(%ebp),%eax 2ab: 89 45 f8 mov %eax,-0x8(%ebp) while(n-- > 0) 2ae: eb 17 jmp 2c7 <memmove+0x2b> *dst++ = *src++; 2b0: 8b 45 fc mov -0x4(%ebp),%eax 2b3: 8d 50 01 lea 0x1(%eax),%edx 2b6: 89 55 fc mov %edx,-0x4(%ebp) 2b9: 8b 55 f8 mov -0x8(%ebp),%edx 2bc: 8d 4a 01 lea 0x1(%edx),%ecx 2bf: 89 4d f8 mov %ecx,-0x8(%ebp) 2c2: 0f b6 12 movzbl (%edx),%edx 2c5: 88 10 mov %dl,(%eax) { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 2c7: 8b 45 10 mov 0x10(%ebp),%eax 2ca: 8d 50 ff lea -0x1(%eax),%edx 2cd: 89 55 10 mov %edx,0x10(%ebp) 2d0: 85 c0 test %eax,%eax 2d2: 7f dc jg 2b0 <memmove+0x14> *dst++ = *src++; return vdst; 2d4: 8b 45 08 mov 0x8(%ebp),%eax } 2d7: c9 leave 2d8: c3 ret 000002d9 <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 2d9: b8 01 00 00 00 mov $0x1,%eax 2de: cd 40 int $0x40 2e0: c3 ret 000002e1 <exit>: SYSCALL(exit) 2e1: b8 02 00 00 00 mov $0x2,%eax 2e6: cd 40 int $0x40 2e8: c3 ret 000002e9 <wait>: SYSCALL(wait) 2e9: b8 03 00 00 00 mov $0x3,%eax 2ee: cd 40 int $0x40 2f0: c3 ret 000002f1 <pipe>: SYSCALL(pipe) 2f1: b8 04 00 00 00 mov $0x4,%eax 2f6: cd 40 int $0x40 2f8: c3 ret 000002f9 <read>: SYSCALL(read) 2f9: b8 05 00 00 00 mov $0x5,%eax 2fe: cd 40 int $0x40 300: c3 ret 00000301 <write>: SYSCALL(write) 301: b8 10 00 00 00 mov $0x10,%eax 306: cd 40 int $0x40 308: c3 ret 00000309 <close>: SYSCALL(close) 309: b8 15 00 00 00 mov $0x15,%eax 30e: cd 40 int $0x40 310: c3 ret 00000311 <kill>: SYSCALL(kill) 311: b8 06 00 00 00 mov $0x6,%eax 316: cd 40 int $0x40 318: c3 ret 00000319 <exec>: SYSCALL(exec) 319: b8 07 00 00 00 mov $0x7,%eax 31e: cd 40 int $0x40 320: c3 ret 00000321 <open>: SYSCALL(open) 321: b8 0f 00 00 00 mov $0xf,%eax 326: cd 40 int $0x40 328: c3 ret 00000329 <mknod>: SYSCALL(mknod) 329: b8 11 00 00 00 mov $0x11,%eax 32e: cd 40 int $0x40 330: c3 ret 00000331 <unlink>: SYSCALL(unlink) 331: b8 12 00 00 00 mov $0x12,%eax 336: cd 40 int $0x40 338: c3 ret 00000339 <fstat>: SYSCALL(fstat) 339: b8 08 00 00 00 mov $0x8,%eax 33e: cd 40 int $0x40 340: c3 ret 00000341 <link>: SYSCALL(link) 341: b8 13 00 00 00 mov $0x13,%eax 346: cd 40 int $0x40 348: c3 ret 00000349 <mkdir>: SYSCALL(mkdir) 349: b8 14 00 00 00 mov $0x14,%eax 34e: cd 40 int $0x40 350: c3 ret 00000351 <chdir>: SYSCALL(chdir) 351: b8 09 00 00 00 mov $0x9,%eax 356: cd 40 int $0x40 358: c3 ret 00000359 <dup>: SYSCALL(dup) 359: b8 0a 00 00 00 mov $0xa,%eax 35e: cd 40 int $0x40 360: c3 ret 00000361 <getpid>: SYSCALL(getpid) 361: b8 0b 00 00 00 mov $0xb,%eax 366: cd 40 int $0x40 368: c3 ret 00000369 <sbrk>: SYSCALL(sbrk) 369: b8 0c 00 00 00 mov $0xc,%eax 36e: cd 40 int $0x40 370: c3 ret 00000371 <sleep>: SYSCALL(sleep) 371: b8 0d 00 00 00 mov $0xd,%eax 376: cd 40 int $0x40 378: c3 ret 00000379 <uptime>: SYSCALL(uptime) 379: b8 0e 00 00 00 mov $0xe,%eax 37e: cd 40 int $0x40 380: c3 ret 00000381 <history>: SYSCALL(history) 381: b8 16 00 00 00 mov $0x16,%eax 386: cd 40 int $0x40 388: c3 ret 00000389 <wait2>: SYSCALL(wait2) 389: b8 17 00 00 00 mov $0x17,%eax 38e: cd 40 int $0x40 390: c3 ret 00000391 <putc>: #include "stat.h" #include "user.h" static void putc(int fd, char c) { 391: 55 push %ebp 392: 89 e5 mov %esp,%ebp 394: 83 ec 18 sub $0x18,%esp 397: 8b 45 0c mov 0xc(%ebp),%eax 39a: 88 45 f4 mov %al,-0xc(%ebp) write(fd, &c, 1); 39d: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 3a4: 00 3a5: 8d 45 f4 lea -0xc(%ebp),%eax 3a8: 89 44 24 04 mov %eax,0x4(%esp) 3ac: 8b 45 08 mov 0x8(%ebp),%eax 3af: 89 04 24 mov %eax,(%esp) 3b2: e8 4a ff ff ff call 301 <write> } 3b7: c9 leave 3b8: c3 ret 000003b9 <printint>: static void printint(int fd, int xx, int base, int sgn) { 3b9: 55 push %ebp 3ba: 89 e5 mov %esp,%ebp 3bc: 56 push %esi 3bd: 53 push %ebx 3be: 83 ec 30 sub $0x30,%esp static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 3c1: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) if(sgn && xx < 0){ 3c8: 83 7d 14 00 cmpl $0x0,0x14(%ebp) 3cc: 74 17 je 3e5 <printint+0x2c> 3ce: 83 7d 0c 00 cmpl $0x0,0xc(%ebp) 3d2: 79 11 jns 3e5 <printint+0x2c> neg = 1; 3d4: c7 45 f0 01 00 00 00 movl $0x1,-0x10(%ebp) x = -xx; 3db: 8b 45 0c mov 0xc(%ebp),%eax 3de: f7 d8 neg %eax 3e0: 89 45 ec mov %eax,-0x14(%ebp) 3e3: eb 06 jmp 3eb <printint+0x32> } else { x = xx; 3e5: 8b 45 0c mov 0xc(%ebp),%eax 3e8: 89 45 ec mov %eax,-0x14(%ebp) } i = 0; 3eb: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) do{ buf[i++] = digits[x % base]; 3f2: 8b 4d f4 mov -0xc(%ebp),%ecx 3f5: 8d 41 01 lea 0x1(%ecx),%eax 3f8: 89 45 f4 mov %eax,-0xc(%ebp) 3fb: 8b 5d 10 mov 0x10(%ebp),%ebx 3fe: 8b 45 ec mov -0x14(%ebp),%eax 401: ba 00 00 00 00 mov $0x0,%edx 406: f7 f3 div %ebx 408: 89 d0 mov %edx,%eax 40a: 0f b6 80 b0 0a 00 00 movzbl 0xab0(%eax),%eax 411: 88 44 0d dc mov %al,-0x24(%ebp,%ecx,1) }while((x /= base) != 0); 415: 8b 75 10 mov 0x10(%ebp),%esi 418: 8b 45 ec mov -0x14(%ebp),%eax 41b: ba 00 00 00 00 mov $0x0,%edx 420: f7 f6 div %esi 422: 89 45 ec mov %eax,-0x14(%ebp) 425: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 429: 75 c7 jne 3f2 <printint+0x39> if(neg) 42b: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 42f: 74 10 je 441 <printint+0x88> buf[i++] = '-'; 431: 8b 45 f4 mov -0xc(%ebp),%eax 434: 8d 50 01 lea 0x1(%eax),%edx 437: 89 55 f4 mov %edx,-0xc(%ebp) 43a: c6 44 05 dc 2d movb $0x2d,-0x24(%ebp,%eax,1) while(--i >= 0) 43f: eb 1f jmp 460 <printint+0xa7> 441: eb 1d jmp 460 <printint+0xa7> putc(fd, buf[i]); 443: 8d 55 dc lea -0x24(%ebp),%edx 446: 8b 45 f4 mov -0xc(%ebp),%eax 449: 01 d0 add %edx,%eax 44b: 0f b6 00 movzbl (%eax),%eax 44e: 0f be c0 movsbl %al,%eax 451: 89 44 24 04 mov %eax,0x4(%esp) 455: 8b 45 08 mov 0x8(%ebp),%eax 458: 89 04 24 mov %eax,(%esp) 45b: e8 31 ff ff ff call 391 <putc> buf[i++] = digits[x % base]; }while((x /= base) != 0); if(neg) buf[i++] = '-'; while(--i >= 0) 460: 83 6d f4 01 subl $0x1,-0xc(%ebp) 464: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 468: 79 d9 jns 443 <printint+0x8a> putc(fd, buf[i]); } 46a: 83 c4 30 add $0x30,%esp 46d: 5b pop %ebx 46e: 5e pop %esi 46f: 5d pop %ebp 470: c3 ret 00000471 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 471: 55 push %ebp 472: 89 e5 mov %esp,%ebp 474: 83 ec 38 sub $0x38,%esp char *s; int c, i, state; uint *ap; state = 0; 477: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) ap = (uint*)(void*)&fmt + 1; 47e: 8d 45 0c lea 0xc(%ebp),%eax 481: 83 c0 04 add $0x4,%eax 484: 89 45 e8 mov %eax,-0x18(%ebp) for(i = 0; fmt[i]; i++){ 487: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) 48e: e9 7c 01 00 00 jmp 60f <printf+0x19e> c = fmt[i] & 0xff; 493: 8b 55 0c mov 0xc(%ebp),%edx 496: 8b 45 f0 mov -0x10(%ebp),%eax 499: 01 d0 add %edx,%eax 49b: 0f b6 00 movzbl (%eax),%eax 49e: 0f be c0 movsbl %al,%eax 4a1: 25 ff 00 00 00 and $0xff,%eax 4a6: 89 45 e4 mov %eax,-0x1c(%ebp) if(state == 0){ 4a9: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 4ad: 75 2c jne 4db <printf+0x6a> if(c == '%'){ 4af: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 4b3: 75 0c jne 4c1 <printf+0x50> state = '%'; 4b5: c7 45 ec 25 00 00 00 movl $0x25,-0x14(%ebp) 4bc: e9 4a 01 00 00 jmp 60b <printf+0x19a> } else { putc(fd, c); 4c1: 8b 45 e4 mov -0x1c(%ebp),%eax 4c4: 0f be c0 movsbl %al,%eax 4c7: 89 44 24 04 mov %eax,0x4(%esp) 4cb: 8b 45 08 mov 0x8(%ebp),%eax 4ce: 89 04 24 mov %eax,(%esp) 4d1: e8 bb fe ff ff call 391 <putc> 4d6: e9 30 01 00 00 jmp 60b <printf+0x19a> } } else if(state == '%'){ 4db: 83 7d ec 25 cmpl $0x25,-0x14(%ebp) 4df: 0f 85 26 01 00 00 jne 60b <printf+0x19a> if(c == 'd'){ 4e5: 83 7d e4 64 cmpl $0x64,-0x1c(%ebp) 4e9: 75 2d jne 518 <printf+0xa7> printint(fd, *ap, 10, 1); 4eb: 8b 45 e8 mov -0x18(%ebp),%eax 4ee: 8b 00 mov (%eax),%eax 4f0: c7 44 24 0c 01 00 00 movl $0x1,0xc(%esp) 4f7: 00 4f8: c7 44 24 08 0a 00 00 movl $0xa,0x8(%esp) 4ff: 00 500: 89 44 24 04 mov %eax,0x4(%esp) 504: 8b 45 08 mov 0x8(%ebp),%eax 507: 89 04 24 mov %eax,(%esp) 50a: e8 aa fe ff ff call 3b9 <printint> ap++; 50f: 83 45 e8 04 addl $0x4,-0x18(%ebp) 513: e9 ec 00 00 00 jmp 604 <printf+0x193> } else if(c == 'x' || c == 'p'){ 518: 83 7d e4 78 cmpl $0x78,-0x1c(%ebp) 51c: 74 06 je 524 <printf+0xb3> 51e: 83 7d e4 70 cmpl $0x70,-0x1c(%ebp) 522: 75 2d jne 551 <printf+0xe0> printint(fd, *ap, 16, 0); 524: 8b 45 e8 mov -0x18(%ebp),%eax 527: 8b 00 mov (%eax),%eax 529: c7 44 24 0c 00 00 00 movl $0x0,0xc(%esp) 530: 00 531: c7 44 24 08 10 00 00 movl $0x10,0x8(%esp) 538: 00 539: 89 44 24 04 mov %eax,0x4(%esp) 53d: 8b 45 08 mov 0x8(%ebp),%eax 540: 89 04 24 mov %eax,(%esp) 543: e8 71 fe ff ff call 3b9 <printint> ap++; 548: 83 45 e8 04 addl $0x4,-0x18(%ebp) 54c: e9 b3 00 00 00 jmp 604 <printf+0x193> } else if(c == 's'){ 551: 83 7d e4 73 cmpl $0x73,-0x1c(%ebp) 555: 75 45 jne 59c <printf+0x12b> s = (char*)*ap; 557: 8b 45 e8 mov -0x18(%ebp),%eax 55a: 8b 00 mov (%eax),%eax 55c: 89 45 f4 mov %eax,-0xc(%ebp) ap++; 55f: 83 45 e8 04 addl $0x4,-0x18(%ebp) if(s == 0) 563: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 567: 75 09 jne 572 <printf+0x101> s = "(null)"; 569: c7 45 f4 64 08 00 00 movl $0x864,-0xc(%ebp) while(*s != 0){ 570: eb 1e jmp 590 <printf+0x11f> 572: eb 1c jmp 590 <printf+0x11f> putc(fd, *s); 574: 8b 45 f4 mov -0xc(%ebp),%eax 577: 0f b6 00 movzbl (%eax),%eax 57a: 0f be c0 movsbl %al,%eax 57d: 89 44 24 04 mov %eax,0x4(%esp) 581: 8b 45 08 mov 0x8(%ebp),%eax 584: 89 04 24 mov %eax,(%esp) 587: e8 05 fe ff ff call 391 <putc> s++; 58c: 83 45 f4 01 addl $0x1,-0xc(%ebp) } else if(c == 's'){ s = (char*)*ap; ap++; if(s == 0) s = "(null)"; while(*s != 0){ 590: 8b 45 f4 mov -0xc(%ebp),%eax 593: 0f b6 00 movzbl (%eax),%eax 596: 84 c0 test %al,%al 598: 75 da jne 574 <printf+0x103> 59a: eb 68 jmp 604 <printf+0x193> putc(fd, *s); s++; } } else if(c == 'c'){ 59c: 83 7d e4 63 cmpl $0x63,-0x1c(%ebp) 5a0: 75 1d jne 5bf <printf+0x14e> putc(fd, *ap); 5a2: 8b 45 e8 mov -0x18(%ebp),%eax 5a5: 8b 00 mov (%eax),%eax 5a7: 0f be c0 movsbl %al,%eax 5aa: 89 44 24 04 mov %eax,0x4(%esp) 5ae: 8b 45 08 mov 0x8(%ebp),%eax 5b1: 89 04 24 mov %eax,(%esp) 5b4: e8 d8 fd ff ff call 391 <putc> ap++; 5b9: 83 45 e8 04 addl $0x4,-0x18(%ebp) 5bd: eb 45 jmp 604 <printf+0x193> } else if(c == '%'){ 5bf: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 5c3: 75 17 jne 5dc <printf+0x16b> putc(fd, c); 5c5: 8b 45 e4 mov -0x1c(%ebp),%eax 5c8: 0f be c0 movsbl %al,%eax 5cb: 89 44 24 04 mov %eax,0x4(%esp) 5cf: 8b 45 08 mov 0x8(%ebp),%eax 5d2: 89 04 24 mov %eax,(%esp) 5d5: e8 b7 fd ff ff call 391 <putc> 5da: eb 28 jmp 604 <printf+0x193> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); 5dc: c7 44 24 04 25 00 00 movl $0x25,0x4(%esp) 5e3: 00 5e4: 8b 45 08 mov 0x8(%ebp),%eax 5e7: 89 04 24 mov %eax,(%esp) 5ea: e8 a2 fd ff ff call 391 <putc> putc(fd, c); 5ef: 8b 45 e4 mov -0x1c(%ebp),%eax 5f2: 0f be c0 movsbl %al,%eax 5f5: 89 44 24 04 mov %eax,0x4(%esp) 5f9: 8b 45 08 mov 0x8(%ebp),%eax 5fc: 89 04 24 mov %eax,(%esp) 5ff: e8 8d fd ff ff call 391 <putc> } state = 0; 604: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 60b: 83 45 f0 01 addl $0x1,-0x10(%ebp) 60f: 8b 55 0c mov 0xc(%ebp),%edx 612: 8b 45 f0 mov -0x10(%ebp),%eax 615: 01 d0 add %edx,%eax 617: 0f b6 00 movzbl (%eax),%eax 61a: 84 c0 test %al,%al 61c: 0f 85 71 fe ff ff jne 493 <printf+0x22> putc(fd, c); } state = 0; } } } 622: c9 leave 623: c3 ret 00000624 <free>: static Header base; static Header *freep; void free(void *ap) { 624: 55 push %ebp 625: 89 e5 mov %esp,%ebp 627: 83 ec 10 sub $0x10,%esp Header *bp, *p; bp = (Header*)ap - 1; 62a: 8b 45 08 mov 0x8(%ebp),%eax 62d: 83 e8 08 sub $0x8,%eax 630: 89 45 f8 mov %eax,-0x8(%ebp) for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 633: a1 cc 0a 00 00 mov 0xacc,%eax 638: 89 45 fc mov %eax,-0x4(%ebp) 63b: eb 24 jmp 661 <free+0x3d> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 63d: 8b 45 fc mov -0x4(%ebp),%eax 640: 8b 00 mov (%eax),%eax 642: 3b 45 fc cmp -0x4(%ebp),%eax 645: 77 12 ja 659 <free+0x35> 647: 8b 45 f8 mov -0x8(%ebp),%eax 64a: 3b 45 fc cmp -0x4(%ebp),%eax 64d: 77 24 ja 673 <free+0x4f> 64f: 8b 45 fc mov -0x4(%ebp),%eax 652: 8b 00 mov (%eax),%eax 654: 3b 45 f8 cmp -0x8(%ebp),%eax 657: 77 1a ja 673 <free+0x4f> free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 659: 8b 45 fc mov -0x4(%ebp),%eax 65c: 8b 00 mov (%eax),%eax 65e: 89 45 fc mov %eax,-0x4(%ebp) 661: 8b 45 f8 mov -0x8(%ebp),%eax 664: 3b 45 fc cmp -0x4(%ebp),%eax 667: 76 d4 jbe 63d <free+0x19> 669: 8b 45 fc mov -0x4(%ebp),%eax 66c: 8b 00 mov (%eax),%eax 66e: 3b 45 f8 cmp -0x8(%ebp),%eax 671: 76 ca jbe 63d <free+0x19> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ 673: 8b 45 f8 mov -0x8(%ebp),%eax 676: 8b 40 04 mov 0x4(%eax),%eax 679: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 680: 8b 45 f8 mov -0x8(%ebp),%eax 683: 01 c2 add %eax,%edx 685: 8b 45 fc mov -0x4(%ebp),%eax 688: 8b 00 mov (%eax),%eax 68a: 39 c2 cmp %eax,%edx 68c: 75 24 jne 6b2 <free+0x8e> bp->s.size += p->s.ptr->s.size; 68e: 8b 45 f8 mov -0x8(%ebp),%eax 691: 8b 50 04 mov 0x4(%eax),%edx 694: 8b 45 fc mov -0x4(%ebp),%eax 697: 8b 00 mov (%eax),%eax 699: 8b 40 04 mov 0x4(%eax),%eax 69c: 01 c2 add %eax,%edx 69e: 8b 45 f8 mov -0x8(%ebp),%eax 6a1: 89 50 04 mov %edx,0x4(%eax) bp->s.ptr = p->s.ptr->s.ptr; 6a4: 8b 45 fc mov -0x4(%ebp),%eax 6a7: 8b 00 mov (%eax),%eax 6a9: 8b 10 mov (%eax),%edx 6ab: 8b 45 f8 mov -0x8(%ebp),%eax 6ae: 89 10 mov %edx,(%eax) 6b0: eb 0a jmp 6bc <free+0x98> } else bp->s.ptr = p->s.ptr; 6b2: 8b 45 fc mov -0x4(%ebp),%eax 6b5: 8b 10 mov (%eax),%edx 6b7: 8b 45 f8 mov -0x8(%ebp),%eax 6ba: 89 10 mov %edx,(%eax) if(p + p->s.size == bp){ 6bc: 8b 45 fc mov -0x4(%ebp),%eax 6bf: 8b 40 04 mov 0x4(%eax),%eax 6c2: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 6c9: 8b 45 fc mov -0x4(%ebp),%eax 6cc: 01 d0 add %edx,%eax 6ce: 3b 45 f8 cmp -0x8(%ebp),%eax 6d1: 75 20 jne 6f3 <free+0xcf> p->s.size += bp->s.size; 6d3: 8b 45 fc mov -0x4(%ebp),%eax 6d6: 8b 50 04 mov 0x4(%eax),%edx 6d9: 8b 45 f8 mov -0x8(%ebp),%eax 6dc: 8b 40 04 mov 0x4(%eax),%eax 6df: 01 c2 add %eax,%edx 6e1: 8b 45 fc mov -0x4(%ebp),%eax 6e4: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 6e7: 8b 45 f8 mov -0x8(%ebp),%eax 6ea: 8b 10 mov (%eax),%edx 6ec: 8b 45 fc mov -0x4(%ebp),%eax 6ef: 89 10 mov %edx,(%eax) 6f1: eb 08 jmp 6fb <free+0xd7> } else p->s.ptr = bp; 6f3: 8b 45 fc mov -0x4(%ebp),%eax 6f6: 8b 55 f8 mov -0x8(%ebp),%edx 6f9: 89 10 mov %edx,(%eax) freep = p; 6fb: 8b 45 fc mov -0x4(%ebp),%eax 6fe: a3 cc 0a 00 00 mov %eax,0xacc } 703: c9 leave 704: c3 ret 00000705 <morecore>: static Header* morecore(uint nu) { 705: 55 push %ebp 706: 89 e5 mov %esp,%ebp 708: 83 ec 28 sub $0x28,%esp char *p; Header *hp; if(nu < 4096) 70b: 81 7d 08 ff 0f 00 00 cmpl $0xfff,0x8(%ebp) 712: 77 07 ja 71b <morecore+0x16> nu = 4096; 714: c7 45 08 00 10 00 00 movl $0x1000,0x8(%ebp) p = sbrk(nu * sizeof(Header)); 71b: 8b 45 08 mov 0x8(%ebp),%eax 71e: c1 e0 03 shl $0x3,%eax 721: 89 04 24 mov %eax,(%esp) 724: e8 40 fc ff ff call 369 <sbrk> 729: 89 45 f4 mov %eax,-0xc(%ebp) if(p == (char*)-1) 72c: 83 7d f4 ff cmpl $0xffffffff,-0xc(%ebp) 730: 75 07 jne 739 <morecore+0x34> return 0; 732: b8 00 00 00 00 mov $0x0,%eax 737: eb 22 jmp 75b <morecore+0x56> hp = (Header*)p; 739: 8b 45 f4 mov -0xc(%ebp),%eax 73c: 89 45 f0 mov %eax,-0x10(%ebp) hp->s.size = nu; 73f: 8b 45 f0 mov -0x10(%ebp),%eax 742: 8b 55 08 mov 0x8(%ebp),%edx 745: 89 50 04 mov %edx,0x4(%eax) free((void*)(hp + 1)); 748: 8b 45 f0 mov -0x10(%ebp),%eax 74b: 83 c0 08 add $0x8,%eax 74e: 89 04 24 mov %eax,(%esp) 751: e8 ce fe ff ff call 624 <free> return freep; 756: a1 cc 0a 00 00 mov 0xacc,%eax } 75b: c9 leave 75c: c3 ret 0000075d <malloc>: void* malloc(uint nbytes) { 75d: 55 push %ebp 75e: 89 e5 mov %esp,%ebp 760: 83 ec 28 sub $0x28,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 763: 8b 45 08 mov 0x8(%ebp),%eax 766: 83 c0 07 add $0x7,%eax 769: c1 e8 03 shr $0x3,%eax 76c: 83 c0 01 add $0x1,%eax 76f: 89 45 ec mov %eax,-0x14(%ebp) if((prevp = freep) == 0){ 772: a1 cc 0a 00 00 mov 0xacc,%eax 777: 89 45 f0 mov %eax,-0x10(%ebp) 77a: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 77e: 75 23 jne 7a3 <malloc+0x46> base.s.ptr = freep = prevp = &base; 780: c7 45 f0 c4 0a 00 00 movl $0xac4,-0x10(%ebp) 787: 8b 45 f0 mov -0x10(%ebp),%eax 78a: a3 cc 0a 00 00 mov %eax,0xacc 78f: a1 cc 0a 00 00 mov 0xacc,%eax 794: a3 c4 0a 00 00 mov %eax,0xac4 base.s.size = 0; 799: c7 05 c8 0a 00 00 00 movl $0x0,0xac8 7a0: 00 00 00 } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 7a3: 8b 45 f0 mov -0x10(%ebp),%eax 7a6: 8b 00 mov (%eax),%eax 7a8: 89 45 f4 mov %eax,-0xc(%ebp) if(p->s.size >= nunits){ 7ab: 8b 45 f4 mov -0xc(%ebp),%eax 7ae: 8b 40 04 mov 0x4(%eax),%eax 7b1: 3b 45 ec cmp -0x14(%ebp),%eax 7b4: 72 4d jb 803 <malloc+0xa6> if(p->s.size == nunits) 7b6: 8b 45 f4 mov -0xc(%ebp),%eax 7b9: 8b 40 04 mov 0x4(%eax),%eax 7bc: 3b 45 ec cmp -0x14(%ebp),%eax 7bf: 75 0c jne 7cd <malloc+0x70> prevp->s.ptr = p->s.ptr; 7c1: 8b 45 f4 mov -0xc(%ebp),%eax 7c4: 8b 10 mov (%eax),%edx 7c6: 8b 45 f0 mov -0x10(%ebp),%eax 7c9: 89 10 mov %edx,(%eax) 7cb: eb 26 jmp 7f3 <malloc+0x96> else { p->s.size -= nunits; 7cd: 8b 45 f4 mov -0xc(%ebp),%eax 7d0: 8b 40 04 mov 0x4(%eax),%eax 7d3: 2b 45 ec sub -0x14(%ebp),%eax 7d6: 89 c2 mov %eax,%edx 7d8: 8b 45 f4 mov -0xc(%ebp),%eax 7db: 89 50 04 mov %edx,0x4(%eax) p += p->s.size; 7de: 8b 45 f4 mov -0xc(%ebp),%eax 7e1: 8b 40 04 mov 0x4(%eax),%eax 7e4: c1 e0 03 shl $0x3,%eax 7e7: 01 45 f4 add %eax,-0xc(%ebp) p->s.size = nunits; 7ea: 8b 45 f4 mov -0xc(%ebp),%eax 7ed: 8b 55 ec mov -0x14(%ebp),%edx 7f0: 89 50 04 mov %edx,0x4(%eax) } freep = prevp; 7f3: 8b 45 f0 mov -0x10(%ebp),%eax 7f6: a3 cc 0a 00 00 mov %eax,0xacc return (void*)(p + 1); 7fb: 8b 45 f4 mov -0xc(%ebp),%eax 7fe: 83 c0 08 add $0x8,%eax 801: eb 38 jmp 83b <malloc+0xde> } if(p == freep) 803: a1 cc 0a 00 00 mov 0xacc,%eax 808: 39 45 f4 cmp %eax,-0xc(%ebp) 80b: 75 1b jne 828 <malloc+0xcb> if((p = morecore(nunits)) == 0) 80d: 8b 45 ec mov -0x14(%ebp),%eax 810: 89 04 24 mov %eax,(%esp) 813: e8 ed fe ff ff call 705 <morecore> 818: 89 45 f4 mov %eax,-0xc(%ebp) 81b: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 81f: 75 07 jne 828 <malloc+0xcb> return 0; 821: b8 00 00 00 00 mov $0x0,%eax 826: eb 13 jmp 83b <malloc+0xde> nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 828: 8b 45 f4 mov -0xc(%ebp),%eax 82b: 89 45 f0 mov %eax,-0x10(%ebp) 82e: 8b 45 f4 mov -0xc(%ebp),%eax 831: 8b 00 mov (%eax),%eax 833: 89 45 f4 mov %eax,-0xc(%ebp) return (void*)(p + 1); } if(p == freep) if((p = morecore(nunits)) == 0) return 0; } 836: e9 70 ff ff ff jmp 7ab <malloc+0x4e> } 83b: c9 leave 83c: c3 ret
; A093390: a(n) = floor(n/9) + floor((n+1)/9) + floor((n+2)/9). ; 0,0,0,0,0,0,0,1,2,3,3,3,3,3,3,3,4,5,6,6,6,6,6,6,6,7,8,9,9,9,9,9,9,9,10,11,12,12,12,12,12,12,12,13,14,15,15,15,15,15,15,15,16,17,18,18,18,18,18,18,18,19,20,21,21,21,21,21,21,21,22,23,24,24,24,24,24,24,24,25,26,27,27,27,27,27,27,27,28,29,30,30,30,30,30,30,30,31,32,33,33,33,33,33,33,33,34,35,36,36,36,36,36,36,36,37,38,39,39,39,39,39,39,39,40,41,42,42,42,42,42,42,42,43,44,45,45,45,45,45,45,45,46,47,48,48,48,48,48,48,48,49,50,51,51,51,51,51,51,51,52,53,54,54,54,54,54,54,54,55,56,57,57,57,57,57,57,57,58,59,60,60,60,60,60,60,60,61,62,63,63,63,63,63,63,63,64,65,66,66,66,66,66,66,66,67,68,69,69,69,69,69,69,69,70,71,72,72,72,72,72,72,72,73,74,75,75,75,75,75,75,75,76,77,78,78,78,78,78,78,78,79,80,81,81,81,81,81,81,81 lpb $0 trn $0,6 add $1,$0 trn $0,3 sub $1,$0 lpe
; A184589: floor(n*e-1); complement of A184590. ; 1,4,7,9,12,15,18,20,23,26,28,31,34,37,39,42,45,47,50,53,56,58,61,64,66,69,72,75,77,80,83,85,88,91,94,96,99,102,105,107,110,113,115,118,121,124,126,129,132,134,137,140,143,145,148,151,153,156,159,162,164,167,170,172,175,178,181,183,186,189,191,194,197,200,202,205,208,211,213,216,219,221,224,227,230,232,235,238,240,243,246,249,251,254,257,259,262,265,268,270,273,276,278,281,284,287,289,292,295,298,300,303,306,308,311,314,317,319,322,325 mov $5,$0 mov $6,$0 mul $6,2 add $6,1 add $0,$6 add $0,2 mov $1,2 mov $4,$0 mul $4,16 add $0,$4 mov $2,70 lpb $0 sub $0,1 sub $1,1 add $2,$1 div $0,$2 mov $3,1 mul $3,$0 mov $0,1 add $3,4 lpe mov $1,$3 sub $1,3 mov $7,$5 mul $7,2 add $1,$7
.model large .586 stackle segment stack there dw 5 dw 7 dw 17 basket equ $ - there dw 128-basket/2 dup(0) stackle ends .data put db "boat", 0ah, 0dh,'$' .code main proc mov ax, @data mov ds, ax lea ax, put mov dx, ax mov sp, 0 pop cx multiply: pop ax imul cx, ax cmp sp, basket jl multiply mov bx, dx cmp cx, 595 jne essa mov al, 'B' mov [bx], al essa: mov ah, 09h int 21h mov ax, 4c00h int 21h main endp end main
// Copyright (c) 2011-2014 The Bitcoin Core developers // Copyright (c) 2014-2020 The Martkist Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "transactionfilterproxy.h" #include "transactiontablemodel.h" #include "transactionrecord.h" #include <cstdlib> #include <QDateTime> // Earliest date that can be represented (far in the past) const QDateTime TransactionFilterProxy::MIN_DATE = QDateTime::fromTime_t(0); // Last date that can be represented (far in the future) const QDateTime TransactionFilterProxy::MAX_DATE = QDateTime::fromTime_t(0xFFFFFFFF); TransactionFilterProxy::TransactionFilterProxy(QObject *parent) : QSortFilterProxyModel(parent), dateFrom(MIN_DATE), dateTo(MAX_DATE), addrPrefix(), typeFilter(COMMON_TYPES), watchOnlyFilter(WatchOnlyFilter_All), minAmount(0), limitRows(-1), showInactive(true) { } bool TransactionFilterProxy::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); int type = index.data(TransactionTableModel::TypeRole).toInt(); QDateTime datetime = index.data(TransactionTableModel::DateRole).toDateTime(); bool involvesWatchAddress = index.data(TransactionTableModel::WatchonlyRole).toBool(); QString address = index.data(TransactionTableModel::AddressRole).toString(); QString label = index.data(TransactionTableModel::LabelRole).toString(); qint64 amount = llabs(index.data(TransactionTableModel::AmountRole).toLongLong()); int status = index.data(TransactionTableModel::StatusRole).toInt(); if(!showInactive && status == TransactionStatus::Conflicted) return false; if(!(TYPE(type) & typeFilter)) return false; if (involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_No) return false; if (!involvesWatchAddress && watchOnlyFilter == WatchOnlyFilter_Yes) return false; if(datetime < dateFrom || datetime > dateTo) return false; if (!address.contains(addrPrefix, Qt::CaseInsensitive) && !label.contains(addrPrefix, Qt::CaseInsensitive)) return false; if(amount < minAmount) return false; return true; } void TransactionFilterProxy::setDateRange(const QDateTime &from, const QDateTime &to) { this->dateFrom = from; this->dateTo = to; invalidateFilter(); } void TransactionFilterProxy::setAddressPrefix(const QString &_addrPrefix) { this->addrPrefix = _addrPrefix; invalidateFilter(); } void TransactionFilterProxy::setTypeFilter(quint32 modes) { this->typeFilter = modes; invalidateFilter(); } void TransactionFilterProxy::setMinAmount(const CAmount& minimum) { this->minAmount = minimum; invalidateFilter(); } void TransactionFilterProxy::setWatchOnlyFilter(WatchOnlyFilter filter) { this->watchOnlyFilter = filter; invalidateFilter(); } void TransactionFilterProxy::setLimit(int limit) { this->limitRows = limit; } void TransactionFilterProxy::setShowInactive(bool _showInactive) { this->showInactive = _showInactive; invalidateFilter(); } int TransactionFilterProxy::rowCount(const QModelIndex &parent) const { if(limitRows != -1) { return std::min(QSortFilterProxyModel::rowCount(parent), limitRows); } else { return QSortFilterProxyModel::rowCount(parent); } }
; A195140: Multiples of 5 and odd numbers interleaved. ; 0,1,5,3,10,5,15,7,20,9,25,11,30,13,35,15,40,17,45,19,50,21,55,23,60,25,65,27,70,29,75,31,80,33,85,35,90,37,95,39,100,41,105,43,110,45,115,47,120,49,125,51,130,53,135,55,140,57,145,59,150,61,155,63,160,65,165,67,170,69,175,71,180,73,185,75,190,77,195,79,200,81,205,83,210,85,215,87,220,89,225,91,230,93,235,95,240,97,245,99,250,101,255,103,260,105,265,107,270,109,275,111,280,113,285,115,290,117,295,119,300,121,305,123,310,125,315,127,320,129,325,131,330,133,335,135,340,137,345,139,350,141,355,143,360,145,365,147,370,149,375,151,380,153,385,155,390,157,395,159,400,161,405,163,410,165,415,167,420,169,425,171,430,173,435,175,440,177,445,179,450,181,455,183,460,185,465,187,470,189,475,191,480,193,485,195,490,197,495,199,500,201,505,203,510,205,515,207,520,209,525,211,530,213,535,215,540,217,545,219,550,221,555,223,560,225,565,227,570,229,575,231,580,233,585,235,590,237,595,239,600,241,605,243,610,245,615,247,620,249 mov $1,$0 mov $2,$0 gcd $0,2 mul $1,$0 mul $1,$0 add $1,$2 div $1,2
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1990 -- All Rights Reserved PROJECT: PC GEOS MODULE: Print Spooler FILE: processText.asm AUTHOR: Dave Durran ROUTINES: Name Description ---- ----------- DoTextPrinting Handles printing in text modes GetTextStrings Extracts text strings from gstrings SendTextStrings Send the text strings down to the printer REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 7/92 Initial 2.0 revision DESCRIPTION: This file contains routines to handle text printing Text printing is done in a rather interesting fashion under PC GEOS. Applications actually draw their spool file just as if they were printing a graphics page. The code here scans through the resulting graphics string and pulls out the text strings, along with the position to draw them and the attributes in affect at the time. A first pass is made through the gstrings containing the page description. In this pass, all the text strings are extracted ajnd stored in chunks, in the TextStrings block. These chunks are sorted in x and y. After all the strings for the page are extracted, they are sent to the printer. This is done by building a line of characters, with spaces separating the runs of text, along with information about the style. A print head positioning command is sent for the beginning of the line, then the entire line is sent down to the printer, a style run at a time. $Id: processText.asm,v 1.1 97/04/07 11:11:12 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PrintText segment resource if _TEXT_PRINTING COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DoTextInit %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Do some initialization for text printing CALLED BY: INTERNAL PrintDocument PASS: inherits lots of local variables from SpoolerLoop RETURN: ax - 0 (signals no error) DESTROYED: di, cx, bx, dx, ds PSEUDO CODE/STRATEGY: Get the strings out of the gstring; Build out a list of the strings, sorted in y order; Send them on down to the printer; KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 03/90 Initial version Dave 7/92 Initial 2.0 version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DoTextInit proc far curJob local SpoolJobInfo .enter inherit ; we need to create a gstate to draw through, even though ; we're not going to really draw anything using the ; graphics system clr di ; pass bogus window handle call GrCreateState ; di = gstate handle mov curJob.SJI_gstate, di ; save gstate ; get the transformation matrix back to start in the gstate segmov ds,ss,si lea si,curJob.SJI_defMatrix ;set to our transformation matrix call GrApplyTransform ; allocate the TextStrings structure. ; (see processConstant.def) mov ax, LMEM_TYPE_GENERAL ;type of block. mov cx, size TextStrings ;size of header. call MemAllocLMem mov curJob.SJI_tsHan, bx ; save handle ;we have our lmem block, now create the structures within. call MemLock ; lock it down mov ds, ax ; ds -> block ; alloc an extra chunk in the TextStrings block to act as ; a buffer for reading in gstring elements clr al ; no object flags mov cx, 0 ; alloc to zero to start call LMemAlloc ; mov ds:[TS_gsBuffer], ax ; save handle for later clr bx ;variable size elements. mov cx,bx ;default ChunkArrayHeader. mov si,bx ;new chunk. mov al, mask OCF_IGNORE_DIRTY call ChunkArrayCreate ;do it. mov ds:TS_styleRunInfo,si ;store the handle to the chunkarray clr si mov bx,size TextAttrInfo call ElementArrayCreate mov ds:TS_textAttributeInfo,si ;store the handle to elementarray mov bx, curJob.SJI_tsHan call MemUnlock ; unlock block for later use clr ax ; signal no error .leave ret DoTextInit endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% InitTextStringsBlock %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Initialize the TextStrings block CALLED BY: INTERNAL DoTextInit, PASS: curJob - passed stack frame RETURN: nothing DESTROYED: ds, dx, cx PSEUDO CODE/STRATEGY: call LMemInitHeap, blah, blah KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 06/90 Initial version Dave 7/92 Initial 2.0 version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ InitTextStringsBlock proc near uses ax curJob local SpoolJobInfo .enter inherit ; lock the block, and initialize the lmem heap push si, di, bp mov bx, curJob.SJI_tsHan ; save handle call MemLock ; lock it down mov ds, ax ; ds -> block pop si, di, bp ; alloc an extra chunk in the TextStrings block to act as ; a buffer for reading in gstring elements clr al ; no object flags mov cx, 0 ; alloc to zero to start call LMemAlloc ; mov ds:[TS_gsBuffer], ax ; save handle for later ;initialize the chunkarray for the string info. mov si,ds:[TS_styleRunInfo] ;get the handle for array. call ChunkArrayGetCount ;get teh number of chunks. jcxz inittedChunks clr ax call ChunkArrayDeleteRange ;get rid of the string infos. inittedChunks: ;initialize the element array for the attribute info. inittedElements:: ; all done, release the block mov bx, curJob.SJI_tsHan ; save handle call MemUnlock .leave ret InitTextStringsBlock endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PrintTextPage %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Print a single text page, including any tiling required CALLED BY: EXTERNAL PrintDocument PASS: curJob stack frame RETURN: ax - return code from GetTextStrings carry - set if some error transmitting to printer DESTROYED: most everything PSEUDO CODE/STRATEGY: do what it takes, man. This routine is responsible for printing a single document page. That means that it deals with printing all the tiles of tiled output, if that is required. KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 06/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PrintTextPage proc far curJob local SpoolJobInfo .enter inherit ; the file is already open, associate it with a graphics ; string handle mov cx, GST_STREAM ; type of gstring it is mov bx, curJob.SJI_fHan ; bx gets file handle call GrLoadGString ; si = string handle mov curJob.SJI_gstring, si ; store the handle mov di, curJob.SJI_gstate ; restore gstate handle ; find/load the strings into the TextStrings block ; then send the strings down to the printer. For big documents ; the GetTextStrings routine will load up all the strings ; for the entire document. Then we can deal with printing ; out the tiles separately. call GetTextStrings ; get the strings cmp ax, GSRT_FAULT ; quit if any problem LONG je done ;source point for ax, and bx later....... ; done with this page, kill the string mov dl, GSKT_LEAVE_DATA ; don't try to kill the data call GrDestroyGString ; si = string handle ;This little bit of mularky is to make sure that ProcessEndPage ;has the correct entry GSRT value from playing the GString. ;The way this works is: GString is played once; for tiling the ;ProcessEndPage routine is called many times in the following ;loops; dx is used to hold the original GSRT passed from the ;playstring stuff; ax is passed out of this routine like normal ;ax is restuffed from dx at the beginning of each page loop, ;so that ProcessEndPage will do the right thing. mov dx,ax ;save the GSRT value. ; now we have all the strings. So print them. ; We need to output all the pages we print tiled documents ; across, then down. Outside loop is for y papers, ; inside loop is for x papers mov cx, curJob.SJI_yPages ; init y loop variable mov curJob.SJI_curyPage, cx mov cx, paperInfo.PSR_margins.PCMP_top ; init top side mov curJob.SJI_textTileY.low, cx clr curJob.SJI_textTileY.high tileInY: mov cx, curJob.SJI_xPages ; init x loop variable mov curJob.SJI_curxPage, cx mov cx, paperInfo.PSR_margins.PCMP_left ; init left side mov curJob.SJI_textTileX, cx add cx, curJob.SJI_printWidth ; set right margin mov curJob.SJI_textTileXright, cx ; First, tell the printer we're starting a new page. tileInX: call BumpPhysPageNumber call ProcessStartPage ; send START_PAGE LONG jc exitError ; all done ; next send the strings for this page call SendTextStrings ; print strings for page LONG jc exitError ; all done ; let the printer know we're done with a page. If the ; SUPRESS_FF flag is set, then don't send the END_PAGE ;ax,bx,and dx have to be preserved through this loop! mov ax,dx ; recover the original GSRT. call ProcessEndPage ; issue a DR_PRINT_END_PAGE LONG jc exitError ; all done ; even though we're done with the page, we need to advance ; down to the end of the document (if we haven't issued a ; form feed). So check for the mode and do the right thing. test curJob.SJI_printState, mask SPS_FORM_FEED jnz checkNextSwoosh mov di, DR_PRINT_SET_CURSOR push bx,dx ;save GSRT and data from ;GetTextStrings routine. mov bx, curJob.SJI_pstate mov dx, curJob.SJI_printHeight ; finish document call curJob.SJI_pDriver pop bx,dx ;recover GSRT and data from ;GetTextStrings routine. ; now we're done with a page. We might have to print out ; a few more to the right, so check that first checkNextSwoosh: sub curJob.SJI_curxPage, 1 ; one less this way jle nextSwoosh ; done this way, check ; We have more to do in this swoosh . Update the current pos ; and go for it. First make sure we have paper... push ax call AskForNextTextPage cmp ax, IC_DISMISS ; verify this fact... pop ax je shutdownCondition ; or go shutdown mov cx, curJob.SJI_printWidth ; add in prntable width add curJob.SJI_textTileX, cx ; bump origin add curJob.SJI_textTileXright, cx ; bump right margin jmp tileInX ; done with a horizontal swoosh of papers. Do the next ; swoosh. Like before, check first to see if there is another nextSwoosh: sub curJob.SJI_curyPage, 1 ; one less jle donePage ; more swooshes to do. Update origin. ; First make sure we have paper... push ax call AskForNextTextPage cmp ax, IC_DISMISS ; except when we're pop ax je shutdownCondition ; shutting down mov cx, curJob.SJI_printHeight ; add printable height add curJob.SJI_textTileY.low, cx ; bump origin adc curJob.SJI_textTileY.high, 0 jmp tileInY ; done with the current document page. donePage: clc ; we're done with this page. Re-init the LMemBlock done: pushf call InitTextStringsBlock ; clear out the strings popf exit: .leave ret ; shutting down GEOS, take evasive action.. shutdownCondition: mov ax, GSRT_FAULT ; something wrong jmp exit ; some error transmitting to printer. set carry and we're gone exitError: stc jmp done ; all done... PrintTextPage endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DoTextCleanup %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Write out a string CALLED BY: GLOBAL PASS: everything is in curJob stack frame RETURN: nothing DESTROYED: bx, di PSEUDO CODE/STRATEGY: free the memory we accumulated KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 06/90 Initial version Dave 7/92 Initial 2.0 version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ DoTextCleanup proc far curJob local SpoolJobInfo .enter inherit ; clean up the normal text-related things mov bx, curJob.SJI_tsHan ; get handle call MemFree ; kill the block mov di, curJob.SJI_gstate ; kill gstate call GrDestroyState ; di = gstate handle ; if we were aborting this print job, then nuke the stream ; buffer, to stop more characters from getting to the printer call CheckForErrors ; see if ABORT is pending... jnc done ; no, just exit ; OK, we're exiting because of an user-initiated abort. We want ; to nuke the stream buffer, then re-open it (since the rest of ; the spooler expects it to be open) mov di, DR_STREAM_FLUSH ; destroy the stream buffer mov ax, STREAM_WRITE ; biff the data in it ; this will get the unit number for either the parallel port ; or the serial port. When another port type is supported ; in the (near) future, then this code will probably have ; to change. mov bx, curJob.SJI_info.JP_portInfo.PPI_params.PP_parallel.PPP_portNum call curJob.SJI_stream ; nuke it. ; after we flush the stream, we should send a form feed mov cl,C_FF ;init for FF mov di, DR_PRINT_END_PAGE mov bx, curJob.SJI_pstate call curJob.SJI_pDriver done: .leave ret DoTextCleanup endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SendTextStrings %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Send out the collected strings to the printer CALLED BY: INTERNAL DoTextPrinting PASS: inherits local frame RETURN: carry - set if some transmission error DESTROYED: nothing PSEUDO CODE/STRATEGY: Go through the TextStrings block, and send each string KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 03/90 Initial version Dave 7/92 Initial 2.0 version. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SendTextStrings proc near uses ax, bx, cx, si, dx curJob local SpoolJobInfo .enter inherit ; for each StyleRunInfo chunk, loop through all the strings mov bx, curJob.SJI_pstate call MemLock mov ds, ax mov dl,ds:[PS_paperInput] ;grab paperpath for test later call MemUnlock ; (preserves flags) ; lock down the TextStrings block mov bx, curJob.SJI_tsHan ; get handle to text block call MemLock mov ds, ax ; ds -> text chunk mov si, ds:[TS_styleRunInfo] ;get the chunks set up. clr ax nextYPos: push ax ;save the chunk element # call ChunkArrayElementToPtr ;deref the chunk. jc doneNoErr ;if after the last element, ex mov ax, ds:[di].SRI_yPosition ;get the y position. add ax, paperInfo.PSR_margins.PCMP_top ;add the margin amount in. ; printer always prints from 0 sub ax, curJob.SJI_textTileY.low ; above current ytop ? jl skipThisElement ; yes, skip this line test curJob.SJI_printState, mask SPS_TILED ; if not tiled in Y, jz checkBottom ; don't care about tractor test dl, mask PIO_TRACTOR jnz checkXPosition ;if tractor, one big page. checkBottom: sub ax, curJob.SJI_printHeight ; bottom margin. jge doneNoErr ; all done with this page checkXPosition: ; Make sure it's past the left margin, since that is where ; we want to start outputting characters. mov ax, ds:[di].SRI_xPosition ;get the x position. add ax, paperInfo.PSR_margins.PCMP_left ;add the margin amount in. ; printer always prints from 0 sub ax, curJob.SJI_textTileX ; past left margin ? jl skipThisElement ; if so, for now, just bail. sub ax,curJob.SJI_printWidth ;see if offpage to right. jge skipThisElement ; if so, reject.... add ax,ds:[di].SRI_stringWidth.WBF_int ;see if the whole string is jl stringOnPage ;on this page. call SnipTextString ;take and cut this string up. jc skipThisElement ;if the whole element moved ;as a result of an incomplete ;character left on left page, ;skip it. stringOnPage: push dx,si ;save the paperpath, SRI handle mov dx, ds ;set dx:si to be element. mov si, di mov ax, curJob.SJI_textTileX ; pass the offset into tiles mov cx, curJob.SJI_textTileY.low ; pass the offset into tiles mov bx, curJob.SJI_pstate mov di, DR_PRINT_STYLE_RUN ;call to print this text. call curJob.SJI_pDriver ; print out the collected buff pop dx,si jc done ; if any error, quit mov bx, curJob.SJI_tsHan ; just in case PRINT_STYLE_RUN call MemDerefDS ; messes with us. ; all done with this style run, on to the next one skipThisElement: pop ax inc ax ;point at next chunk. jmp nextYPos doneNoErr: clc done: mov bx, curJob.SJI_tsHan ; release text block call MemUnlock pop ax ;adjust stack. .leave ret SendTextStrings endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SnipTextString %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: cut the string in two peices at the right margin, store both back into chunkarray CALLED BY: INTERNAL PASS: *ds:si - textStrings array ds:di - textStrings array element being snipped ax - number of points the string extends to the right of margin. RETURN: ds:di - address of left element (may have moved) DESTROYED: nothing PSEUDO CODE/STRATEGY: 1 Get the string width and # chars for the left part. 2 Insert a new chunk and copy everything up to the last left part character in it from the original. 3 fix up the number of characters and stringWidth in each part, and the x position for the right part. 4 move the characters from the end of the origional string to the beginning of the right part string. 5 resize the right part chunk. 6 deref the left chunk to return. KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 03/93 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SnipTextString proc near uses ax, bx, cx, dx, es curJob local SpoolJobInfo .enter inherit push si ;save chunk array handle ;Get the string width and # chars for the left part. mov dx,ds:[di].SRI_stringWidth.WBF_int sub dx,ax ;get the width of the string to left. ;dx is now the width to left, ax the ;width to right. We start on the right ;first. push dx ;save the left part. clr ax clr cx mov bx,ds:[di].SRI_stringWidth.WBF_int call GrUDivWWFixed ;get fraction of string width to right. mov bx,ds:[di].SRI_numChars ;x total number of chars = clr ax call GrMulWWFixed ;dx.cx = # chars to left ;always round down. ;see if there are any whole character in the left part after ;the rounding down. ;at this point dx = #char to left, ;width to left is on stack tst dx ;any chars left on left? jnz insertNewChunk ;if so, then we add a new chunk to ;hold them. pop cx ;get back the position to right. add ds:[di].SRI_xPosition,cx ;adjust the x position of right part. sub ds:[di].SRI_stringWidth.WBF_int,cx ;set the right width ;Now the whole string has been moved to ;the right part to be printed on the ;next page. pop si ;adjust stack. stc ;set to not print this element now... jmp exit ;leave. ;Insert a new chunk and copy everything up to the last left ;part character in it from the original. insertNewChunk: ;at this point dx = chars to left, and ;stringWidth to left is on stack. mov ax,offset SRI_text ;size req'd for header DBCS < shl dx, 1 > add ax,dx ;size required for string call ChunkArrayInsertAt ;create the new chunk for right part. mov bx,di ;save this offset. call ChunkArrayPtrToElement ;get this element #. inc ax ;get element # of source chunk. call ChunkArrayElementToPtr ;get offset of source chunk. mov si,di ;switch so source is in si. mov di,bx ;get back new chunk offset. segmov es,ds,cx ;set up same segment. mov cx,offset SRI_text ;size of information header. add cx,dx ;size required for string. push si,di ;save indices for chunks. rep movsb ;fill in info pop si,di ;get back indices. ;fix up the number of characters and stringWidth in each part, ;and the x position for the right part. ;at this point we have a duplicate ;chunk added in front of the original ;chunk with only the left side ;characters. DBCS < shr dx, 1 > mov ds:[di].SRI_numChars,dx ;replace the number of characters. sub ds:[si].SRI_numChars,dx ;set remaining number to right. pop cx ;retreive the width to left. mov ds:[di].SRI_stringWidth.WBF_int,cx ;set the left width. add ds:[si].SRI_xPosition,cx ;adjust the x position of right part. sub ds:[si].SRI_stringWidth.WBF_int,cx ;set the right width clr ds:[di].SRI_stringWidth.WBF_frac ;clear left fraction. ;move the characters from the end of the origional string ;to the beginning of the right part string. ;at this point the new (first, left) ;chunk is ready to go, and all that ;needs to be done is move the text from ;the end of the string in the right part ;chunk to the beginning of the text ;field, and lopp of the end of the ;chunk. push si ;save the offset to right chunk. mov cx,ds:[si].SRI_numChars ;number of chars to right add si,offset SRI_text ;now offset to text start. mov di,si ;into dest. DBCS < shl dx, 1 > add si,dx ;source index is start of chars to right LocalCopyNString ;transfer them to beginning. pop di ;recover the offset to chunk. ;resize the right part chunk. pop si ;recover chunk array handle call ChunkArrayPtrToElement ;get element # in ax. mov cx,ds:[di].SRI_numChars ;size required for string DBCS < shl cx, 1 > add cx,offset SRI_text ;size req'd for header call ChunkArrayElementResize ;resize the right part ;now deref the left chunk to return. dec ax call ChunkArrayElementToPtr clc ;OK to print this element now..... exit: .leave ret SnipTextString endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetTextStrings %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Extract text strings from a gstring for one document page CALLED BY: INTERNAL DoTextPrinting PASS: si - gstring handle di - gstate handle RETURN: ax - GSRetType bx - data accompanying GSRetType DESTROYED: nothing PSEUDO CODE/STRATEGY: Search for output elements in the gstrings... Accumulate/sort them in a separate block KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 03/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetTextStrings proc near uses cx, dx curJob local SpoolJobInfo .enter inherit ; first off, lock down the TextStrings block mov bx, curJob.SJI_tsHan ; lock down block call MemLock mov ds, ax ; ds -> TextString blk ; search for the next output element keepScanning: mov dx, mask GSC_NEW_PAGE or mask GSC_OUTPUT clr ax clr bx call GrDrawGString ; go until we hit one mov ax, dx ; save return code ; if we're done with the page, exit. If the last element in ; the entire string is an output element, we will FAULT here, ; so just map it to COMPLETE cmp ax, GSRT_FAULT ; if some problem... jne checkFormFeed ; ...exit mov ax, GSRT_COMPLETE ; map FAULT to COMPLETE checkFormFeed: cmp ax, GSRT_NEW_PAGE ; if at end of page.. je donePage ; ...exit cmp ax, GSRT_COMPLETE ; same if at end of je donePage ; document ; not at end of page, so we must have hit some output. ; check to see what it is... clr bx ; use bx as table index tryNextCode: cmp cl, cs:textOpcodes[bx] ; check for valid code je foundValidCode inc bx cmp bx, NUM_VALID_TEXT_CODES jb tryNextCode ; it's not a text-output code, skip it. Need to execute it ; so that the current position is updated correctly ; We can return to our normal processing here, since the ; call will skip this element and go on. jmp keepScanning ; found a valid text opcode, extract the string ; We need to get the current transformation matrix elements, ; so we may apply the appropriate translation. We do not ; do scales/rotates. foundValidCode: shl bx, 1 ; make it a word index call cs:extractRouts[bx] ; call routine jmp keepScanning ; all done, exit donePage: mov bx, curJob.SJI_tsHan ; unlock the block call MemUnlock mov bx, cx ; bx <- GSRetType data .leave ret GetTextStrings endp ;------------------------------------------------------------------------- ; Text opcode table and extraction routine table ;------------------------------------------------------------------------- ; table of valid text opcodes textOpcodes label byte byte GR_DRAW_TEXT_FIELD ; this is most common byte GR_DRAW_TEXT byte GR_DRAW_TEXT_CP byte GR_DRAW_CHAR byte GR_DRAW_CHAR_CP NUM_VALID_TEXT_CODES equ $-textOpcodes ; table of extraction routines extractRouts label nptr nptr offset cs:GetTextFieldString nptr offset cs:GetTextString nptr offset cs:GetTextCPString nptr offset cs:GetCharString nptr offset cs:GetCharCPString COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetTextString %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Extract a text string from a gstring element and put it it our TextStrings block CALLED BY: INTERNAL GetTextStrings PASS: si - handle to gstring di - handle to gstate (contains current attr) ds - segment of TextStrings block bp - pointer to stack frame RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: The current position in the gstring is at the element, so use GetElement to read in the data, then put the text string in the chunk. KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 03/90 Initial version Dave 08/92 Initial 2.0 version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetTextString proc near uses ax, bx, cx, si, di, dx .enter ; Get the element to see how big the string is call ReadNextElement ; get the element ; OK, we have the element and how big it is, so alloc ; a new text string chunk and init to current attributes mov cx, ds:[bx].ODT_len ; get string length mov ax, ds:[bx].ODT_x1 ; get x,y coordinates mov bx, ds:[bx].ODT_y1 call TransformStringPosition ; apply any transform mov dx, size OpDrawText ; ds:si -> string mov si, ds:[TS_gsBuffer] ; string is in buffer call AllocStringChunk ; make some space .leave ret GetTextString endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetTextCPString %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Extract a text string from a gstring element and put it it our TextStrings block CALLED BY: INTERNAL GetTextStrings PASS: si - handle to gstring di - handle to gstate (contains current attr) ds - segment of TextStrings block RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: The current position in the gstring is at the element, so use GetElement to read in the data, then put the text string in the chunk. KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 03/90 Initial version Dave 08/92 Initial 2.0 version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetTextCPString proc near uses ax, bx, cx, si, di, dx .enter ; Get the element to see how big the string is call ReadNextElement ; get the element ; OK, we have the element and how big it is, so alloc ; a new text string chunk and init to current attributes mov cx, ds:[bx].ODTCP_len ; get string length call GrGetCurPos ; ax,bx = cur pen pos call TransformStringPosition ; apply any transform mov dx, size OpDrawTextAtCP ; ds:si -> string mov si, ds:[TS_gsBuffer] ; string is in buffer call AllocStringChunk ; make some space .leave ret GetTextCPString endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetTextFieldString %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Extract a text string from a gstring element and put it it our TextStrings block CALLED BY: INTERNAL GetTextStrings PASS: si - handle to gstring di - handle to gstate (contains current attr) ds - segment of TextStrings block RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: Since the element could have multiple Style runs, we use GrCopyGString to copy it from the gstring to our local buffer, using the GST_CHUNK option on creating a gstring. Then we can take it apart. KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 03/90 Initial version Dave 08/92 Initial 2.0 version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetTextFieldString proc near uses ax, bx, cx, si, di, dx curJob local SpoolJobInfo .enter inherit push di ; save our gstate handle ; first resize the buffer chunk to zero mov ax, ds:[TS_gsBuffer] ; pass chunk handle too mov cx, 0 ; call LMemFree ; first set up to draw into our buffer push si ;save GString handle mov cl, GST_CHUNK ; it's a memory type gstring mov bx, ds:[TS_header].LMBH_handle ; get block handle call GrCreateGString ; di = gstring handle mov ds:[TS_gsBuffer], si pop si ;recover GString handle ; now draw the one element into our buffer mov dx, mask GSC_ONE ; return after one element clr ax clr bx call GrCopyGString ; that's all we need, so biff the string mov si, di ; si -> destination GString clr di ; no associated GState mov dl, GSKT_LEAVE_DATA ; don't kill the data call GrDestroyGString pop di ; restore gstate handle ; Now in the process of GrCopyGString-ing to the buffer, the ; block may have moved (it being an LMem block and all). We ; wouldn't know it, of course, since ds is pushed/poped ; by GrDrawGString. So let's dereference it here. mov bx, curJob.SJI_tsHan ; get the handle call MemDerefDS ; dereference it mov bx, ds:[TS_gsBuffer] ; get pointer to buffer mov bx, ds:[bx] ; ds:bx -> buffer ; get the size of the fixed part of the element mov dx, (size OpDrawTextField + size TFStyleRun) mov si, size OpDrawTextField ; bx.dx -> string mov cx,ds:[bx].ODTF_saved.GDFS_nChars ;get # chars. ; do the first style run, it might be the only one too... mov ax, ds:[bx].ODTF_saved.GDFS_drawPos.PWBF_x.WBF_int ; loop through the style runs, getting out the attributes styleRuns: ; check for auto hyphen test ds:[bx].ODTF_saved.GDFS_flags, \ mask HF_AUTO_HYPHEN jz stringFixed call FixUpAutoHyphen stringFixed: call HandleStyleRun ; handle next run cmp cx, 0 ; fewer characters to go jle done ; all done, exit ; done with this style run, bump pointers on to the next one ; also dereference the chunk again mov bx, ds:[TS_gsBuffer] ; get chunk handle mov bx, ds:[bx] ; dereference it if DBCS_PCGEOS push ax mov ax, ds:[bx].[si].TFSR_count ;add past the text +... shl ax, 1 add si, ax pop ax else add si,ds:[bx].[si].TFSR_count ;add past the text +... endif add si, size TFStyleRun ; the size of this structure jmp styleRuns ; do another run.... ; all done, just leave done: .leave ret GetTextFieldString endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetCharString %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Extract a Character from a gstring element and put it it our CharStrings block CALLED BY: INTERNAL GetTextStrings PASS: si - handle to gstring di - handle to gstate (contains current attr) ds - segment of TextStrings block bp - pointer to stack frame RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: The current position in the gstring is at the element, so use GetElement to read in the data, then put the text string in the chunk. KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 08/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetCharString proc near uses ax, bx, cx, si, di, dx .enter ; Get the element to see how big the string is call ReadNextElement ; get the element ; OK, we have the element and how big it is, so alloc ; a new text string chunk and init to current attributes mov cx, 1 ; get string length mov ax, ds:[bx].ODC_x1 ; get x,y coordinates mov bx, ds:[bx].ODC_y1 call TransformStringPosition ; apply any transform mov dx, offset ODC_char ; ds:si -> string mov si, ds:[TS_gsBuffer] ; string is in buffer call AllocStringChunk ; make some space .leave ret GetCharString endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetCharCPString %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Extract a Character from a gstring element and put it it our TextStrings block CALLED BY: INTERNAL GetTextStrings PASS: si - handle to gstring di - handle to gstate (contains current attr) ds - segment of TextStrings block RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: The current position in the gstring is at the element, so use GetElement to read in the data, then put the text string in the chunk. KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 08/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetCharCPString proc near uses ax, bx, cx, si, di, dx .enter ; Get the element to see how big the string is call ReadNextElement ; get the element ; OK, we have the element and how big it is, so alloc ; a new text string chunk and init to current attributes mov cx, 1 ; get string length call GrGetCurPos ; ax,bx = cur pen pos call TransformStringPosition ; apply any transform mov dx, offset ODCCP_char ; ds:si -> string mov si, ds:[TS_gsBuffer] ; string is in buffer call AllocStringChunk ; make some space .leave ret GetCharCPString endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TransformStringPosition %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Transform the string position, adding the base line offset to the y position before using the GrTransform routine. CALLED BY: INTERNAL GString extraction routines - GetTextString,GetTextCPString,GetCharString,GetCharCPString PASS: si - handle to gstring di - handle to gstate (contains current attr) ax - Xposition bx - Yposition RETURN: ax,bx transformed DESTROYED: dx PSEUDO CODE/STRATEGY: add the baseline offset to the y position, call GrTransform to do the rest. KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 11/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ TransformStringPosition proc near push ax,si ;save the X position. call GrGetTextMode ;see how we are positioned. and al,mask TM_DRAW_BASE or mask TM_DRAW_BOTTOM \ or mask TM_DRAW_ACCENT jz drawFromTop and al,not mask TM_DRAW_BASE ;see if baseline ref. jz yPosCorrected ;jmp if baseline... and al,not mask TM_DRAW_BOTTOM ;see if bottom ref. jz drawFromBottom mov si,GFMI_ROUNDED or GFMI_ASCENT ;must be accent ref. jmp correctTheYPos drawFromBottom: mov si,GFMI_ROUNDED or GFMI_DESCENT ;I'm assuming this is jmp correctTheYPos ;a signed value. drawFromTop: mov si,GFMI_ROUNDED or GFMI_BASELINE correctTheYPos: call GrFontMetrics add bx,dx ;add the baseline to y pos. yPosCorrected: pop ax,si ;recover the X position. call GrTransform ; apply any transform ret TransformStringPosition endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FixUpAutoHyphen %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Check to see if we need to put a hyphen at the end CALLED BY: INTERNAL GetTextFieldString PASS: ds:bx - pointer to TextField element (base of current chunk) ds:bx.dx - pointer to text string (within ds:bx) ds:bx.si - pointer to TFStyleRun cx - character count RETURN: cx - real char count ds:bx - fixed up ds:dx - pointer to text string DESTROYED: nothing PSEUDO CODE/STRATEGY: have an auto-hyphen. Re alloc the chunk and add a hyphen at end.. has to be the last string in the text field KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 11/93 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FixUpAutoHyphen proc near uses ax, di cmp cx,ds:[si].[bx].TFSR_count ; see if this is the last run jne exit ; if not, dont bother. .enter push si push cx ; save string length mov ax, ds:[TS_gsBuffer] ; load the handle of chunk add cx,dx ; add stuff from before... add cx, 2 ; add some space call LMemReAlloc pop cx ; recover string length mov di, ax ; di -> chunk handle mov bx, ds:[di] ; get pointer to chunk mov si,dx ; pointer to string add si,cx ; point at end of string mov {byte} ds:[si].[bx], '-' ; stuff a hyphen there. inc cx ; really is one more pop si mov ds:[si].[bx].TFSR_count,cx ; save in the TFStyleRun. .leave exit: ret FixUpAutoHyphen endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% HandleStyleRun %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Handle a single style run of a GrDrawTextField element, including any embedded graphics strings CALLED BY: INTERNAL GetTextFieldString PASS: ds:bx - pointer to element ds:bx+si - pointer to TFStyleRun structure ax - x position to draw string cx - #chars still left to draw (before this run) dx - offset into string chunk to find string di - gstate handle RETURN: cx - #chars still left to draw (after this run) dx - updated to past style run characters ax - modified x position for next style run. ds - probably has moved due to AllocStringChunk. DESTROYED: none PSEUDO CODE/STRATEGY: Set the current attributes, allocate a StyleRunInfo element, blah, blah, blah KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 06/90 Initial version Dave 7/92 Initial 2.0 version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ HandleStyleRun proc near uses bx,si,di curJob local SpoolJobInfo .enter inherit push cx ; save #chars left (total) add si, bx ; ds:si -> TFStyleRun add si, TFSR_attr ; point to attributes mov ds:[si].TA_spacePad.WBF_int, 0 ; set no space padding mov ds:[si].TA_spacePad.WBF_frac, 0 ; set no space padding call GrSetTextAttr ; set the text attributes sub si, TFSR_attr sub si, bx ; things back to normal mov cx, ds:[bx][si].TFSR_count ; get character count push dx,si mov curJob.SJI_textXPosition,ax ;save this runs x position. mov si, bx ;get offset to text. add si, dx call GrTextWidth ; get the width of this text string add ax,dx ; add to the xPosition for next time. pop dx,si push ax,dx,si mov ax, ds:[bx].ODTF_saved.GDFS_drawPos.PWBF_y.WBF_int ; get y pos add ax, ds:[bx].ODTF_saved.GDFS_baseline.WBF_int ; get baseline pos mov bx,ax ; get into bx now that we are done. mov ax,curJob.SJI_textXPosition ;recover this runs x position. call GrTransform ; transform the coordinates call GrSaveState ; save font, point size... call AllocStringChunk ; save the string call GrRestoreState ; restore font, point size... pop ax,dx,si haveString:: add dx, cx ; bump string offset DBCS < add dx, cx ; char offset -> byte offset > add dx, size TFStyleRun ; add the size of this structure mov di, cx ; save char count pop cx ; restore #chars left (total) sub cx, di ; are we done ? .leave ret HandleStyleRun endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ReadNextElement %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Read the next gstring element into our buffer CALLED BY: INTERNAL GetTextString PASS: ds - segment of TextString block si - gstring handle di - gstate handle RETURN: bx - pointer to start of buffer DESTROYED: nothing PSEUDO CODE/STRATEGY: Read the element into our buffer, resizing if necc. KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 03/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ReadNextElement proc near uses si, ax .enter tryAgain: mov bx, ds:[TS_gsBuffer] ; handle of buff chunk ChunkSizeHandle ds, bx, cx ; get size of chunk tst cx ; if null, enlarge it jz reallocChunk getElement: mov bx, ds:[bx] ; get ptr to chunk call GrGetGStringElement ; extract GR_DRAW_TEXT cmp bx, si ; was it copied ? jne done ; yes, all done mov ax, ds:[TS_gsBuffer] ; no, resize chunk call LMemReAlloc ; re-alloc the buffer jmp tryAgain done: .leave ret reallocChunk: mov ax, bx ; get chunk handle mov cx, 512 ; make it big enough call LMemReAlloc jmp getElement ReadNextElement endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% AllocStringChunk %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Alloc a text string chunk, and fill in the info CALLED BY: INTERNAL GetTextString, GetTextStringCP PASS: *ds:si - chunk to find string in dx - offset into chunk to find string cx - length of string ax,bx - x,y position to draw string di - gstate handle RETURN: ds - may have moved through allocs. DESTROYED: ax PSEUDO CODE/STRATEGY: use the Y position, and X position of the passed text to build out an ordered array of increaseing Y position. If the Y position is equal, the X position is use to order the elements. At the same time, another array is built of the font/style/color/etc info associated with the text. At print time the array is enumerated in order, and the text sent out in an order that the printer (dot-matrix especially) needs. KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 07/92 Initial 2.0 version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ AllocStringChunk proc near uses cx, dx, di, si, es curJob local SpoolJobInfo .enter inherit ;if cx=0, then we either have an embedded graphic or an ;empty string. In either case, lets bail. test cx,cx LONG jz exit ;if the suppress form-feed flag is set, them bump the y ;positions by the margin amount. test curJob.SJI_printState, mask SPS_FORM_FEED jnz findControlCodes add bx, paperInfo.PSR_margins.PCMP_top ; add in top end ;ferret out those nasty one-character control codes and ;skip the allocation findControlCodes: mov si,ds:TS_gsBuffer ;source for string. mov si, ds:[si] ; deref chunk add si, dx ; get ptr to string cmp cx, 1 ; one character ? jne allocNewChunk ; no, continue SBCS < cmp {char} ds:[si], C_SPACE ; control code > DBCS < cmp {wchar} ds:[si],C_SPACE ; control code > jae allocNewChunk ; OK if real character clr si ; no string allocated jmp exit ; find/alloc a Chunk Array Element for this text string. ;ds:si has to be the locked array here...... ;ax = x position ;bx = y position allocNewChunk: call TranslateSpecialChars ;fix the hyphens etc.... mov ds:TS_textOffset,dx ;save the text offset in gstring chunk. mov curJob.SJI_textXPosition,ax ;save x pos. mov curJob.SJI_textYPosition,bx ;save y pos. push di ;save GState handle. push cx ;save the length of the string text mov si,ds:TS_styleRunInfo ;handle of the chunkarray. call ChunkArrayGetCount ;see if there are any elements yet. clc ;set up to append jcxz popNGo ;if not, pop the length of string.... mov cx,curJob.SJI_textXPosition mov dx,curJob.SJI_textYPosition mov bx,cs ;address of callback routine. mov di,offset FindXYPosition call ChunkArrayEnum ;get the element with the next lower ;position to insert in front of. ;on return from the enum routine, ;the carry will be set for a peice of ;text that should remain after the ;new text. In this case ;ChunkArrayInsertAt is called ;If the carry is cleared, then there is ;no text below or to the right, and ;this text should go at the end of the ;array. mov di,ax ;get ds:di = element address. popNGo: pop cx ;recover the length of the string text pushf mov ax,cx ;size required for string DBCS < shl ax, 1 > add ax,offset SRI_text ;size req'd for header popf jc insertTheElement call ChunkArrayAppend ;add it on the end. jmp initElement insertTheElement: call ChunkArrayInsertAt ;insert the string here initElement: mov ax,curJob.SJI_textXPosition mov bx,curJob.SJI_textYPosition mov ds:[di].SRI_yPosition,bx ;load the new y position. mov ds:[di].SRI_xPosition,ax ;load the new x position. mov ds:[di].SRI_numChars,cx ;load the length of string. ;now load the text string into the chunk. push di ;save offset to this chunk. add di,offset SRI_text ;point at the text position. segmov es,ds,ax ;get destination (same lmem block) mov si,ds:TS_gsBuffer ;source for string. mov si,ds:[si] ;deref chunk. add si,ds:TS_textOffset ;add to get past the gstring structure. if not DBCS_PCGEOS shr cx,1 ;divide /2 for word move. jnc textMove movsb jcxz afterTextMove ;if there was only one character in the ;style run, skip the move following... textMove: rep movsw afterTextMove: else rep movsw endif ;now we need to see if there is an existing attribute block ;that matches what we have passed here. If there is one, then ;just load the SRI_attributes pointer with the element number ;of the matching attribute block. If there is no matching ;block, we add one at the end of the array, and store that ;element number. ;ds = lmem block ;di = GState handle ;fill out the element to add..... pop si ;offset to SRI chunk pop di ;GState handle. mov cx, ds:[si].SRI_numChars ;get #chars push si ;save chunk offset add si,offset SRI_text ;offset to beginning of chars call GrTextWidthWBFixed ; figure out how wide pop si ;recover chunk offset add ds:[si].SRI_stringWidth.WBF_frac, ah adc ds:[si].SRI_stringWidth.WBF_int, dx ; call GetTextAttr ;load the TestAttribute table ;from GState. ;Now that we have all the good info to set a font/style/size, ;either add or get the element # of an identical set of ;attributes. mov di,si mov si,ds:[TS_styleRunInfo] ;handle of the chunk array. call ChunkArrayPtrToElement ;get # of this style run. push ax ;save away for later. mov si,ds:TS_textAttributeInfo ;element array mov cx,ds ;in this lmem segment mov dx,offset TS_testAttribute ;element to compare and add EC < mov bx,ss ;stuff es w/valid > EC < mov es,bx ;segment info > clr bx mov di,bx ;set to zero to do compare. call ElementArrayAddElement ;return the element number mov dx,ax ;save attr element # mov bx, curJob.SJI_tsHan ; get the handle call MemDerefDS ; dereference it ; the code above may screw up if the block moves, so here we copy the ; data again to make sure it's correct. We could copy it to the ; stack before calling ElementArrayAddElement, but here we don't use ; up valuable stack space (20+ bytes). mov si,ds:TS_textAttributeInfo ;element array call ChunkArrayElementToPtr ; ds:di -> element just added mov cx, size TextAttrInfo ; cx = element size segmov es, ds ; es:di -> element just added mov si, offset TS_testAttribute ; ds:si -> source of attr info rep movsb pop ax ;recover chunk # mov si,ds:[TS_styleRunInfo] ;handle of the chunk array. call ChunkArrayElementToPtr ;get the address of this style run. mov ds:[di].SRI_attributes,dx ;in ax for StyleRunInfo. exit: .leave ret AllocStringChunk endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TranslateSpecialChars %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Fix up the special characters that may be in the string. CALLED BY: INTERNAL PASS: ds:si - string address cx - length of string di - Gstate handle RETURN: cx - length of string (may have changed) string adjusted to contain the right hyphenation, etc. DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 04/93 Initial 2.0 version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ TranslateSpecialChars proc near uses ax,bx,dx,si,es .enter push cx mov bx,di ;GState handle segmov es,ds,di mov di,si ;everything points at the string. clr dx ;dx now counts skipped chars. checkLoop: LocalGetChar ax, dssi ;get a char SBCS < cmp al,C_NONBRKHYPHEN ;is it a non breaking hyphen? > DBCS < cmp ax,C_NON_BREAKING_HYPHEN ;is it a non breaking hyphen? > jne checkOptHyphen SBCS < mov al,C_HYPHEN ;if it is, replace with printable "-".> DBCS < mov ax,C_HYPHEN ;if it is, replace with printable "-".> jmp thisCharTested checkOptHyphen: ;Now we see if this char was an Optional hyphen. SBCS < cmp al,C_OPTHYPHEN ;is it? > DBCS < cmp ax,C_SOFT_HYPHEN ;is it? > jne thisCharTested ;if here then it is an opt hyphen... cmp cx,1 ;if we are not at end, jne thisCharSkipped ;just skip this char xchg bx,di call GrGetTextMode ;see if we need to print it. xchg bx,di cmp al,mask TM_DRAW_OPTIONAL_HYPHENS jz thisCharSkipped ;if not, just exit.... SBCS < mov al,C_HYPHEN ;if so, replace with printable "-".> DBCS < mov ax,C_HYPHEN ;if so, replace with printable "-".> thisCharTested: LocalPutChar esdi, ax ;stuff the char back in the string loopBack: loop checkLoop ;check the next character. pop cx sub cx,dx ;subtract the number of skipped chars mov di,bx ;recover GState handle .leave ret thisCharSkipped: inc dx jmp loopBack TranslateSpecialChars endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetTextAttr %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: get the important attributes out of the GState CALLED BY: INTERNAL PASS: ds - segment of the TextAttributes lmem block di - Gstate handle RETURN: ds:[TS_testAttribute] structure loaded. DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 06/92 Initial 2.0 version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetTextAttr proc near uses ax,bx,si,di,ds,es .enter segmov es,ds,ax ;move the lmem to es. mov bx,di ;lock GState call MemLock mov ds,ax ;get segment of GState. mov di,offset TS_testAttribute.TAI_color ;start of my table. ;set RGB value. mov si,offset [GS_textAttr].[CA_colorRGB] movsw movsb ;set system draw mask. mov al,ds:[GS_textAttr].[CA_maskType] stosb ;set styles. mov al,[GS_fontAttr].[FCA_textStyle] call MapToPrinterStyle ;translate the mess stosw ;set text mode. mov al,ds:[GS_textMode] stosb ;set space padding. mov si,offset [GS_textSpacePad] movsb movsw ;set FontID enum. mov si,offset [GS_fontAttr].[FCA_fontID] movsw ;set size. movsb movsw ;set track kerning. mov ax, {word}ds:[GS_trackKernValue] stosw ;set the font weight. mov al,ds:[GS_fontAttr].[FCA_weight] ;set the font width. mov ah,ds:[GS_fontAttr].[FCA_width] stosw call MemUnlock ;bx should still be GState han .leave ret GetTextAttr endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FindXYPosition %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: find the element with the next lower position in Y and X, (higher numbers) CALLED BY: INTERNAL Callback for ChunkArrayEnum in AllocStringChunk PASS: *ds:si - array ds:di - array element being enumerated ax - element size cx - x position of new text. dx - y position of new text. RETURN: ds:ax - address of this element carry set if this is the one to insert in front of. DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 06/92 Initial 2.0 version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FindXYPosition proc far .enter mov bx,di ;save the offset of this element. cmp dx,ds:[di].SRI_yPosition ;check the Y position. ja exitClr ;jump if new text is below this text jb exitSet ;insert if above this text ;if here must be equal y positions. cmp cx,ds:[di].SRI_xPosition ;check the X position. jbe exitSet ;if to left or same, then insert clc jmp exit ;haven't found what we want yet. exitSet: stc exit: mov ax,bx ;recover the offset to the element .leave ret exitClr: clc jmp exit FindXYPosition endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% MapToPrinterStyle %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Translate the current TextStyle setting to a valid PrintTextStyle record CALLED BY: INTERNAL AllocStringChunk PASS: al - TextStyle record to translate RETURN: ax - PrintTextStyle equivalent DESTROYED: nothing PSEUDO CODE/STRATEGY: The bit mapping is screwed. Just do it brute force. Style TextStyle PrintTextStyle ----- ---------- --------------- OUTLINE bit 6 bit 6 BOLD bit 5 bit 11 ITALIC bit 4 bit 10 SUPERSCRIPT bit 3 bit 13 SUBSCRIPT bit 2 bit 14 STRIKE_THRU bit 1 bit 8 UNDERLINE bit 0 bit 9 KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 03/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ MapToPrinterStyle proc near uses dx, bx, cx .enter clr dx clr ah tst al ; if zero, we're done jz done ; have some bits set, so handle them mov cx, NUM_TEST_BITS clr bx testLoop: test ax, cs:sourceBitTable[bx] ; next bit set ? jz nextBit ; no, on to next one or dx, cs:destBitTable[bx] ; yes, set the bit nextBit: add bx, 2 ; on to next entry loop testLoop done: mov ax, dx .leave ret MapToPrinterStyle endp sourceBitTable label word word mask TS_OUTLINE word mask TS_BOLD word mask TS_ITALIC word mask TS_SUPERSCRIPT word mask TS_SUBSCRIPT word mask TS_STRIKE_THRU word mask TS_UNDERLINE NUM_TEST_BITS equ ($-sourceBitTable)/2 destBitTable label word word mask PTS_OUTLINE word mask PTS_BOLD word mask PTS_ITALIC word mask PTS_SUPERSCRIPT word mask PTS_SUBSCRIPT word mask PTS_STRIKETHRU word mask PTS_UNDERLINE COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% AskForNextTextPage %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Ask for the next piece of paper for manual feed, if needed CALLED BY: GLOBAL PASS: nothing RETURN: ax - dialog box results DESTROYED: cx PSEUDO CODE/STRATEGY: check manual feed flag and do the right thing KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Jim 03/90 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ AskForNextTextPage proc near curJob local SpoolJobInfo uses bx,dx .enter inherit push ds mov bx, curJob.SJI_pstate call MemLock mov ds, ax test ds:[PS_paperInput], mask PIO_MANUAL call MemUnlock ; (preserves flags) pop ds jz done ; no, auto-fed paper ; we have a manual feed situation. Ask the user to stick ; another piece (but nicely) mov cx, SERROR_MANUAL_PAPER_FEED ; ask for next piece clr dx call SpoolErrorBox ; he can only answer OK TestUserStandardDialogResponses SPOOL_BAD_USER_STANDARD_DIALOG_RESPONSE, IC_OK, IC_DISMISS done: .leave ret AskForNextTextPage endp endif ;_TEXT_PRINTING PrintText ends
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r9 push %rax push %rbp push %rbx push %rcx push %rdi push %rsi lea addresses_normal_ht+0x175d4, %r9 nop nop nop nop nop cmp $64800, %rbp mov $0x6162636465666768, %rcx movq %rcx, %xmm7 movups %xmm7, (%r9) nop nop nop dec %rbx lea addresses_normal_ht+0x7dcf, %rsi lea addresses_normal_ht+0x12a7c, %rdi nop nop nop xor $32979, %rax mov $15, %rcx rep movsw nop nop nop nop nop sub %rcx, %rcx lea addresses_UC_ht+0x1070f, %rsi nop xor %rbx, %rbx mov $0x6162636465666768, %rcx movq %rcx, %xmm3 vmovups %ymm3, (%rsi) nop nop nop nop nop add %rsi, %rsi lea addresses_WT_ht+0xd7af, %rsi lea addresses_D_ht+0x7b0f, %rdi clflush (%rdi) nop nop nop nop xor $49362, %rbx mov $75, %rcx rep movsq nop nop nop dec %rsi lea addresses_A_ht+0xab0f, %rdi nop cmp %rcx, %rcx mov (%rdi), %r9d nop nop cmp $7120, %rbp lea addresses_WT_ht+0x1d4ad, %rbp nop nop nop nop nop and %rbx, %rbx movb $0x61, (%rbp) nop nop nop nop cmp $18378, %rax lea addresses_D_ht+0x11817, %r9 clflush (%r9) and %rax, %rax vmovups (%r9), %ymm2 vextracti128 $1, %ymm2, %xmm2 vpextrq $1, %xmm2, %rcx nop nop nop nop nop sub $37416, %rbp lea addresses_normal_ht+0x1ea3b, %rsi lea addresses_WT_ht+0x70f, %rdi nop nop nop nop cmp $4820, %r12 mov $65, %rcx rep movsw nop dec %r9 lea addresses_WC_ht+0x76b5, %rsi nop cmp %rax, %rax movb (%rsi), %r12b add %r12, %r12 lea addresses_UC_ht+0xd8f, %rsi lea addresses_WC_ht+0xd08f, %rdi and %r12, %r12 mov $26, %rcx rep movsb nop nop nop dec %rcx lea addresses_D_ht+0x16a63, %rbx nop nop sub %r12, %r12 movl $0x61626364, (%rbx) nop nop nop nop dec %rbx pop %rsi pop %rdi pop %rcx pop %rbx pop %rbp pop %rax pop %r9 pop %r12 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %r14 push %rbp push %rcx push %rdi push %rdx push %rsi // Store lea addresses_A+0x12d96, %r12 nop nop nop nop nop add $52742, %r13 movw $0x5152, (%r12) xor $38788, %rbp // REPMOV lea addresses_WC+0x108cf, %rsi lea addresses_UC+0x1f0bf, %rdi and $35650, %rdx mov $45, %rcx rep movsq nop nop sub %rsi, %rsi // Store lea addresses_WC+0xdf0f, %rbp nop nop nop nop nop and $19, %rdx mov $0x5152535455565758, %r13 movq %r13, (%rbp) nop nop and %rcx, %rcx // Load lea addresses_WT+0xa4f, %r14 sub $46255, %r13 vmovups (%r14), %ymm6 vextracti128 $0, %ymm6, %xmm6 vpextrq $0, %xmm6, %rdi nop nop nop nop and %rbp, %rbp // Store lea addresses_D+0x1da07, %r14 clflush (%r14) and %rsi, %rsi movw $0x5152, (%r14) nop nop nop nop add $56789, %rdi // Store lea addresses_WT+0x16f0f, %rbp nop nop nop nop nop sub $45586, %r13 mov $0x5152535455565758, %rcx movq %rcx, %xmm2 vmovntdq %ymm2, (%rbp) nop nop nop nop nop cmp $57830, %r12 // Faulty Load lea addresses_PSE+0x18b0f, %rdi nop dec %rcx mov (%rdi), %r12 lea oracles, %rbp and $0xff, %r12 shlq $12, %r12 mov (%rbp,%r12,1), %r12 pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r14 pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0, 'same': True, 'type': 'addresses_PSE'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0, 'same': False, 'type': 'addresses_A'}, 'OP': 'STOR'} {'src': {'congruent': 6, 'same': False, 'type': 'addresses_WC'}, 'dst': {'congruent': 4, 'same': False, 'type': 'addresses_UC'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': True, 'size': 8, 'congruent': 7, 'same': False, 'type': 'addresses_WC'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 2, 'same': False, 'type': 'addresses_WT'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': True, 'size': 2, 'congruent': 3, 'same': False, 'type': 'addresses_D'}, 'OP': 'STOR'} {'dst': {'NT': True, 'AVXalign': False, 'size': 32, 'congruent': 8, 'same': False, 'type': 'addresses_WT'}, 'OP': 'STOR'} [Faulty Load] {'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0, 'same': True, 'type': 'addresses_PSE'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'STOR'} {'src': {'congruent': 6, 'same': False, 'type': 'addresses_normal_ht'}, 'dst': {'congruent': 0, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 7, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'} {'src': {'congruent': 3, 'same': False, 'type': 'addresses_WT_ht'}, 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM'} {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 11, 'same': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 1, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 1, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 1, 'same': False, 'type': 'addresses_normal_ht'}, 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM'} {'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 1, 'same': True, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 5, 'same': False, 'type': 'addresses_UC_ht'}, 'dst': {'congruent': 5, 'same': True, 'type': 'addresses_WC_ht'}, 'OP': 'REPM'} {'dst': {'NT': False, 'AVXalign': True, 'size': 4, 'congruent': 2, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'STOR'} {'33': 21829} 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 */
// Copyright 2019 Proyectos y Sistemas de Mantenimiento SL (eProsima). // // 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. /** * @file SubscriberListener.hpp */ #ifndef _FASTDDS_SUBLISTENER_HPP_ #define _FASTDDS_SUBLISTENER_HPP_ #include <fastrtps/fastrtps_dll.h> #include <fastrtps/qos/DeadlineMissedStatus.h> #include <fastrtps/qos/LivelinessChangedStatus.h> #include <fastdds/dds/core/status/SubscriptionMatchedStatus.hpp> #include <fastdds/dds/subscriber/DataReaderListener.hpp> namespace eprosima { namespace fastdds { namespace dds { class Subscriber; /** * Class SubscriberListener, it should be used by the end user to implement specific callbacks to certain actions. * It also inherits all DataReaderListener callbacks. * * @ingroup FASTDDS_MODULE */ class SubscriberListener : public DataReaderListener { public: /** * @brief Constructor */ RTPS_DllAPI SubscriberListener() { } /** * @brief Destructor */ RTPS_DllAPI virtual ~SubscriberListener() { } /** * Virtual function to be implemented by the user containing the actions to be performed when a new * Data Message is available on any reader. * * @param sub Subscriber */ RTPS_DllAPI virtual void on_data_on_readers( Subscriber* sub) { (void)sub; } }; } /* namespace dds */ } /* namespace fastdds */ } /* namespace eprosima */ #endif /* _FASTDDS_SUBLISTENER_HPP_ */
#include <QtGlobal> // Automatically generated by extract_strings.py #ifdef __GNUC__ #define UNUSED __attribute__((unused)) #else #define UNUSED #endif static const char UNUSED *bitcoin_strings[] = { QT_TRANSLATE_NOOP("bitcoin-core", "" "%s, you must set a rpcpassword in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=musdcoinrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file " "permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"Musdcoin Alert\" admin@foo.com\n"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:" "@STRENGTH)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "An error occurred while setting up the RPC port %u for listening on IPv4: %s"), QT_TRANSLATE_NOOP("bitcoin-core", "" "An error occurred while setting up the RPC port %u for listening on IPv6, " "falling back to IPv4: %s"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Bind to given address and always listen on it. Use [host]:port notation for " "IPv6"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Cannot obtain a lock on data directory %s. Musdcoin is probably already " "running."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Error: The transaction was rejected! This might happen if some of the coins " "in your wallet were already spent, such as if you used a copy of wallet.dat " "and coins were spent in the copy but not marked as spent here."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Error: This transaction requires a transaction fee of at least %s because of " "its amount, complexity, or use of recently received funds!"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when a relevant alert is received (%s in cmd is replaced by " "message)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when a wallet transaction changes (%s in cmd is replaced by " "TxID)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Execute command when the best block changes (%s in cmd is replaced by block " "hash)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Listen for JSON-RPC connections on <port> (default: 9776 or testnet: 59776)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Number of seconds to keep misbehaving peers from reconnecting (default: " "86400)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Set maximum size of high-priority/low-fee transactions in bytes (default: " "27000)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Set the number of script verification threads (up to 16, 0 = auto, <0 = " "leave that many cores free, default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "" "This is a pre-release test build - use at your own risk - do not use for " "mining or merchant applications"), QT_TRANSLATE_NOOP("bitcoin-core", "" "Unable to bind to %s on this computer. Musdcoin is probably already running."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: -paytxfee is set very high! This is the transaction fee you will " "pay if you send a transaction."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: Displayed transactions may not be correct! You may need to upgrade, " "or other nodes may need to upgrade."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: Please check that your computer's date and time are correct! If " "your clock is wrong Musdcoin will not work properly."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: error reading wallet.dat! All keys read correctly, but transaction " "data or address book entries might be missing or incorrect."), QT_TRANSLATE_NOOP("bitcoin-core", "" "Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as " "wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect " "you should restore from a backup."), QT_TRANSLATE_NOOP("bitcoin-core", "" "You must set rpcpassword=<password> in the configuration file:\n" "%s\n" "If the file does not exist, create it with owner-readable-only file " "permissions."), QT_TRANSLATE_NOOP("bitcoin-core", "Accept command line and JSON-RPC commands"), QT_TRANSLATE_NOOP("bitcoin-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"), QT_TRANSLATE_NOOP("bitcoin-core", "Add a node to connect to and attempt to keep the connection open"), QT_TRANSLATE_NOOP("bitcoin-core", "Allow DNS lookups for -addnode, -seednode and -connect"), QT_TRANSLATE_NOOP("bitcoin-core", "Allow JSON-RPC connections from specified IP address"), QT_TRANSLATE_NOOP("bitcoin-core", "Attempt to recover private keys from a corrupt wallet.dat"), QT_TRANSLATE_NOOP("bitcoin-core", "Musdcoin version"), QT_TRANSLATE_NOOP("bitcoin-core", "Block creation options:"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot downgrade wallet"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -bind address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -externalip address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Cannot write default address"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect only to the specified node(s)"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect through socks proxy"), QT_TRANSLATE_NOOP("bitcoin-core", "Connect to a node to retrieve peer addresses, and disconnect"), QT_TRANSLATE_NOOP("bitcoin-core", "Corrupted block database detected"), QT_TRANSLATE_NOOP("bitcoin-core", "Discover own IP address (default: 1 when listening and no -externalip)"), QT_TRANSLATE_NOOP("bitcoin-core", "Do you want to rebuild the block database now?"), QT_TRANSLATE_NOOP("bitcoin-core", "Done loading"), QT_TRANSLATE_NOOP("bitcoin-core", "Error initializing block database"), QT_TRANSLATE_NOOP("bitcoin-core", "Error initializing wallet database environment %s!"), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading block database"), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat"), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet corrupted"), QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet requires newer version of Musdcoin"), QT_TRANSLATE_NOOP("bitcoin-core", "Error opening block database"), QT_TRANSLATE_NOOP("bitcoin-core", "Error"), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Disk space is low!"), QT_TRANSLATE_NOOP("bitcoin-core", "Error: Wallet locked, unable to create transaction!"), QT_TRANSLATE_NOOP("bitcoin-core", "Error: system error: "), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to listen on any port. Use -listen=0 if you want this."), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to read block info"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to read block"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to sync block index"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write block index"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write block info"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write block"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write file info"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write to coin database"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write transaction index"), QT_TRANSLATE_NOOP("bitcoin-core", "Failed to write undo data"), QT_TRANSLATE_NOOP("bitcoin-core", "Fee per KB to add to transactions you send"), QT_TRANSLATE_NOOP("bitcoin-core", "Find peers using DNS lookup (default: 1 unless -connect)"), QT_TRANSLATE_NOOP("bitcoin-core", "Generate coins (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Get help for a command"), QT_TRANSLATE_NOOP("bitcoin-core", "How many blocks to check at startup (default: 288, 0 = all)"), QT_TRANSLATE_NOOP("bitcoin-core", "How thorough the block verification is (0-4, default: 3)"), QT_TRANSLATE_NOOP("bitcoin-core", "Imports blocks from external blk000??.dat file"), QT_TRANSLATE_NOOP("bitcoin-core", "Information"), QT_TRANSLATE_NOOP("bitcoin-core", "Insufficient funds"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -proxy address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid -tor address: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -minrelaytxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -mintxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount for -paytxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Invalid amount"), QT_TRANSLATE_NOOP("bitcoin-core", "List commands"), QT_TRANSLATE_NOOP("bitcoin-core", "Listen for connections on <port> (default: 9777 or testnet: 59777)"), QT_TRANSLATE_NOOP("bitcoin-core", "Loading addresses..."), QT_TRANSLATE_NOOP("bitcoin-core", "Loading block index..."), QT_TRANSLATE_NOOP("bitcoin-core", "Loading wallet..."), QT_TRANSLATE_NOOP("bitcoin-core", "Maintain a full transaction index (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maintain at most <n> connections to peers (default: 125)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Not enough file descriptors available."), QT_TRANSLATE_NOOP("bitcoin-core", "Only accept block chain matching built-in checkpoints (default: 1)"), QT_TRANSLATE_NOOP("bitcoin-core", "Only connect to nodes in network <net> (IPv4, IPv6 or Tor)"), QT_TRANSLATE_NOOP("bitcoin-core", "Options:"), QT_TRANSLATE_NOOP("bitcoin-core", "Output extra debugging information. Implies all other -debug* options"), QT_TRANSLATE_NOOP("bitcoin-core", "Output extra network debugging information"), QT_TRANSLATE_NOOP("bitcoin-core", "Password for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "Prepend debug output with timestamp"), QT_TRANSLATE_NOOP("bitcoin-core", "Rebuild block chain index from current blk000??.dat files"), QT_TRANSLATE_NOOP("bitcoin-core", "Rescan the block chain for missing wallet transactions"), QT_TRANSLATE_NOOP("bitcoin-core", "Rescanning..."), QT_TRANSLATE_NOOP("bitcoin-core", "Run in the background as a daemon and accept commands"), QT_TRANSLATE_NOOP("bitcoin-core", "SSL options: (see the Musdcoin Wiki for SSL setup instructions)"), QT_TRANSLATE_NOOP("bitcoin-core", "Select the version of socks proxy to use (4-5, default: 5)"), QT_TRANSLATE_NOOP("bitcoin-core", "Send command to -server or musdcoind"), QT_TRANSLATE_NOOP("bitcoin-core", "Send commands to node running on <ip> (default: 127.0.0.1)"), QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to console instead of debug.log file"), QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to debugger"), QT_TRANSLATE_NOOP("bitcoin-core", "Server certificate file (default: server.cert)"), QT_TRANSLATE_NOOP("bitcoin-core", "Server private key (default: server.pem)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set database cache size in megabytes (default: 25)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set key pool size to <n> (default: 100)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set maximum block size in bytes (default: 250000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set minimum block size in bytes (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Set the number of threads to service RPC calls (default: 4)"), QT_TRANSLATE_NOOP("bitcoin-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"), QT_TRANSLATE_NOOP("bitcoin-core", "Signing transaction failed"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify configuration file (default: musdcoin.conf)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify connection timeout in milliseconds (default: 5000)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify data directory"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify pid file (default: musdcoind.pid)"), QT_TRANSLATE_NOOP("bitcoin-core", "Specify your own public address"), QT_TRANSLATE_NOOP("bitcoin-core", "System error: "), QT_TRANSLATE_NOOP("bitcoin-core", "This help message"), QT_TRANSLATE_NOOP("bitcoin-core", "Threshold for disconnecting misbehaving peers (default: 100)"), QT_TRANSLATE_NOOP("bitcoin-core", "To use the %s option"), QT_TRANSLATE_NOOP("bitcoin-core", "Transaction amount too small"), QT_TRANSLATE_NOOP("bitcoin-core", "Transaction amounts must be positive"), QT_TRANSLATE_NOOP("bitcoin-core", "Transaction too large"), QT_TRANSLATE_NOOP("bitcoin-core", "Unable to bind to %s on this computer (bind returned error %d, %s)"), QT_TRANSLATE_NOOP("bitcoin-core", "Unknown -socks proxy version requested: %i"), QT_TRANSLATE_NOOP("bitcoin-core", "Unknown network specified in -onlynet: '%s'"), QT_TRANSLATE_NOOP("bitcoin-core", "Upgrade wallet to latest format"), QT_TRANSLATE_NOOP("bitcoin-core", "Usage:"), QT_TRANSLATE_NOOP("bitcoin-core", "Use OpenSSL (https) for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 0)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use UPnP to map the listening port (default: 1 when listening)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use proxy to reach tor hidden services (default: same as -proxy)"), QT_TRANSLATE_NOOP("bitcoin-core", "Use the test network"), QT_TRANSLATE_NOOP("bitcoin-core", "Username for JSON-RPC connections"), QT_TRANSLATE_NOOP("bitcoin-core", "Verifying blocks..."), QT_TRANSLATE_NOOP("bitcoin-core", "Verifying wallet..."), QT_TRANSLATE_NOOP("bitcoin-core", "Wallet needed to be rewritten: restart Musdcoin to complete"), QT_TRANSLATE_NOOP("bitcoin-core", "Warning"), QT_TRANSLATE_NOOP("bitcoin-core", "Warning: This version is obsolete, upgrade required!"), QT_TRANSLATE_NOOP("bitcoin-core", "You need to rebuild the database using -reindex to change -txindex"), QT_TRANSLATE_NOOP("bitcoin-core", "wallet.dat corrupt, salvage failed"), };
COMMENT @---------------------------------------------------------------------- Copyright (c) GeoWorks 1989 -- All Rights Reserved PROJECT: PC GEOS MODULE: User/Text FILE: taRunManip.asm ROUTINES: Name Description ---- ----------- routine REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 10/89 Initial version DESCRIPTION: This file contains the internal routines to handle charAttr, paraAttr and type runs. None of these routines are directly accessable outisde the text object. $Id: taRunTrans.asm,v 1.1 97/04/07 11:18:52 newdeal Exp $ ------------------------------------------------------------------------------@ TRANS_PARAMS equ <\ .warn -unref_local\ ssParams local StyleSheetParams\ styleAttrOffset local word\ copyRange local VisTextRange\ runOffset local word\ optBlock local hptr\ fromTransfer local word\ objFile local hptr\ objRunDataBX local word\ objRunDataSI local word\ objRunDataDI local word\ objRunCount local word\ xferFile local word\ xferRunPtr local fptr\ xferRunCount local word\ xferRunToken local word\ textobject local optr\ transferHeader local hptr\ fileToken local word\ .warn @unref_local\ > TextTransfer segment resource COMMENT @---------------------------------------------------------------------- FUNCTION: TA_CopyRunToTransfer DESCRIPTION: Copy run information from a text object to a transfer run CALLED BY: INTERNAL PASS: *ds:si - text object ax - transfer file bx - offset of run in text object cx - xfer run vm block dx - optimization block (or 0 to allocate) ss:bp - VisTextRange in source to copy di - handle of (locked) TextTransferBlockHeader RETURN: dx - optimization block DESTROYED: none REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: sourceRun = GetRunForPosition(sourceRunArray, sourcePos) destRun = destRunArray if (graphicRun} { sourcePos = sourceRun.pos } do { if ((charAttr or paraAttr) && style array exists) { newToken = StyleSheetCopyElementToTransfer(sourceRun.token) } else { temp = GetElement(sourceRunArray, sourceRun.token) newToken = AddElement(destRunArray, element) } InsertRun(destRun, range.start - sourceRun.position, newToken) destRun++ /* point at TEXT_ADDRESS_PAST_END */ sourceRun++ range.start = sourceRun.pos } while (range.start < range.end) KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 1/90 Initial version ------------------------------------------------------------------------------@ TA_CopyRunToTransfer proc near uses ax, bx, cx, si, di, bp, ds class VisTextClass TRANS_PARAMS sourceStart local dword .enter ; sourceRun = GetRunForPosition(sourceRunArray, sourcePos) ; destRun = destRunArray call LoadCopyRunParams mov fromTransfer, 0 ; if this is a graphic run, then check for the graphic being out of the ; selection call TTLoadObjRun clr dx mov dl, ds:[si].TRAE_position.WAAH_high mov ax, ds:[si].TRAE_position.WAAH_low movdw sourceStart, dxax cmp runOffset, OFFSET_FOR_GRAPHIC_RUNS jnz notGraphics jgedw dxax, copyRange.VTR_end, afterLoop movdw sourceStart, copyRange.VTR_start, ax notGraphics: runLoop: mov bx, CA_NULL_ELEMENT ;style to use if no styles mov dx, CA_NULL_ELEMENT ;copy style also call CopyTransferElement ;bx = token jc afterLoop ; InsertRun(destRun, sourceRun.position - sourceStart, newToken) ; destRun++ /* point at TEXT_ADDRESS_PAST_END */ ; sourceRun++ ; sourceStart = range.start ; } while (range.start < range.end) call TTLoadObjRun clr dx mov dl, ds:[si].TRAE_position.WAAH_high mov ax, ds:[si].TRAE_position.WAAH_low subdw dxax, sourceStart call TTLoadXferRun call FarRunArrayInsert push bx call FarRunArrayNext pop bx call TTStoreXferRun call RemoveElement ;remove extra reference call TTLoadObjRun call FarRunArrayNext ;dxax = next pos call TTStoreObjRun cmpdw dxax, copyRange.VTR_end movdw sourceStart, copyRange.VTR_start, ax jb runLoop afterLoop: call TTLoadXferRun call FarRunArrayUnlock ; leaves source file set call TTLoadObjRun call FarRunArrayUnlock mov dx, optBlock .leave ret TA_CopyRunToTransfer endp COMMENT @---------------------------------------------------------------------- FUNCTION: TA_CopyRunFromTransfer DESCRIPTION: Copy run information from a transfer run to a text object CALLED BY: INTERNAL PASS: *ds:si - text object ax - transfer file bx - offset of run in text object cx - xfer run vm block dx - optimization block (or 0 to allocate) ss:bp - VisTextRange in source to copy di - handle of (locked) TextTransferBlockHeader RETURN: dx - optimization block DESTROYED: none REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: Handling of paraAttrs: ($ means C_CR) Transfer: ab$cd$ef where paraAttr runs are: AA$BB$CC Object: 12$34$56 where paraAttr runs are: XX$YY$ZZ, cursor btw 3 & 4 Result: 12$3ab$cd$ef4$56 ParaAttr runs: XX$YYY$BB$YYY$ZZZ sourceRun = GetRunForPosition(sourceRunArray, 0) destRun = GetRunForPosition(destRunArray, range.start) if (graphicRuns) { range.start += sourceRun.pos } else { newToken = destRun.token destRun++ if (destRun.pos != destEnd && destEnd != end of text) { InsertRun(destRunArray, destEnd, newToken) } } if (paraAttr) { nextPara = T_FindPara(range.start) adjustment = nextPara - range.start range.start = nextPara } do { if ((charAttr or paraAttr) && style array exists) { newToken = StyleSheetCopyElementFromTransfer(sourceRun.token) } else { temp = GetElement(sourceRunArray, sourceRun.token) newToken = AddElement(destRunArray, element) } InsertRun(destRunArray, range.start, newToken) range.start += (sourceRun+1.pos - sourceRun.pos) destRun++ sourceRun++ } while (range.start != TEXT_ADDRESS_PAST_END) KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 1/90 Initial version ------------------------------------------------------------------------------@ TA_CopyRunFromTransfer proc near uses ax, bx, cx, di, bp class VisTextClass TRANS_PARAMS textsize local dword adjustment local dword insertedRunFlag local byte runTokenAtAreaStart local word posToStartStyleCopy local dword posToEndStyleCopy local dword valueToPassToCopy local word baseStyleIfNone local word .enter pushdw dxax call TS_GetTextSize movdw textsize, dxax popdw dxax ; sourceRun = GetRunForPosition(sourceRunArray, 0) ; destRun = GetRunForPosition(destRunArray, range.start) call LoadCopyRunParams mov fromTransfer, -1 push ds, si call TTLoadObject push di mov di, ds:[si] add di, ds:[di].VisText_offset test ds:[di].VTI_features, mask VTF_ALLOW_UNDO pop di jz noUndo push ax call GenProcessUndoCheckIfIgnoring ;Don't create any actions if tst ax ; ignoring undo pop ax jnz noUndo ; Add an undo item to delete these runs. push bp, cx mov cx, runOffset lea bp, copyRange call CheckIfRunsInRangeForUndoFar tst ax jz noUndoRuns push bx mov bx, bp call TU_CreateUndoForRunsInRange pop bx noUndoRuns: call TU_CreateUndoForRunModification pop bp, cx noUndo: pop ds, si ; if (graphicRuns) { ; range.start += sourceRun.pos clr insertedRunFlag cmp runOffset, OFFSET_FOR_GRAPHIC_RUNS jnz notGraphics call TTLoadXferRun clr dx mov dl, ds:[si].TRAE_position.WAAH_high mov ax, ds:[si].TRAE_position.WAAH_low adddw copyRange.VTR_start, dxax jmp common ; Since we will be splitting a run and putting information in the ; middle, we must ensure that the parts before and after the part we ; change retain the same run. In the general case, this involves ; inserting a run after the run to be split, positioning it just after ; the end of the area we change, and giving it the token of the run ; that we split. ; There are some boundry cases to take care of when inserting at the ; edge of a run: ; * if we are at the right edge of a run, do not insert a run ; } else { ; newToken = destRun.token ; destRun++ ; if (destRun.pos != destEnd && destEnd != end of text) { ; InsertRun(destRunArray, destEnd, newToken) ; } ; } notGraphics: call TTLoadObjRun ;load dest push ds:[si].TRAE_token call FarRunArrayNext ;dxax = next pos pop bx mov runTokenAtAreaStart, bx push bp sub sp, size VisTextMaxParaAttr mov bp, sp call GetElement mov ax, ss:[bp].SSEH_style add sp, size VisTextMaxParaAttr pop bp mov baseStyleIfNone, ax movdw dxax, copyRange.VTR_end cmp dl, ds:[si].TRAE_position.WAAH_high jnz 10$ cmp ax, ds:[si].TRAE_position.WAAH_low 10$: jz noInsertRun cmpdw dxax, textsize jz noInsertRun call FarRunArrayInsert inc insertedRunFlag noInsertRun: call TTStoreObjRun common: ; if (paraAttr) { ; nextPara = T_FindPara(range.start) ; adjustment = nextPara - range.start ; range.start = nextPara ; } movdw posToEndStyleCopy, TEXT_ADDRESS_PAST_END clr ax clrdw adjustment, ax clrdw posToStartStyleCopy, ax call TTLoadObject cmp runOffset, offset VTI_paraAttrRuns jnz notParaAttr movdw dxax, copyRange.VTR_start call TSL_IsParagraphStart LONG jc runLoop call TSL_FindParagraphEnd ;dxax = para end jc toAfterLoop incdw dxax pushdw dxax subdw dxax, copyRange.VTR_start movdw adjustment, dxax popdw dxax movdw copyRange.VTR_start, dxax ;range.start = nextPara ; if the adjustment is bigger than the range to paste then we're not ; pasting any CR's, so bail cmpdw dxax, copyRange.VTR_end jbe runLoop toAfterLoop: jmp afterLoop ; if we are adjusting character attribute runs then we need to not ; copy the style until the next paragraph notParaAttr: cmp runOffset, offset VTI_charAttrRuns jnz runLoop movdw dxax, copyRange.VTR_start call TSL_IsParagraphStart jc notCAParaStart call TSL_FindParagraphEnd ;dxax = para end movdw posToStartStyleCopy, dxax notCAParaStart: movdw dxax, copyRange.VTR_end stc call TSL_FindParagraphStart jc 20$ decdw dxax 20$: cmpdw dxax, copyRange.VTR_start ja 30$ movdw dxax, TEXT_ADDRESS_PAST_END 30$: movdw posToEndStyleCopy, dxax ; now loop through all of the runs in the source (the transfer item) ; and copy each run to the destination (the text object) ; we must be careful with character attribute styles since we do ; not want to copy the underlying style unless we are copying the ; entire para runLoop: movdw dxax, copyRange.VTR_start cmpdw dxax, posToStartStyleCopy jb copyNoStyle cmpdw dxax, posToEndStyleCopy mov dx, CA_NULL_ELEMENT jb copyCommon copyNoStyle: mov dx, runTokenAtAreaStart copyCommon: mov bx, baseStyleIfNone call CopyTransferElement ;bx = token LONG jc toAfterLoop ; InsertRun(destRunArray, range.start, newToken) ; range.start += (sourceRun+1.pos - sourceRun.pos) - adjustment ; destRun++ ; sourceRun++ ; adjustment = 0 ; } while (range.start != TEXT_ADDRESS_PAST_END) call TTLoadObjRun movdw dxax, copyRange.VTR_start pushdw dxax call FarRunArrayInsert ; Since FarRunArrayInsert adds another reference for the element, ; we now have an extra reference,so delete this extra reference call RemoveElement call FarRunArrayNext ; if we're not copying style information until we hit a paragraph ; edge so see if we've hit one yet cmpdw dxax, posToStartStyleCopy jb noLookForParaEdge clrdw dxax xchgdw dxax, posToStartStyleCopy tstdw dxax jz noLookForParaEdge mov valueToPassToCopy, CA_NULL_ELEMENT ;copy with style call insertAtDXAX noLookForParaEdge: popdw dxax ; if we're at the point to stop copying style information then ; deal with that cmpdw dxax, posToEndStyleCopy jb noLookForParaEdgeEnd mov ax, runTokenAtAreaStart mov valueToPassToCopy, ax movdw dxax, TEXT_ADDRESS_PAST_END xchgdw dxax, posToEndStyleCopy cmp dl, TEXT_ADDRESS_PAST_END_HIGH jz noLookForParaEdgeEnd call insertAtDXAX noLookForParaEdgeEnd: call TTStoreObjRun call TTLoadXferRun clr dx mov dl, ds:[si].TRAE_position.WAAH_high mov ax, ds:[si].TRAE_position.WAAH_low pushdw dxax ;save sourceRun.pos call FarRunArrayNext call TTStoreXferRun popdw cxbx subdw dxax, cxbx ;dxax = diff between adddw dxax, copyRange.VTR_start subdw dxax, adjustment clrdw adjustment movdw copyRange.VTR_start, dxax cmpdw dxax, copyRange.VTR_end LONG jb runLoop afterLoop: ; if were dealing with paraAttr runs and if the last run does not point ; at a C_CR remove it and move its token to the previous run cmp runOffset, offset VTI_paraAttrRuns jnz noParaAttrPatch tst insertedRunFlag jz noParaAttrPatch ; The last paragraph is partially from the inserted data and partially ; from the original. We cannot leave it this way since a paragraph can ; have only one paraAttr (and the EC code would barf on the run in the ; middle of a paragraph). ; We need to move this run that is in the middle of a paragraph back ; to the start of the last paragraph. call TTLoadObjRun clr dx mov dl, ds:[si].TRAE_position.WAAH_high mov ax, ds:[si].TRAE_position.WAAH_low call TTLoadObject stc call TSL_FindParagraphStart ;dxax = paragraph start pushdw dxax call TTLoadObjRun popdw dxax mov ds:[si].TRAE_position.WAAH_high, dl mov ds:[si].TRAE_position.WAAH_low, ax call FarRunArrayMarkDirty noParaAttrPatch: ; if were dealing with charAttr runs and if the last run does not point ; at a C_CR then insert a token at the paragraph start call TTLoadXferRun call FarRunArrayUnlock ; leaves dest file set call TTLoadObjRun call FarRunArrayUnlock call TTLoadObject mov bx, runOffset cmp bx, OFFSET_FOR_GRAPHIC_RUNS jz noCoalesce call CoalesceRun noCoalesce: mov dx, optBlock .leave ret insertAtDXAX: call TTStoreObjRun pushdw dxax mov dx, valueToPassToCopy mov cx, 1 ;mark "from" mov bx, baseStyleIfNone call CopyTransferElement popdw dxax call TTLoadObjRun call FarRunArrayInsert call FarRunArrayNext retn TA_CopyRunFromTransfer endp ;--- COMMENT @---------------------------------------------------------------------- FUNCTION: LoadCopyRunParams DESCRIPTION: Load parameters for TA_CopyRunToTransfer and TA_CopyRunFromTransfer CALLED BY: INTERNAL PASS: *ds:si - text object ax - transfer file bx - offset of run in text object cx - xfer run vm block dx - optimization block (or 0 to allocate) ss:bp - VisTextRange in source to copy RETURN: parameters - set DESTROYED: ax, bx, cx, dx, si, di, ds KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 1/90 Initial version ------------------------------------------------------------------------------@ LoadCopyRunParams proc near TRANS_PARAMS class VisTextClass .enter inherit near mov xferFile, ax mov optBlock, dx mov transferHeader, di xchg bx, di call MemDerefES xchg bx, di mov runOffset, bx mov di, ss:[bp] movdw copyRange.VTR_start, ss:[di].VTR_start, ax movdw copyRange.VTR_end, ss:[di].VTR_end, ax mov ax, ds:[LMBH_handle] movdw textobject, axsi push bx call T_GetVMFile mov objFile, bx pop bx push bp lea bp, ssParams clc ;copy all call LoadSSParams pop bp mov ax, es:TTBH_charAttrElements.high mov ssParams.SSP_xferAttrArrays[0*(size StyleChunkDesc)].\ SCD_vmBlockOrMemHandle, ax mov ax, es:TTBH_paraAttrElements.high mov ssParams.SSP_xferAttrArrays[1*(size StyleChunkDesc)].\ SCD_vmBlockOrMemHandle, ax mov ax, es:TTBH_styles.high mov ssParams.SSP_xferStyleArray.SCD_vmBlockOrMemHandle, ax mov ax, VM_ELEMENT_ARRAY_CHUNK mov ssParams.SSP_xferAttrArrays[0*(size StyleChunkDesc)].\ SCD_chunk, ax mov ssParams.SSP_xferAttrArrays[1*(size StyleChunkDesc)].\ SCD_chunk, ax mov ssParams.SSP_xferStyleArray.SCD_chunk, ax clr ax ;assume char attr cmp bx, offset VTI_charAttrRuns jz gotAttrOffset mov ax, 1 gotAttrOffset: mov styleAttrOffset, ax ; objRun = GetRunForPosition(objRunArray, copyRange.start) push cx ;save xfer run block movdw dxax, copyRange.VTR_start cmp runOffset, OFFSET_FOR_GRAPHIC_RUNS jz 10$ call FarGetRunForPosition jmp 20$ 10$: call GetGraphicRunForPosition 20$: call TTStoreObjRun pop di ;di = xfer run ; destRun = destRunArray mov bx, xferFile mov ssParams.SSP_xferStyleArray.SCD_vmFile, bx mov ssParams.SSP_xferAttrArrays[0*(size StyleChunkDesc)].\ SCD_vmFile, bx mov ssParams.SSP_xferAttrArrays[1*(size StyleChunkDesc)].\ SCD_vmFile, bx call TransRunArrayLock call TTStoreXferRun .leave ret LoadCopyRunParams endp COMMENT @---------------------------------------------------------------------- FUNCTION: CopyTransferElement DESCRIPTION: Copy an element to/from a transfer space CALLED BY: TA_CopyRunToTransfer, TA_CopyRunFromTransfer PASS: bx - style to be based on if copying with no style dx - CA_NULL_ELEMENT to copy style or attribute token to base destination on ss:bp - inherited variables RETURN: bx - token carry - set if at end of runs DESTROYED: ax, cx, dx, si, di, ds KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 1/90 Initial version ------------------------------------------------------------------------------@ CopyTransferElement proc near TRANS_PARAMS class VisTextClass .enter inherit near ; do { ; if ((charAttr or paraAttr) && style array exists) { tst fromTransfer jz 10$ ;load SOURCE call TTLoadXferRun ;to -> object is source jmp 20$ 10$: call TTLoadObjRun ;from -> xfer is source 20$: cmp ds:[si].TRAE_position.WAAH_high, TEXT_ADDRESS_PAST_END_HIGH jnz notAtEnd stc .leave ret notAtEnd: mov ax, ds:[si].TRAE_token ;ax = sourceRun.token tst ssParams.SSP_styleArray.SCD_vmBlockOrMemHandle jz noStyleSheetDest tst ssParams.SSP_xferStyleArray.SCD_vmBlockOrMemHandle jz noStyleSheet cmp runOffset, offset VTI_charAttrRuns jz styleSheet cmp runOffset, offset VTI_paraAttrRuns jnz noStyleSheet styleSheet: ; newToken = StyleSheetCopyElementToTransfer(sourceRun.token) push bp ; check for a character only style, if which case we always pass ; CA_NULL_ELEMENT cmp dx, CA_NULL_ELEMENT jz callStyleSheet tst styleAttrOffset jnz callStyleSheet specialCheck:: push ax, si, ds mov_tr bx, ax call GetElementStyle ;ax = style sheet lea si, ssParams lea bx, ss:[si].SSP_styleArray jcxz 25$ lea bx, ss:[si].SSP_xferStyleArray 25$: call StyleSheetLockStyleChunk ;*ds:si = style array ;carry = value to pass to unlock pushf call ChunkArrayElementToPtr test ds:[di].TSEH_privateData.TSPD_flags, mask TSF_APPLY_TO_SELECTION_ONLY jz notCharOnlyStyle mov dx, CA_NULL_ELEMENT notCharOnlyStyle: popf call StyleSheetUnlockStyleChunk pop ax, si, ds callStyleSheet: call TTLoadObject mov bx, styleAttrOffset mov cx, fromTransfer mov di, optBlock lea bp, ssParams call StyleSheetCopyElement pop bp mov optBlock, di jmp gotToken ;bx = token noStyleSheetDest: ; since there are no style sheets in the destination space we always ; want to have the base style be NULL mov bx, CA_NULL_ELEMENT noStyleSheet: ; } else { ; temp = GetElement(sourceRunArray, sourceRun.token) sub sp, size VisTextMaxParaAttr mov dx, sp push bp push bx ;save style push runOffset mov bp, dx mov_tr bx, ax ;bx = token call GetElement pop ax ;ax = run offset pop bx ;bx = style (if applicable) cmp ax, offset VTI_charAttrRuns jz stuffStyle cmp ax, offset VTI_paraAttrRuns jnz noStuffStyle mov dx, bp stuffStyle: mov ss:[bp].SSEH_style, bx noStuffStyle: pop bp tst fromTransfer jz 50$ ;load DEST call TTLoadObjRun ;from -> object is dest mov bx, objFile ;bx = dest file mov cx, xferFile ;cx = source file jmp 60$ 50$: call TTLoadXferRun ;to -> xfer is dest mov bx, xferFile ;bx = dest file mov cx, objFile ;cx = source file 60$: ; if the element is a type then we must copy the names in (or ; ensure that it already exists) cmp runOffset, OFFSET_FOR_TYPE_RUNS jnz notTypeElement push di mov di, dx call TypeRunCopyNames pop di notTypeElement: ; newToken = AddElement(destRunArray, element) push bp cmp runOffset, OFFSET_FOR_GRAPHIC_RUNS jnz notGraphicElement push fromTransfer mov bp, dx ;ss:bp = element mov dx, cx ;dx = source file (bx = dest) tst ss:[bp].VTG_vmChain.high ;if graphic is stored in lmem jnz gotGraphicToCopy ;then zero it out clr ss:[bp].VTG_vmChain.low gotGraphicToCopy: call AddGraphicElement ;bx = token pop cx ;cx = frpm transfer flag jnc common tst cx jnz common ; we copied a graphic to a transfer file -- link it into the chain movdw dxdi, ss:[bp].VTG_vmChain pop bp add sp, size VisTextMaxParaAttr push bx mov bx, transferHeader call MemDerefDS inc ds:TTBH_meta.VMCT_count mov si, ds:TTBH_meta.VMCT_count shl si shl si add si, ds:TTBH_meta.VMCT_offset ; test for resize needed mov ax, MGIT_SIZE call MemGetInfo ;ax = size cmp ax, si jae noRealloc mov ax, si mov ch, mask HAF_NO_ERR call MemReAlloc mov ds, ax noRealloc: movdw <ds:[si-(size dword)]>, dxdi pop bx jmp commonAfterPop notGraphicElement: mov bp, dx ;ss:bp = element call AddElement ;bx = token common: pop bp add sp, size VisTextMaxParaAttr commonAfterPop: gotToken: clc .leave ret CopyTransferElement endp ;--- COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TypeRunCopyNames %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Copy the context names from the text object to the clipboard, or vice versa CALLED BY: CopyTransferElement PASS: ds:si = current TextRunArrayElement ss:di = VisTextType assoc. w/ the current TextRunArrayElement RETURN: the passed VisTextType may be possibly changed. DESTROYED: SIDE EFFECTS: ds gets updated if the block moves. PSEUDO CODE/STRATEGY: fileToken = -1; // the VTND_file of the first element in Name Array is always // -1(current file). This is true because we handle // VTT_hyperlinkFile before VTT_hyperlinkName (i.e. in the // name array, the element that contains the context // associated w/ the file "foo" always comes after the element // that contains "foo", this is the reason we check // VTT_hyperlinkFile before VTT_hyperlinkName) while (a VTT field contains a name element token) { if(CopyFromTextObjectToClipboard) { Get the name element from the text object; // now see if element is a context element // if true, then update its VTND_file to the // the name token of the file element if(the element's VTND_file != -1) { the element's VTND_file = fileToken; } new name token = Clipboard NameArrayAdd(element); fileToken = new name token; } else { // CopyFromClipboardToTextObject Get the name element from the clipboard; // now see if element is a context element // if true, then update its VTND_file to the // the name token of the file element if(the element's VTND_file != -1) { the element's VTND_file = fileToken; } new name token = TextObject NameArrayAdd(element); fileToken = new name token; send notification to the name list; } } Important Concept: We always define a file before defining a context for that file. Thus, the file element is always before the context element in the Name array. REVISION HISTORY: Name Date Description ---- ---- ----------- Edwin 3/ 8/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ TypeRunCopyNamesNameType etype byte TRCNNT_HYPERLINK_FILE enum TypeRunCopyNamesNameType TRCNNT_HYPERLINK_NAME enum TypeRunCopyNamesNameType TRCNNT_CONTEXT enum TypeRunCopyNamesNameType TypeRunCopyNames proc near TRANS_PARAMS class VisTextClass uses ax, bx,cx,dx,si,di,bp,es push ds:[LMBH_handle] .enter inherit near mov fileToken, -1 ; Stores an initial value for ; the file. ; ; check whether there is a name element to insert ; mov dx, TRCNNT_HYPERLINK_FILE ; add a file name mov ax, ss:[di].VTT_hyperlinkFile cmp ax, -1 jnz insert mov dx, TRCNNT_HYPERLINK_NAME ; add a hyperlink name mov ax, ss:[di].VTT_hyperlinkName cmp ax, -1 jnz insert mov dx, TRCNNT_CONTEXT ; add a context name mov ax, ss:[di].VTT_context cmp ax, -1 jnz insert jmp quit ; no name element to insert insert: ; ; Add a name element for the hyperlink file, hyperlink name, or ; context to the destination Name array. ; push dx ; save which VTT field will be modified push di push bp tst fromTransfer LONG jnz CopyFromClipboardToTextObject ; ; CopyFromTextObjectToClipboard (from -> clipboard is dest) ; call TTLoadObject push ax ; save the name token of the VTI field call FarLockNameArray ; *ds:si = text object's name array pop ax ; restore the value of VTT field push bx ; save the value for unlock name array call ChunkArrayElementToPtr ; ds:di = VisTextNameArrayElement ; ; Make sure the merde-filled element is actually in use before ; trying to use it. Otherwise the element size is 3, and the ; manipulations below will result in a negative (ie. large positive ; size), which wreaks havoc in NameArrayAdd(). ; cmp ds:[di].VTNAE_meta.NAE_meta.REH_refCount.WAAH_high, EA_FREE_ELEMENT LONG je quitUnlock ; branch if free element ; cx = element size sub cx, (size VisTextNameArrayElement) ; cx = string size DBCS < shr cx, 1 ; cx <- string length add di, (size NameArrayElement) ; ; Now check if the context doesn't belong to *same file* ; cmp ds:[di].VTND_file, -1 mov bx, ds:[di].VTND_file je fine ; jumps if context belongs to *same file* mov bx, fileToken ; Otherwise, update VTND_file of ; the context with the new token ; for the file that the context ; associates with fine: ; ; Push VisTextNameData onto the stack for NameArrayAdd ; push ds:[di].VTND_helpText.DBGI_item push ds:[di].VTND_helpText.DBGI_group push bx push {word} ds:[di].VTND_type ; push both VTND_type ; & VTND_contextType add di, (size VisTextNameData) segmov es, ds ; es:di = string pointer clr bx ; NameArrayAddFlags mov dx, ss mov ax, sp push cx ; cx = length of the context string call GetClipboardNameArray ; *ds:si - name array mov bp, cx pop cx call NameArrayAdd ; ax = name token call VMUnlock add sp, (size VisTextNameData) pop bx call FarUnlockNameArray update: ; ; Update the name token in the VisTextType element ; pop bp ; to access local var in TRANS_PARAMS pop di pop dx ; see which field we need to modify mov fileToken, ax ; save the new file name token cmp dx, TRCNNT_HYPERLINK_FILE jne cntxt2 mov ss:[di].VTT_hyperlinkFile, ax mov ax, ss:[di].VTT_hyperlinkName cmp ax, -1 ; is there a hyperlinkName to add? je quit ; No? How can this happen? mov dx, TRCNNT_HYPERLINK_NAME jmp insert ; add the hyperlinkName to Name array cntxt2: cmp dx, TRCNNT_HYPERLINK_NAME jne cntxt3 mov ss:[di].VTT_hyperlinkName, ax ; ; Can a type element have both a hyperlink and a context? ; mov ax, ss:[di].VTT_context cmp ax, -1 LONG je quit mov dx, TRCNNT_CONTEXT jmp insert ; add context name to the Name array cntxt3: EC < cmp dx, TRCNNT_CONTEXT > EC < LONG jne quit > mov ss:[di].VTT_context, ax quit: .leave pop bx call MemDerefDS ret quitUnlock: pop bx ;bx <- value from FarLockNameArray call FarUnlockNameArray pop bp pop di pop dx jmp quit CopyFromClipboardToTextObject: ; to -> xfer is push bp call GetClipboardNameArray ;*ds:si = name array of the clipboard push cx ; cx = value for VMUnlock call ChunkArrayElementToPtr ; ds:di = element ; ; Make sure the merde-filled element is actually in use. ; EC < cmp ds:[di].VTNAE_meta.NAE_meta.REH_refCount.WAAH_high, EA_FREE_ELEMENT > EC < ERROR_E VIS_TEXT_NAME_NOT_IN_USE_IN_CLIPBOARD > sub cx, (size VisTextNameArrayElement) DBCS < shr cx, 1 > add di, (size NameArrayElement) ; ; Check to see if the file name of this name element is the ; same as the name of the text object's file. If so, the ; name element is not added to the text object's Name array. ; cmp ds:[di].VTND_type, VTNT_FILE ; is this a file name element? jne notFile ; movdw bxax, textobject ; check if text object's file ; name matches this name call CheckDestFileName ; if yes, don't paste the cmp ax, -1 ; does ax = *same file* token? je skip ; if yes, don't add the name notFile: mov bx, ds:[di].VTND_file cmp bx, -1 je fine2 mov bx, fileToken fine2: ; ; Push VisTextNameData onto the stack for NameArrayAdd ; push ds:[di].VTND_helpText.DBGI_item push ds:[di].VTND_helpText.DBGI_group push bx push {word} ds:[di].VTND_type ; push both VTND_type ; & VTND_contextType add di, (size VisTextNameData) segmov es, ds ; es:di string pointer call TTLoadObject ; from -> object is dest call FarLockNameArray ; *ds:si = name array mov bp, bx ; value for unlock name array clr bx ; NameArrayAddFlags mov dx, ss mov ax, sp ; dx:ax = data call NameArrayAdd ; ax = name token mov bx, bp call FarUnlockNameArray add sp, (size VisTextNameData) skip: ; ; Unlock the name array ; pop bp ; bp = value for VMUnlock call VMUnlock pop bp ; bp = point to stack jmp update TypeRunCopyNames endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetClipboardNameArray %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Get the name array of the clipboard CALLED BY: TypeRunCopyNames PASS: TRANS_PARAMS data structure RETURN: *ds:si = name array of the clipboard cx = value for unlock vm block DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- Edwin 3/22/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetClipboardNameArray proc near TRANS_PARAMS class VisTextClass uses ax, dx, bx, bp .enter inherit near mov bx, transferHeader mov si, VM_ELEMENT_ARRAY_CHUNK call MemDerefDS mov ax, ds:TTBH_names.high ;ax = vm handle of name array ; of the clipboard mov bx, xferFile ;bx = vm file of the clipboard call VMLock ;ax = segment of VM block mov ds, ax mov cx, bp .leave ret GetClipboardNameArray endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% CheckDestFileName %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Checks to see if the file name of the destination already exists in the name array of the clipboard CALLED BY: TypeRunCopyNames PASS: ds:di = name array element bxax = optr of textobj cx = length of the name associated w/ the name array element RETURN: ax = -1 if the file name of current GeoWrite exists in the name array of the clipboard ax = 0 otherwise DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: (note for TypeRunCopyNames: If the file name of the destination already exists in the name array of the clipboard, TypeRunCopyNames will not add the name element to the destination file. TypeRunCopyNames will change the name token that associates with the file name to the *same file* token (-1) in the type elements before adding them to the destination name array. REVISION HISTORY: Name Date Description ---- ---- ----------- Edwin 3/22/94 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ CheckDestFileName proc near buffer local FileLongName nameAddr local fptr.char nameLen local word class VisTextClass uses bx,cx,dx,si,di,bp,ds,es .enter mov nameAddr.high, ds add di, (size VisTextNameData) mov nameAddr.low, di ; *nameAddr = string mov nameLen, cx ; nameLen = length of string mov {word}buffer, 0 ; put an emptry string in buffer push bp pushdw bxax mov cx, ss lea dx, buffer mov ax, MSG_GEN_DOCUMENT_GET_FILE_NAME mov bx, segment GenDocumentClass mov si, offset GenDocumentClass mov di, mask MF_RECORD call ObjMessage popdw bxsi ; ^lbx:si <- text object call MemDerefDS mov ax, MSG_VIS_VUP_CALL_OBJECT_OF_CLASS mov cx, di call ObjCallInstanceNoLock ; now buffer contains file name pop bp ; of the current GeoWrite file segmov es, ss, ax lea di, buffer ; es:di <- file name call LocalStringLength ; cx = # chars, not counting null mov ax, 0 ; assume names are not the same cmp cx, nameLen jne exit ; exit if file names are not equal segmov ds, ss, ax mov si, di ; ds:si = file name of GeoWrite doc les di, nameAddr ; es:di = file name from name array call LocalCmpStrings jnz exit mov ax, -1 ; token of the current file exit: .leave ret CheckDestFileName endp ;--- TTStoreXferRun proc near TRANS_PARAMS .enter inherit near movdw xferRunPtr, dssi mov xferRunCount, cx mov xferRunToken, di .leave ret TTStoreXferRun endp TTStoreObjRun proc near uses bx TRANS_PARAMS .enter inherit near call RunArrayUnref mov objRunDataBX, bx mov objRunDataSI, si mov objRunDataDI, di mov objRunCount, cx .leave ret TTStoreObjRun endp TTLoadXferRun proc near uses bx TRANS_PARAMS .enter inherit near movdw dssi, xferRunPtr mov di, xferRunToken mov cx, xferRunCount .leave ret TTLoadXferRun endp TTLoadObjRun proc near uses bx TRANS_PARAMS .enter inherit near mov bx, objRunDataBX mov si, objRunDataSI mov di, objRunDataDI call RunArrayReref mov cx, objRunCount .leave ret TTLoadObjRun endp TTLoadObject proc near uses bx TRANS_PARAMS .enter inherit near movdw bxsi, textobject call MemDerefDS .leave ret TTLoadObject endp TextTransfer ends
#ifndef NDNPH_TLV_VALUE_HPP #define NDNPH_TLV_VALUE_HPP #include "decoder.hpp" #include "encoder.hpp" namespace ndnph { namespace tlv { /** @brief A sequence of bytes, usually TLV-VALUE. */ class Value { public: static Value fromString(const char* str) { return Value(reinterpret_cast<const uint8_t*>(str), std::strlen(str)); } explicit Value() = default; /** @brief Reference a byte range. */ explicit Value(const uint8_t* value, size_t size) : m_value(value) , m_size(size) {} /** @brief Reference a byte range. */ explicit Value(const uint8_t* first, const uint8_t* last) : m_value(first) , m_size(last - first) {} /** @brief Reference encoder output. */ explicit Value(const Encoder& encoder) : Value(encoder.begin(), encoder.size()) {} /** @brief Return true if value is non-empty. */ explicit operator bool() const { return size() > 0; } const uint8_t* begin() const { return m_value; } const uint8_t* end() const { return m_value + m_size; } size_t size() const { return m_size; } void encodeTo(Encoder& encoder) const { uint8_t* room = encoder.prependRoom(m_size); if (room != nullptr) { std::copy_n(m_value, m_size, room); } } bool decodeFrom(const Decoder::Tlv& d) { m_value = d.value; m_size = d.length; return true; } /** @brief Create a Decoder over this value buffer. */ Decoder makeDecoder() const { return Decoder(m_value, m_size); } /** * @brief Clone buffer into given region. * @return new Value that does not reference memory of this Value, * or empty Value if allocation fails. */ Value clone(Region& region) const { uint8_t* copyV = region.alloc(m_size); if (copyV == nullptr) { return Value(); } std::copy(begin(), end(), copyV); return Value(copyV, m_size); } private: const uint8_t* m_value = nullptr; size_t m_size = 0; }; inline bool operator==(const Value& lhs, const Value& rhs) { return lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin()); } NDNPH_DECLARE_NE(Value, inline) } // namespace tlv } // namespace ndnph #endif // NDNPH_TLV_VALUE_HPP
/*Given an integer A, how many structurally unique BST’s (binary search trees) exist that can store values */ // Catalan Number uses. /* 1. Count the number of expressions containing n pairs of parentheses which are correctly matched. For n = 3, possible expressions are ((())), ()(()), ()()(), (())(), (()()). 2. Count the number of possible Binary Search Trees with n keys (See this) 3. Count the number of full binary trees (A rooted binary tree is full if every vertex has either two children or no children) with n+1 leaves. 4. Given a number n, return the number of ways you can draw n chords in a circle with 2 x n points such that no 2 chords intersect. */ int Solution::numTrees(int A) { int n=A; vector<int>dp(n+1,0); dp[0]=1; dp[1]=1; for(int i=2;i<=A;i++) { for(int j=0;j<i;j++) { dp[i]+=dp[j]*dp[i-j-1]; } } return dp[n]; }
;***************************************************************** ;* - Description: Device definition file for RC Calibration ;* - File: m323.asm ;* - AppNote: AVR053 - Production calibration of the ;* RC oscillator ;* ;* - Author: Atmel Corporation: http://www.atmel.com ;* Support email: avr@atmel.com ;* ;* $Name$ ;* $Revision: 56 $ ;* $RCSfile$ ;* $Date: 2006-02-16 17:44:45 +0100 (to, 16 feb 2006) $ ;***************************************************************** .include "m323def.inc" .include "Common\memoryMap.inc" .include "Device specific\m16_family_pinout.inc" .equ OSC_VER = 2
/* Copyright 2018 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_serving/util/net_http/compression/gzip_zlib.h" #include <algorithm> #include <random> #include <string> #include <vector> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" namespace tensorflow { namespace serving { namespace net_http { namespace { std::random_device rd; typedef std::mt19937_64 RandomEngine; int GetUniformRand(RandomEngine* rng, int max) { std::uniform_int_distribution<int> uniform(0, max); return uniform(*rng); } // Take some test headers and pass them to a GZipHeader, fragmenting // the headers in many different random ways. TEST(GzipHeader, FragmentTest) { RandomEngine rng(rd()); struct TestCase { const char* str; int len; // total length of the string int cruft_len; // length of the gzip header part }; TestCase tests[] = { // Basic header: {"\037\213\010\000\216\176\356\075\002\003", 10, 0}, // Basic headers with crud on the end: {"\037\213\010\000\216\176\356\075\002\003X", 11, 1}, {"\037\213\010\000\216\176\356\075\002\003XXX", 13, 3}, { "\037\213\010\010\321\135\265\100\000\003" "emacs\000", 16, 0 // with an FNAME of "emacs" }, { "\037\213\010\010\321\135\265\100\000\003" "\000", 11, 0 // with an FNAME of zero bytes }, { "\037\213\010\020\321\135\265\100\000\003" "emacs\000", 16, 0, // with an FCOMMENT of "emacs" }, { "\037\213\010\020\321\135\265\100\000\003" "\000", 11, 0, // with an FCOMMENT of zero bytes }, { "\037\213\010\002\321\135\265\100\000\003" "\001\002", 12, 0 // with an FHCRC }, { "\037\213\010\004\321\135\265\100\000\003" "\003\000foo", 15, 0 // with an extra of "foo" }, { "\037\213\010\004\321\135\265\100\000\003" "\000\000", 12, 0 // with an extra of zero bytes }, { "\037\213\010\032\321\135\265\100\000\003" "emacs\000" "emacs\000" "\001\002", 24, 0 // with an FNAME of "emacs", FCOMMENT of "emacs", and FHCRC }, { "\037\213\010\036\321\135\265\100\000\003" "\003\000foo" "emacs\000" "emacs\000" "\001\002", 29, 0 // with an FNAME of "emacs", FCOMMENT of "emacs", FHCRC, "foo" }, { "\037\213\010\036\321\135\265\100\000\003" "\003\000foo" "emacs\000" "emacs\000" "\001\002" "XXX", 32, 3 // FNAME of "emacs", FCOMMENT of "emacs", FHCRC, "foo", crud }, }; // Test all the headers test cases. for (auto test : tests) { // Test many random ways they might be fragmented. for (int j = 0; j < 1000; ++j) { // Get the test case set up. const char* p = test.str; int bytes_left = test.len; int bytes_read = 0; // Pick some random places to fragment the headers. const int num_fragments = GetUniformRand(&rng, bytes_left); std::vector<int> fragment_starts; for (int frag_num = 0; frag_num < num_fragments; ++frag_num) { fragment_starts.push_back(GetUniformRand(&rng, bytes_left)); } sort(fragment_starts.begin(), fragment_starts.end()); GZipHeader gzip_headers; // Go through several fragments and pass them to the headers for parsing. int frag_num = 0; while (bytes_left > 0) { const int fragment_len = (frag_num < num_fragments) ? (fragment_starts[frag_num] - bytes_read) : (test.len - bytes_read); EXPECT_GE(fragment_len, 0); const char* header_end = nullptr; GZipHeader::Status status = gzip_headers.ReadMore(p, fragment_len, &header_end); bytes_read += fragment_len; bytes_left -= fragment_len; EXPECT_GE(bytes_left, 0); p += fragment_len; frag_num++; if (bytes_left <= test.cruft_len) { EXPECT_EQ(status, GZipHeader::COMPLETE_HEADER); break; } else { EXPECT_EQ(status, GZipHeader::INCOMPLETE_HEADER); } } // while } // for many fragmentations } // for all test case headers } // 1048576 == 2^20 == 1 MB #define MAX_BUF_SIZE 1048500 #define MAX_BUF_FLEX 1048576 void TestCompression(ZLib* zlib, const std::string& uncompbuf, const char* msg) { uLongf complen = ZLib::MinCompressbufSize(uncompbuf.size()); std::string compbuf(complen, '\0'); int err = zlib->Compress((Bytef*)compbuf.data(), &complen, (Bytef*)uncompbuf.data(), uncompbuf.size()); EXPECT_EQ(Z_OK, err) << " " << uncompbuf.size() << " bytes down to " << complen << " bytes."; // Output data size should match input data size. uLongf uncomplen2 = uncompbuf.size(); std::string uncompbuf2(uncomplen2, '\0'); err = zlib->Uncompress((Bytef*)&uncompbuf2[0], &uncomplen2, (Bytef*)compbuf.data(), complen); EXPECT_EQ(Z_OK, err); if (msg != nullptr) { printf("Orig: %7lu Compressed: %7lu %5.3f %s\n", uncomplen2, complen, (float)complen / uncomplen2, msg); } EXPECT_EQ(uncompbuf, absl::string_view(uncompbuf2.data(), uncomplen2)) << "Uncompression mismatch!"; } // Take some test inputs and pass them to zlib, fragmenting the input randomly. void TestRandomGzipHeaderUncompress(ZLib* zlib) { RandomEngine rng(rd()); struct TestCase { const char* str; int len; // total length of the string }; TestCase tests[] = { { // header, body ("hello, world!\n"), footer "\037\213\010\000\216\176\356\075\002\003" "\313\110\315\311\311\327\121\050\317\057\312\111\121\344\002\000" "\300\337\061\266\016\000\000\000", 34, }, }; std::string uncompbuf2(MAX_BUF_FLEX, '\0'); // Test all the headers test cases. for (uint32_t i = 0; i < ABSL_ARRAYSIZE(tests); ++i) { // Test many random ways they might be fragmented. for (int j = 0; j < 5 * 1000; ++j) { // Get the test case set up. const char* p = tests[i].str; int bytes_left = tests[i].len; int bytes_read = 0; int bytes_uncompressed = 0; zlib->Reset(); // Pick some random places to fragment the headers. const int num_fragments = GetUniformRand(&rng, bytes_left); std::vector<int> fragment_starts; for (int frag_num = 0; frag_num < num_fragments; ++frag_num) { fragment_starts.push_back(GetUniformRand(&rng, bytes_left)); } sort(fragment_starts.begin(), fragment_starts.end()); // Go through several fragments and pass them in for parsing. int frag_num = 0; while (bytes_left > 0) { const int fragment_len = (frag_num < num_fragments) ? (fragment_starts[frag_num] - bytes_read) : (tests[i].len - bytes_read); ASSERT_GE(fragment_len, 0); if (fragment_len != 0) { // zlib doesn't like 0-length buffers uLongf uncomplen2 = uncompbuf2.size() - bytes_uncompressed; auto complen_src = static_cast<uLongf>(fragment_len); int err = zlib->UncompressAtMost( (Bytef*)&uncompbuf2[0] + bytes_uncompressed, &uncomplen2, (const Bytef*)p, &complen_src); ASSERT_EQ(err, Z_OK); bytes_uncompressed += uncomplen2; bytes_read += fragment_len; bytes_left -= fragment_len; ASSERT_GE(bytes_left, 0); p += fragment_len; } frag_num++; } // while bytes left to uncompress ASSERT_TRUE(zlib->UncompressChunkDone()); EXPECT_EQ(sizeof("hello, world!\n") - 1, bytes_uncompressed); EXPECT_EQ( 0, strncmp(uncompbuf2.data(), "hello, world!\n", bytes_uncompressed)) << "Uncompression mismatch, expected 'hello, world!\\n', " << "got '" << absl::string_view(uncompbuf2.data(), bytes_uncompressed) << "'"; } // for many fragmentations } // for all test case headers } constexpr int32_t kMaxSizeUncompressedData = 10 * 1024 * 1024; // 10MB void TestErrors(ZLib* zlib, const std::string& uncompbuf_str) { const char* uncompbuf = uncompbuf_str.data(); const uLongf uncomplen = uncompbuf_str.size(); std::string compbuf(MAX_BUF_SIZE, '\0'); std::string uncompbuf2(MAX_BUF_FLEX, '\0'); int err; uLongf complen = 23; // don't give it enough space to compress err = zlib->Compress((Bytef*)compbuf.data(), &complen, (Bytef*)uncompbuf, uncomplen); EXPECT_EQ(Z_BUF_ERROR, err); // OK, now successfully compress complen = compbuf.size(); err = zlib->Compress((Bytef*)compbuf.data(), &complen, (Bytef*)uncompbuf, uncomplen); EXPECT_EQ(Z_OK, err) << " " << uncomplen << " bytes down to " << complen << " bytes."; uLongf uncomplen2 = 10; // not enough space to uncompress err = zlib->Uncompress((Bytef*)&uncompbuf2[0], &uncomplen2, (Bytef*)compbuf.data(), complen); EXPECT_EQ(Z_BUF_ERROR, err); // Here we check what happens when we don't try to uncompress enough bytes uncomplen2 = uncompbuf2.size(); err = zlib->Uncompress((Bytef*)&uncompbuf2[0], &uncomplen2, (Bytef*)compbuf.data(), 23); EXPECT_EQ(Z_BUF_ERROR, err); uncomplen2 = uncompbuf2.size(); uLongf comlen2 = 23; err = zlib->UncompressAtMost((Bytef*)&uncompbuf2[0], &uncomplen2, (Bytef*)compbuf.data(), &comlen2); EXPECT_EQ(Z_OK, err); // it's ok if a single chunk is too small if (err == Z_OK) { EXPECT_FALSE(zlib->UncompressChunkDone()) << "UncompresDone() was happy with its 3 bytes of compressed data"; } const int changepos = 0; const char oldval = compbuf[changepos]; // corrupt the input compbuf[changepos]++; uncomplen2 = uncompbuf2.size(); err = zlib->Uncompress((Bytef*)&uncompbuf2[0], &uncomplen2, (Bytef*)compbuf.data(), complen); EXPECT_NE(Z_OK, err); compbuf[changepos] = oldval; // Make sure our memory-allocating uncompressor deals with problems gracefully char* tmpbuf; char tmp_compbuf[10] = "\255\255\255\255\255\255\255\255\255"; uncomplen2 = kMaxSizeUncompressedData; err = zlib->UncompressGzipAndAllocate( (Bytef**)&tmpbuf, &uncomplen2, (Bytef*)tmp_compbuf, sizeof(tmp_compbuf)); EXPECT_NE(Z_OK, err); EXPECT_EQ(nullptr, tmpbuf); } void TestBogusGunzipRequest(ZLib* zlib) { const Bytef compbuf[] = "This is not compressed"; const uLongf complen = sizeof(compbuf); Bytef* uncompbuf; uLongf uncomplen = 0; int err = zlib->UncompressGzipAndAllocate(&uncompbuf, &uncomplen, compbuf, complen); EXPECT_EQ(Z_DATA_ERROR, err); } void TestGzip(ZLib* zlib, const std::string& uncompbuf_str) { const char* uncompbuf = uncompbuf_str.data(); const uLongf uncomplen = uncompbuf_str.size(); std::string compbuf(MAX_BUF_SIZE, '\0'); std::string uncompbuf2(MAX_BUF_FLEX, '\0'); uLongf complen = compbuf.size(); int err = zlib->Compress((Bytef*)compbuf.data(), &complen, (Bytef*)uncompbuf, uncomplen); EXPECT_EQ(Z_OK, err) << " " << uncomplen << " bytes down to " << complen << " bytes."; uLongf uncomplen2 = uncompbuf2.size(); err = zlib->Uncompress((Bytef*)&uncompbuf2[0], &uncomplen2, (Bytef*)compbuf.data(), complen); EXPECT_EQ(Z_OK, err); EXPECT_EQ(uncomplen, uncomplen2) << "Uncompression mismatch!"; EXPECT_EQ(0, memcmp(uncompbuf, uncompbuf2.data(), uncomplen)) << "Uncompression mismatch!"; // Also try the auto-allocate uncompressor char* tmpbuf; err = zlib->UncompressGzipAndAllocate((Bytef**)&tmpbuf, &uncomplen2, (Bytef*)compbuf.data(), complen); EXPECT_EQ(Z_OK, err); EXPECT_EQ(uncomplen, uncomplen2) << "Uncompression mismatch!"; EXPECT_EQ(0, memcmp(uncompbuf, uncompbuf2.data(), uncomplen)) << "Uncompression mismatch!"; if (tmpbuf) { std::allocator<char>().deallocate(tmpbuf, uncomplen2); } } void TestChunkedGzip(ZLib* zlib, const std::string& uncompbuf_str, int num_chunks) { const char* uncompbuf = uncompbuf_str.data(); const uLongf uncomplen = uncompbuf_str.size(); std::string compbuf(MAX_BUF_SIZE, '\0'); std::string uncompbuf2(MAX_BUF_FLEX, '\0'); EXPECT_GT(num_chunks, 2); // uncompbuf2 is larger than uncompbuf to test for decoding too much // // Note that it is possible to receive num_chunks+1 total // chunks, due to rounding error. const int chunklen = uncomplen / num_chunks; int chunknum, i, err; int cum_len[100]; // cumulative compressed length, max to 100 cum_len[0] = 0; for (chunknum = 0, i = 0; i < uncomplen; i += chunklen, chunknum++) { uLongf complen = compbuf.size() - cum_len[chunknum]; // Make sure the last chunk gets the correct chunksize. uLongf chunksize = (uncomplen - i) < chunklen ? (uncomplen - i) : chunklen; err = zlib->CompressAtMost((Bytef*)compbuf.data() + cum_len[chunknum], &complen, (Bytef*)uncompbuf + i, &chunksize); ASSERT_EQ(Z_OK, err) << " " << uncomplen << " bytes down to " << complen << " bytes."; cum_len[chunknum + 1] = cum_len[chunknum] + complen; } uLongf complen = compbuf.size() - cum_len[chunknum]; err = zlib->CompressChunkDone((Bytef*)compbuf.data() + cum_len[chunknum], &complen); EXPECT_EQ(Z_OK, err); cum_len[chunknum + 1] = cum_len[chunknum] + complen; for (chunknum = 0, i = 0; i < uncomplen; i += chunklen, chunknum++) { uLongf uncomplen2 = uncomplen - i; // Make sure the last chunk gets the correct chunksize. int expected = uncomplen2 < chunklen ? uncomplen2 : chunklen; uLongf complen_src = cum_len[chunknum + 1] - cum_len[chunknum]; err = zlib->UncompressAtMost((Bytef*)&uncompbuf2[0] + i, &uncomplen2, (Bytef*)compbuf.data() + cum_len[chunknum], &complen_src); EXPECT_EQ(Z_OK, err); EXPECT_EQ(expected, uncomplen2) << "Uncompress size is " << uncomplen2 << ", not " << expected; } // There should be no further uncompressed bytes, after uncomplen bytes. uLongf uncomplen2 = uncompbuf2.size() - uncomplen; EXPECT_NE(0, uncomplen2); uLongf complen_src = cum_len[chunknum + 1] - cum_len[chunknum]; err = zlib->UncompressAtMost((Bytef*)&uncompbuf2[0] + uncomplen, &uncomplen2, (Bytef*)compbuf.data() + cum_len[chunknum], &complen_src); EXPECT_EQ(Z_OK, err); EXPECT_EQ(0, uncomplen2); EXPECT_TRUE(zlib->UncompressChunkDone()); // Those uncomplen bytes should match. EXPECT_EQ(0, memcmp(uncompbuf, uncompbuf2.data(), uncomplen)) << "Uncompression mismatch!"; // Now test to make sure resetting works properly // (1) First, uncompress the first chunk and make sure it's ok uncomplen2 = uncompbuf2.size(); complen_src = cum_len[1]; err = zlib->UncompressAtMost((Bytef*)&uncompbuf2[0], &uncomplen2, (Bytef*)compbuf.data(), &complen_src); EXPECT_EQ(Z_OK, err); EXPECT_EQ(chunklen, uncomplen2) << "Uncompression mismatch!"; // The first uncomplen2 bytes should match, where uncomplen2 is the number of // successfully uncompressed bytes by the most recent UncompressChunk call. // The remaining (uncomplen - uncomplen2) bytes would still match if the // uncompression guaranteed not to modify the buffer other than those first // uncomplen2 bytes, but there is no such guarantee. EXPECT_EQ(0, memcmp(uncompbuf, uncompbuf2.data(), uncomplen2)) << "Uncompression mismatch!"; // (2) Now, try the first chunk again and see that there's an error uncomplen2 = uncompbuf2.size(); complen_src = cum_len[1]; err = zlib->UncompressAtMost((Bytef*)&uncompbuf2[0], &uncomplen2, (Bytef*)compbuf.data(), &complen_src); EXPECT_EQ(Z_DATA_ERROR, err); // (3) Now reset it and try again, and see that it's ok zlib->Reset(); uncomplen2 = uncompbuf2.size(); complen_src = cum_len[1]; err = zlib->UncompressAtMost((Bytef*)&uncompbuf2[0], &uncomplen2, (Bytef*)compbuf.data(), &complen_src); EXPECT_EQ(Z_OK, err); EXPECT_EQ(chunklen, uncomplen2) << "Uncompression mismatch!"; EXPECT_EQ(0, memcmp(uncompbuf, uncompbuf2.data(), uncomplen2)) << "Uncompression mismatch!"; // (4) Make sure we can tackle output buffers that are too small // with the *AtMost() interfaces. uLong source_len = cum_len[2] - cum_len[1]; EXPECT_GT(source_len, 1); // uncomplen2 = source_len/2; uncomplen2 = 2; // fixed as we use fixed strings now err = zlib->UncompressAtMost((Bytef*)&uncompbuf2[0], &uncomplen2, (Bytef*)(compbuf.data() + cum_len[1]), &source_len); EXPECT_EQ(Z_BUF_ERROR, err); EXPECT_EQ(0, memcmp(uncompbuf + chunklen, uncompbuf2.data(), uncomplen2)) << "Uncompression mismatch!"; const int saveuncomplen2 = uncomplen2; uncomplen2 = uncompbuf2.size() - uncomplen2; // Uncompress the rest of the chunk. err = zlib->UncompressAtMost( (Bytef*)&uncompbuf2[0], &uncomplen2, (Bytef*)(compbuf.data() + cum_len[2] - source_len), &source_len); EXPECT_EQ(Z_OK, err); EXPECT_EQ(0, memcmp(uncompbuf + chunklen + saveuncomplen2, uncompbuf2.data(), uncomplen2)) << "Uncompression mismatch!"; // (5) Finally, reset again zlib->Reset(); } void TestFooterBufferTooSmall(ZLib* zlib) { uLongf footer_len = zlib->MinFooterSize() - 1; ASSERT_EQ(9, footer_len); Bytef footer_buffer[9]; int err = zlib->CompressChunkDone(footer_buffer, &footer_len); ASSERT_EQ(Z_BUF_ERROR, err); ASSERT_EQ(0, footer_len); } TEST(ZLibTest, HugeCompression) { // Just big enough to trigger 32 bit overflow in MinCompressbufSize() // calculation. const uLong HUGE_DATA_SIZE = 0x81000000; // Construct an easily compressible huge buffer. std::string uncompbuf(HUGE_DATA_SIZE, 'A'); ZLib zlib; zlib.SetCompressionLevel(1); // as fast as possible TestCompression(&zlib, uncompbuf, nullptr); } // TODO(wenboz): random size randm data const char kText[] = "1234567890abcdefghijklmnopqrstuvwxyz"; TEST(ZLibTest, Compression) { const std::string uncompbuf = kText; ZLib zlib; zlib.SetCompressionLevel(6); TestCompression(&zlib, uncompbuf, "fixed size"); } TEST(ZLibTest, OtherErrors) { const std::string uncompbuf = kText; ZLib zlib; TestErrors(&zlib, uncompbuf); TestBogusGunzipRequest(&zlib); } TEST(ZLibTest, UncompressChunkedHeaders) { // TestGzipHeaderUncompress(&zlib); ZLib zlib; TestRandomGzipHeaderUncompress(&zlib); } TEST(ZLibTest, GzipCompression) { const std::string uncompbuf = kText; ZLib zlib; TestGzip(&zlib, uncompbuf); // Try compressing again using the same ZLib TestGzip(&zlib, uncompbuf); } TEST(ZLibTest, ChunkedCompression) { const std::string uncompbuf = kText; ZLib zlib; TestChunkedGzip(&zlib, uncompbuf, 5); // Try compressing again using the same ZLib TestChunkedGzip(&zlib, uncompbuf, 6); // In theory we can mix and match the type of compression we do TestGzip(&zlib, uncompbuf); TestChunkedGzip(&zlib, uncompbuf, 8); // Test writing final chunk and footer into buffer that's too small. TestFooterBufferTooSmall(&zlib); TestGzip(&zlib, uncompbuf); } TEST(ZLibTest, BytewiseRead) { std::string text = "v nedrah tundry vydra v getrah tyrit v vedrah yadra kedra"; size_t text_len = text.size(); size_t archive_len = ZLib::MinCompressbufSize(text_len); std::string archive(archive_len, '\0'); size_t decompressed_len = text_len + 1; std::string decompressed(decompressed_len, '\0'); size_t decompressed_offset = 0; ZLib compressor; int rc = compressor.Compress((Bytef*)archive.data(), &archive_len, (Bytef*)text.data(), text_len); ASSERT_EQ(rc, Z_OK); ZLib zlib; for (size_t i = 0; i < archive_len; ++i) { size_t source_len = 1; size_t dest_len = decompressed_len - decompressed_offset; rc = zlib.UncompressAtMost( (Bytef*)decompressed.data() + decompressed_offset, &dest_len, (Bytef*)archive.data() + i, &source_len); ASSERT_EQ(rc, Z_OK); ASSERT_EQ(source_len, 0); decompressed_offset += dest_len; } ASSERT_TRUE(zlib.IsGzipFooterValid()); ASSERT_EQ(decompressed_offset, text_len); std::string truncated_output(decompressed.data(), text_len); ASSERT_EQ(truncated_output, text); } TEST(ZLibTest, TruncatedData) { const int kBufferLen = 64; std::string uncompressed = "Hello, World!"; std::string compressed( "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\xf3\x48\xcd\xc9\xc9" "\xd7\x51\x08\xcf\x2f\xca\x49\x51\x04\x00\xd0\xc3\x4a\xec\x0d" "\x00\x00\x00", 33); // Verify that "compressed" contains valid gzip data. { ZLib zlib; // zlib.SetGzipHeaderMode(); char uncompbuf[kBufferLen]; bzero(uncompbuf, kBufferLen); uLongf uncomplen = kBufferLen; int err = zlib.Uncompress( reinterpret_cast<Bytef*>(uncompbuf), &uncomplen, reinterpret_cast<const Bytef*>(compressed.c_str()), compressed.size()); ASSERT_EQ(err, Z_OK); ASSERT_EQ(uncompressed, absl::string_view(uncompbuf, uncomplen)); } // Test truncated data with ZLib::Uncompress(). for (int len = compressed.size() - 1; len > 0; len--) { SCOPED_TRACE(absl::StrCat("Decompressing first ", len, " out of ", compressed.size(), " bytes")); ZLib zlib; // zlib.SetGzipHeaderMode(); char uncompbuf[kBufferLen]; bzero(uncompbuf, kBufferLen); uLongf uncomplen = kBufferLen; int err = zlib.Uncompress( reinterpret_cast<Bytef*>(uncompbuf), &uncomplen, reinterpret_cast<const Bytef*>(compressed.c_str()), len); ASSERT_NE(err, Z_OK); } // Test truncated data with ZLib::UncompressAtMost() and // ZLib::UncompressDone(). for (int len = compressed.size() - 1; len > 0; len--) { SCOPED_TRACE(absl::StrCat("Decompressing first ", len, " out of ", compressed.size(), " bytes")); ZLib zlib; // zlib.SetGzipHeaderMode(); char uncompbuf[kBufferLen]; bzero(uncompbuf, kBufferLen); uLongf uncomplen = kBufferLen; uLongf complen = len; int err = zlib.UncompressAtMost( reinterpret_cast<Bytef*>(uncompbuf), &uncomplen, reinterpret_cast<const Bytef*>(compressed.c_str()), &complen); ASSERT_EQ(err, Z_OK); ASSERT_EQ(complen, 0); if (uncomplen > 0) { EXPECT_THAT( uncompressed, testing::StartsWith(std::string(uncompbuf).substr(0, uncomplen))); } ASSERT_FALSE(zlib.UncompressChunkDone()); } } TEST(ZLibTest, GzipUncompressedLength) { ZLib zlib; // "Hello, World!", compressed. std::string hello_world( "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\xf3\x48\xcd\xc9\xc9" "\xd7\x51\x08\xcf\x2f\xca\x49\x51\x04\x00\xd0\xc3\x4a\xec\x0d" "\x00\x00\x00", 33); EXPECT_EQ(13, zlib.GzipUncompressedLength( reinterpret_cast<const Bytef*>(hello_world.c_str()), hello_world.size())); // Empty string, "", compressed. std::string empty( "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03\x03\x00\x00\x00\x00" "\x00\x00\x00\x00\x00", 20); EXPECT_EQ(0, zlib.GzipUncompressedLength( reinterpret_cast<const Bytef*>(empty.c_str()), empty.size())); std::string bad_data("\x01\x01\x01\x01", 4); for (int len = 0; len <= bad_data.size(); len++) { EXPECT_EQ(0, zlib.GzipUncompressedLength( reinterpret_cast<const Bytef*>(bad_data.c_str()), len)); } } } // namespace } // namespace net_http } // namespace serving } // namespace tensorflow
/* * Copyright 2010 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "tests/Test.h" #ifdef SK_SUPPORT_PDF #include "include/core/SkData.h" #include "include/core/SkStream.h" #include "include/private/SkTo.h" #include "src/pdf/SkPDFMakeToUnicodeCmap.h" static constexpr SkGlyphID kMaximumGlyphIndex = UINT16_MAX; static bool stream_equals(const SkDynamicMemoryWStream& stream, size_t offset, const char* buffer, size_t len) { if (len != strlen(buffer)) { return false; } const size_t streamSize = stream.bytesWritten(); if (offset + len > streamSize) { return false; } SkAutoTMalloc<char> data(streamSize); stream.copyTo(data.get()); return memcmp(data.get() + offset, buffer, len) == 0; } DEF_TEST(SkPDF_ToUnicode, reporter) { SkTDArray<SkUnichar> glyphToUnicode; SkTDArray<uint16_t> glyphsInSubset; SkPDFGlyphUse subset(1, kMaximumGlyphIndex); glyphToUnicode.push_back(0); // 0 glyphToUnicode.push_back(0); // 1 glyphToUnicode.push_back(0); // 2 glyphsInSubset.push_back(3); glyphToUnicode.push_back(0x20); // 3 glyphsInSubset.push_back(4); glyphToUnicode.push_back(0x25); // 4 glyphsInSubset.push_back(5); glyphToUnicode.push_back(0x27); // 5 glyphsInSubset.push_back(6); glyphToUnicode.push_back(0x28); // 6 glyphsInSubset.push_back(7); glyphToUnicode.push_back(0x29); // 7 glyphsInSubset.push_back(8); glyphToUnicode.push_back(0x2F); // 8 glyphsInSubset.push_back(9); glyphToUnicode.push_back(0x33); // 9 glyphToUnicode.push_back(0); // 10 glyphsInSubset.push_back(11); glyphToUnicode.push_back(0x35); // 11 glyphsInSubset.push_back(12); glyphToUnicode.push_back(0x36); // 12 glyphsInSubset.push_back(13); glyphToUnicode.push_back(0x37); // 13 for (uint16_t i = 14; i < 0xFE; ++i) { glyphToUnicode.push_back(0); // Zero from index 0x9 to 0xFD } glyphsInSubset.push_back(0xFE); glyphToUnicode.push_back(0x1010); glyphsInSubset.push_back(0xFF); glyphToUnicode.push_back(0x1011); glyphsInSubset.push_back(0x100); glyphToUnicode.push_back(0x1012); glyphsInSubset.push_back(0x101); glyphToUnicode.push_back(0x1013); SkGlyphID lastGlyphID = SkToU16(glyphToUnicode.count() - 1); SkDynamicMemoryWStream buffer; for (uint16_t v : glyphsInSubset) { subset.set(v); } SkPDFAppendCmapSections(&glyphToUnicode[0], &subset, &buffer, true, 0, std::min<SkGlyphID>(0xFFFF, lastGlyphID)); char expectedResult[] = "4 beginbfchar\n\ <0003> <0020>\n\ <0004> <0025>\n\ <0008> <002F>\n\ <0009> <0033>\n\ endbfchar\n\ 4 beginbfrange\n\ <0005> <0007> <0027>\n\ <000B> <000D> <0035>\n\ <00FE> <00FF> <1010>\n\ <0100> <0101> <1012>\n\ endbfrange\n"; REPORTER_ASSERT(reporter, stream_equals(buffer, 0, expectedResult, buffer.bytesWritten())); // Remove characters and ranges. buffer.reset(); SkPDFAppendCmapSections(&glyphToUnicode[0], &subset, &buffer, true, 8, std::min<SkGlyphID>(0x00FF, lastGlyphID)); char expectedResultChop1[] = "2 beginbfchar\n\ <0008> <002F>\n\ <0009> <0033>\n\ endbfchar\n\ 2 beginbfrange\n\ <000B> <000D> <0035>\n\ <00FE> <00FF> <1010>\n\ endbfrange\n"; REPORTER_ASSERT(reporter, stream_equals(buffer, 0, expectedResultChop1, buffer.bytesWritten())); // Remove characters from range to downdrade it to one char. buffer.reset(); SkPDFAppendCmapSections(&glyphToUnicode[0], &subset, &buffer, true, 0x00D, std::min<SkGlyphID>(0x00FE, lastGlyphID)); char expectedResultChop2[] = "2 beginbfchar\n\ <000D> <0037>\n\ <00FE> <1010>\n\ endbfchar\n"; REPORTER_ASSERT(reporter, stream_equals(buffer, 0, expectedResultChop2, buffer.bytesWritten())); buffer.reset(); SkPDFAppendCmapSections(&glyphToUnicode[0], nullptr, &buffer, false, 0xFC, std::min<SkGlyphID>(0x110, lastGlyphID)); char expectedResultSingleBytes[] = "2 beginbfchar\n\ <01> <0000>\n\ <02> <0000>\n\ endbfchar\n\ 1 beginbfrange\n\ <03> <06> <1010>\n\ endbfrange\n"; REPORTER_ASSERT(reporter, stream_equals(buffer, 0, expectedResultSingleBytes, buffer.bytesWritten())); glyphToUnicode.reset(); glyphsInSubset.reset(); SkPDFGlyphUse subset2(1, kMaximumGlyphIndex); // Test mapping: // I n s t a l // Glyph id 2c 51 56 57 44 4f // Unicode 49 6e 73 74 61 6c for (SkUnichar i = 0; i < 100; ++i) { glyphToUnicode.push_back(i + 29); } lastGlyphID = SkToU16(glyphToUnicode.count() - 1); glyphsInSubset.push_back(0x2C); glyphsInSubset.push_back(0x44); glyphsInSubset.push_back(0x4F); glyphsInSubset.push_back(0x51); glyphsInSubset.push_back(0x56); glyphsInSubset.push_back(0x57); SkDynamicMemoryWStream buffer2; for (uint16_t v : glyphsInSubset) { subset2.set(v); } SkPDFAppendCmapSections(&glyphToUnicode[0], &subset2, &buffer2, true, 0, std::min<SkGlyphID>(0xFFFF, lastGlyphID)); char expectedResult2[] = "4 beginbfchar\n\ <002C> <0049>\n\ <0044> <0061>\n\ <004F> <006C>\n\ <0051> <006E>\n\ endbfchar\n\ 1 beginbfrange\n\ <0056> <0057> <0073>\n\ endbfrange\n"; REPORTER_ASSERT(reporter, stream_equals(buffer2, 0, expectedResult2, buffer2.bytesWritten())); } #endif
; char *fgets(char *s, int n, FILE *stream) SECTION code_stdio PUBLIC fgets_unlocked EXTERN asm_fgets_unlocked fgets_unlocked: pop af pop ix pop bc pop de push de push bc push hl push af jp asm_fgets_unlocked
; A036291: a(n) = n*5^n. ; 0,5,50,375,2500,15625,93750,546875,3125000,17578125,97656250,537109375,2929687500,15869140625,85449218750,457763671875,2441406250000,12969970703125,68664550781250,362396240234375,1907348632812500,10013580322265625,52452087402343750,274181365966796875,1430511474609375000,7450580596923828125,38743019104003906250,201165676116943359375,1043081283569335937500,5401670932769775390625,27939677238464355468750,144354999065399169921875,745058059692382812500000,3841705620288848876953125 mov $1,5 pow $1,$0 mul $1,$0 mov $0,$1
// Copyright (c) 2011 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 "base/bind.h" #include "base/files/scoped_temp_dir.h" #include "base/run_loop.h" #include "base/threading/sequenced_task_runner_handle.h" #include "content/browser/download/download_manager_impl.h" #include "content/browser/download/save_package.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/download_manager.h" #include "content/public/browser/web_contents.h" #include "content/public/test/content_browser_test.h" #include "content/public/test/content_browser_test_utils.h" #include "content/public/test/download_test_observer.h" #include "content/shell/browser/shell.h" #include "content/shell/browser/shell_download_manager_delegate.h" #include "net/test/embedded_test_server/embedded_test_server.h" namespace content { namespace { const char kTestFile[] = "/simple_page.html"; class TestShellDownloadManagerDelegate : public ShellDownloadManagerDelegate { public: explicit TestShellDownloadManagerDelegate(SavePageType save_page_type) : save_page_type_(save_page_type) {} void ChooseSavePath(WebContents* web_contents, const base::FilePath& suggested_path, const base::FilePath::StringType& default_extension, bool can_save_as_complete, SavePackagePathPickedCallback callback) override { std::move(callback).Run(suggested_path, save_page_type_, SavePackageDownloadCreatedCallback()); } void GetSaveDir(BrowserContext* context, base::FilePath* website_save_dir, base::FilePath* download_save_dir) override { *website_save_dir = download_dir_; *download_save_dir = download_dir_; } bool ShouldCompleteDownload(download::DownloadItem* download, base::OnceClosure closure) override { return true; } base::FilePath download_dir_; SavePageType save_page_type_; }; class DownloadicidalObserver : public DownloadManager::Observer { public: DownloadicidalObserver(bool remove_download, base::OnceClosure after_closure) : remove_download_(remove_download), after_closure_(std::move(after_closure)) {} void OnDownloadCreated(DownloadManager* manager, download::DownloadItem* item) override { base::SequencedTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce( [](bool remove_download, base::OnceClosure closure, download::DownloadItem* item) { remove_download ? item->Remove() : item->Cancel(true); std::move(closure).Run(); }, remove_download_, std::move(after_closure_), item)); } private: bool remove_download_; base::OnceClosure after_closure_; }; class DownloadCancelObserver : public DownloadManager::Observer { public: explicit DownloadCancelObserver(base::OnceClosure canceled_closure, std::string* mime_type_out) : canceled_closure_(std::move(canceled_closure)), mime_type_out_(mime_type_out) {} DownloadCancelObserver(const DownloadCancelObserver&) = delete; DownloadCancelObserver& operator=(const DownloadCancelObserver&) = delete; void OnDownloadCreated(DownloadManager* manager, download::DownloadItem* item) override { *mime_type_out_ = item->GetMimeType(); DCHECK(!item_cancel_observer_); item_cancel_observer_ = std::make_unique<DownloadItemCancelObserver>( item, std::move(canceled_closure_)); } private: class DownloadItemCancelObserver : public download::DownloadItem::Observer { public: DownloadItemCancelObserver(download::DownloadItem* item, base::OnceClosure canceled_closure) : item_(item), canceled_closure_(std::move(canceled_closure)) { item_->AddObserver(this); } DownloadItemCancelObserver(const DownloadItemCancelObserver&) = delete; DownloadItemCancelObserver& operator=(const DownloadItemCancelObserver&) = delete; ~DownloadItemCancelObserver() override { if (item_) item_->RemoveObserver(this); } private: void OnDownloadUpdated(download::DownloadItem* item) override { DCHECK_EQ(item_, item); if (item_->GetState() == download::DownloadItem::CANCELLED) std::move(canceled_closure_).Run(); } void OnDownloadDestroyed(download::DownloadItem* item) override { DCHECK_EQ(item_, item); item_->RemoveObserver(this); item_ = nullptr; } download::DownloadItem* item_; base::OnceClosure canceled_closure_; }; std::unique_ptr<DownloadItemCancelObserver> item_cancel_observer_; base::OnceClosure canceled_closure_; std::string* mime_type_out_; }; } // namespace class SavePackageBrowserTest : public ContentBrowserTest { protected: void SetUp() override { ASSERT_TRUE(save_dir_.CreateUniqueTempDir()); ContentBrowserTest::SetUp(); } // Returns full paths of destination file and directory. void GetDestinationPaths(const std::string& prefix, base::FilePath* full_file_name, base::FilePath* dir) { *full_file_name = save_dir_.GetPath().AppendASCII(prefix + ".htm"); *dir = save_dir_.GetPath().AppendASCII(prefix + "_files"); } // Start a SavePackage download and then cancels it. If |remove_download| is // true, the download item will be removed while page is being saved. // Otherwise, the download item will be canceled. void RunAndCancelSavePackageDownload(SavePageType save_page_type, bool remove_download) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url = embedded_test_server()->GetURL("/page_with_iframe.html"); EXPECT_TRUE(NavigateToURL(shell(), url)); auto* download_manager = static_cast<DownloadManagerImpl*>(BrowserContext::GetDownloadManager( shell()->web_contents()->GetBrowserContext())); auto delegate = std::make_unique<TestShellDownloadManagerDelegate>(save_page_type); delegate->download_dir_ = save_dir_.GetPath(); auto* old_delegate = download_manager->GetDelegate(); download_manager->SetDelegate(delegate.get()); { base::RunLoop run_loop; DownloadicidalObserver download_item_killer(remove_download, run_loop.QuitClosure()); download_manager->AddObserver(&download_item_killer); scoped_refptr<SavePackage> save_package( new SavePackage(shell()->web_contents())); save_package->GetSaveInfo(); run_loop.Run(); download_manager->RemoveObserver(&download_item_killer); EXPECT_TRUE(save_package->canceled()); } // Run a second download to completion so that any pending tasks will get // flushed out. If the previous SavePackage operation didn't cleanup after // itself, then there could be stray tasks that invoke the now defunct // download item. { base::RunLoop run_loop; SavePackageFinishedObserver finished_observer(download_manager, run_loop.QuitClosure()); shell()->web_contents()->OnSavePage(); run_loop.Run(); } download_manager->SetDelegate(old_delegate); } // Temporary directory we will save pages to. base::ScopedTempDir save_dir_; }; // Create a SavePackage and delete it without calling Init. // SavePackage dtor has various asserts/checks that should not fire. IN_PROC_BROWSER_TEST_F(SavePackageBrowserTest, ImplicitCancel) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url = embedded_test_server()->GetURL(kTestFile); EXPECT_TRUE(NavigateToURL(shell(), url)); base::FilePath full_file_name, dir; GetDestinationPaths("a", &full_file_name, &dir); scoped_refptr<SavePackage> save_package(new SavePackage( shell()->web_contents(), SAVE_PAGE_TYPE_AS_ONLY_HTML, full_file_name, dir)); } // Create a SavePackage, call Cancel, then delete it. // SavePackage dtor has various asserts/checks that should not fire. IN_PROC_BROWSER_TEST_F(SavePackageBrowserTest, ExplicitCancel) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url = embedded_test_server()->GetURL(kTestFile); EXPECT_TRUE(NavigateToURL(shell(), url)); base::FilePath full_file_name, dir; GetDestinationPaths("a", &full_file_name, &dir); scoped_refptr<SavePackage> save_package(new SavePackage( shell()->web_contents(), SAVE_PAGE_TYPE_AS_ONLY_HTML, full_file_name, dir)); save_package->Cancel(true); } IN_PROC_BROWSER_TEST_F(SavePackageBrowserTest, DownloadItemDestroyed) { RunAndCancelSavePackageDownload(SAVE_PAGE_TYPE_AS_COMPLETE_HTML, true); } IN_PROC_BROWSER_TEST_F(SavePackageBrowserTest, DownloadItemCanceled) { RunAndCancelSavePackageDownload(SAVE_PAGE_TYPE_AS_MHTML, false); } // Currently, SavePageAsWebBundle feature is not implemented yet. // WebContentsImpl::GenerateWebBundle() will call the passed callback with 0 // file size and WebBundlerError::kNotImplemented via WebBundler in the utility // process which means it cancels all SavePageAsWebBundle requests. So this test // checks that the request is successfully canceled. // TODO(crbug.com/1040752): Implement WebBundler and update this test. IN_PROC_BROWSER_TEST_F(SavePackageBrowserTest, SaveAsWebBundleCanceled) { ASSERT_TRUE(embedded_test_server()->Start()); GURL url = embedded_test_server()->GetURL("/page_with_iframe.html"); EXPECT_TRUE(NavigateToURL(shell(), url)); auto* download_manager = static_cast<DownloadManagerImpl*>(BrowserContext::GetDownloadManager( shell()->web_contents()->GetBrowserContext())); auto delegate = std::make_unique<TestShellDownloadManagerDelegate>( SAVE_PAGE_TYPE_AS_WEB_BUNDLE); delegate->download_dir_ = save_dir_.GetPath(); auto* old_delegate = download_manager->GetDelegate(); download_manager->SetDelegate(delegate.get()); { base::RunLoop run_loop; std::string mime_type; DownloadCancelObserver observer(run_loop.QuitClosure(), &mime_type); download_manager->AddObserver(&observer); scoped_refptr<SavePackage> save_package( new SavePackage(shell()->web_contents())); save_package->GetSaveInfo(); run_loop.Run(); download_manager->RemoveObserver(&observer); EXPECT_TRUE(save_package->canceled()); EXPECT_EQ("application/webbundle", mime_type); } download_manager->SetDelegate(old_delegate); } } // namespace content
/* BSD 3-Clause License Copyright (c) 2018, KORG 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: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the 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. //*/ /* * Morphs between several wave shapes: triangle, sine, square, sawtooth */ #include "userosc.h" const float PWM_MIN = 0.00f; const float PWM_MAX = 1.0f; // 0.95f; const float TROUGH = -1.0f; const float PEAK = 1.0f; const float AMPLITUDE = PEAK - TROUGH; float myremainder(float a, float b) { float d = a / b; d = floorf(d); return a - (d * b); } class MorphOsc { public: // Current frame counter float frame; float shape; float shiftshape; MorphOsc(void) { frame = 0; shape = 0; shiftshape = 0; } void note_on(void) { } void note_off(void) { } void set_param_shape(float value) { shape = value; } void set_param_shiftshape(float value) { shiftshape = value; } void set_param_id1(float value) { } void set_param_id2(float value) { } void set_param_id3(float value) { } void set_param_id4(float value) { } void set_param_id5(float value) { } void set_param_id6(float value) { } float y(float x, float lfo) { float lfo_weight = 1 - shiftshape; x += (lfo_weight * lfo); x = myremainder(x, 1.0); const int NUM_OSC = 3; float vals[NUM_OSC]; vals[0] = osc_sawf(x); vals[1] = osc_sqrf(x); vals[2] = osc_sinf(x); float tmp_shape = shape + shiftshape * lfo; tmp_shape = clip01f(tmp_shape); float weight = 0; int index_0 = 0; int index_1 = 1; const float NUM_SLICES = NUM_OSC - 1; const float SLICE = (1.0 / NUM_SLICES); if (tmp_shape <= SLICE) { index_0 = 0; index_1 = 1; weight = tmp_shape * NUM_SLICES; } else { index_0 = 1; index_1 = 2; weight = (tmp_shape - SLICE) * NUM_SLICES; } return ((1.0 - weight) * vals[index_0]) + (weight * vals[index_1]); } float cycle(float hz, float lfo) { float frames_per_cycle = float(k_samplerate) / hz; if (frames_per_cycle < 1) frames_per_cycle = 1; frame = myremainder(frame, frames_per_cycle); if (frame < 0) frame = 0; float x = frame / frames_per_cycle; float ret = y(x, lfo); frame++; return ret; } void NOTEON(const user_osc_param_t * const params) { note_on(); } void NOTEOFF(const user_osc_param_t * const params) { note_off(); } void CYCLE(const user_osc_param_t * const params, int32_t *yn, const uint32_t frames) { q31_t * __restrict y = (q31_t *)yn; uint8_t note = (params->pitch) >> 8; uint8_t mod = params->pitch & 0xFF; const float lfo = q31_to_f32(params->shape_lfo); const float cutoff = param_val_to_f32(params->cutoff); const float resonance = param_val_to_f32(params->resonance); const float f0 = osc_notehzf(note); const float f1 = osc_notehzf(note + 1); float hz = linintf(mod * k_note_mod_fscale, f0, f1); hz = clipmaxf(hz, k_note_max_hz); if (hz < 1) hz = 1.0f; for (int i = 0; i < frames; i++) { float sig = cycle(hz, lfo); y[i] = f32_to_q31(sig); } } void PARAM(uint16_t index, uint16_t value) { float valf = param_val_to_f32(value); switch (index) { case k_osc_param_shape: set_param_shape(valf); break; case k_osc_param_shiftshape: set_param_shiftshape(valf); break; case k_osc_param_id1: set_param_id1(valf); break; case k_osc_param_id2: set_param_id2(valf); break; case k_osc_param_id3: set_param_id3(valf); break; case k_osc_param_id4: set_param_id4(valf); break; case k_osc_param_id5: set_param_id5(valf); break; case k_osc_param_id6: set_param_id6(valf); break; default: break; } } void INIT(uint32_t platform, uint32_t api) { } }; static MorphOsc s_osc; void OSC_INIT(uint32_t platform, uint32_t api) { s_osc.INIT(platform, api); } void OSC_CYCLE(const user_osc_param_t * const params, int32_t *yn, const uint32_t frames) { s_osc.CYCLE(params, yn, frames); } void OSC_NOTEON(const user_osc_param_t * const params) { s_osc.NOTEON(params); } void OSC_NOTEOFF(const user_osc_param_t * const params) { s_osc.NOTEOFF(params); } void OSC_PARAM(uint16_t index, uint16_t value) { s_osc.PARAM(index, value); }
.global s_prepare_buffers s_prepare_buffers: push %r13 push %r14 push %r15 push %r9 push %rcx push %rdi push %rdx push %rsi lea addresses_A_ht+0x218a, %rcx nop nop nop nop and $62363, %r15 mov $0x6162636465666768, %r14 movq %r14, %xmm1 movups %xmm1, (%rcx) nop nop lfence lea addresses_normal_ht+0x717c, %rsi lea addresses_A_ht+0x71bc, %rdi nop nop nop nop nop add %rdx, %rdx mov $74, %rcx rep movsb nop nop xor %rdx, %rdx lea addresses_D_ht+0xdefc, %rsi nop nop nop nop cmp %r13, %r13 mov (%rsi), %di nop nop nop add $44950, %rsi lea addresses_WT_ht+0x5836, %rdi clflush (%rdi) nop nop nop dec %r14 mov (%rdi), %si nop nop cmp $43905, %rcx lea addresses_UC_ht+0x437c, %rsi lea addresses_UC_ht+0x517c, %rdi nop nop sub %r9, %r9 mov $57, %rcx rep movsw nop nop nop dec %rdx lea addresses_WC_ht+0x37dc, %rsi lea addresses_A_ht+0x1e9c, %rdi nop nop nop nop nop mfence mov $47, %rcx rep movsb nop and %rdi, %rdi lea addresses_WT_ht+0x1433c, %rsi lea addresses_WT_ht+0xa57c, %rdi nop nop nop xor $1425, %rdx mov $31, %rcx rep movsb nop nop nop nop nop xor %r9, %r9 lea addresses_UC_ht+0x16b74, %rsi lea addresses_normal_ht+0x1bbc, %rdi nop xor $19263, %r13 mov $45, %rcx rep movsw nop nop nop nop inc %r9 lea addresses_A_ht+0x194e5, %rdi nop cmp $61499, %r15 mov $0x6162636465666768, %r14 movq %r14, (%rdi) nop nop nop nop cmp $18177, %r14 lea addresses_WT_ht+0x2ad4, %rsi lea addresses_WC_ht+0x9944, %rdi clflush (%rsi) clflush (%rdi) dec %rdx mov $105, %rcx rep movsl nop xor $42804, %rcx lea addresses_WT_ht+0x6c7c, %r13 nop add %rsi, %rsi movb (%r13), %cl nop nop nop nop nop sub %rdx, %rdx lea addresses_UC_ht+0x1597c, %rdi nop nop nop nop nop cmp $51478, %rsi movw $0x6162, (%rdi) nop and %r15, %r15 pop %rsi pop %rdx pop %rdi pop %rcx pop %r9 pop %r15 pop %r14 pop %r13 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r13 push %r14 push %rdx // Faulty Load lea addresses_A+0x1c17c, %r11 nop nop nop nop xor $37202, %r10 mov (%r11), %r13 lea oracles, %r11 and $0xff, %r13 shlq $12, %r13 mov (%r11,%r13,1), %r13 pop %rdx pop %r14 pop %r13 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_A', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_A', 'AVXalign': False, 'size': 8, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 1}} {'src': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 6, 'same': False}} {'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 2, 'NT': True, 'same': True, 'congruent': 6}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 1}, 'OP': 'LOAD'} {'src': {'type': 'addresses_UC_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}} {'src': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}} {'src': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 9, 'same': False}} {'src': {'type': 'addresses_UC_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 5, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 0}} {'src': {'type': 'addresses_WT_ht', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 1, 'same': True}} {'src': {'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 1, 'NT': True, 'same': False, 'congruent': 8}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 9}} {'35': 21829} 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 */
;;*************************************** ;; Origially based an example at http://www.cpcwiki.eu/index.php/Programming An_example_loader ;;*************************************** ColourPalette: ; hardware colours defb &54,&42,&56,&4A,&4C,&5E,&4E,&5E,&5E,&4C,&4C,&4C,&4C,&4C,&4C,&4B,&54 Palette_Init: ;; CPC has some quirks here as well, seems to be caused by the ability to flash each colour ;; ;; http://www.cpcwiki.eu/forum/programming/screen-scrolling-and-ink-commands/ ;; https://www.cpcwiki.eu/forum/programming/bios-call-scr_set_ink-and-interrupts/ ;; di for safety ;di ld hl,ColourPalette call SetupColours ;; but for this to work, make sure these values are left in the shadow registers ;; so we've only got one switch in here ;exx ;ei ret SetupColours: ;; Inputs: HL Address the palette values are stored ld b,17 ;; 16 colours + 1 border xor a ;; start with pen 0 DoColours: push bc ;; need to stash b as we are using it for our loop and need it ;; below to write to the port ld e,(hl) ;; read the value of the colour we want into e inc hl ;; move along ready for next time ld bc,&7F00 out (c),a ;; PENR:&7F{pp} - where pp is the palette/pen number out (c),e ;; INKR:&7F{hc} - where hc is the hardware colour number pop bc inc a ;; increment pen number djnz DoColours ret
if not defined FMUL INCLUDE "print_fp.asm" ; HL = BC * DE DEBUG@FMUL: FMUL: CALL @FMUL ; 3:17 PUSH HL ; 1:11 LD HL, '*'+' ' * 256 ; 3:10 "* " LD A, COL_BLUE ; 2:7 JP PRINT_XFP ; 3:10 else if not defined DEBUG@FMUL .WARNING You must include the file: debug_fmul.asm before. endif endif
; ; Colour Genie EG2000 graphics routines ; Fast background restore ; ; ; $Id: bkrestore.asm,v 1.1 2015/10/28 07:18:49 stefano Exp $ ; PUBLIC bkrestore EXTERN pixeladdress .bkrestore ; __FASTCALL__ : sprite ptr in HL push hl pop ix ld h,(ix+2) ; restore sprite position ld l,(ix+3) ld a,(ix+0) ld b,(ix+1) cp 9 jr nc,bkrestore ._sloop push bc push hl ld a,(ix+4) and @10101010 ld (hl),a inc hl ld a,(ix+4) and @01010101 rla ld (hl),a inc hl ld a,(ix+5) and @10101010 ld (hl),a inc hl ld a,(ix+5) and @01010101 rla ld (hl),a inc hl inc ix inc ix pop hl ld bc,40 ;Go to next line add hl,bc pop bc djnz _sloop ret .bkrestorew push bc ld a,(ix+4) and @10101010 ld (hl),a inc hl ld a,(ix+4) and @01010101 rla ld (hl),a inc hl ld a,(ix+5) and @10101010 ld (hl),a inc hl ld a,(ix+5) and @01010101 rla ld (hl),a inc hl ld a,(ix+6) and @10101010 ld (hl),a inc hl ld a,(ix+6) and @01010101 rla ld (hl),a inc ix inc ix inc ix pop hl ld bc,40 ;Go to next line add hl,bc pop bc djnz bkrestorew ret
user/_forktest: file format elf64-littleriscv Disassembly of section .text: 0000000000000000 <print>: #define N 1000 void print(const char *s) { 0: 1101 addi sp,sp,-32 2: ec06 sd ra,24(sp) 4: e822 sd s0,16(sp) 6: e426 sd s1,8(sp) 8: 1000 addi s0,sp,32 a: 84aa mv s1,a0 write(1, s, strlen(s)); c: 00000097 auipc ra,0x0 10: 15a080e7 jalr 346(ra) # 166 <strlen> 14: 0005061b sext.w a2,a0 18: 85a6 mv a1,s1 1a: 4505 li a0,1 1c: 00000097 auipc ra,0x0 20: 390080e7 jalr 912(ra) # 3ac <write> } 24: 60e2 ld ra,24(sp) 26: 6442 ld s0,16(sp) 28: 64a2 ld s1,8(sp) 2a: 6105 addi sp,sp,32 2c: 8082 ret 000000000000002e <forktest>: void forktest(void) { 2e: 1101 addi sp,sp,-32 30: ec06 sd ra,24(sp) 32: e822 sd s0,16(sp) 34: e426 sd s1,8(sp) 36: e04a sd s2,0(sp) 38: 1000 addi s0,sp,32 int n, pid; print("fork test\n"); 3a: 00000517 auipc a0,0x0 3e: 40650513 addi a0,a0,1030 # 440 <sigreturn+0xc> 42: 00000097 auipc ra,0x0 46: fbe080e7 jalr -66(ra) # 0 <print> for(n=0; n<N; n++){ 4a: 4481 li s1,0 4c: 3e800913 li s2,1000 pid = fork(); 50: 00000097 auipc ra,0x0 54: 334080e7 jalr 820(ra) # 384 <fork> if(pid < 0) 58: 02054763 bltz a0,86 <forktest+0x58> break; if(pid == 0) 5c: c10d beqz a0,7e <forktest+0x50> for(n=0; n<N; n++){ 5e: 2485 addiw s1,s1,1 60: ff2498e3 bne s1,s2,50 <forktest+0x22> exit(0); } if(n == N){ print("fork claimed to work N times!\n"); 64: 00000517 auipc a0,0x0 68: 3ec50513 addi a0,a0,1004 # 450 <sigreturn+0x1c> 6c: 00000097 auipc ra,0x0 70: f94080e7 jalr -108(ra) # 0 <print> exit(1); 74: 4505 li a0,1 76: 00000097 auipc ra,0x0 7a: 316080e7 jalr 790(ra) # 38c <exit> exit(0); 7e: 00000097 auipc ra,0x0 82: 30e080e7 jalr 782(ra) # 38c <exit> if(n == N){ 86: 3e800793 li a5,1000 8a: fcf48de3 beq s1,a5,64 <forktest+0x36> } for(; n > 0; n--){ 8e: 00905b63 blez s1,a4 <forktest+0x76> if(wait(0) < 0){ 92: 4501 li a0,0 94: 00000097 auipc ra,0x0 98: 300080e7 jalr 768(ra) # 394 <wait> 9c: 02054a63 bltz a0,d0 <forktest+0xa2> for(; n > 0; n--){ a0: 34fd addiw s1,s1,-1 a2: f8e5 bnez s1,92 <forktest+0x64> print("wait stopped early\n"); exit(1); } } if(wait(0) != -1){ a4: 4501 li a0,0 a6: 00000097 auipc ra,0x0 aa: 2ee080e7 jalr 750(ra) # 394 <wait> ae: 57fd li a5,-1 b0: 02f51d63 bne a0,a5,ea <forktest+0xbc> print("wait got too many\n"); exit(1); } print("fork test OK\n"); b4: 00000517 auipc a0,0x0 b8: 3ec50513 addi a0,a0,1004 # 4a0 <sigreturn+0x6c> bc: 00000097 auipc ra,0x0 c0: f44080e7 jalr -188(ra) # 0 <print> } c4: 60e2 ld ra,24(sp) c6: 6442 ld s0,16(sp) c8: 64a2 ld s1,8(sp) ca: 6902 ld s2,0(sp) cc: 6105 addi sp,sp,32 ce: 8082 ret print("wait stopped early\n"); d0: 00000517 auipc a0,0x0 d4: 3a050513 addi a0,a0,928 # 470 <sigreturn+0x3c> d8: 00000097 auipc ra,0x0 dc: f28080e7 jalr -216(ra) # 0 <print> exit(1); e0: 4505 li a0,1 e2: 00000097 auipc ra,0x0 e6: 2aa080e7 jalr 682(ra) # 38c <exit> print("wait got too many\n"); ea: 00000517 auipc a0,0x0 ee: 39e50513 addi a0,a0,926 # 488 <sigreturn+0x54> f2: 00000097 auipc ra,0x0 f6: f0e080e7 jalr -242(ra) # 0 <print> exit(1); fa: 4505 li a0,1 fc: 00000097 auipc ra,0x0 100: 290080e7 jalr 656(ra) # 38c <exit> 0000000000000104 <main>: int main(void) { 104: 1141 addi sp,sp,-16 106: e406 sd ra,8(sp) 108: e022 sd s0,0(sp) 10a: 0800 addi s0,sp,16 forktest(); 10c: 00000097 auipc ra,0x0 110: f22080e7 jalr -222(ra) # 2e <forktest> exit(0); 114: 4501 li a0,0 116: 00000097 auipc ra,0x0 11a: 276080e7 jalr 630(ra) # 38c <exit> 000000000000011e <strcpy>: #include "kernel/fcntl.h" #include "user/user.h" char* strcpy(char *s, const char *t) { 11e: 1141 addi sp,sp,-16 120: e422 sd s0,8(sp) 122: 0800 addi s0,sp,16 char *os; os = s; while((*s++ = *t++) != 0) 124: 87aa mv a5,a0 126: 0585 addi a1,a1,1 128: 0785 addi a5,a5,1 12a: fff5c703 lbu a4,-1(a1) 12e: fee78fa3 sb a4,-1(a5) 132: fb75 bnez a4,126 <strcpy+0x8> ; return os; } 134: 6422 ld s0,8(sp) 136: 0141 addi sp,sp,16 138: 8082 ret 000000000000013a <strcmp>: int strcmp(const char *p, const char *q) { 13a: 1141 addi sp,sp,-16 13c: e422 sd s0,8(sp) 13e: 0800 addi s0,sp,16 while(*p && *p == *q) 140: 00054783 lbu a5,0(a0) 144: cb91 beqz a5,158 <strcmp+0x1e> 146: 0005c703 lbu a4,0(a1) 14a: 00f71763 bne a4,a5,158 <strcmp+0x1e> p++, q++; 14e: 0505 addi a0,a0,1 150: 0585 addi a1,a1,1 while(*p && *p == *q) 152: 00054783 lbu a5,0(a0) 156: fbe5 bnez a5,146 <strcmp+0xc> return (uchar)*p - (uchar)*q; 158: 0005c503 lbu a0,0(a1) } 15c: 40a7853b subw a0,a5,a0 160: 6422 ld s0,8(sp) 162: 0141 addi sp,sp,16 164: 8082 ret 0000000000000166 <strlen>: uint strlen(const char *s) { 166: 1141 addi sp,sp,-16 168: e422 sd s0,8(sp) 16a: 0800 addi s0,sp,16 int n; for(n = 0; s[n]; n++) 16c: 00054783 lbu a5,0(a0) 170: cf91 beqz a5,18c <strlen+0x26> 172: 0505 addi a0,a0,1 174: 87aa mv a5,a0 176: 4685 li a3,1 178: 9e89 subw a3,a3,a0 17a: 00f6853b addw a0,a3,a5 17e: 0785 addi a5,a5,1 180: fff7c703 lbu a4,-1(a5) 184: fb7d bnez a4,17a <strlen+0x14> ; return n; } 186: 6422 ld s0,8(sp) 188: 0141 addi sp,sp,16 18a: 8082 ret for(n = 0; s[n]; n++) 18c: 4501 li a0,0 18e: bfe5 j 186 <strlen+0x20> 0000000000000190 <memset>: void* memset(void *dst, int c, uint n) { 190: 1141 addi sp,sp,-16 192: e422 sd s0,8(sp) 194: 0800 addi s0,sp,16 char *cdst = (char *) dst; int i; for(i = 0; i < n; i++){ 196: ca19 beqz a2,1ac <memset+0x1c> 198: 87aa mv a5,a0 19a: 1602 slli a2,a2,0x20 19c: 9201 srli a2,a2,0x20 19e: 00a60733 add a4,a2,a0 cdst[i] = c; 1a2: 00b78023 sb a1,0(a5) for(i = 0; i < n; i++){ 1a6: 0785 addi a5,a5,1 1a8: fee79de3 bne a5,a4,1a2 <memset+0x12> } return dst; } 1ac: 6422 ld s0,8(sp) 1ae: 0141 addi sp,sp,16 1b0: 8082 ret 00000000000001b2 <strchr>: char* strchr(const char *s, char c) { 1b2: 1141 addi sp,sp,-16 1b4: e422 sd s0,8(sp) 1b6: 0800 addi s0,sp,16 for(; *s; s++) 1b8: 00054783 lbu a5,0(a0) 1bc: cb99 beqz a5,1d2 <strchr+0x20> if(*s == c) 1be: 00f58763 beq a1,a5,1cc <strchr+0x1a> for(; *s; s++) 1c2: 0505 addi a0,a0,1 1c4: 00054783 lbu a5,0(a0) 1c8: fbfd bnez a5,1be <strchr+0xc> return (char*)s; return 0; 1ca: 4501 li a0,0 } 1cc: 6422 ld s0,8(sp) 1ce: 0141 addi sp,sp,16 1d0: 8082 ret return 0; 1d2: 4501 li a0,0 1d4: bfe5 j 1cc <strchr+0x1a> 00000000000001d6 <gets>: char* gets(char *buf, int max) { 1d6: 711d addi sp,sp,-96 1d8: ec86 sd ra,88(sp) 1da: e8a2 sd s0,80(sp) 1dc: e4a6 sd s1,72(sp) 1de: e0ca sd s2,64(sp) 1e0: fc4e sd s3,56(sp) 1e2: f852 sd s4,48(sp) 1e4: f456 sd s5,40(sp) 1e6: f05a sd s6,32(sp) 1e8: ec5e sd s7,24(sp) 1ea: 1080 addi s0,sp,96 1ec: 8baa mv s7,a0 1ee: 8a2e mv s4,a1 int i, cc; char c; for(i=0; i+1 < max; ){ 1f0: 892a mv s2,a0 1f2: 4481 li s1,0 cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; if(c == '\n' || c == '\r') 1f4: 4aa9 li s5,10 1f6: 4b35 li s6,13 for(i=0; i+1 < max; ){ 1f8: 89a6 mv s3,s1 1fa: 2485 addiw s1,s1,1 1fc: 0344d863 bge s1,s4,22c <gets+0x56> cc = read(0, &c, 1); 200: 4605 li a2,1 202: faf40593 addi a1,s0,-81 206: 4501 li a0,0 208: 00000097 auipc ra,0x0 20c: 19c080e7 jalr 412(ra) # 3a4 <read> if(cc < 1) 210: 00a05e63 blez a0,22c <gets+0x56> buf[i++] = c; 214: faf44783 lbu a5,-81(s0) 218: 00f90023 sb a5,0(s2) if(c == '\n' || c == '\r') 21c: 01578763 beq a5,s5,22a <gets+0x54> 220: 0905 addi s2,s2,1 222: fd679be3 bne a5,s6,1f8 <gets+0x22> for(i=0; i+1 < max; ){ 226: 89a6 mv s3,s1 228: a011 j 22c <gets+0x56> 22a: 89a6 mv s3,s1 break; } buf[i] = '\0'; 22c: 99de add s3,s3,s7 22e: 00098023 sb zero,0(s3) return buf; } 232: 855e mv a0,s7 234: 60e6 ld ra,88(sp) 236: 6446 ld s0,80(sp) 238: 64a6 ld s1,72(sp) 23a: 6906 ld s2,64(sp) 23c: 79e2 ld s3,56(sp) 23e: 7a42 ld s4,48(sp) 240: 7aa2 ld s5,40(sp) 242: 7b02 ld s6,32(sp) 244: 6be2 ld s7,24(sp) 246: 6125 addi sp,sp,96 248: 8082 ret 000000000000024a <stat>: int stat(const char *n, struct stat *st) { 24a: 1101 addi sp,sp,-32 24c: ec06 sd ra,24(sp) 24e: e822 sd s0,16(sp) 250: e426 sd s1,8(sp) 252: e04a sd s2,0(sp) 254: 1000 addi s0,sp,32 256: 892e mv s2,a1 int fd; int r; fd = open(n, O_RDONLY); 258: 4581 li a1,0 25a: 00000097 auipc ra,0x0 25e: 172080e7 jalr 370(ra) # 3cc <open> if(fd < 0) 262: 02054563 bltz a0,28c <stat+0x42> 266: 84aa mv s1,a0 return -1; r = fstat(fd, st); 268: 85ca mv a1,s2 26a: 00000097 auipc ra,0x0 26e: 17a080e7 jalr 378(ra) # 3e4 <fstat> 272: 892a mv s2,a0 close(fd); 274: 8526 mv a0,s1 276: 00000097 auipc ra,0x0 27a: 13e080e7 jalr 318(ra) # 3b4 <close> return r; } 27e: 854a mv a0,s2 280: 60e2 ld ra,24(sp) 282: 6442 ld s0,16(sp) 284: 64a2 ld s1,8(sp) 286: 6902 ld s2,0(sp) 288: 6105 addi sp,sp,32 28a: 8082 ret return -1; 28c: 597d li s2,-1 28e: bfc5 j 27e <stat+0x34> 0000000000000290 <atoi>: int atoi(const char *s) { 290: 1141 addi sp,sp,-16 292: e422 sd s0,8(sp) 294: 0800 addi s0,sp,16 int n; n = 0; while('0' <= *s && *s <= '9') 296: 00054603 lbu a2,0(a0) 29a: fd06079b addiw a5,a2,-48 29e: 0ff7f793 andi a5,a5,255 2a2: 4725 li a4,9 2a4: 02f76963 bltu a4,a5,2d6 <atoi+0x46> 2a8: 86aa mv a3,a0 n = 0; 2aa: 4501 li a0,0 while('0' <= *s && *s <= '9') 2ac: 45a5 li a1,9 n = n*10 + *s++ - '0'; 2ae: 0685 addi a3,a3,1 2b0: 0025179b slliw a5,a0,0x2 2b4: 9fa9 addw a5,a5,a0 2b6: 0017979b slliw a5,a5,0x1 2ba: 9fb1 addw a5,a5,a2 2bc: fd07851b addiw a0,a5,-48 while('0' <= *s && *s <= '9') 2c0: 0006c603 lbu a2,0(a3) 2c4: fd06071b addiw a4,a2,-48 2c8: 0ff77713 andi a4,a4,255 2cc: fee5f1e3 bgeu a1,a4,2ae <atoi+0x1e> return n; } 2d0: 6422 ld s0,8(sp) 2d2: 0141 addi sp,sp,16 2d4: 8082 ret n = 0; 2d6: 4501 li a0,0 2d8: bfe5 j 2d0 <atoi+0x40> 00000000000002da <memmove>: void* memmove(void *vdst, const void *vsrc, int n) { 2da: 1141 addi sp,sp,-16 2dc: e422 sd s0,8(sp) 2de: 0800 addi s0,sp,16 char *dst; const char *src; dst = vdst; src = vsrc; if (src > dst) { 2e0: 02b57463 bgeu a0,a1,308 <memmove+0x2e> while(n-- > 0) 2e4: 00c05f63 blez a2,302 <memmove+0x28> 2e8: 1602 slli a2,a2,0x20 2ea: 9201 srli a2,a2,0x20 2ec: 00c507b3 add a5,a0,a2 dst = vdst; 2f0: 872a mv a4,a0 *dst++ = *src++; 2f2: 0585 addi a1,a1,1 2f4: 0705 addi a4,a4,1 2f6: fff5c683 lbu a3,-1(a1) 2fa: fed70fa3 sb a3,-1(a4) while(n-- > 0) 2fe: fee79ae3 bne a5,a4,2f2 <memmove+0x18> src += n; while(n-- > 0) *--dst = *--src; } return vdst; } 302: 6422 ld s0,8(sp) 304: 0141 addi sp,sp,16 306: 8082 ret dst += n; 308: 00c50733 add a4,a0,a2 src += n; 30c: 95b2 add a1,a1,a2 while(n-- > 0) 30e: fec05ae3 blez a2,302 <memmove+0x28> 312: fff6079b addiw a5,a2,-1 316: 1782 slli a5,a5,0x20 318: 9381 srli a5,a5,0x20 31a: fff7c793 not a5,a5 31e: 97ba add a5,a5,a4 *--dst = *--src; 320: 15fd addi a1,a1,-1 322: 177d addi a4,a4,-1 324: 0005c683 lbu a3,0(a1) 328: 00d70023 sb a3,0(a4) while(n-- > 0) 32c: fee79ae3 bne a5,a4,320 <memmove+0x46> 330: bfc9 j 302 <memmove+0x28> 0000000000000332 <memcmp>: int memcmp(const void *s1, const void *s2, uint n) { 332: 1141 addi sp,sp,-16 334: e422 sd s0,8(sp) 336: 0800 addi s0,sp,16 const char *p1 = s1, *p2 = s2; while (n-- > 0) { 338: ca05 beqz a2,368 <memcmp+0x36> 33a: fff6069b addiw a3,a2,-1 33e: 1682 slli a3,a3,0x20 340: 9281 srli a3,a3,0x20 342: 0685 addi a3,a3,1 344: 96aa add a3,a3,a0 if (*p1 != *p2) { 346: 00054783 lbu a5,0(a0) 34a: 0005c703 lbu a4,0(a1) 34e: 00e79863 bne a5,a4,35e <memcmp+0x2c> return *p1 - *p2; } p1++; 352: 0505 addi a0,a0,1 p2++; 354: 0585 addi a1,a1,1 while (n-- > 0) { 356: fed518e3 bne a0,a3,346 <memcmp+0x14> } return 0; 35a: 4501 li a0,0 35c: a019 j 362 <memcmp+0x30> return *p1 - *p2; 35e: 40e7853b subw a0,a5,a4 } 362: 6422 ld s0,8(sp) 364: 0141 addi sp,sp,16 366: 8082 ret return 0; 368: 4501 li a0,0 36a: bfe5 j 362 <memcmp+0x30> 000000000000036c <memcpy>: void * memcpy(void *dst, const void *src, uint n) { 36c: 1141 addi sp,sp,-16 36e: e406 sd ra,8(sp) 370: e022 sd s0,0(sp) 372: 0800 addi s0,sp,16 return memmove(dst, src, n); 374: 00000097 auipc ra,0x0 378: f66080e7 jalr -154(ra) # 2da <memmove> } 37c: 60a2 ld ra,8(sp) 37e: 6402 ld s0,0(sp) 380: 0141 addi sp,sp,16 382: 8082 ret 0000000000000384 <fork>: # generated by usys.pl - do not edit #include "kernel/syscall.h" .global fork fork: li a7, SYS_fork 384: 4885 li a7,1 ecall 386: 00000073 ecall ret 38a: 8082 ret 000000000000038c <exit>: .global exit exit: li a7, SYS_exit 38c: 4889 li a7,2 ecall 38e: 00000073 ecall ret 392: 8082 ret 0000000000000394 <wait>: .global wait wait: li a7, SYS_wait 394: 488d li a7,3 ecall 396: 00000073 ecall ret 39a: 8082 ret 000000000000039c <pipe>: .global pipe pipe: li a7, SYS_pipe 39c: 4891 li a7,4 ecall 39e: 00000073 ecall ret 3a2: 8082 ret 00000000000003a4 <read>: .global read read: li a7, SYS_read 3a4: 4895 li a7,5 ecall 3a6: 00000073 ecall ret 3aa: 8082 ret 00000000000003ac <write>: .global write write: li a7, SYS_write 3ac: 48c1 li a7,16 ecall 3ae: 00000073 ecall ret 3b2: 8082 ret 00000000000003b4 <close>: .global close close: li a7, SYS_close 3b4: 48d5 li a7,21 ecall 3b6: 00000073 ecall ret 3ba: 8082 ret 00000000000003bc <kill>: .global kill kill: li a7, SYS_kill 3bc: 4899 li a7,6 ecall 3be: 00000073 ecall ret 3c2: 8082 ret 00000000000003c4 <exec>: .global exec exec: li a7, SYS_exec 3c4: 489d li a7,7 ecall 3c6: 00000073 ecall ret 3ca: 8082 ret 00000000000003cc <open>: .global open open: li a7, SYS_open 3cc: 48bd li a7,15 ecall 3ce: 00000073 ecall ret 3d2: 8082 ret 00000000000003d4 <mknod>: .global mknod mknod: li a7, SYS_mknod 3d4: 48c5 li a7,17 ecall 3d6: 00000073 ecall ret 3da: 8082 ret 00000000000003dc <unlink>: .global unlink unlink: li a7, SYS_unlink 3dc: 48c9 li a7,18 ecall 3de: 00000073 ecall ret 3e2: 8082 ret 00000000000003e4 <fstat>: .global fstat fstat: li a7, SYS_fstat 3e4: 48a1 li a7,8 ecall 3e6: 00000073 ecall ret 3ea: 8082 ret 00000000000003ec <link>: .global link link: li a7, SYS_link 3ec: 48cd li a7,19 ecall 3ee: 00000073 ecall ret 3f2: 8082 ret 00000000000003f4 <mkdir>: .global mkdir mkdir: li a7, SYS_mkdir 3f4: 48d1 li a7,20 ecall 3f6: 00000073 ecall ret 3fa: 8082 ret 00000000000003fc <chdir>: .global chdir chdir: li a7, SYS_chdir 3fc: 48a5 li a7,9 ecall 3fe: 00000073 ecall ret 402: 8082 ret 0000000000000404 <dup>: .global dup dup: li a7, SYS_dup 404: 48a9 li a7,10 ecall 406: 00000073 ecall ret 40a: 8082 ret 000000000000040c <getpid>: .global getpid getpid: li a7, SYS_getpid 40c: 48ad li a7,11 ecall 40e: 00000073 ecall ret 412: 8082 ret 0000000000000414 <sbrk>: .global sbrk sbrk: li a7, SYS_sbrk 414: 48b1 li a7,12 ecall 416: 00000073 ecall ret 41a: 8082 ret 000000000000041c <sleep>: .global sleep sleep: li a7, SYS_sleep 41c: 48b5 li a7,13 ecall 41e: 00000073 ecall ret 422: 8082 ret 0000000000000424 <uptime>: .global uptime uptime: li a7, SYS_uptime 424: 48b9 li a7,14 ecall 426: 00000073 ecall ret 42a: 8082 ret 000000000000042c <sigalarm>: .global sigalarm sigalarm: li a7, SYS_sigalarm 42c: 48d9 li a7,22 ecall 42e: 00000073 ecall ret 432: 8082 ret 0000000000000434 <sigreturn>: .global sigreturn sigreturn: li a7, SYS_sigreturn 434: 48dd li a7,23 ecall 436: 00000073 ecall ret 43a: 8082 ret
! SPARC v9 __gmpn_add_n -- Add two limb vectors of the same length > 0 and store ! sum in a third limb vector. ! Copyright (C) 1999, 2000 Free Software Foundation, Inc. ! This file is part of the GNU MP Library. ! The GNU MP Library is free software; you can redistribute it and/or modify ! it under the terms of the GNU Library General Public License as published by ! the Free Software Foundation; either version 2 of the License, or (at your ! option) any later version. ! The GNU MP Library is distributed in the hope that it will be useful, but ! WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY ! or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public ! License for more details. ! You should have received a copy of the GNU Library General Public License ! along with the GNU MP Library; see the file COPYING.LIB. If not, write to ! the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, ! MA 02111-1307, USA. ! INPUT PARAMETERS ! res_ptr %o0 ! s1_ptr %o1 ! s2_ptr %o2 ! size %o3 include(`../config.m4') ASM_START() .register %g2,#scratch .register %g3,#scratch PROLOGUE(mpn_add_n) ! 12 mem ops >= 12 cycles ! 8 shift insn >= 8 cycles ! 8 addccc, executing alone, +8 cycles ! Unrolling not mandatory...perhaps 2-way is best? ! Put one ldx/stx and one s?lx per issue tuple, fill with pointer arith and loop ctl ! All in all, it runs at 5 cycles/limb save %sp,-160,%sp addcc %g0,%g0,%g0 add %i3,-4,%i3 brlz,pn %i3,L(there) nop ldx [%i1+0],%l0 ldx [%i2+0],%l4 ldx [%i1+8],%l1 ldx [%i2+8],%l5 ldx [%i1+16],%l2 ldx [%i2+16],%l6 ldx [%i1+24],%l3 ldx [%i2+24],%l7 add %i1,32,%i1 add %i2,32,%i2 add %i3,-4,%i3 brlz,pn %i3,L(skip) nop b L(loop1) ! jump instead of executing many NOPs nop ALIGN(32) !--------- Start main loop --------- L(loop1): addccc %l0,%l4,%g1 !- srlx %l0,32,%o0 ldx [%i1+0],%l0 !- srlx %l4,32,%o4 ldx [%i2+0],%l4 !- addccc %o0,%o4,%g0 !- addccc %l1,%l5,%g2 !- srlx %l1,32,%o1 ldx [%i1+8],%l1 !- srlx %l5,32,%o5 ldx [%i2+8],%l5 !- addccc %o1,%o5,%g0 !- addccc %l2,%l6,%g3 !- srlx %l2,32,%o2 ldx [%i1+16],%l2 !- srlx %l6,32,%g5 ! asymmetry ldx [%i2+16],%l6 !- addccc %o2,%g5,%g0 !- addccc %l3,%l7,%g4 !- srlx %l3,32,%o3 ldx [%i1+24],%l3 add %i1,32,%i1 !- srlx %l7,32,%o7 ldx [%i2+24],%l7 add %i2,32,%i2 !- addccc %o3,%o7,%g0 !- stx %g1,[%i0+0] !- stx %g2,[%i0+8] !- stx %g3,[%i0+16] add %i3,-4,%i3 !- stx %g4,[%i0+24] add %i0,32,%i0 brgez,pt %i3,L(loop1) nop !--------- End main loop --------- L(skip): addccc %l0,%l4,%g1 srlx %l0,32,%o0 srlx %l4,32,%o4 addccc %o0,%o4,%g0 addccc %l1,%l5,%g2 srlx %l1,32,%o1 srlx %l5,32,%o5 addccc %o1,%o5,%g0 addccc %l2,%l6,%g3 srlx %l2,32,%o2 srlx %l6,32,%g5 ! asymmetry addccc %o2,%g5,%g0 addccc %l3,%l7,%g4 srlx %l3,32,%o3 srlx %l7,32,%o7 addccc %o3,%o7,%g0 stx %g1,[%i0+0] stx %g2,[%i0+8] stx %g3,[%i0+16] stx %g4,[%i0+24] add %i0,32,%i0 L(there): add %i3,4,%i3 brz,pt %i3,L(end) nop L(loop2): ldx [%i1+0],%l0 add %i1,8,%i1 ldx [%i2+0],%l4 add %i2,8,%i2 srlx %l0,32,%g2 srlx %l4,32,%g3 addccc %l0,%l4,%g1 addccc %g2,%g3,%g0 stx %g1,[%i0+0] add %i0,8,%i0 add %i3,-1,%i3 brgz,pt %i3,L(loop2) nop L(end): addc %g0,%g0,%i0 ret restore EPILOGUE(mpn_add_n)
extern m7_ippsECCPSetStd:function extern n8_ippsECCPSetStd:function extern y8_ippsECCPSetStd:function extern e9_ippsECCPSetStd:function extern l9_ippsECCPSetStd:function extern n0_ippsECCPSetStd:function extern k0_ippsECCPSetStd:function extern ippcpJumpIndexForMergedLibs extern ippcpSafeInit:function segment .data align 8 dq .Lin_ippsECCPSetStd .Larraddr_ippsECCPSetStd: dq m7_ippsECCPSetStd dq n8_ippsECCPSetStd dq y8_ippsECCPSetStd dq e9_ippsECCPSetStd dq l9_ippsECCPSetStd dq n0_ippsECCPSetStd dq k0_ippsECCPSetStd segment .text global ippsECCPSetStd:function (ippsECCPSetStd.LEndippsECCPSetStd - ippsECCPSetStd) .Lin_ippsECCPSetStd: db 0xf3, 0x0f, 0x1e, 0xfa call ippcpSafeInit wrt ..plt align 16 ippsECCPSetStd: db 0xf3, 0x0f, 0x1e, 0xfa mov rax, qword [rel ippcpJumpIndexForMergedLibs wrt ..gotpc] movsxd rax, dword [rax] lea r11, [rel .Larraddr_ippsECCPSetStd] mov r11, qword [r11+rax*8] jmp r11 .LEndippsECCPSetStd:
frame 1, 03 frame 0, 03 frame 2, 03 endanim
/*Write C++/Java program to implement Cohen-Sutherland line clipping algorithm for given window. Draw line using mouse interfacing to draw polygon*/ #include<iostream> #include<graphics.h> using namespace std; class lineClip { private : int RIGHT = 2,LEFT = 1,TOP = 8,BOTTOM = 4; int x1,x2,y1,y2,xl,yl,xh,yh,x,y; public : int getcode(int x,int y); void process(); }; int lineClip :: getcode(int x,int y) { int code = 0; if(y>yh) code |= TOP; if(y<yl) code |= BOTTOM; if(x<xl) code |= LEFT; if(x>xh) code |= RIGHT; return code; } void lineClip :: process() { int code1,code2; cout<<"\n Enter the botttom left and upper right coordinate of the rectangle : "; cin>>xl>>yl>>xh>>yh; setcolor(YELLOW); rectangle(xl,yl,xh,yh); cout<<"\n Enter the line coordinate :"; cout<<"\n Starting Coordinate :"; cin>>x1>>y1; cout<<"\n Ending coordinate : "; cin>>x2>>y2; setcolor(WHITE); line(x1,y1,x2,y2); delay(1000); code1 = getcode(x1,y1); code2 = getcode(x2,y2); int temp; float m; int flag = 0; while(1) { m = (float)(y2-y1)/(x2-x1); if(code1 == 0 && code2 ==0) { flag = 1; break; } else if((code1 & code2) != 0) { break; } else { if(code1 == 0) temp = code2; else temp = code1; if(temp & TOP) { x = x1 + (yh-y1)/m; y = yh; } else if(temp & BOTTOM) { x = x1 + (yl-y1)/m; y = yl; } else if(temp & LEFT){ y = y1 + m*(xl-x1); x = xl; } else if(temp & RIGHT){ y = y1 + m*(xh-x1); x = xh; } if(temp == code1){ x1 = x; y1 = y; code1 = getcode(x1,y2); }else { x2 = x; y2 = y; code2 = getcode(x2,y2); } } } cleardevice(); rectangle(xl,yl,xh,yh); setcolor(YELLOW); if(flag == 1) line(x1,y1,x2,y2); getch(); closegraph(); } int main() { int gd = DETECT,gm; initgraph(&gd,&gm,NULL); lineClip l1; l1.process(); return 0; }
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1990 -- All Rights Reserved PROJECT: PC GEOS MODULE: Printer Drivers FILE: printcomNoText.asm AUTHOR: Dave Durran ROUTINES: REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 5/92 Initial version from parsed routines DESCRIPTION: $Id: printcomNoText.asm,v 1.1 97/04/18 11:50:12 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ include Text/textPrintRaw.asm PrintStyleRun proc far PrintText label far PrintSetFont label far PrintGetLineSpacing label far PrintSetLineSpacing label far clc ret PrintStyleRun endp PrintSetSymbolSet proc near PrintLoadSymbolSet label near clc ret PrintSetSymbolSet endp
#include "caffe2/core/logging.h" #include "caffe2/core/operator.h" #include "caffe2/onnx/backend.h" #include "caffe2/onnx/device.h" #include "caffe2/onnx/helper.h" #include "caffe2/utils/map_utils.h" #include "caffe2/utils/proto_utils.h" #ifndef C10_MOBILE #include "onnx/checker.h" #include "onnx/optimizer/optimize.h" #endif #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/io/zero_copy_stream_impl_lite.h" #include <cmath> #include <iostream> #include <limits> #include <sstream> #include <unordered_map> #include <unordered_set> namespace caffe2 { namespace onnx { namespace { bool AlmostEqual(double a, double b) { constexpr static double kEps = 1e-15; return (fabs(a - b) < kEps); } template <class T> bool TryConvertingTensorRawValues( const TensorProto& onnx_tensor, ::google::protobuf::RepeatedField<T>* field) { if (!onnx_tensor.has_raw_data()) { return false; } size_t raw_size = onnx_tensor.raw_data().size(); CAFFE_ENFORCE_EQ(raw_size % sizeof(T), 0); size_t num_elements = raw_size / sizeof(T); const void* src_ptr = static_cast<const void*>(onnx_tensor.raw_data().data()); field->Resize(num_elements, 0); void* target_ptr = static_cast<void*>(field->mutable_data()); memcpy(target_ptr, src_ptr, raw_size); return true; } bool IsOperator(const std::string& op_type) { // pull in all the operators upon first invocation // Intentional leaky static std::set<std::string>* ops_ = new std::set<std::string>(caffe2::GetRegisteredOperators()); return ops_->count(caffe2::OpRegistryKey(op_type, "DEFAULT")); } caffe2::DeviceOption GetDeviceOption(const Device& onnx_device) { static const std::unordered_map<DeviceType, caffe2::DeviceType> m = { {DeviceType::CPU, caffe2::DeviceType::CPU}, {DeviceType::CUDA, caffe2::DeviceType::CUDA}}; caffe2::DeviceOption d; d.set_device_type(static_cast<int32_t>(m.at(onnx_device.type))); d.set_device_id(onnx_device.device_id); return d; } #ifndef C10_MOBILE ModelProto OptimizeOnnx(const ModelProto& input, bool init) { std::vector<std::string> passes{"fuse_consecutive_transposes", "eliminate_nop_transpose", "fuse_transpose_into_gemm"}; if (init) { passes.emplace_back("split_init"); } else { passes.emplace_back("split_predict"); } return ::ONNX_NAMESPACE::optimization::Optimize(input, passes); } #endif template <class T, class U> U LookUpWithDefault( const std::unordered_map<T, U>& map, const T& key, const U& default_value) { const auto it = map.find(key); if (it == map.end()) { return default_value; } else { return it->second; } } void UpdateNames(std::shared_ptr<DummyName> dummy, const caffe2::OperatorDef& op) { for (const auto& n : op.input()) { dummy->AddName(n); } for (const auto& n : op.output()) { dummy->AddName(n); } } void BuildOperator( caffe2::OperatorDef* c2_op, const std::string& op_type, const std::vector<std::string>& inputs, const std::vector<std::string>& outputs, const std::vector<caffe2::Argument>& args) { c2_op->set_name(""); c2_op->set_type(op_type); for (const auto& input : inputs) { c2_op->add_input(input); } for (const auto& output : outputs) { c2_op->add_output(output); } for (const auto& arg : args) { auto* tmp = c2_op->add_arg(); tmp->CopyFrom(arg); } } void BuildOperator( caffe2::OperatorDef* c2_op, const std::string& op_type, const std::vector<std::string>& inputs, const std::vector<std::string>& outputs) { std::vector<caffe2::Argument> empty; BuildOperator(c2_op, op_type, inputs, outputs, empty); } void CopyOnnxAttrValueToCaffe2Arg( caffe2::Argument* arg, const AttributeProto& attr) { if (attr.has_f()) { arg->set_f(attr.f()); } else if (attr.has_i()) { arg->set_i(attr.i()); } else if (attr.has_s()) { arg->set_s(attr.s()); } else if (attr.has_t()) { // For proto, we convert it to serialized string std::string buffer; attr.t().SerializeToString(&buffer); arg->set_s(buffer); } else if (attr.floats_size()) { arg->mutable_floats()->CopyFrom(attr.floats()); } else if (attr.ints_size()) { arg->mutable_ints()->CopyFrom(attr.ints()); } else if (attr.strings_size()) { arg->mutable_strings()->CopyFrom(attr.strings()); } else { CAFFE_THROW("Unsupported ONNX attribute: ", attr.name()); } } } // namespace OnnxAttributes::OnnxAttributes(const NodeProto& node) { for (const auto& attr : node.attribute()) { onnx_attrs_.emplace(attr.name(), &attr); } } template <> int64_t OnnxAttributes::get(const std::string& key) const { int64_t value = 0; const auto it = onnx_attrs_.find(key); if (it != onnx_attrs_.end()) { const AttributeProto& attr = *it->second; value = attr.i(); } return value; } template <> float OnnxAttributes::get(const std::string& key) const { float value = 0.0; const auto it = onnx_attrs_.find(key); if (it != onnx_attrs_.end()) { const AttributeProto& attr = *it->second; value = attr.f(); } return value; } template <> ::google::protobuf::RepeatedPtrField<std::string> OnnxAttributes::get( const std::string& key) const { ::google::protobuf::RepeatedPtrField<std::string> value; const auto it = onnx_attrs_.find(key); if (it != onnx_attrs_.end()) { const AttributeProto& attr = *it->second; value.CopyFrom(attr.strings()); } return value; } template <> ::google::protobuf::RepeatedField<::google::protobuf::int64> OnnxAttributes::get(const std::string& key) const { ::google::protobuf::RepeatedField<::google::protobuf::int64> value; const auto it = onnx_attrs_.find(key); if (it != onnx_attrs_.end()) { const AttributeProto& attr = *it->second; value.CopyFrom(attr.ints()); } return value; } template <> ::google::protobuf::RepeatedField<float> OnnxAttributes::get(const std::string& key) const { ::google::protobuf::RepeatedField<float> value; const auto it = onnx_attrs_.find(key); if (it != onnx_attrs_.end()) { const AttributeProto& attr = *it->second; value.CopyFrom(attr.floats()); } return value; } template <> const TensorProto* OnnxAttributes::get(const std::string& key) const { const TensorProto* value = nullptr; const auto it = onnx_attrs_.find(key); if (it != onnx_attrs_.end()) { const AttributeProto& attr = *it->second; value = &attr.t(); } return value; } ::google::protobuf::RepeatedPtrField<caffe2::Argument> OnnxAttributes::OnnxAttrToCaffe2Arg( std::function<std::string(const std::string&)> mapper) const { ::google::protobuf::RepeatedPtrField<caffe2::Argument> args; for (const auto& kv : onnx_attrs_) { // If the attribute was rewritten, we use it instead. Note that the // rewritten attribute still has the unmapped name const auto& attr = rewritten_onnx_attrs_.count(kv.first) ? rewritten_onnx_attrs_.at(kv.first) : (*kv.second); auto* arg = args.Add(); arg->set_name(mapper(attr.name())); CopyOnnxAttrValueToCaffe2Arg(arg, attr); } for (const auto& kv : rewritten_onnx_attrs_) { // If rewritten attribute doesn't appear in the original attributes, this is // a newlly added one and we need to add this to argument too if (!onnx_attrs_.count(kv.first)) { const auto& attr = kv.second; auto* arg = args.Add(); arg->set_name(mapper(attr.name())); CopyOnnxAttrValueToCaffe2Arg(arg, attr); } } return args; } const std::unordered_map<std::string, int>& Caffe2Backend::get_broken_operators() const { const static std::unordered_map<std::string, int> kBrokenOperators{}; return kBrokenOperators; } // Temporary hack for RNN related operators, as we don't have C++ interface in // C2 to build those operators yet const std::unordered_set<std::string>& Caffe2Backend::get_rnn_operators() const { const static std::unordered_set<std::string> kRNNOperators{ "LSTM", "GRU", "RNN"}; return kRNNOperators; } // Operators that are different between Caffe2 and // ONNX but only in their name. // In most cases, this should be empty - as the effort of ONNX is // to unify the operator definitions. const std::unordered_map<std::string, std::string>& Caffe2Backend::get_renamed_operators() const { const static std::unordered_map<std::string, std::string> kRenamedOperators{ {"Caffe2ConvTranspose", "ConvTranspose"}, {"GlobalMaxPool", "MaxPool"}, {"GlobalAveragePool", "AveragePool"}, {"Pad", "PadImage"}, {"Neg", "Negative"}, {"BatchNormalization", "SpatialBN"}, {"InstanceNormalization", "InstanceNorm"}, {"MatMul", "BatchMatMul"}, {"Upsample", "ResizeNearest"}, {"Identity", "Copy"}, {"InstanceNormalization", "InstanceNorm"}, {"Equal", "EQ"}, {"Less", "LT"}, {"Greater", "GT"}, {"Unsqueeze", "ExpandDims"}, {"Tile", "NumpyTile"}, {"DynamicSlice", "Slice"}, {"ConstantOfShape", "ConstantFill"}, {"RandomNormal", "GaussianFill"}, {"RandomNormalLike", "GaussianFill"}}; return kRenamedOperators; } const std::unordered_map<std::string, std::string>& Caffe2Backend::get_renamed_attrs() const { const static std::unordered_map<std::string, std::string> kRenamedAttrs{ {"kernel_shape", "kernels"}}; return kRenamedAttrs; } const std:: unordered_map<std::string, std::unordered_map<std::string, std::string>>& Caffe2Backend::get_per_op_renamed_attrs() const { const static std:: unordered_map<std::string, std::unordered_map<std::string, std::string>> kPerOpRenamedAttrs = {{"Squeeze", {{"axes", "dims"}}}, {"Unsqueeze", {{"axes", "dims"}}}, {"Transpose", {{"perm", "axes"}}}, {"ConvTranspose", {{"output_padding", "adjs"}}}, {"Selu", {{"gamma", "scale"}}}}; return kPerOpRenamedAttrs; } // operators whose behavior is different beyond renaming // the value is an attribute of this class that is a // function from ToffeIR node_def to caffe2 op_def const std::unordered_map<std::string, Caffe2Backend::SpecialOpConverter>& Caffe2Backend::get_special_operators() const { const static std:: unordered_map<std::string, Caffe2Backend::SpecialOpConverter> kSpecialOperators = { {"ArgMax", &Caffe2Backend::CreateArgMaxMin}, {"ArgMin", &Caffe2Backend::CreateArgMaxMin}, {"Cast", &Caffe2Backend::CreateCast}, {"Constant", &Caffe2Backend::CreateConstant}, {"ConstantOfShape", &Caffe2Backend::CreateConstantOfShape}, {"Conv", &Caffe2Backend::CreateConvPoolOpBase}, {"AveragePool", &Caffe2Backend::CreateConvPoolOpBase}, {"GlobalAveragePool", &Caffe2Backend::CreateConvPoolOpBase}, {"GlobalMaxPool", &Caffe2Backend::CreateConvPoolOpBase}, {"MaxPool", &Caffe2Backend::CreateConvPoolOpBase}, {"Reshape", &Caffe2Backend::CreateReshape}, {"Int8Reshape", &Caffe2Backend::CreateReshape}, {"Gather", &Caffe2Backend::CreateGather}, {"Gemm", &Caffe2Backend::CreateGemm}, {"Pad", &Caffe2Backend::CreatePad}, {"Concat", &Caffe2Backend::CreateConcat}, {"Int8Concat", &Caffe2Backend::CreateConcat}, {"LogSoftmax", &Caffe2Backend::CreateLogSoftmax}, {"Slice", &Caffe2Backend::CreateSlice}, {"Split", &Caffe2Backend::CreateSplit}, {"Reciprocal", &Caffe2Backend::CreateReciprocal}, {"BatchNormalization", &Caffe2Backend::CreateBatchNormalization}, {"MatMul", &Caffe2Backend::CreateMatMul}, {"Upsample", &Caffe2Backend::CreateUpsample}, {"Dropout", &Caffe2Backend::CreateDropout}, {"LRN", &Caffe2Backend::CreateLRN}, {"DynamicSlice", &Caffe2Backend::CreateDynamicSlice}, {"RandomNormal", &Caffe2Backend::CreateRandomNormal}, {"RandomNormalLike", &Caffe2Backend::CreateRandomNormal}, {"Where", &Caffe2Backend::CreateWhereOp}, {"NonZero", &Caffe2Backend::CreateNonZeroOp}, {"Multinomial", &Caffe2Backend::CreateMultinomialOp}}; return kSpecialOperators; } //============================ // Special Operator Converters //============================ Caffe2Ops Caffe2Backend::CreateArgMaxMin( OnnxNode* onnx_node, const ConversionContext& ctx) { auto& attributes = onnx_node->attributes; if (!attributes.HasAttribute("axis")) { auto* attr = attributes.AddRewrittenAttribute("axis"); attr->set_i(0); } return CommonOnnxNodeToCaffe2Ops(onnx_node, ctx); } Caffe2Ops Caffe2Backend::CreateCast( OnnxNode* onnx_node, const ConversionContext& ctx) { auto c2_op = CommonOnnxNodeToCaffe2Ops(onnx_node, ctx); auto onnx_dtype = onnx_node->attributes.get<int64_t>("to", TensorProto::UNDEFINED); auto c2_dtype = caffe2::TensorProto::UNDEFINED; switch (onnx_dtype) { case ::ONNX_NAMESPACE::TensorProto::FLOAT: c2_dtype = caffe2::TensorProto::FLOAT; break; case ::ONNX_NAMESPACE::TensorProto::UINT8: c2_dtype = caffe2::TensorProto::UINT8; break; case ::ONNX_NAMESPACE::TensorProto::INT8: c2_dtype = caffe2::TensorProto::INT8; break; case ::ONNX_NAMESPACE::TensorProto::UINT16: c2_dtype = caffe2::TensorProto::UINT16; break; case ::ONNX_NAMESPACE::TensorProto::INT16: c2_dtype = caffe2::TensorProto::INT16; break; case ::ONNX_NAMESPACE::TensorProto::INT32: c2_dtype = caffe2::TensorProto::INT32; break; case ::ONNX_NAMESPACE::TensorProto::INT64: c2_dtype = caffe2::TensorProto::INT64; break; case ::ONNX_NAMESPACE::TensorProto::STRING: c2_dtype = caffe2::TensorProto::STRING; break; case ::ONNX_NAMESPACE::TensorProto::BOOL: c2_dtype = caffe2::TensorProto::BOOL; break; case ::ONNX_NAMESPACE::TensorProto::FLOAT16: c2_dtype = caffe2::TensorProto::FLOAT16; break; case ::ONNX_NAMESPACE::TensorProto::DOUBLE: c2_dtype = caffe2::TensorProto::DOUBLE; break; case ::ONNX_NAMESPACE::TensorProto::UINT32: case ::ONNX_NAMESPACE::TensorProto::UINT64: case ::ONNX_NAMESPACE::TensorProto::COMPLEX64: case ::ONNX_NAMESPACE::TensorProto::COMPLEX128: case ::ONNX_NAMESPACE::TensorProto::UNDEFINED: c2_dtype = caffe2::TensorProto::UNDEFINED; break; }; CAFFE_ENFORCE_NE( c2_dtype, caffe2::TensorProto::UNDEFINED, "Casting to '", onnx_dtype, "' dtype is not supported"); CAFFE_ENFORCE_EQ( c2_op.ops.Get(0).arg().size(), 1, "Unexpected number of attributes in 'Cast'"); c2_op.ops.Mutable(0)->mutable_arg(0)->set_i(c2_dtype); return c2_op; } Caffe2Ops Caffe2Backend::CreateConstant( OnnxNode* onnx_node, const ConversionContext& ctx) { CAFFE_ENFORCE_EQ(onnx_node->node.output_size(), 1); Caffe2Ops ret; auto* c2_op = ret.ops.Add(); const auto* value = onnx_node->attributes.get<const TensorProto*>("value"); BuildTensorFillingOp(c2_op, *value, onnx_node->node.output(0)); return ret; } Caffe2Ops Caffe2Backend::CreateConstantOfShape( OnnxNode* onnx_node, const ConversionContext& ctx) { CAFFE_ENFORCE_EQ(onnx_node->node.input_size(), 1); CAFFE_ENFORCE_EQ(onnx_node->node.output_size(), 1); Caffe2Ops ret; auto* c2_op = ret.ops.Add(); const auto* value = onnx_node->attributes.get<const TensorProto*>("value"); if (value) { BuildTensorFillingOp(c2_op, *value, onnx_node->node.output(0), onnx_node->node.input(0)); } else { c2_op->set_type("ConstantFill"); c2_op->add_input(onnx_node->node.input(0)); c2_op->add_output(onnx_node->node.output(0)); auto c2_input_as_shape = c2_op->add_arg(); c2_input_as_shape->set_name("input_as_shape"); c2_input_as_shape->set_i(1); } return ret; } // Note [Caffe2 ConvPoolOpBase] // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // To understand what is going on here, we have to talk a little bit about // Caffe2's internals. // // First, it's important to know that all of Caffe2's pooling and convolution // operators inherit from "ConvPoolOpBase", which is an abstract class that // defines all of the attributes (kernels, dilations, strides, etc) which one // sees on these operators. Unfortunately, Caffe2's documentation generator // doesn't know how to handle cases like this, so for example, if you look at // the docs for MaxPool at // <https://caffe2.ai/docs/operators-catalogue.html#maxpool> you won't see any // of the attributes. You have to go source diving to find the information; in // particular, you want to look at: // https://github.com/caffe2/caffe2/blob/master/caffe2/operators/conv_pool_op_base.h // This class handles *global* pooling as well. // // Second, it's important to know what Caffe2 expects for padding, which can // be somewhat difficult to understand from the code because Caffe2 handles // both singular/pluralized spellings of padding, and there is also legacy // padding business. The short version of the story is that, for NON-legacy // padding (which is what we want to output), padding is expected to be // *twice* the size of kernels. So if you have a 2D convolution, Caffe2 // will accept two values in 'kernels', but FOUR values in 'pads'; // furthermore, this is *mandatory.* // // Finally, ConvPoolOpBase is not the only class of it's kind; there is // be tricked by the fact that Conv and ConvTranspose have similar // parameters; they exercise different codepaths and need to be handled // differently. Caffe2Ops Caffe2Backend::CreateConvPoolOpBase( OnnxNode* onnx_node, const ConversionContext& ctx) { const auto& node = onnx_node->node; auto& attributes = onnx_node->attributes; if (node.op_type().find("Global") == 0) { auto* attr = attributes.AddRewrittenAttribute("global_pooling"); attr->set_i(1); } if (attributes.HasAttribute("kernel_shape") && attributes.HasAttribute("pads")) { auto kernel_shape = attributes .get<::google::protobuf::RepeatedField<::google::protobuf::int64>>( "kernel_shape"); auto pads = attributes .get<::google::protobuf::RepeatedField<::google::protobuf::int64>>( "pads"); if (kernel_shape.size() == pads.size()) { // Caffe2 requires pads to be twice the size of kernels. auto* attr = attributes.AddRewrittenAttribute("pads"); attr->mutable_ints()->CopyFrom(pads); attr->mutable_ints()->MergeFrom(pads); } } return CommonOnnxNodeToCaffe2Ops(onnx_node, ctx); } Caffe2Ops Caffe2Backend::CreateReshape( OnnxNode* onnx_node, const ConversionContext& ctx) { auto c2_op = CommonOnnxNodeToCaffe2Ops(onnx_node, ctx); CAFFE_ENFORCE_EQ(c2_op.ops.size(), 1); auto* op = c2_op.ops.Mutable(0); op->add_output(dummy_->NewDummyName()); return c2_op; } Caffe2Ops Caffe2Backend::CreateRandomNormal( OnnxNode* onnx_node, const ConversionContext& ctx) { auto& attributes = onnx_node->attributes; if (attributes.HasAttribute("seed")) { CAFFE_THROW("Caffe2 GaussianFill does not support random seed"); } if (attributes.HasAttribute("dtype")) { if (attributes.get<int64_t>("dtype") != TensorProto::FLOAT) { CAFFE_THROW("Caffe2 GaussianFill only support FLOAT dtype"); } attributes.remove("dtype"); } if (attributes.HasAttribute("scale")) { auto scale = attributes.get<float>("scale"); auto* attr = attributes.AddRewrittenAttribute("std"); attr->set_f(scale); attributes.remove("scale"); } return CommonOnnxNodeToCaffe2Ops(onnx_node, ctx); } Caffe2Ops Caffe2Backend::CreateWhereOp( OnnxNode* onnx_node, const ConversionContext& ctx) { // The native Caffe2 op doesn't support broadcasting, so we defer the handling // of this op to the ATen library that does. onnx::NodeProto converted; converted.CopyFrom(onnx_node->node); converted.set_op_type("ATen"); onnx::AttributeProto* attr = converted.add_attribute(); attr->set_name("operator"); attr->set_s("where"); OnnxNode new_node(converted); return CommonOnnxNodeToCaffe2Ops(&new_node, ctx); } Caffe2Ops Caffe2Backend::CreateNonZeroOp( OnnxNode* onnx_node, const ConversionContext& ctx) { // Native Caffe2 doesn't support NonZero, fallback to ATen. // ATen nonzero is equivalent to Transpose(ONNX::NonZero). onnx::NodeProto converted; converted.CopyFrom(onnx_node->node); auto nonzero_output = dummy_->NewDummyName(); converted.set_output(0, nonzero_output); converted.set_op_type("ATen"); onnx::AttributeProto* attr = converted.add_attribute(); attr->set_name("operator"); attr->set_s("nonzero"); OnnxNode new_node(converted); auto ret = CommonOnnxNodeToCaffe2Ops(&new_node, ctx); auto* c2_transpose = ret.ops.Add(); BuildOperator(c2_transpose, "Transpose", {nonzero_output}, {onnx_node->node.output(0)}); return ret; } Caffe2Ops Caffe2Backend::CreateMultinomialOp( OnnxNode* onnx_node, const ConversionContext& ctx) { // Fallback to ATen. // ATen::Multinomial takes probabilities as input, ONNX Multinomial expects input to be log probabilities. Caffe2Ops ret; auto c2_exp_output = dummy_->NewDummyName(); auto* c2_exp = ret.ops.Add(); BuildOperator(c2_exp, "Exp", {onnx_node->node.input(0)}, {c2_exp_output}); auto* c2_multinomial = ret.ops.Add(); caffe2::Argument c2_arg_op; c2_arg_op.set_name("operator"); c2_arg_op.set_s("multinomial"); // ONNX Multinomial only supports replacement=True. caffe2::Argument c2_arg_rep; c2_arg_rep.set_name("replacement"); c2_arg_rep.set_i(1); auto& onnx_attributes = onnx_node->attributes; caffe2::Argument c2_arg_num; c2_arg_num.set_name("num_samples"); c2_arg_num.set_i(onnx_attributes.get<int64_t>("sample_size")); // ONNX Multinomial has attribute dtype in {int64, int32}, which specifies output datatype. // ATen::Multinomial output dtype is always int64. auto onnx_dtype = onnx_attributes.get<int64_t>("dtype", TensorProto::UNDEFINED); if (onnx_dtype == ::ONNX_NAMESPACE::TensorProto::INT64) { BuildOperator( c2_multinomial, "ATen", {c2_exp_output}, {onnx_node->node.output(0)}, {c2_arg_op, c2_arg_rep, c2_arg_num}); } else if (onnx_dtype == ::ONNX_NAMESPACE::TensorProto::INT32) { auto c2_multinomial_output = dummy_->NewDummyName(); BuildOperator( c2_multinomial, "ATen", {c2_exp_output}, {c2_multinomial_output}, {c2_arg_op, c2_arg_rep, c2_arg_num}); auto* c2_cast = ret.ops.Add(); caffe2::Argument to; to.set_name("to"); to.set_i(caffe2::TensorProto::INT32); BuildOperator(c2_cast, "Cast", {c2_multinomial_output}, {onnx_node->node.output(0)}, {to}); } else { CAFFE_THROW("ONNX does not support dtype other than int32/int64 in Multinomial, but get ", onnx_dtype); } return ret; } Caffe2Ops Caffe2Backend::CreateReciprocal( OnnxNode* onnx_node, const ConversionContext& ctx) { const auto& node = onnx_node->node; if (node.input_size() != 1 || node.output_size() != 1) { CAFFE_THROW("Caffe2 Reciprocal should have 1 input and 1 output"); } Caffe2Ops ret; auto* c2_op = ret.ops.Add(); caffe2::Argument exponent; exponent.set_name("exponent"); exponent.set_f(-1.0); BuildOperator(c2_op, "Pow", {node.input(0)}, {node.output(0)}, {exponent}); return ret; } Caffe2Ops Caffe2Backend::CreateGather( OnnxNode* onnx_node, const ConversionContext& ctx) { const auto& node = onnx_node->node; if (node.input_size() < 2 || node.output_size() < 1) { CAFFE_THROW("Caffe2 Gather should have 2 inputs and 1 output"); } Caffe2Ops ret; auto* c2_op = ret.ops.Add(); std::vector<std::string> inputs; inputs.emplace_back(node.input(0)); inputs.emplace_back(node.input(1)); std::vector<std::string> outputs; outputs.emplace_back(node.output(0)); auto axis = onnx_node->attributes.get<int64_t>("axis", 0L); if (axis == 0) { BuildOperator(c2_op, "Gather", inputs, outputs); } else if (axis == 1) { BuildOperator(c2_op, "BatchGather", inputs, outputs); } else { CAFFE_THROW( "Caffe2 only supports Gather with axis being 0 or 1, ", "whereas axis is ", axis); } return ret; } Caffe2Ops Caffe2Backend::CreateGemm( OnnxNode* onnx_node, const ConversionContext& ctx) { const auto& node = onnx_node->node; if (node.input_size() < 3 || node.output_size() < 1) { CAFFE_THROW("Caffe2 Gemm should have 3 inputs and 1 output"); } Caffe2Ops ret; auto input_a = node.input(0); auto input_b = node.input(1); auto input_c = node.input(2); auto output = node.output(0); auto alpha = onnx_node->attributes.get<float>("alpha", 1.0); auto beta = onnx_node->attributes.get<float>("beta", 1.0); if (!AlmostEqual(alpha, 1)) { auto scaled_a = dummy_->NewDummyName(); caffe2::Argument scale; scale.set_name("scale"); scale.set_f(alpha); auto* c2_op = ret.ops.Add(); BuildOperator(c2_op, "Scale", {input_a}, {scaled_a}, {scale}); input_a = scaled_a; } if (!AlmostEqual(beta, 1)) { auto scaled_c = dummy_->NewDummyName(); caffe2::Argument scale; scale.set_name("scale"); scale.set_f(beta); auto* c2_op = ret.ops.Add(); BuildOperator(c2_op, "Scale", {input_c}, {scaled_c}, {scale}); input_c = scaled_c; } auto trans_a = onnx_node->attributes.get<int64_t>("transA", 0L); auto trans_b = onnx_node->attributes.get<int64_t>("transB", 0L); // Support broadcast by default when opset_version > 6. auto broadcast = onnx_node->attributes.get<int64_t>("broadcast", (ctx.opset_version() > 6) ? 1L : 0L); // If the c's shape information is available and c is a 1d tensor(except // c is a scalar), use FC aggressively. auto check_fc = [&]() -> bool { const auto input_c_vi_iter = ctx.value_infos().find(node.input(2)); if (input_c_vi_iter == ctx.value_infos().end()) { return false; } const auto input_c_shape = input_c_vi_iter->second.type().tensor_type().shape(); if (input_c_shape.dim_size() != 1) { return false; } // c is a scalar. if (input_c_shape.dim(0).dim_value() == 1) { const auto input_b_vi_iter = ctx.value_infos().find(node.input(1)); // If the b's shape is not available, skip FC. if (input_b_vi_iter == ctx.value_infos().end()) { return false; } const auto input_b_shape = input_b_vi_iter->second.type().tensor_type().shape(); int input_b_last_dim_index = (trans_b) ? 0 : 1; // If b's last dim is not 1, skip FC. if (input_b_shape.dim_size() <= input_b_last_dim_index || input_b_shape.dim(input_b_last_dim_index).dim_value() != 1) { return false; } } return true; }; if (!trans_a && broadcast && check_fc()) { auto* c2_op = ret.ops.Add(); if (trans_b) { BuildOperator(c2_op, "FC", {input_a, input_b, input_c}, {output}); } else { BuildOperator(c2_op, "FCTransposed", {input_a, input_b, input_c}, {output}); } } else { auto ab = dummy_->NewDummyName(); caffe2::Argument arg_trans_a; arg_trans_a.set_name("trans_a"); arg_trans_a.set_i(trans_a); caffe2::Argument arg_trans_b; arg_trans_b.set_name("trans_b"); arg_trans_b.set_i(trans_b); auto* c2_op = ret.ops.Add(); BuildOperator( c2_op, "MatMul", {input_a, input_b}, {ab}, {arg_trans_a, arg_trans_b}); c2_op = ret.ops.Add(); if (ctx.opset_version() >= 7) { BuildOperator(c2_op, "Add", {ab, input_c}, {output}); } else { caffe2::Argument arg_broadcast; arg_broadcast.set_name("broadcast"); arg_broadcast.set_i(broadcast); BuildOperator(c2_op, "Add", {ab, input_c}, {output}, {arg_broadcast}); } } return ret; } Caffe2Ops Caffe2Backend::CreatePad( OnnxNode* onnx_node, const ConversionContext& ctx) { auto& attributes = onnx_node->attributes; ::google::protobuf::RepeatedField<::google::protobuf::int64> pads; std::string pad_name = ctx.opset_version() < 2 ? "paddings" : "pads"; pads = attributes .get<::google::protobuf::RepeatedField<::google::protobuf::int64>>( pad_name); std::string str; std::stringstream ss; ss << "["; for (const auto& i : pads) { ss << i << ", "; } ss << "]"; str = ss.str(); // Guard the invalid (negative) pads attribute. for (const auto i : pads) { if (i < 0) { CAFFE_THROW("ONNX does not support negative pads in Pad, but get ", str); } } // first two dim is for batch and channel. Note that now all the values are // non-negative if (!(pads.size() == 8 && (pads.Get(0) + pads.Get(1) + pads.Get(4) + pads.Get(5) == 0))) { CAFFE_THROW( "Caffe2 only supports padding 2D Tensor, whereas padding is ", str); } // rewrite the padding info auto* attr = attributes.AddRewrittenAttribute(pad_name); attr->add_ints(pads.Get(2)); attr->add_ints(pads.Get(3)); attr->add_ints(pads.Get(6)); attr->add_ints(pads.Get(7)); return CommonOnnxNodeToCaffe2Ops(onnx_node, ctx); } // TODO: Caffe2 Concat has an extra output. It should be only // used when doing training, so we should change Caffe2 to allow // 1 output. Caffe2Ops Caffe2Backend::CreateConcat( OnnxNode* onnx_node, const ConversionContext& ctx) { auto c2_op = CommonOnnxNodeToCaffe2Ops(onnx_node, ctx); CAFFE_ENFORCE_EQ(c2_op.ops.size(), 1); auto* op = c2_op.ops.Mutable(0); op->add_output(dummy_->NewDummyName()); return c2_op; } Caffe2Ops Caffe2Backend::CreateLogSoftmax( OnnxNode* onnx_node, const ConversionContext& ctx) { const auto& node = onnx_node->node; if (node.input_size() < 1 || node.output_size() < 1) { CAFFE_THROW("LogSoftmax should have 1 input and 1 output"); } auto axis = onnx_node->attributes.get<int64_t>("axis", 1L); caffe2::Argument arg_axis; arg_axis.set_name("axis"); arg_axis.set_i(axis); auto softmax_a = dummy_->NewDummyName(); Caffe2Ops ret; auto* c2_op = ret.ops.Add(); BuildOperator(c2_op, "Softmax", {node.input(0)}, {softmax_a}, {arg_axis}); c2_op = ret.ops.Add(); BuildOperator(c2_op, "Log", {softmax_a}, {node.output(0)}); return ret; } Caffe2Ops Caffe2Backend::CreateSlice( OnnxNode* onnx_node, const ConversionContext& ctx) { auto op_tmp = CommonOnnxNodeToCaffe2Ops(onnx_node, ctx); CAFFE_ENFORCE_EQ(op_tmp.ops.size(), 1); auto* op = op_tmp.ops.Mutable(0); std::unordered_map<std::string, caffe2::Argument*> args; for (auto& arg : *op->mutable_arg()) { args.emplace(arg.name(), &arg); } caffe2::Argument starts_vals; starts_vals.set_name("values"); auto pos = args.find("starts"); if (pos != args.end()) { for (auto i : pos->second->ints()) { starts_vals.add_ints(i < 0 ? i - 1 : i); } args.erase(pos); } caffe2::Argument ends_vals; ends_vals.set_name("values"); pos = args.find("ends"); if (pos != args.end()) { for (auto i : pos->second->ints()) { if (i == std::numeric_limits<int64_t>::max()) { ends_vals.add_ints(-1); } else { ends_vals.add_ints(i < 0 ? i - 1 : i); } } args.erase(pos); } caffe2::Argument axes_vals; axes_vals.set_name("values"); pos = args.find("axes"); if (pos != args.end()) { for (auto i : pos->second->ints()) { axes_vals.add_ints(i); } args.erase(pos); } else { auto ndim = starts_vals.ints_size(); for (int64_t i = 0; i < ndim; ++i) { axes_vals.add_ints(i); } } CAFFE_ENFORCE_GE(op->input_size(), 1); auto data = op->input(0); auto shape_tensor = dummy_->NewDummyName(); Caffe2Ops ret; auto* c2_op = ret.ops.Add(); BuildOperator(c2_op, "Shape", {data}, {shape_tensor}); auto axes_tensor = dummy_->NewDummyName(); c2_op = ret.ops.Add(); { caffe2::Argument shape; shape.set_name("shape"); shape.add_ints(axes_vals.ints_size()); BuildOperator( c2_op, "GivenTensorIntFill", {}, {axes_tensor}, {shape, axes_vals}); } auto starts_vals_tensor = dummy_->NewDummyName(); auto starts_tensor = dummy_->NewDummyName(); c2_op = ret.ops.Add(); { caffe2::Argument shape_starts; shape_starts.set_name("shape"); shape_starts.add_ints(starts_vals.ints_size()); BuildOperator( c2_op, "GivenTensorInt64Fill", {}, {starts_vals_tensor}, {shape_starts, starts_vals}); } caffe2::Argument dtype; dtype.set_name("dtype"); dtype.set_i(static_cast<int64_t>(caffe2::TensorProto::INT64)); caffe2::Argument constant; constant.set_name("value"); constant.set_i(0); c2_op = ret.ops.Add(); BuildOperator( c2_op, "ConstantFill", {shape_tensor}, {starts_tensor}, {dtype, constant}); c2_op = ret.ops.Add(); BuildOperator( c2_op, "ScatterAssign", {starts_tensor, axes_tensor, starts_vals_tensor}, {starts_tensor}); // Slice only accepts starts as int caffe2::Argument to; to.set_name("to"); to.set_i(static_cast<int64_t>(caffe2::TensorProto::INT32)); auto ends_vals_tensor = dummy_->NewDummyName(); auto ends_tensor = dummy_->NewDummyName(); c2_op = ret.ops.Add(); { caffe2::Argument shape_ends; shape_ends.set_name("shape"); shape_ends.add_ints(ends_vals.ints_size()); BuildOperator( c2_op, "GivenTensorInt64Fill", {}, {ends_vals_tensor}, {shape_ends, ends_vals}); } constant.set_i(-1); c2_op = ret.ops.Add(); BuildOperator( c2_op, "ConstantFill", {shape_tensor}, {ends_tensor}, {dtype, constant}); c2_op = ret.ops.Add(); BuildOperator( c2_op, "ScatterAssign", {ends_tensor, axes_tensor, ends_vals_tensor}, {ends_tensor}); // attach the original op at the end c2_op = ret.ops.Add(); c2_op->CopyFrom(*op); c2_op->mutable_input()->Clear(); c2_op->add_input(data); c2_op->add_input(starts_tensor); c2_op->add_input(ends_tensor); c2_op->mutable_arg()->Clear(); for (const auto& kv : args) { c2_op->add_arg()->CopyFrom(*kv.second); } return ret; } // Do the following: // for a given index tensor (i.e. `starts` or `ends`): // 1) Hilariously subtract 1 from the value if it is negative. This due to // the behavior of Caffe2's slice operator not matching that of ONNX's slice // 2) Fully expand the index tensor out to the rank of the data tensor. // pseudocode: indices_full = zeros(rank); indices_full[axes] = indices.int() std::string Caffe2Backend::PreprocessSliceIndexTensor(OnnxNode* onnx_node, Caffe2Ops& ret, std::string indices_tensor, std::string axes_tensor, std::string rank_tensor, std::string zero_tensor, std::string one_tensor, int default_value) { auto indices_tensor_full = dummy_->NewDummyName(); { caffe2::Argument value; value.set_name("value"); value.set_i(default_value); caffe2::Argument dtype; dtype.set_name("dtype"); dtype.set_i(static_cast<int64_t>(caffe2::TensorProto::INT64)); caffe2::Argument input_as_shape; input_as_shape.set_name("input_as_shape"); input_as_shape.set_i(1); auto c2_op = ret.ops.Add(); BuildOperator(c2_op, "ConstantFill", {rank_tensor}, {indices_tensor_full}, {value, dtype, input_as_shape}); } // Subtract 1 from each element of the indices tensor that is negative auto lt_tensor = dummy_->NewDummyName(); { caffe2::Argument broadcast; broadcast.set_name("broadcast"); broadcast.set_i(1); auto c2_op = ret.ops.Add(); BuildOperator(c2_op, "LT", {indices_tensor, zero_tensor}, {lt_tensor}, {broadcast}); } auto sub_one_tensor = dummy_->NewDummyName(); { caffe2::Argument broadcast; broadcast.set_name("broadcast"); broadcast.set_i(1); auto c2_op = ret.ops.Add(); BuildOperator(c2_op, "Sub", {indices_tensor, one_tensor}, {sub_one_tensor}, {broadcast}); } auto indices_tensor_adjusted = dummy_->NewDummyName(); auto c2_op = ret.ops.Add(); BuildOperator(c2_op, "Conditional", {lt_tensor, sub_one_tensor, indices_tensor}, {indices_tensor_adjusted}, {}); // Fill in values specified from the partially-specified ONNX indices tensor c2_op = ret.ops.Add(); BuildOperator(c2_op, "ScatterAssign", {indices_tensor_full, axes_tensor, indices_tensor_adjusted}, {indices_tensor_full}); return indices_tensor_full; } Caffe2Ops Caffe2Backend::CreateDynamicSlice( OnnxNode* onnx_node, const ConversionContext& ctx) { auto op_tmp = CommonOnnxNodeToCaffe2Ops(onnx_node, ctx); CAFFE_ENFORCE_EQ(op_tmp.ops.size(), 1); auto* op = op_tmp.ops.Mutable(0); std::unordered_map<std::string, caffe2::Argument*> args; for (auto& arg : *op->mutable_arg()) { args.emplace(arg.name(), &arg); } CAFFE_ENFORCE_GE(op->input_size(), 1); auto data = op->input(0); Caffe2Ops ret; // First get the shape of the input tensor auto* c2_op = ret.ops.Add(); auto size_tensor = dummy_->NewDummyName(); BuildOperator(c2_op, "Shape", {data}, {size_tensor}); // Now get the rank of the tensor by getting the shape of the shape of // the input tensor c2_op = ret.ops.Add(); auto rank_tensor = dummy_->NewDummyName(); BuildOperator(c2_op, "Shape", {size_tensor}, {rank_tensor}); // Axes tensor will be used to populate the fully-specified starts and ends // arguments to the caffe2 Slice operator. std::string axes_tensor; if (onnx_node->node.input_size() > 3) { axes_tensor = onnx_node->node.input(3); } else { axes_tensor = dummy_->NewDummyName(); auto* c2_op = ret.ops.Add(); BuildOperator(c2_op, "Range", {rank_tensor}, {axes_tensor}, {}); } // Useful int tensors auto define_integer_constant = [this, &ret](int val) { caffe2::Argument value; value.set_name("value"); value.set_i(val); caffe2::Argument dtype; dtype.set_name("dtype"); dtype.set_i(static_cast<int64_t>(caffe2::TensorProto::INT64)); caffe2::Argument shape; shape.set_name("shape"); shape.add_ints(1); auto c2_op = ret.ops.Add(); auto name = dummy_->NewDummyName(); BuildOperator(c2_op, "ConstantFill", {}, {name}, {value, dtype, shape}); return name; }; auto zero_tensor = define_integer_constant(0); auto one_tensor = define_integer_constant(1); auto starts_tensor_full = PreprocessSliceIndexTensor(onnx_node, ret, onnx_node->node.input(1), // starts axes_tensor, rank_tensor, zero_tensor, one_tensor, 0); auto ends_tensor_full = PreprocessSliceIndexTensor(onnx_node, ret, onnx_node->node.input(2), // ends axes_tensor, rank_tensor, zero_tensor, one_tensor, -1); // attach the original op at the end c2_op = ret.ops.Add(); c2_op->CopyFrom(*op); c2_op->mutable_input()->Clear(); c2_op->add_input(data); c2_op->add_input(starts_tensor_full); c2_op->add_input(ends_tensor_full); c2_op->mutable_arg()->Clear(); for (const auto& kv : args) { c2_op->add_arg()->CopyFrom(*kv.second); } return ret; } Caffe2Ops Caffe2Backend::CreateBatchNormalization( OnnxNode* onnx_node, const ConversionContext& ctx) { auto& attributes = onnx_node->attributes; if (ctx.opset_version() < 6) { attributes.remove("consumed_inputs"); } if (ctx.opset_version() >= 7) { auto* attr = attributes.AddRewrittenAttribute("is_test"); attr->set_i(1); } if (attributes.HasAttribute("spatial") && attributes.get<int64_t>("spatial") == 1) { attributes.remove("spatial"); } return CommonOnnxNodeToCaffe2Ops(onnx_node, ctx); } Caffe2Ops Caffe2Backend::CreateSplit( OnnxNode* onnx_node, const ConversionContext& ctx) { auto& attributes = onnx_node->attributes; if (!attributes.HasAttribute("axis")) { auto* attr = attributes.AddRewrittenAttribute("axis"); attr->set_i(0); } return CommonOnnxNodeToCaffe2Ops(onnx_node, ctx); } Caffe2Ops Caffe2Backend::CreateMatMul( OnnxNode* onnx_node, const ConversionContext& ctx) { const auto& node = onnx_node->node; if (node.input_size() != 2) { CAFFE_THROW("MatMul should have 2 inputs"); } auto c2_op = CommonOnnxNodeToCaffe2Ops(onnx_node, ctx); CAFFE_ENFORCE_EQ(c2_op.ops.size(), 1); auto* op = c2_op.ops.Mutable(0); auto* broadcast_arg = op->add_arg(); broadcast_arg->set_name("broadcast"); broadcast_arg->set_i(1); return c2_op; } Caffe2Ops Caffe2Backend::CreateUpsample( OnnxNode* onnx_node, const ConversionContext& ctx) { auto& attributes = onnx_node->attributes; attributes.remove("mode"); if (ctx.opset_version() >= 7 && ctx.opset_version() < 9) { const auto& scales = attributes.get<::google::protobuf::RepeatedField<float>>("scales"); if (scales.size() != 4) { CAFFE_THROW("The scales argument should have size 4"); } else if (!AlmostEqual(scales.Get(0), 1) || !AlmostEqual(scales.Get(1), 1)) { CAFFE_THROW("The first two elements in the scales argument must be 1"); } attributes.remove("scales"); auto c2_op = CommonOnnxNodeToCaffe2Ops(onnx_node, ctx); auto* op = c2_op.ops.Mutable(0); auto* c2_height = op->add_arg(); c2_height->set_name("height_scale"); c2_height->set_f(scales.Get(2)); auto* c2_width = op->add_arg(); c2_width->set_name("width_scale"); c2_width->set_f(scales.Get(3)); return c2_op; } else if (ctx.opset_version() >= 9) { const auto& node = onnx_node->node; if (node.input_size() != 2) { CAFFE_THROW("Expects 2 input in upsample after onnx version 9"); } Caffe2Ops ret; // Slice the input {1, 1, height, width} -> {height, width} auto* c2_op = ret.ops.Add(); auto sliced_input = dummy_->NewDummyName(); caffe2::Argument arg_starts, arg_ends; arg_starts.set_name("starts"); arg_starts.add_ints(2); arg_ends.set_name("ends"); arg_ends.add_ints(-1); BuildOperator( c2_op, "Slice", {node.input(1)}, {sliced_input}, {arg_starts, arg_ends}); // Upsample c2_op = ret.ops.Add(); BuildOperator( c2_op, "ResizeNearest", {node.input(0), sliced_input}, {node.output(0)}, {}); return ret; } return CommonOnnxNodeToCaffe2Ops(onnx_node, ctx); } Caffe2Ops Caffe2Backend::CreateDropout( OnnxNode* onnx_node, const ConversionContext& ctx) { if (ctx.opset_version() >= 7) { auto& attributes = onnx_node->attributes; auto* attr = attributes.AddRewrittenAttribute("is_test"); attr->set_i(1); } return CommonOnnxNodeToCaffe2Ops(onnx_node, ctx); } Caffe2Ops Caffe2Backend::CreateLRN( OnnxNode* onnx_node, const ConversionContext& ctx) { auto c2_op = CommonOnnxNodeToCaffe2Ops(onnx_node, ctx); const auto& attributes = onnx_node->attributes; if (!attributes.HasAttribute("alpha")) { auto* arg = c2_op.ops.Mutable(0)->add_arg(); arg->set_name("alpha"); arg->set_f(1e-4); } if (!attributes.HasAttribute("beta")) { auto* arg = c2_op.ops.Mutable(0)->add_arg(); arg->set_name("beta"); arg->set_f(0.75); } return c2_op; } //============================================== // Rest of the member functions for Caffe2Backend //============================================== std::unordered_set<std::string> Caffe2Backend::AllNamesInGraph(const GraphProto &graph) { std::unordered_set<std::string> names; for (const auto& input : graph.input()) { names.emplace(input.name()); } for (const auto& output : graph.output()) { names.emplace(output.name()); } for (const auto& node : graph.node()) { for (const auto& n : node.input()) { names.emplace(n); } for (const auto& n : node.output()) { names.emplace(n); } } return names; } // This translator performs the basic translation of ONNX nodes into // Caffe2 operators. Besides doing a straightforward marshalling from // one format to another, it also does these extra things: // // - Renames operators based on 'renamed_operators' // - Renames attributes based on 'renamed_attrs' and // 'get_per_op_renamed_attrs' // // If you're writing a custom translator, consider calling this first, // and then fixing things up further. Caffe2Ops Caffe2Backend::CommonOnnxNodeToCaffe2Ops( OnnxNode* onnx_node, const ConversionContext& ctx) { Caffe2Ops ret; auto* c2_op = ret.ops.Add(); const auto& node = onnx_node->node; c2_op->mutable_input()->MergeFrom(node.input()); c2_op->mutable_output()->MergeFrom(node.output()); c2_op->set_name(node.name()); const auto onnx_op_type = node.op_type(); auto broken_version = caffe2::get_default( get_broken_operators(), onnx_op_type, std::numeric_limits<int>::max()); if (broken_version <= ctx.opset_version()) { CAFFE_THROW( "Don't know how to translate op ", onnx_op_type, " in ONNX operator set v", ctx.opset_version(), " (I only support prior to v", broken_version); } c2_op->set_type( caffe2::get_default(get_renamed_operators(), onnx_op_type, onnx_op_type)); if (!IsOperator(c2_op->type())) { CAFFE_THROW( "Don't know how to translate op ", onnx_op_type); } auto mapper = [&, this](const std::string& k) { const auto it = get_per_op_renamed_attrs().find(onnx_op_type); if (it != get_per_op_renamed_attrs().end()) { const auto it_op = it->second.find(k); if (it_op != it->second.end()) { return it_op->second; } } const auto it_global = get_renamed_attrs().find(k); if (it_global != get_renamed_attrs().end()) { return it_global->second; } return k; }; c2_op->mutable_arg()->MergeFrom( onnx_node->attributes.OnnxAttrToCaffe2Arg(mapper)); return ret; } Caffe2Ops Caffe2Backend::ConvertNode( const std::string& node_str, const ConversionContext& ctx) { ::google::protobuf::RepeatedPtrField<NodeProto> nodes; auto* n = nodes.Add(); ParseProtoFromLargeString(node_str, n); ModelProto init_model; ModelProto pred_model; OnnxNode onnx_node = OnnxNode(nodes.Get(0)); return OnnxNodeToCaffe2Ops(init_model, pred_model, ctx, &onnx_node); } void Caffe2Backend::CheckOpSchemaArguments( const caffe2::OpSchema& schema, const caffe2::OperatorDef& op) { const auto& schema_args = schema.args(); if (schema_args.size() > 0){ std::vector<std::string> argnames; std::transform( schema_args.begin(), schema_args.end(), std::back_inserter(argnames), [](caffe2::OpSchema::Argument elem) { return elem.name(); }); for (const auto& arg : op.arg()) { if (std::count(argnames.begin(), argnames.end(), arg.name()) == 0) { CAFFE_THROW( "Don't know how to map unexpected argument ", arg.name(), " (from operator ", op.type(), ")"); } } } else { // A number of C2 operators do not declare proper arguments. Let's log the error VLOG(2) << "Operator " << op.type() << " does not declare arguments in its schema. Please file a Caffe2 issue."; } } Caffe2Ops Caffe2Backend::OnnxNodeToCaffe2Ops( const ModelProto& init_model, const ModelProto& pred_model, const ConversionContext& ctx, OnnxNode* onnx_node) { Caffe2Ops res; if (get_special_operators().count(onnx_node->node.op_type())) { res = (this->*get_special_operators().at(onnx_node->node.op_type()))( onnx_node, ctx); } else { res = CommonOnnxNodeToCaffe2Ops(onnx_node, ctx); } for (const auto& result_op: res.ops){ const auto* schema = OpSchemaRegistry::Schema(result_op.type()); if (schema) { CheckOpSchemaArguments(*schema, result_op); } else { CAFFE_THROW("Caffe2 has no such operator, could not find schema for ", result_op.type()); } } return res; } void Caffe2Backend::OnnxToCaffe2( caffe2::NetDef* init_net, caffe2::NetDef* pred_net, const ModelProto& onnx_model, const std::string& device, int opset_version, bool include_initializers, const std::vector<Caffe2Ops>& extras) { auto device_option = GetDeviceOption(Device(device)); #ifndef C10_MOBILE ModelProto init_model = OptimizeOnnx(onnx_model, true); ModelProto pred_model = OptimizeOnnx(onnx_model, false); #else ModelProto init_model = ModelProto(); ModelProto pred_model = onnx_model; pred_model.mutable_graph()->mutable_initializer()->Clear(); #endif init_net->set_name(onnx_model.graph().name() + "_init"); pred_net->set_name(onnx_model.graph().name() + "_predict"); // Convert initializer if necessary if (include_initializers) { for (const auto& tp : onnx_model.graph().initializer()) { auto* c2_op = init_net->add_op(); BuildTensorFillingOp(c2_op, tp); } } auto name_set = AllNamesInGraph(init_model.graph()); auto name_set_pred = AllNamesInGraph(pred_model.graph()); name_set.insert(name_set_pred.begin(), name_set_pred.end()); dummy_->Reset(name_set); ValueInfoMap graph_value_infos{}; for (const auto& vi : pred_model.graph().input()) { graph_value_infos[vi.name()].CopyFrom(vi); } for (const auto& vi : pred_model.graph().output()) { graph_value_infos[vi.name()].CopyFrom(vi); } for (const auto& vi : pred_model.graph().value_info()) { graph_value_infos[vi.name()].CopyFrom(vi); } size_t idx_extra = 0; auto converter = [&](const ModelProto& model, caffe2::NetDef* net) mutable { net->mutable_device_option()->CopyFrom(device_option); for (const auto& node : model.graph().node()) { auto* init_net_tmp = include_initializers ? init_net : net; // For RNN operators, we rely on Python code to convert them for us, and // we simply deserilize the string. This is hack and eventually we want to // get rid of this to have one flow. Note that we need to update the dummy // name generator to avoid having duplicated names between Python and C++ // generated dummies if (get_rnn_operators().count(node.op_type())) { if (idx_extra < extras.size()) { const auto& c2ops = extras[idx_extra++]; for (const auto& op : c2ops.init_ops) { UpdateNames(dummy_, op); } init_net_tmp->mutable_op()->MergeFrom(c2ops.init_ops); for (const auto& op : c2ops.ops) { UpdateNames(dummy_, op); } net->mutable_op()->MergeFrom(c2ops.ops); for (const auto& input : c2ops.interface_blobs) { dummy_->AddName(input); } net->mutable_external_input()->MergeFrom(c2ops.interface_blobs); } else { CAFFE_THROW( "Don't know how to convert ", node.op_type(), " without enough extra preconverted string"); } } else { ValueInfoMap value_infos{}; for (const auto& name : node.input()) { auto iter = graph_value_infos.find(name); if (iter != graph_value_infos.end()) { value_infos[name].CopyFrom(iter->second); } } auto onnx_node = OnnxNode(node); auto c2ops = OnnxNodeToCaffe2Ops( init_model, pred_model, {value_infos, opset_version}, &onnx_node); init_net_tmp->mutable_op()->MergeFrom(c2ops.init_ops); net->mutable_op()->MergeFrom(c2ops.ops); net->mutable_external_input()->MergeFrom(c2ops.interface_blobs); } } for (const auto& value : model.graph().output()) { net->add_external_output(value.name()); } for (const auto& value : model.graph().input()) { net->add_external_input(value.name()); } }; converter(init_model, init_net); converter(pred_model, pred_net); } Caffe2BackendRep* Caffe2Backend::Prepare( const std::string& onnx_model_str, const std::string& device, const std::vector<Caffe2Ops>& extras) { Caffe2BackendRep* rep = new Caffe2BackendRep(); ModelProto onnx_model; ParseProtoFromLargeString(onnx_model_str, &onnx_model); #ifndef C10_MOBILE ::ONNX_NAMESPACE::checker::check_model(onnx_model); #endif int opset_version = -1; for (const auto& imp : onnx_model.opset_import()) { if ((!imp.has_domain()) || imp.domain().empty()) { opset_version = imp.version(); if (opset_version > kKnownOpsetVersion) { std::cout << "This version of onnx-caffe2 targets ONNX operator set version " << kKnownOpsetVersion << ", but the model we are trying to import uses version " << opset_version << ". We will try to import it anyway, " << "but if the model uses operators which had BC-breaking changes " "in the intervening versions, import will fail." << std::endl; } } else { std::cout << "Unrecognized operator set " << opset_version << std::endl; } } if (opset_version < 0) { if (onnx_model.ir_version() >= 0x00000003) { CAFFE_THROW( "Model with IR version >= 3 did not specify ONNX operator set " "version (onnx-caffe2 requires it)"); } else { opset_version = 1; } } // TODO: avoid extra copy by directly feed initializers to backend blobs OnnxToCaffe2( &rep->init_net(), &rep->pred_net(), onnx_model, device, opset_version, true, extras); // Get a list of uninitialized inputs to help with the inference setup auto& uninitialized_inputs = rep->uninitialized_inputs(); std::unordered_set<std::string> initialized_inputs; for (const auto& tp : onnx_model.graph().initializer()) { initialized_inputs.emplace(tp.name()); } for (const auto& input : onnx_model.graph().input()) { if (!initialized_inputs.count(input.name())) { uninitialized_inputs.emplace_back(input.name()); } } return rep; } template <typename T> void ConvertIntegralValueToCaffe2(caffe2::OperatorDef* c2_op, caffe2::Argument* c2_values, const TensorProto& onnx_tensor) { c2_op->set_type( onnx_tensor.data_type() == TensorProto::BOOL ? "GivenTensorBoolFill" : "GivenTensorIntFill"); ::google::protobuf::RepeatedField<T> tmp; const ::google::protobuf::RepeatedField<T>* src = &tmp; bool converted = TryConvertingTensorRawValues<T>(onnx_tensor, &tmp); if (converted) { for (const auto i : *src) { c2_values->add_ints(i); } } else { const ::google::protobuf::RepeatedField<::google::protobuf::int32> *int32_src = \ &onnx_tensor.int32_data(); for (const auto i : *int32_src) { c2_values->add_ints(i); } } } template <> void ConvertIntegralValueToCaffe2<::google::protobuf::int64>(caffe2::OperatorDef* c2_op, caffe2::Argument* c2_values, const TensorProto& onnx_tensor) { c2_op->set_type("GivenTensorInt64Fill"); auto* ints = c2_values->mutable_ints(); if (!TryConvertingTensorRawValues<::google::protobuf::int64>( onnx_tensor, ints)) { ints->CopyFrom(onnx_tensor.int64_data()); } } template <> void ConvertIntegralValueToCaffe2<::google::protobuf::uint64>(caffe2::OperatorDef* c2_op, caffe2::Argument* c2_values, const TensorProto& onnx_tensor) { c2_op->set_type("GivenTensorInt64Fill"); ::google::protobuf::RepeatedField<::google::protobuf::uint64> tmp; const ::google::protobuf::RepeatedField<::google::protobuf::uint64>* src = &tmp; if (!TryConvertingTensorRawValues<::google::protobuf::uint64>( onnx_tensor, &tmp)) { src = &onnx_tensor.uint64_data(); } for (const auto i : *src) { c2_values->add_ints(i); } } void Caffe2Backend::BuildTensorFillingOp( caffe2::OperatorDef* c2_op, const TensorProto& onnx_tensor, const std::string& output_name, const std::string& shape_name) { auto fill_name = output_name.empty() ? onnx_tensor.name() : output_name; CAFFE_ENFORCE(!fill_name.empty()); if (onnx_tensor.has_segment()) { CAFFE_THROW("Currently not supporting loading segments."); } auto* c2_values = c2_op->add_arg(); // if shape_name is empty, we generate GivenTensorFill // otherwise, we generate ConstantFill, which accept shape as input if (shape_name.empty()) { // GivenTensor*Fill uses values c2_values->set_name("values"); if (onnx_tensor.data_type() == TensorProto::FLOAT) { c2_op->set_type("GivenTensorFill"); auto* floats = c2_values->mutable_floats(); if (!TryConvertingTensorRawValues<float>(onnx_tensor, floats)) { floats->CopyFrom(onnx_tensor.float_data()); } } else if (onnx_tensor.data_type() == TensorProto::DOUBLE) { c2_op->set_type("GivenTensorDoubleFill"); ::google::protobuf::RepeatedField<double> tmp; const ::google::protobuf::RepeatedField<double>* src = &tmp; if (!TryConvertingTensorRawValues<double>(onnx_tensor, &tmp)) { src = &onnx_tensor.double_data(); } for (const auto i : *src) { c2_values->add_floats(i); } } else if (onnx_tensor.data_type() == TensorProto::INT64) { ConvertIntegralValueToCaffe2<::google::protobuf::int64>(c2_op, c2_values, onnx_tensor); } else if (onnx_tensor.data_type() == TensorProto::UINT32) { ConvertIntegralValueToCaffe2<::google::protobuf::uint64>(c2_op, c2_values, onnx_tensor); } else if (onnx_tensor.data_type() == TensorProto::BOOL) { ConvertIntegralValueToCaffe2<::google::protobuf::int8>(c2_op, c2_values, onnx_tensor); } else if (onnx_tensor.data_type() == TensorProto::UINT8) { ConvertIntegralValueToCaffe2<::google::protobuf::uint8>(c2_op, c2_values, onnx_tensor); } else if (onnx_tensor.data_type() == TensorProto::INT8) { ConvertIntegralValueToCaffe2<::google::protobuf::int8>(c2_op, c2_values, onnx_tensor); } else if (onnx_tensor.data_type() == TensorProto::UINT16) { ConvertIntegralValueToCaffe2<::google::protobuf::uint16>(c2_op, c2_values, onnx_tensor); } else if (onnx_tensor.data_type() == TensorProto::INT16) { ConvertIntegralValueToCaffe2<::google::protobuf::int16>(c2_op, c2_values, onnx_tensor); } else if (onnx_tensor.data_type() == TensorProto::INT32) { ConvertIntegralValueToCaffe2<::google::protobuf::int32>(c2_op, c2_values, onnx_tensor); } else if (onnx_tensor.data_type() == TensorProto::STRING) { c2_op->set_type("GivenTensorStringFill"); auto* strings = c2_values->mutable_strings(); strings->CopyFrom(onnx_tensor.string_data()); } else { CAFFE_THROW("unrecognized tensor type: ", onnx_tensor.data_type()); } auto* c2_shape = c2_op->add_arg(); c2_shape->set_name("shape"); for (const auto d : onnx_tensor.dims()) { c2_shape->add_ints(d); } } else { int value_size = 1; for (const auto d : onnx_tensor.dims()) { value_size *= d; } CAFFE_ENFORCE(value_size == 1); auto c2_input_as_shape = c2_op->add_arg(); c2_input_as_shape->set_name("input_as_shape"); c2_input_as_shape->set_i(1); c2_values->set_name("value"); auto* c2_dtype = c2_op->add_arg(); c2_dtype->set_name("dtype"); if (onnx_tensor.data_type() == TensorProto::FLOAT) { c2_dtype->set_i(caffe2::TensorProto::FLOAT); if (onnx_tensor.float_data_size() > 0) { c2_values->set_f(onnx_tensor.float_data(0)); } else { CAFFE_ENFORCE(onnx_tensor.raw_data().size() == sizeof(float)); float f; memcpy(&f, onnx_tensor.raw_data().c_str(), sizeof(float)); c2_values->set_f(f); } } else if (onnx_tensor.data_type() == TensorProto::DOUBLE) { c2_dtype->set_i(caffe2::TensorProto::DOUBLE); if (onnx_tensor.double_data_size() > 0) { c2_values->set_f(static_cast<float>(onnx_tensor.double_data(0))); } else { CAFFE_ENFORCE(onnx_tensor.raw_data().size() == sizeof(double)); double d; memcpy(&d, onnx_tensor.raw_data().c_str(), sizeof(double)); c2_values->set_f(static_cast<float>(d)); } } else if (onnx_tensor.data_type() == TensorProto::INT64) { c2_dtype->set_i(caffe2::TensorProto::INT64); if (onnx_tensor.int64_data_size() > 0) { c2_values->set_i(onnx_tensor.int64_data(0)); } else { CAFFE_ENFORCE(onnx_tensor.raw_data().size() == sizeof(int64_t)); int64_t i; memcpy(&i, onnx_tensor.raw_data().c_str(), sizeof(int64_t)); c2_values->set_i(i); } } else if (onnx_tensor.data_type() == TensorProto::INT32) { c2_dtype->set_i(caffe2::TensorProto::INT32); if (onnx_tensor.int32_data_size() > 0) { c2_values->set_i(onnx_tensor.int32_data(0)); } else { CAFFE_ENFORCE(onnx_tensor.raw_data().size() == sizeof(int32_t)); int32_t i; memcpy(&i, onnx_tensor.raw_data().c_str(), sizeof(int32_t)); c2_values->set_i(i); } } else { // TODO: to support more data type std::stringstream oss; oss << "Unsupported dtype: " << onnx_tensor.data_type(); CAFFE_THROW(oss.str()); } // ConstantFill uses value c2_op->set_type("ConstantFill"); c2_op->add_input(shape_name); } c2_op->add_output(fill_name); } bool Caffe2Backend::SupportOp(const std::string type) const { return get_special_operators().count(type); } } // namespace onnx } // namespace caffe2
.model small .stack 64 .data ;; take decimal and print on screen as a decimal value num dw 1 ; input value str db 4 dup('0') .code main proc mov ax,@data mov ds,ax mov ax,num lea si,str+3 lea di,str mov cx,4 mov dx,0 label1: mov bx,10 div bx mov dh,30h add dl,dh mov [si],dl dec si mov dx,0 loop label1 mov cx,4 loopPrint: mov ah,2 mov dl,[di] int 21h inc di loop loopPrint main endp end main
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r15 push %r9 push %rbp push %rbx push %rcx push %rsi lea addresses_normal_ht+0x1ecc8, %rsi nop nop nop nop xor %rbp, %rbp movw $0x6162, (%rsi) nop nop nop nop dec %rsi lea addresses_D_ht+0x12f68, %r15 cmp %r9, %r9 movups (%r15), %xmm4 vpextrq $0, %xmm4, %rbx add $43964, %rbp lea addresses_A_ht+0x187e8, %rcx nop nop nop add $10776, %rsi movb (%rcx), %r9b nop nop nop add %rsi, %rsi lea addresses_UC_ht+0xb468, %rbp add $17469, %r12 movups (%rbp), %xmm1 vpextrq $0, %xmm1, %rbx nop nop nop nop nop and $18822, %r12 lea addresses_D_ht+0x1b768, %rbp nop add $31598, %rbx movb $0x61, (%rbp) nop nop nop nop dec %r12 pop %rsi pop %rcx pop %rbx pop %rbp pop %r9 pop %r15 pop %r12 ret .global s_faulty_load s_faulty_load: push %r12 push %r8 push %rbp push %rbx push %rdi // Faulty Load lea addresses_WC+0x1f768, %rdi clflush (%rdi) nop nop lfence mov (%rdi), %r12w lea oracles, %r8 and $0xff, %r12 shlq $12, %r12 mov (%r8,%r12,1), %r12 pop %rdi pop %rbx pop %rbp pop %r8 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_WC', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_WC', 'AVXalign': False, 'size': 2, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'AVXalign': False, 'size': 2, 'NT': True, 'same': False, 'congruent': 5}} {'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 11}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 6}, 'OP': 'LOAD'} {'src': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': True, 'congruent': 8}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 10}} {'38': 21829} 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 38 */
; =============================================================== ; Mar 2014 ; =============================================================== ; ; int bv_priority_queue_resize(bv_priority_queue_t *q, size_t n) ; ; Attempt to resize the queue to n bytes. ; ; If n <= queue.capacity, the array owned by the queue will ; have its size set to n. ; ; This resize operation does not change the contents of the queue ; array; instead it is assumed the queue array of the new size ; contains all valid data, possibly not in heap order. The ; resize operation therefore triggers a heapify to make sure ; the queue is kept in heap order. This means the caller can ; place data directly into the queue's array and then call this ; function to have it ordered into a heap. ; ; =============================================================== SECTION code_adt_bv_priority_queue PUBLIC asm_bv_priority_queue_resize EXTERN asm_ba_priority_queue_resize defc asm_bv_priority_queue_resize = asm_ba_priority_queue_resize ; enter : hl = queue * ; de = n = desired size in bytes ; ; exit : success ; ; hl = 0 ; carry reset ; ; fail if queue is too small ; ; hl = -1 ; carry set ; ; uses : af, bc, de, hl, ix
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Copyright (C) 2015, Itseez Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" #include <iostream> namespace cv { static Mutex* __initialization_mutex = NULL; Mutex& getInitializationMutex() { if (__initialization_mutex == NULL) __initialization_mutex = new Mutex(); return *__initialization_mutex; } // force initialization (single-threaded environment) Mutex* __initialization_mutex_initializer = &getInitializationMutex(); } // namespace cv #ifdef _MSC_VER # if _MSC_VER >= 1700 # pragma warning(disable:4447) // Disable warning 'main' signature found without threading model # endif #endif #if defined ANDROID || defined __linux__ || defined __FreeBSD__ # include <unistd.h> # include <fcntl.h> # include <elf.h> #if defined ANDROID || defined __linux__ # include <linux/auxvec.h> #endif #endif #if defined WIN32 || defined _WIN32 || defined WINCE #ifndef _WIN32_WINNT // This is needed for the declaration of TryEnterCriticalSection in winbase.h with Visual Studio 2005 (and older?) #define _WIN32_WINNT 0x0400 // http://msdn.microsoft.com/en-us/library/ms686857(VS.85).aspx #endif #include <windows.h> #if (_WIN32_WINNT >= 0x0602) #include <synchapi.h> #endif #undef small #undef min #undef max #undef abs #include <tchar.h> #if defined _MSC_VER #if _MSC_VER >= 1400 #include <intrin.h> #elif defined _M_IX86 static void __cpuid(int* cpuid_data, int) { __asm { push ebx push edi mov edi, cpuid_data mov eax, 1 cpuid mov [edi], eax mov [edi + 4], ebx mov [edi + 8], ecx mov [edi + 12], edx pop edi pop ebx } } static void __cpuidex(int* cpuid_data, int, int) { __asm { push edi mov edi, cpuid_data mov eax, 7 mov ecx, 0 cpuid mov [edi], eax mov [edi + 4], ebx mov [edi + 8], ecx mov [edi + 12], edx pop edi } } #endif #endif #ifdef WINRT #include <wrl/client.h> #ifndef __cplusplus_winrt #include <windows.storage.h> #pragma comment(lib, "runtimeobject.lib") #endif std::wstring GetTempPathWinRT() { #ifdef __cplusplus_winrt return std::wstring(Windows::Storage::ApplicationData::Current->TemporaryFolder->Path->Data()); #else Microsoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationDataStatics> appdataFactory; Microsoft::WRL::ComPtr<ABI::Windows::Storage::IApplicationData> appdataRef; Microsoft::WRL::ComPtr<ABI::Windows::Storage::IStorageFolder> storagefolderRef; Microsoft::WRL::ComPtr<ABI::Windows::Storage::IStorageItem> storageitemRef; HSTRING str; HSTRING_HEADER hstrHead; std::wstring wstr; if (FAILED(WindowsCreateStringReference(RuntimeClass_Windows_Storage_ApplicationData, (UINT32)wcslen(RuntimeClass_Windows_Storage_ApplicationData), &hstrHead, &str))) return wstr; if (FAILED(RoGetActivationFactory(str, IID_PPV_ARGS(appdataFactory.ReleaseAndGetAddressOf())))) return wstr; if (FAILED(appdataFactory->get_Current(appdataRef.ReleaseAndGetAddressOf()))) return wstr; if (FAILED(appdataRef->get_TemporaryFolder(storagefolderRef.ReleaseAndGetAddressOf()))) return wstr; if (FAILED(storagefolderRef.As(&storageitemRef))) return wstr; str = NULL; if (FAILED(storageitemRef->get_Path(&str))) return wstr; wstr = WindowsGetStringRawBuffer(str, NULL); WindowsDeleteString(str); return wstr; #endif } std::wstring GetTempFileNameWinRT(std::wstring prefix) { wchar_t guidStr[40]; GUID g; CoCreateGuid(&g); wchar_t* mask = L"%08x_%04x_%04x_%02x%02x_%02x%02x%02x%02x%02x%02x"; swprintf(&guidStr[0], sizeof(guidStr)/sizeof(wchar_t), mask, g.Data1, g.Data2, g.Data3, UINT(g.Data4[0]), UINT(g.Data4[1]), UINT(g.Data4[2]), UINT(g.Data4[3]), UINT(g.Data4[4]), UINT(g.Data4[5]), UINT(g.Data4[6]), UINT(g.Data4[7])); return prefix.append(std::wstring(guidStr)); } #endif #else #include <pthread.h> #include <sys/time.h> #include <time.h> #if defined __MACH__ && defined __APPLE__ #include <mach/mach.h> #include <mach/mach_time.h> #endif #endif #ifdef _OPENMP #include "omp.h" #endif #include <stdarg.h> #if defined __linux__ || defined __APPLE__ || defined __EMSCRIPTEN__ || defined __FreeBSD__ #include <unistd.h> #include <stdio.h> #include <sys/types.h> #if defined ANDROID #include <sys/sysconf.h> #endif #endif #ifdef ANDROID # include <android/log.h> #endif namespace cv { Exception::Exception() { code = 0; line = 0; } Exception::Exception(int _code, const String& _err, const String& _func, const String& _file, int _line) : code(_code), err(_err), func(_func), file(_file), line(_line) { formatMessage(); } Exception::~Exception() throw() {} /*! \return the error description and the context as a text string. */ const char* Exception::what() const throw() { return msg.c_str(); } void Exception::formatMessage() { if( func.size() > 0 ) msg = format("%s:%d: error: (%d) %s in function %s\n", file.c_str(), line, code, err.c_str(), func.c_str()); else msg = format("%s:%d: error: (%d) %s\n", file.c_str(), line, code, err.c_str()); } struct HWFeatures { enum { MAX_FEATURE = CV_HARDWARE_MAX_FEATURE }; HWFeatures(void) { memset( have, 0, sizeof(have) ); x86_family = 0; } static HWFeatures initialize(void) { HWFeatures f; int cpuid_data[4] = { 0, 0, 0, 0 }; #if defined _MSC_VER && (defined _M_IX86 || defined _M_X64) __cpuid(cpuid_data, 1); #elif defined __GNUC__ && (defined __i386__ || defined __x86_64__) #ifdef __x86_64__ asm __volatile__ ( "movl $1, %%eax\n\t" "cpuid\n\t" :[eax]"=a"(cpuid_data[0]),[ebx]"=b"(cpuid_data[1]),[ecx]"=c"(cpuid_data[2]),[edx]"=d"(cpuid_data[3]) : : "cc" ); #else asm volatile ( "pushl %%ebx\n\t" "movl $1,%%eax\n\t" "cpuid\n\t" "popl %%ebx\n\t" : "=a"(cpuid_data[0]), "=c"(cpuid_data[2]), "=d"(cpuid_data[3]) : : "cc" ); #endif #endif f.x86_family = (cpuid_data[0] >> 8) & 15; if( f.x86_family >= 6 ) { f.have[CV_CPU_MMX] = (cpuid_data[3] & (1 << 23)) != 0; f.have[CV_CPU_SSE] = (cpuid_data[3] & (1<<25)) != 0; f.have[CV_CPU_SSE2] = (cpuid_data[3] & (1<<26)) != 0; f.have[CV_CPU_SSE3] = (cpuid_data[2] & (1<<0)) != 0; f.have[CV_CPU_SSSE3] = (cpuid_data[2] & (1<<9)) != 0; f.have[CV_CPU_FMA3] = (cpuid_data[2] & (1<<12)) != 0; f.have[CV_CPU_SSE4_1] = (cpuid_data[2] & (1<<19)) != 0; f.have[CV_CPU_SSE4_2] = (cpuid_data[2] & (1<<20)) != 0; f.have[CV_CPU_POPCNT] = (cpuid_data[2] & (1<<23)) != 0; f.have[CV_CPU_AVX] = (((cpuid_data[2] & (1<<28)) != 0)&&((cpuid_data[2] & (1<<27)) != 0));//OS uses XSAVE_XRSTORE and CPU support AVX f.have[CV_CPU_FP16] = (cpuid_data[2] & (1<<29)) != 0; // make the second call to the cpuid command in order to get // information about extended features like AVX2 #if defined _MSC_VER && (defined _M_IX86 || defined _M_X64) __cpuidex(cpuid_data, 7, 0); #elif defined __GNUC__ && (defined __i386__ || defined __x86_64__) #ifdef __x86_64__ asm __volatile__ ( "movl $7, %%eax\n\t" "movl $0, %%ecx\n\t" "cpuid\n\t" :[eax]"=a"(cpuid_data[0]),[ebx]"=b"(cpuid_data[1]),[ecx]"=c"(cpuid_data[2]),[edx]"=d"(cpuid_data[3]) : : "cc" ); #else asm volatile ( "pushl %%ebx\n\t" "movl $7,%%eax\n\t" "movl $0,%%ecx\n\t" "cpuid\n\t" "movl %%ebx, %0\n\t" "popl %%ebx\n\t" : "=r"(cpuid_data[1]), "=c"(cpuid_data[2]) : : "cc" ); #endif #endif f.have[CV_CPU_AVX2] = (cpuid_data[1] & (1<<5)) != 0; f.have[CV_CPU_AVX_512F] = (cpuid_data[1] & (1<<16)) != 0; f.have[CV_CPU_AVX_512DQ] = (cpuid_data[1] & (1<<17)) != 0; f.have[CV_CPU_AVX_512IFMA512] = (cpuid_data[1] & (1<<21)) != 0; f.have[CV_CPU_AVX_512PF] = (cpuid_data[1] & (1<<26)) != 0; f.have[CV_CPU_AVX_512ER] = (cpuid_data[1] & (1<<27)) != 0; f.have[CV_CPU_AVX_512CD] = (cpuid_data[1] & (1<<28)) != 0; f.have[CV_CPU_AVX_512BW] = (cpuid_data[1] & (1<<30)) != 0; f.have[CV_CPU_AVX_512VL] = (cpuid_data[1] & (1<<31)) != 0; f.have[CV_CPU_AVX_512VBMI] = (cpuid_data[2] & (1<<1)) != 0; } #if defined ANDROID || defined __linux__ #ifdef __aarch64__ f.have[CV_CPU_NEON] = true; f.have[CV_CPU_FP16] = true; #elif defined __arm__ int cpufile = open("/proc/self/auxv", O_RDONLY); if (cpufile >= 0) { Elf32_auxv_t auxv; const size_t size_auxv_t = sizeof(auxv); while ((size_t)read(cpufile, &auxv, size_auxv_t) == size_auxv_t) { if (auxv.a_type == AT_HWCAP) { f.have[CV_CPU_NEON] = (auxv.a_un.a_val & 4096) != 0; f.have[CV_CPU_FP16] = (auxv.a_un.a_val & 2) != 0; break; } } close(cpufile); } #endif #elif (defined __clang__ || defined __APPLE__) #if (defined __ARM_NEON__ || (defined __ARM_NEON && defined __aarch64__)) f.have[CV_CPU_NEON] = true; #endif #if (defined __ARM_FP && (((__ARM_FP & 0x2) != 0) && defined __ARM_NEON__)) f.have[CV_CPU_FP16] = true; #endif #endif return f; } int x86_family; bool have[MAX_FEATURE+1]; }; static HWFeatures featuresEnabled = HWFeatures::initialize(), featuresDisabled = HWFeatures(); static HWFeatures* currentFeatures = &featuresEnabled; bool checkHardwareSupport(int feature) { CV_DbgAssert( 0 <= feature && feature <= CV_HARDWARE_MAX_FEATURE ); return currentFeatures->have[feature]; } volatile bool useOptimizedFlag = true; void setUseOptimized( bool flag ) { useOptimizedFlag = flag; currentFeatures = flag ? &featuresEnabled : &featuresDisabled; ipp::setUseIPP(flag); #ifdef HAVE_OPENCL ocl::setUseOpenCL(flag); #endif #ifdef HAVE_TEGRA_OPTIMIZATION ::tegra::setUseTegra(flag); #endif } bool useOptimized(void) { return useOptimizedFlag; } int64 getTickCount(void) { #if defined WIN32 || defined _WIN32 || defined WINCE LARGE_INTEGER counter; QueryPerformanceCounter( &counter ); return (int64)counter.QuadPart; #elif defined __linux || defined __linux__ struct timespec tp; clock_gettime(CLOCK_MONOTONIC, &tp); return (int64)tp.tv_sec*1000000000 + tp.tv_nsec; #elif defined __MACH__ && defined __APPLE__ return (int64)mach_absolute_time(); #else struct timeval tv; struct timezone tz; gettimeofday( &tv, &tz ); return (int64)tv.tv_sec*1000000 + tv.tv_usec; #endif } double getTickFrequency(void) { #if defined WIN32 || defined _WIN32 || defined WINCE LARGE_INTEGER freq; QueryPerformanceFrequency(&freq); return (double)freq.QuadPart; #elif defined __linux || defined __linux__ return 1e9; #elif defined __MACH__ && defined __APPLE__ static double freq = 0; if( freq == 0 ) { mach_timebase_info_data_t sTimebaseInfo; mach_timebase_info(&sTimebaseInfo); freq = sTimebaseInfo.denom*1e9/sTimebaseInfo.numer; } return freq; #else return 1e6; #endif } #if defined __GNUC__ && (defined __i386__ || defined __x86_64__ || defined __ppc__) #if defined(__i386__) int64 getCPUTickCount(void) { int64 x; __asm__ volatile (".byte 0x0f, 0x31" : "=A" (x)); return x; } #elif defined(__x86_64__) int64 getCPUTickCount(void) { unsigned hi, lo; __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi)); return (int64)lo | ((int64)hi << 32); } #elif defined(__ppc__) int64 getCPUTickCount(void) { int64 result = 0; unsigned upper, lower, tmp; __asm__ volatile( "0: \n" "\tmftbu %0 \n" "\tmftb %1 \n" "\tmftbu %2 \n" "\tcmpw %2,%0 \n" "\tbne 0b \n" : "=r"(upper),"=r"(lower),"=r"(tmp) ); return lower | ((int64)upper << 32); } #else #error "RDTSC not defined" #endif #elif defined _MSC_VER && defined WIN32 && defined _M_IX86 int64 getCPUTickCount(void) { __asm _emit 0x0f; __asm _emit 0x31; } #else //#ifdef HAVE_IPP //int64 getCPUTickCount(void) //{ // return ippGetCpuClocks(); //} //#else int64 getCPUTickCount(void) { return getTickCount(); } //#endif #endif const String& getBuildInformation() { static String build_info = #include "version_string.inc" ; return build_info; } String format( const char* fmt, ... ) { AutoBuffer<char, 1024> buf; for ( ; ; ) { va_list va; va_start(va, fmt); int bsize = static_cast<int>(buf.size()), len = vsnprintf((char *)buf, bsize, fmt, va); va_end(va); if (len < 0 || len >= bsize) { buf.resize(std::max(bsize << 1, len + 1)); continue; } return String((char *)buf, len); } } String tempfile( const char* suffix ) { String fname; #ifndef WINRT const char *temp_dir = getenv("OPENCV_TEMP_PATH"); #endif #if defined WIN32 || defined _WIN32 #ifdef WINRT RoInitialize(RO_INIT_MULTITHREADED); std::wstring temp_dir = GetTempPathWinRT(); std::wstring temp_file = GetTempFileNameWinRT(L"ocv"); if (temp_file.empty()) return String(); temp_file = temp_dir.append(std::wstring(L"\\")).append(temp_file); DeleteFileW(temp_file.c_str()); char aname[MAX_PATH]; size_t copied = wcstombs(aname, temp_file.c_str(), MAX_PATH); CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1)); fname = String(aname); RoUninitialize(); #else char temp_dir2[MAX_PATH] = { 0 }; char temp_file[MAX_PATH] = { 0 }; if (temp_dir == 0 || temp_dir[0] == 0) { ::GetTempPathA(sizeof(temp_dir2), temp_dir2); temp_dir = temp_dir2; } if(0 == ::GetTempFileNameA(temp_dir, "ocv", 0, temp_file)) return String(); DeleteFileA(temp_file); fname = temp_file; #endif # else # ifdef ANDROID //char defaultTemplate[] = "/mnt/sdcard/__opencv_temp.XXXXXX"; char defaultTemplate[] = "/data/local/tmp/__opencv_temp.XXXXXX"; # else char defaultTemplate[] = "/tmp/__opencv_temp.XXXXXX"; # endif if (temp_dir == 0 || temp_dir[0] == 0) fname = defaultTemplate; else { fname = temp_dir; char ech = fname[fname.size() - 1]; if(ech != '/' && ech != '\\') fname = fname + "/"; fname = fname + "__opencv_temp.XXXXXX"; } const int fd = mkstemp((char*)fname.c_str()); if (fd == -1) return String(); close(fd); remove(fname.c_str()); # endif if (suffix) { if (suffix[0] != '.') return fname + "." + suffix; else return fname + suffix; } return fname; } static CvErrorCallback customErrorCallback = 0; static void* customErrorCallbackData = 0; static bool breakOnError = false; bool setBreakOnError(bool value) { bool prevVal = breakOnError; breakOnError = value; return prevVal; } void error( const Exception& exc ) { if (customErrorCallback != 0) customErrorCallback(exc.code, exc.func.c_str(), exc.err.c_str(), exc.file.c_str(), exc.line, customErrorCallbackData); else { const char* errorStr = cvErrorStr(exc.code); char buf[1 << 16]; sprintf( buf, "OpenCV Error: %s (%s) in %s, file %s, line %d", errorStr, exc.err.c_str(), exc.func.size() > 0 ? exc.func.c_str() : "unknown function", exc.file.c_str(), exc.line ); fprintf( stderr, "%s\n", buf ); fflush( stderr ); # ifdef __ANDROID__ __android_log_print(ANDROID_LOG_ERROR, "cv::error()", "%s", buf); # endif } if(breakOnError) { static volatile int* p = 0; *p = 0; } throw exc; } void error(int _code, const String& _err, const char* _func, const char* _file, int _line) { error(cv::Exception(_code, _err, _func, _file, _line)); } CvErrorCallback redirectError( CvErrorCallback errCallback, void* userdata, void** prevUserdata) { if( prevUserdata ) *prevUserdata = customErrorCallbackData; CvErrorCallback prevCallback = customErrorCallback; customErrorCallback = errCallback; customErrorCallbackData = userdata; return prevCallback; } } CV_IMPL int cvCheckHardwareSupport(int feature) { CV_DbgAssert( 0 <= feature && feature <= CV_HARDWARE_MAX_FEATURE ); return cv::currentFeatures->have[feature]; } CV_IMPL int cvUseOptimized( int flag ) { int prevMode = cv::useOptimizedFlag; cv::setUseOptimized( flag != 0 ); return prevMode; } CV_IMPL int64 cvGetTickCount(void) { return cv::getTickCount(); } CV_IMPL double cvGetTickFrequency(void) { return cv::getTickFrequency()*1e-6; } CV_IMPL CvErrorCallback cvRedirectError( CvErrorCallback errCallback, void* userdata, void** prevUserdata) { return cv::redirectError(errCallback, userdata, prevUserdata); } CV_IMPL int cvNulDevReport( int, const char*, const char*, const char*, int, void* ) { return 0; } CV_IMPL int cvStdErrReport( int, const char*, const char*, const char*, int, void* ) { return 0; } CV_IMPL int cvGuiBoxReport( int, const char*, const char*, const char*, int, void* ) { return 0; } CV_IMPL int cvGetErrInfo( const char**, const char**, const char**, int* ) { return 0; } CV_IMPL const char* cvErrorStr( int status ) { static char buf[256]; switch (status) { case CV_StsOk : return "No Error"; case CV_StsBackTrace : return "Backtrace"; case CV_StsError : return "Unspecified error"; case CV_StsInternal : return "Internal error"; case CV_StsNoMem : return "Insufficient memory"; case CV_StsBadArg : return "Bad argument"; case CV_StsNoConv : return "Iterations do not converge"; case CV_StsAutoTrace : return "Autotrace call"; case CV_StsBadSize : return "Incorrect size of input array"; case CV_StsNullPtr : return "Null pointer"; case CV_StsDivByZero : return "Division by zero occured"; case CV_BadStep : return "Image step is wrong"; case CV_StsInplaceNotSupported : return "Inplace operation is not supported"; case CV_StsObjectNotFound : return "Requested object was not found"; case CV_BadDepth : return "Input image depth is not supported by function"; case CV_StsUnmatchedFormats : return "Formats of input arguments do not match"; case CV_StsUnmatchedSizes : return "Sizes of input arguments do not match"; case CV_StsOutOfRange : return "One of arguments\' values is out of range"; case CV_StsUnsupportedFormat : return "Unsupported format or combination of formats"; case CV_BadCOI : return "Input COI is not supported"; case CV_BadNumChannels : return "Bad number of channels"; case CV_StsBadFlag : return "Bad flag (parameter or structure field)"; case CV_StsBadPoint : return "Bad parameter of type CvPoint"; case CV_StsBadMask : return "Bad type of mask argument"; case CV_StsParseError : return "Parsing error"; case CV_StsNotImplemented : return "The function/feature is not implemented"; case CV_StsBadMemBlock : return "Memory block has been corrupted"; case CV_StsAssert : return "Assertion failed"; case CV_GpuNotSupported : return "No CUDA support"; case CV_GpuApiCallError : return "Gpu API call"; case CV_OpenGlNotSupported : return "No OpenGL support"; case CV_OpenGlApiCallError : return "OpenGL API call"; }; sprintf(buf, "Unknown %s code %d", status >= 0 ? "status":"error", status); return buf; } CV_IMPL int cvGetErrMode(void) { return 0; } CV_IMPL int cvSetErrMode(int) { return 0; } CV_IMPL int cvGetErrStatus(void) { return 0; } CV_IMPL void cvSetErrStatus(int) { } CV_IMPL void cvError( int code, const char* func_name, const char* err_msg, const char* file_name, int line ) { cv::error(cv::Exception(code, err_msg, func_name, file_name, line)); } /* function, which converts int to int */ CV_IMPL int cvErrorFromIppStatus( int status ) { switch (status) { case CV_BADSIZE_ERR: return CV_StsBadSize; case CV_BADMEMBLOCK_ERR: return CV_StsBadMemBlock; case CV_NULLPTR_ERR: return CV_StsNullPtr; case CV_DIV_BY_ZERO_ERR: return CV_StsDivByZero; case CV_BADSTEP_ERR: return CV_BadStep; case CV_OUTOFMEM_ERR: return CV_StsNoMem; case CV_BADARG_ERR: return CV_StsBadArg; case CV_NOTDEFINED_ERR: return CV_StsError; case CV_INPLACE_NOT_SUPPORTED_ERR: return CV_StsInplaceNotSupported; case CV_NOTFOUND_ERR: return CV_StsObjectNotFound; case CV_BADCONVERGENCE_ERR: return CV_StsNoConv; case CV_BADDEPTH_ERR: return CV_BadDepth; case CV_UNMATCHED_FORMATS_ERR: return CV_StsUnmatchedFormats; case CV_UNSUPPORTED_COI_ERR: return CV_BadCOI; case CV_UNSUPPORTED_CHANNELS_ERR: return CV_BadNumChannels; case CV_BADFLAG_ERR: return CV_StsBadFlag; case CV_BADRANGE_ERR: return CV_StsBadArg; case CV_BADCOEF_ERR: return CV_StsBadArg; case CV_BADFACTOR_ERR: return CV_StsBadArg; case CV_BADPOINT_ERR: return CV_StsBadPoint; default: return CV_StsError; } } namespace cv { bool __termination = false; } namespace cv { #if defined WIN32 || defined _WIN32 || defined WINCE struct Mutex::Impl { Impl() { #if (_WIN32_WINNT >= 0x0600) ::InitializeCriticalSectionEx(&cs, 1000, 0); #else ::InitializeCriticalSection(&cs); #endif refcount = 1; } ~Impl() { DeleteCriticalSection(&cs); } void lock() { EnterCriticalSection(&cs); } bool trylock() { return TryEnterCriticalSection(&cs) != 0; } void unlock() { LeaveCriticalSection(&cs); } CRITICAL_SECTION cs; int refcount; }; #else struct Mutex::Impl { Impl() { pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); pthread_mutex_init(&mt, &attr); pthread_mutexattr_destroy(&attr); refcount = 1; } ~Impl() { pthread_mutex_destroy(&mt); } void lock() { pthread_mutex_lock(&mt); } bool trylock() { return pthread_mutex_trylock(&mt) == 0; } void unlock() { pthread_mutex_unlock(&mt); } pthread_mutex_t mt; int refcount; }; #endif Mutex::Mutex() { impl = new Mutex::Impl; } Mutex::~Mutex() { if( CV_XADD(&impl->refcount, -1) == 1 ) delete impl; impl = 0; } Mutex::Mutex(const Mutex& m) { impl = m.impl; CV_XADD(&impl->refcount, 1); } Mutex& Mutex::operator = (const Mutex& m) { CV_XADD(&m.impl->refcount, 1); if( CV_XADD(&impl->refcount, -1) == 1 ) delete impl; impl = m.impl; return *this; } void Mutex::lock() { impl->lock(); } void Mutex::unlock() { impl->unlock(); } bool Mutex::trylock() { return impl->trylock(); } //////////////////////////////// thread-local storage //////////////////////////////// #ifdef WIN32 #ifdef _MSC_VER #pragma warning(disable:4505) // unreferenced local function has been removed #endif #ifndef TLS_OUT_OF_INDEXES #define TLS_OUT_OF_INDEXES ((DWORD)0xFFFFFFFF) #endif #endif // TLS platform abstraction layer class TlsAbstraction { public: TlsAbstraction(); ~TlsAbstraction(); void* GetData() const; void SetData(void *pData); private: #ifdef WIN32 #ifndef WINRT DWORD tlsKey; #endif #else // WIN32 pthread_key_t tlsKey; #endif }; #ifdef WIN32 #ifdef WINRT static __declspec( thread ) void* tlsData = NULL; // using C++11 thread attribute for local thread data TlsAbstraction::TlsAbstraction() {} TlsAbstraction::~TlsAbstraction() {} void* TlsAbstraction::GetData() const { return tlsData; } void TlsAbstraction::SetData(void *pData) { tlsData = pData; } #else //WINRT TlsAbstraction::TlsAbstraction() { tlsKey = TlsAlloc(); CV_Assert(tlsKey != TLS_OUT_OF_INDEXES); } TlsAbstraction::~TlsAbstraction() { TlsFree(tlsKey); } void* TlsAbstraction::GetData() const { return TlsGetValue(tlsKey); } void TlsAbstraction::SetData(void *pData) { CV_Assert(TlsSetValue(tlsKey, pData) == TRUE); } #endif #else // WIN32 TlsAbstraction::TlsAbstraction() { CV_Assert(pthread_key_create(&tlsKey, NULL) == 0); } TlsAbstraction::~TlsAbstraction() { CV_Assert(pthread_key_delete(tlsKey) == 0); } void* TlsAbstraction::GetData() const { return pthread_getspecific(tlsKey); } void TlsAbstraction::SetData(void *pData) { CV_Assert(pthread_setspecific(tlsKey, pData) == 0); } #endif // Per-thread data structure struct ThreadData { ThreadData() { idx = 0; slots.reserve(32); } std::vector<void*> slots; // Data array for a thread size_t idx; // Thread index in TLS storage. This is not OS thread ID! }; // Main TLS storage class class TlsStorage { public: TlsStorage() { tlsSlots.reserve(32); threads.reserve(32); } ~TlsStorage() { for(size_t i = 0; i < threads.size(); i++) { if(threads[i]) { /* Current architecture doesn't allow proper global objects relase, so this check can cause crashes // Check if all slots were properly cleared for(size_t j = 0; j < threads[i]->slots.size(); j++) { CV_Assert(threads[i]->slots[j] == 0); } */ delete threads[i]; } } threads.clear(); } void releaseThread() { AutoLock guard(mtxGlobalAccess); ThreadData *pTD = (ThreadData*)tls.GetData(); for(size_t i = 0; i < threads.size(); i++) { if(pTD == threads[i]) { threads[i] = 0; break; } } tls.SetData(0); delete pTD; } // Reserve TLS storage index size_t reserveSlot() { AutoLock guard(mtxGlobalAccess); // Find unused slots for(size_t slot = 0; slot < tlsSlots.size(); slot++) { if(!tlsSlots[slot]) { tlsSlots[slot] = 1; return slot; } } // Create new slot tlsSlots.push_back(1); return (tlsSlots.size()-1); } // Release TLS storage index and pass assosiated data to caller void releaseSlot(size_t slotIdx, std::vector<void*> &dataVec) { AutoLock guard(mtxGlobalAccess); CV_Assert(tlsSlots.size() > slotIdx); for(size_t i = 0; i < threads.size(); i++) { if(threads[i]) { std::vector<void*>& thread_slots = threads[i]->slots; if (thread_slots.size() > slotIdx && thread_slots[slotIdx]) { dataVec.push_back(thread_slots[slotIdx]); threads[i]->slots[slotIdx] = 0; } } } tlsSlots[slotIdx] = 0; } // Get data by TLS storage index void* getData(size_t slotIdx) const { CV_Assert(tlsSlots.size() > slotIdx); ThreadData* threadData = (ThreadData*)tls.GetData(); if(threadData && threadData->slots.size() > slotIdx) return threadData->slots[slotIdx]; return NULL; } // Gather data from threads by TLS storage index void gather(size_t slotIdx, std::vector<void*> &dataVec) { AutoLock guard(mtxGlobalAccess); CV_Assert(tlsSlots.size() > slotIdx); for(size_t i = 0; i < threads.size(); i++) { if(threads[i]) { std::vector<void*>& thread_slots = threads[i]->slots; if (thread_slots.size() > slotIdx && thread_slots[slotIdx]) dataVec.push_back(thread_slots[slotIdx]); } } } // Set data to storage index void setData(size_t slotIdx, void* pData) { CV_Assert(tlsSlots.size() > slotIdx && pData != NULL); ThreadData* threadData = (ThreadData*)tls.GetData(); if(!threadData) { threadData = new ThreadData; tls.SetData((void*)threadData); { AutoLock guard(mtxGlobalAccess); threadData->idx = threads.size(); threads.push_back(threadData); } } if(slotIdx >= threadData->slots.size()) { AutoLock guard(mtxGlobalAccess); while(slotIdx >= threadData->slots.size()) threadData->slots.push_back(NULL); } threadData->slots[slotIdx] = pData; } private: TlsAbstraction tls; // TLS abstraction layer instance Mutex mtxGlobalAccess; // Shared objects operation guard std::vector<int> tlsSlots; // TLS keys state std::vector<ThreadData*> threads; // Array for all allocated data. Thread data pointers are placed here to allow data cleanup }; // Create global TLS storage object static TlsStorage &getTlsStorage() { CV_SINGLETON_LAZY_INIT_REF(TlsStorage, new TlsStorage()) } TLSDataContainer::TLSDataContainer() { key_ = (int)getTlsStorage().reserveSlot(); // Reserve key from TLS storage } TLSDataContainer::~TLSDataContainer() { CV_Assert(key_ == -1); // Key must be released in child object } void TLSDataContainer::gatherData(std::vector<void*> &data) const { getTlsStorage().gather(key_, data); } void TLSDataContainer::release() { std::vector<void*> data; data.reserve(32); getTlsStorage().releaseSlot(key_, data); // Release key and get stored data for proper destruction for(size_t i = 0; i < data.size(); i++) // Delete all assosiated data deleteDataInstance(data[i]); key_ = -1; } void* TLSDataContainer::getData() const { void* pData = getTlsStorage().getData(key_); // Check if data was already allocated if(!pData) { // Create new data instance and save it to TLS storage pData = createDataInstance(); getTlsStorage().setData(key_, pData); } return pData; } TLSData<CoreTLSData>& getCoreTlsData() { CV_SINGLETON_LAZY_INIT_REF(TLSData<CoreTLSData>, new TLSData<CoreTLSData>()) } #if defined CVAPI_EXPORTS && defined WIN32 && !defined WINCE #ifdef WINRT #pragma warning(disable:4447) // Disable warning 'main' signature found without threading model #endif extern "C" BOOL WINAPI DllMain(HINSTANCE, DWORD fdwReason, LPVOID lpReserved); extern "C" BOOL WINAPI DllMain(HINSTANCE, DWORD fdwReason, LPVOID lpReserved) { if (fdwReason == DLL_THREAD_DETACH || fdwReason == DLL_PROCESS_DETACH) { if (lpReserved != NULL) // called after ExitProcess() call { cv::__termination = true; } else { // Not allowed to free resources if lpReserved is non-null // http://msdn.microsoft.com/en-us/library/windows/desktop/ms682583.aspx cv::deleteThreadAllocData(); cv::getTlsStorage().releaseThread(); } } return TRUE; } #endif #ifdef CV_COLLECT_IMPL_DATA ImplCollector& getImplData() { CV_SINGLETON_LAZY_INIT_REF(ImplCollector, new ImplCollector()) } void setImpl(int flags) { cv::AutoLock lock(getImplData().mutex); getImplData().implFlags = flags; getImplData().implCode.clear(); getImplData().implFun.clear(); } void addImpl(int flag, const char* func) { cv::AutoLock lock(getImplData().mutex); getImplData().implFlags |= flag; if(func) // use lazy collection if name was not specified { size_t index = getImplData().implCode.size(); if(!index || (getImplData().implCode[index-1] != flag || getImplData().implFun[index-1].compare(func))) // avoid duplicates { getImplData().implCode.push_back(flag); getImplData().implFun.push_back(func); } } } int getImpl(std::vector<int> &impl, std::vector<String> &funName) { cv::AutoLock lock(getImplData().mutex); impl = getImplData().implCode; funName = getImplData().implFun; return getImplData().implFlags; // return actual flags for lazy collection } bool useCollection() { return getImplData().useCollection; } void setUseCollection(bool flag) { cv::AutoLock lock(getImplData().mutex); getImplData().useCollection = flag; } #endif namespace instr { bool useInstrumentation() { #ifdef ENABLE_INSTRUMENTATION return getInstrumentStruct().useInstr; #else return false; #endif } void setUseInstrumentation(bool flag) { #ifdef ENABLE_INSTRUMENTATION getInstrumentStruct().useInstr = flag; #else CV_UNUSED(flag); #endif } InstrNode* getTrace() { #ifdef ENABLE_INSTRUMENTATION return &getInstrumentStruct().rootNode; #else return NULL; #endif } void resetTrace() { #ifdef ENABLE_INSTRUMENTATION getInstrumentStruct().rootNode.removeChilds(); getInstrumentTLSStruct().pCurrentNode = &getInstrumentStruct().rootNode; #endif } void setFlags(int modeFlags) { #ifdef ENABLE_INSTRUMENTATION getInstrumentStruct().enableMapping = (modeFlags & FLAGS_MAPPING); #else CV_UNUSED(modeFlags); #endif } int getFlags() { #ifdef ENABLE_INSTRUMENTATION int flags = 0; if(getInstrumentStruct().enableMapping) flags |= FLAGS_MAPPING; return flags; #else return 0; #endif } NodeData::NodeData(const char* funName, const char* fileName, int lineNum, int instrType, int implType) { m_instrType = TYPE_GENERAL; m_implType = IMPL_PLAIN; m_funError = false; m_counter = 0; m_stopPoint = false; m_ticksMean = 0; m_funName = funName; m_instrType = instrType; m_implType = implType; m_fileName = fileName; m_lineNum = lineNum; } NodeData::NodeData(NodeData &ref) { *this = ref; } NodeData& NodeData::operator=(const NodeData &right) { this->m_funName = right.m_funName; this->m_instrType = right.m_instrType; this->m_implType = right.m_implType; this->m_funError = right.m_funError; this->m_counter = right.m_counter; this->m_stopPoint = right.m_stopPoint; this->m_ticksMean = right.m_ticksMean; this->m_fileName = right.m_fileName; this->m_lineNum = right.m_lineNum; return *this; } NodeData::~NodeData() { } bool operator==(const NodeData& left, const NodeData& right) { if(left.m_lineNum == right.m_lineNum && left.m_funName == right.m_funName && left.m_fileName == right.m_fileName) return true; return false; } #ifdef ENABLE_INSTRUMENTATION InstrStruct& getInstrumentStruct() { static InstrStruct instr; return instr; } InstrTLSStruct& getInstrumentTLSStruct() { return *getInstrumentStruct().tlsStruct.get(); } InstrNode* getCurrentNode() { return getInstrumentTLSStruct().pCurrentNode; } IntrumentationRegion::IntrumentationRegion(const char* funName, const char* fileName, int lineNum, int instrType, int implType) { m_disabled = false; m_regionTicks = 0; InstrStruct *pStruct = &getInstrumentStruct(); if(pStruct->useInstr) { InstrTLSStruct *pTLS = &getInstrumentTLSStruct(); // Disable in case of failure if(!pTLS->pCurrentNode) { m_disabled = true; return; } m_disabled = pTLS->pCurrentNode->m_payload.m_stopPoint; if(m_disabled) return; NodeData payload(funName, fileName, lineNum, instrType, implType); Node<NodeData>* pChild = NULL; if(pStruct->enableMapping) { // Critical section cv::AutoLock guard(pStruct->mutexCreate); // Guard from concurrent child creation pChild = pTLS->pCurrentNode->findChild(payload); if(!pChild) { pChild = new Node<NodeData>(payload); pTLS->pCurrentNode->addChild(pChild); } } else { pChild = pTLS->pCurrentNode->findChild(payload); if(!pChild) { pTLS->pCurrentNode->m_payload.m_stopPoint = true; return; } } pTLS->pCurrentNode = pChild; m_regionTicks = getTickCount(); } } IntrumentationRegion::~IntrumentationRegion() { InstrStruct *pStruct = &getInstrumentStruct(); if(pStruct->useInstr) { if(!m_disabled) { InstrTLSStruct *pTLS = &getInstrumentTLSStruct(); if(pTLS->pCurrentNode->m_payload.m_stopPoint) { pTLS->pCurrentNode->m_payload.m_stopPoint = false; } else { if(pTLS->pCurrentNode->m_payload.m_implType == cv::instr::IMPL_OPENCL && pTLS->pCurrentNode->m_payload.m_instrType == cv::instr::TYPE_FUN) cv::ocl::finish(); uint64 ticks = (getTickCount() - m_regionTicks); { cv::AutoLock guard(pStruct->mutexCount); // Concurrent ticks accumulation pTLS->pCurrentNode->m_payload.m_counter++; if(pTLS->pCurrentNode->m_payload.m_counter <= 1) pTLS->pCurrentNode->m_payload.m_ticksMean = ticks; else pTLS->pCurrentNode->m_payload.m_ticksMean = (pTLS->pCurrentNode->m_payload.m_ticksMean*(pTLS->pCurrentNode->m_payload.m_counter-1) + ticks)/pTLS->pCurrentNode->m_payload.m_counter; } pTLS->pCurrentNode = pTLS->pCurrentNode->m_pParent; } } } } #endif } namespace ipp { struct IPPInitSingleton { public: IPPInitSingleton() { useIPP = true; ippStatus = 0; funcname = NULL; filename = NULL; linen = 0; ippFeatures = 0; #ifdef HAVE_IPP const char* pIppEnv = getenv("OPENCV_IPP"); cv::String env = pIppEnv; if(env.size()) { if(env == "disabled") { std::cerr << "WARNING: IPP was disabled by OPENCV_IPP environment variable" << std::endl; useIPP = false; } #if IPP_VERSION_X100 >= 900 else if(env == "sse") ippFeatures = ippCPUID_SSE; else if(env == "sse2") ippFeatures = ippCPUID_SSE2; else if(env == "sse3") ippFeatures = ippCPUID_SSE3; else if(env == "ssse3") ippFeatures = ippCPUID_SSSE3; else if(env == "sse41") ippFeatures = ippCPUID_SSE41; else if(env == "sse42") ippFeatures = ippCPUID_SSE42; else if(env == "avx") ippFeatures = ippCPUID_AVX; else if(env == "avx2") ippFeatures = ippCPUID_AVX2; #endif else std::cerr << "ERROR: Improper value of OPENCV_IPP: " << env.c_str() << std::endl; } IPP_INITIALIZER(ippFeatures) #endif } bool useIPP; int ippStatus; // 0 - all is ok, -1 - IPP functions failed const char *funcname; const char *filename; int linen; int ippFeatures; }; static IPPInitSingleton& getIPPSingleton() { CV_SINGLETON_LAZY_INIT_REF(IPPInitSingleton, new IPPInitSingleton()) } int getIppFeatures() { #ifdef HAVE_IPP return getIPPSingleton().ippFeatures; #else return 0; #endif } void setIppStatus(int status, const char * const _funcname, const char * const _filename, int _line) { getIPPSingleton().ippStatus = status; getIPPSingleton().funcname = _funcname; getIPPSingleton().filename = _filename; getIPPSingleton().linen = _line; } int getIppStatus() { return getIPPSingleton().ippStatus; } String getIppErrorLocation() { return format("%s:%d %s", getIPPSingleton().filename ? getIPPSingleton().filename : "", getIPPSingleton().linen, getIPPSingleton().funcname ? getIPPSingleton().funcname : ""); } bool useIPP() { #ifdef HAVE_IPP CoreTLSData* data = getCoreTlsData().get(); if(data->useIPP < 0) { data->useIPP = getIPPSingleton().useIPP; } return (data->useIPP > 0); #else return false; #endif } void setUseIPP(bool flag) { CoreTLSData* data = getCoreTlsData().get(); #ifdef HAVE_IPP data->useIPP = (getIPPSingleton().useIPP)?flag:false; #else (void)flag; data->useIPP = false; #endif } } // namespace ipp } // namespace cv #ifdef HAVE_TEGRA_OPTIMIZATION namespace tegra { bool useTegra() { cv::CoreTLSData* data = cv::getCoreTlsData().get(); if (data->useTegra < 0) { const char* pTegraEnv = getenv("OPENCV_TEGRA"); if (pTegraEnv && (cv::String(pTegraEnv) == "disabled")) data->useTegra = false; else data->useTegra = true; } return (data->useTegra > 0); } void setUseTegra(bool flag) { cv::CoreTLSData* data = cv::getCoreTlsData().get(); data->useTegra = flag; } } // namespace tegra #endif /* End of file. */
;********** PVM player *********** ; 19-08-2015 v0.01: Beat display at logo. ; v0.02: Raster bars added - Stable raster from Ricardo's code ; xx-09-2015 v0.10: VUMeter added ; 02-09-2015 v0.15: Playtime timer added ; 04-09-2015 v0.16: Code cleanup !to "mp1.prg" !sl "labels.txt" !source "macros.asm" ; ***** variables ***** _charcount = $FB ;16-bit char counter _topline = $05 ;closing borders top raster _bottomline = $06 ;closing borders bottom raster _framecnt = $07 ;frameskip counter _flag = $23 ;generic flag _beat = $02 ;beat color cycle counter _vucnt = $10 ;VU Meter frame skip counter $10, $11, $12 _vunote = $13 ;VU Meter note played previous frame (for sustain effect) $13, $14, $15 _vufrm = $16 ;VU Meter current animframe $16, $17, $18 _vustat = $19 ;VU Meter state machine status $19, $1a, $1b (0 = idle, 4 = attack, 3 = decay, 2 = sustain, 1 = release) _vugate = $1c ;Gate status for previous frame $1c, $1d, $1e _tframe = $30 ;playtime frame count _tsecs = $31 ;playtime seconds _tmins = $32 ;playtime minutes _tpos = $33 ;playtime digit screen address $33,$34 ; ***** Constants ***** BEATINST = $02 ;Instrument to use for beat effect VUMETERS = $7f8 ;VU Meters sprite pointers ;********************** *= $0801 !zone start !word $080B,2015 !raw $9e,"2061",0,0,0 lda #$00 sta _flag sta _beat jsr initmem .xx06 bit _flag bpl .xx06 lda #$6b sta $d011 ;disable screen ;color fade ldx #$04 .xx07 lda _framecnt bne .xx07 lda #$04 sta _framecnt lda _colortable1,x sta $d020 dex bpl .xx07 ;set main irq sei lda #$fb ;this is how to tell at which rasterline we want the irq to be triggered sta $d012 inc _flag ;make music wait for us to be ready lda #<mainirq ;this is how we set up sta $fffe ;the address of our interrupt code lda #>mainirq sta $ffff cli ;--- jsr initscr ;Init screen lda #$1b sta $d011 ; enable screen dec _flag ;signal IRQ we're ready ;**** Main Loop **** ;Print Playtime .pp0 lda _tframe cmp #$31 ;wait for tframe reset bne .cc0 ;if not go check BEATINST lda _tsecs ldy #$04 jsr printbcd ;print seconds dey lda _tmins jsr printbcd ;print minutes ;Color cycle logo bars when BEATINST is played .cc0 ldy #$02 .cc2 lda shinst,y cmp _tinst,y ;check instrument playing changed beq .cc1 sta _tinst,y cmp #BEATINST ;changed, now check that is BEATINST bne .cc1 ; trigger color cycle lda #$03 sta _beat ; .cc1 dey bpl .cc2 bmi .pp0 .end jmp .end ;**** Print BCD **** printbcd: tax and #$0f jsr .pbcd txa lsr lsr lsr lsr .pbcd ora #$30 sta (_tpos),y dey rts ;***** White flash color cyble after initial screen close effect ***** _colortable1: !byte $00,$0b,$0c,$0f,$01 ;***** Color cycle for the beat effect ***** _colortable2: !byte $02,$0a,$01 ;***** temp inst status ***** _tinst: !byte $00, $00, $00 ;***** sprite block table ***** _sustainmap: _spblock: !byte $00,$01,$01,$02,$03,$03,$04,$05,$05,$06,$07,$07,$08,$09,$09,$0a ;***** Attack frame skip ***** _attackframes: !byte $00,$00,$00,$00,$00,$00,$00,$00,$00,$01,$02,$03,$04,$0e,$18,$27 ;***** Attack sprite frame increase _attackinc: !byte $0a,$0a,$0a,$0a,$05,$04,$04,$03,$02,$02,$02,$01,$01,$01,$01,$01 ;***** Decay/Release frame skip ***** _drframes: !byte $01,$01,$01,$01,$01,$01,$00,$01,$02,$03,$06,$0b,$0e,$2c,$4a,$77 ; !byte $00,$00,$00,$00,$00,$01,$00,$01,$02,$03,$06,$0b,$0e,$2c,$4a,$77 ;***** Decay/Release sprite frame decrease ***** _drinc: !byte $01,$01,$01,$01,$01,$01,$01,$02,$02,$01,$01,$01,$01,$01,$01,$01 ; !byte $0a,$0a,$05,$03,$02,$03,$01,$02,$02,$01,$01,$01,$01,$01,$01,$01 ;********* Init Screen ********* initscr: ldx #$00 stx $D021 ;clear screen lda #$20 ldx #$00 .ic1 sta $0400,x sta $0500,x sta $0600,x sta $0700,x inx bne .ic1 ;set color ram lda #$03 ldx #$00 .ic0 sta $D900,x sta $DA00,x sta $DB00,x inx bne .ic0 ;set color for logo - 10 rows unrolled ldx #$27 ;40 columns .lx1 !set lrow = 0 !do { lda map_data+lrow,x tay lda charset_attrib_data,y sta $d800+lrow,x !set lrow = lrow + 40 } while lrow < 400 dex bpl .lx1 ;Init sprites lda #$d3 sta VUMETERS ;set block sta VUMETERS+1 sta VUMETERS+2 ldx #$07 stx $d01c ;set multicolor stx $d015 ;enable ldx #$05 ;colors stx $d027 stx $d028 stx $d029 ldx #$0d stx $d025 ldx #$0b stx $d026 lda #$a8 ;Y-coordinates sta $d001 sta $d003 sta $d005 ldx #$ff ;X-coordinates stx $d010 stx $d017 stx $d01d ;expand lda #$04 sta $d000 lda #$17 sta $d002 lda #$2A sta $d004 ;print data fields labels ;Changed from single routine + init for each string, to dedicated hardcoded routine for each string, shorter and easier to read. ;Name 1x2 charset +PRINT1X2 _SNameLabel, $16, 8, 11, $400, $05 ;Author 1x1 charset +PRINT1X1 _SAuthorLabel, $0f, 1, 17, $400, $0f ;Date 1x1 charset +PRINT1X1 _SDateLabel, $11, 1, 19, $400, $0f ;Playtime 1x1 charset +PRINT1X1 _SPlayLabel, $0e, 1, 15, $400, $0f ;Credits 1x1 charset +PRINT1X1 _SChipLabel, $0c, 13, 24, $400, $0b +PRINT1X1 _SCodeLabel, $0d, 13, 23, $400, $0b +PRINT1X1 _SCharLabel, $11, 11, 22, $400, $0b +PRINT1X1 _SGFXLabel, $0d, 13, 21, $400, $0b ;VUMeter label ; +PRINT1X1 _SVULabel, $04, 31, 18, $400, $0f rts ; **** Configure memory, set IRQ routine **** initmem: sei ;disable maskable IRQs lda #$7f sta $dc0d ;disable timer interrupts which can be generated by the two CIA chips sta $dd0d ;the kernal uses such an interrupt to flash the cursor and scan the keyboard, so we better ;stop it. lda $dc0d ;by reading this two registers we negate any pending CIA irqs. lda $dd0d ;if we don't do this, a pending CIA irq might occur after we finish setting up our irq. ;we don't want that to happen. lda #COLR_CHAR_MC1 sta $d022 ;Multi color 1 lda #COLR_CHAR_MC2 sta $d023 ;Multi color 2 lda #$01 ;this is how to tell the VICII to generate a raster interrupt sta $d01a lda #$33 sta _topline lda #$fa ;this is how to tell at which rasterline we want the irq to be triggered sta _bottomline sta $d012 lda $D020 sta _charcount ;temp lda #$1b ;as there are more than 256 rasterlines, the topmost bit of $d011 serves as sta $d011 ;the 8th bit for the rasterline we want our irq to be triggered. ;here we simply set up a character screen, leaving the topmost bit 0. lda #$35 ;we turn off the BASIC and KERNAL rom here sta $01 ;the cpu now sees RAM everywhere except at $d000-$e000, where still the registers of ;SID/VICII/etc are visible lda #<bottom_irq ;this is how we set up sta $fffe ;the address of our interrupt code lda #>bottom_irq sta $ffff ; Init VU Meters variables ldx #$0c lda #$00 .im1 sta _vucnt,x dex bpl .im1 sta _tsecs ; Init playtime sta _tmins lda #$fe sta _vugate sta _vugate+1 sta _vugate+2 lda #$03 sta _framecnt ; Init frame counter lda #$31 ; Init playtime frame counter (for 50Hz) sta _tframe lda #$63 ldx #$06 sta _tpos stx _tpos+1 lda #$00 jsr $1000 ; Init music cli ;enable maskable interrupts again rts ; ******** IRQ Routine ******** ; *main irq, play music (1x speed) mainirq: pha txa pha tya pha lda #$3d ;set up next raster irq at line $40 (for raster bars) sta $d012 lda #<irq_rasterbars ;this is how we set up sta $fffe ;the address of our interrupt code lda #>irq_rasterbars sta $ffff lda #%10111101 ;chargen at $3000 - matrix at $2c00 sta $d018 lda $d016 ora #%00010000 ;set multicolor mode sta $d016 ;----- dec _framecnt bpl .ir01 ;---- ;**** Beat color cycle **** ldy _beat ;check if color cycle is in progress beq .ir03 dey sty _beat lda _colortable2,y sta $d022 sta rr1+1 ;modify code for raster bars .ir03 lda #$03 sta _framecnt .ir01 bit _flag ;Wait until main program flags us to start playing music. bpl .ir02 ;inc $d020 jsr $1003 ;Play music ;dec $d020 jsr VUpdate ;Update VU Meters jsr PTUpdate ;Update Playtime .ir02 ;----- asl $d019 pla tay pla tax pla rti ; *raster bars IRQ - for logo bars irq_rasterbars: pha ; saves A, X, Y txa pha tya pha +STABILIZE_RASTER sei jsr tworeds ldy #$01 jsr blacks1 ;two blacks - bad line jsr tworeds ldy #$33 jsr blacks1 ;six blacks jsr tworeds ldy #$08 jsr blacks1 ;two blacks jsr tworeds ldy #$33 jsr blacks1 ;six blacks jsr tworeds ldy #$01 ;two blacks - bad line jsr blacks1 jsr tworeds ldy #$32 jsr blacks1 ;six blacks jsr tworeds ldy#$08 jsr blacks1 ;two blacks jsr tworeds asl $d019 cli lda #$82 ;set up next raster irq at line $82 (just before 10th text row) sta $d012 lda #<secirq ;this is how we set up sta $fffe ;the address of our interrupt code lda #>secirq sta $ffff pla ; restores A, X, Y tay pla tax pla rti ; restores previous PC, status tworeds: ldy #$09 ;+2 .rra dey ;+2 bne .rra ;+2 +1 bit $00 ;+3 rr1 lda#$02 ;+2 sta$d020 ;+4 ldy #$17 ;+2 .rrb dey ;+2 bne .rrb ;+2 +1 bit $00 ;+3 lda #$00 sta $d020 rts blacks1: ;ldy #$01 ;+2 .rrc dey ;+2 bne .rrc ;+2 +1 bit $00 ;+3 rts ; *secondary IRQ - switchs from logo charset to 'normal' one secirq: pha txa pha tya pha lda #$fb ;set up next raster irq at line $fb (just after start of bottom border) sta $d012 lda #<mainirq ;this is how we set up sta $fffe ;the address of our interrupt code lda #>mainirq sta $ffff lda #%00011111 ;chargen at $1000 - matrix at $0400 sta $d018 lda $d016 and #%11101111 ;disable multicolor mode sta $d016 asl $d019 pla tay pla tax pla rti ; ******* subs IRQ ******* bottom_irq: pha txa pha tya pha ;----- lda _bottomline and #$07 cmp #$03 bne .bi01 nop nop nop nop nop nop nop nop nop nop nop nop .bi01 nop nop nop nop nop nop nop ; nop ; nop lda #$00 sta $d020 lda #$7b ;0b sta $d011 lda _topline sta $d012 lda #<top_irq ;this is how we set up sta $fffe ;the address of our interrupt code lda #>top_irq sta $ffff ;----- asl $d019 pla tay pla tax pla rti top_irq: pha txa pha tya pha ;----- ldx _topline inx cpx _bottomline bne .tpi01 ;center reached lda #$04 sta _framecnt lda #$0f ;this is how to tell at which rasterline we want the irq to be triggered sta $d012 dec _flag ;flag main routine, we're ready for next part lda #<idle_irq sta $fffe lda #>idle_irq bne .tpi02 ;sta $ffff .tpi01 lda _topline and #$07 cmp #$03 bne .ti01 ;bad line ; nop nop nop nop nop nop nop nop nop nop nop nop ; nop ; nop ; nop ; nop ; nop .ti01 nop nop nop nop lda #$1b sta $d011 lda _charcount sta $d020 stx _topline dec _bottomline lda _bottomline sta $d012 lda #<bottom_irq ;this is how we set up sta $fffe ;the address of our interrupt code lda #>bottom_irq .tpi02 sta $ffff ;----- asl $d019 pla tay pla tax pla rti idle_irq: pha txa pha tya pha ;----- dec _framecnt ;----- asl $d019 pla tay pla tax pla rti ;**** ;***** VUMeters code VUpdate: ;first check if gate status changed ldx #$03 .vu1 lda gate,x cmp _vugate,x beq .vu2 ;no change sta _vugate,x bcs .vu3 ;change to gate set -> attack ;change to gate clear -> release lda shad,x ;get Attack value lsr lsr lsr lsr tay lda _attackframes,y ;load frameskip counter sta _vucnt,x lda #$01 bne .vu4 .vu3 lda shsr ;ger Release value and #$15 tay lda _drframes,y ;load frameskip counter sta _vucnt,x lda #$04 .vu4 sta _vustat,x .vu2 dex bpl .vu1 ;state machine ldx #$02 .vu5 lda _vustat,x ;sta $720,x ;<-debug bne .vu0 jmp .vu6 ;idle .vu0 cmp #$04 bcc .vu7 ;-----attack ;check if frameskip reached 0 lda _vucnt,x beq .vu8b jmp .vu8 ;no .vu8b lda shnote,x ;get note ;sta $6f8,x ;Debug sta _vunote,x ;save for later lda shad,x ;get Attack value lsr lsr lsr lsr tay ;Yreg = Attack ;sta $748,x ;<-debug lda _attackframes,y ;reload frame skip counter sta _vucnt,x lda _attackinc,y ;get by how much we got to change sprite animation clc adc _vufrm,x ;and add to animation frame cmp #$0a bcc .vu9 lda #$0a ;reached full volume dec _vustat,x ;go to decay state pha lda _drframes,y ;set new frameskip sta _vucnt,x pla .vu9 sta _vufrm,x jmp .vu6 .vu7 cmp #$03 bcc .vu10 ;-----decay ;check if frameskip reached 0 lda _vucnt,x beq .vu8a jmp .vu8 ;no .vu8a lda shad,x ;get Delay value and #$0f ;sta $770,x ;<-debug tay ;Yreg = Decay lda _drframes,y ;reload frame skip counter sta _vucnt,x lda _vufrm,x ;get animation frame sec sbc _drinc,y ;and subtract appropriate value pha ;sta _vufrm,x lda shsr,x ;get curret sustain level lsr lsr lsr lsr tay pla clc cmp _sustainmap,y ;map sustain level to animation frame ;cmp _vufrm,x beq .vu11 ;reached sustain level bcs .vu14 ;not yet lda _sustainmap,y ;sta _vufrm,x ;we were below sustain level .vu11 dec _vustat,x ;go to sustain state .vu14 sta _vufrm,x bne .vu6 .vu10 cmp #$02 bcc .vu12 ;-----sustain lda _vucnt,x bne .vu8 ;no lda #$02 sta _vucnt,x lda shsr,x ;get Sustain value lsr lsr lsr lsr ;sta $798,x ;<-debug tay ;Yreg = Sustain lda _sustainmap,y ;map sustain level to animation frame cmp _vufrm,x bcs .vu15 ;sustain level is greater or equal than current animation frame, nothing to do sta _vufrm,x ;update frame only if sustain level decreases .vu15 cmp #$0a ;animate it a little if note changes while in sustain beq .vu6 ;if full volume, continue lda shnote,x ;otherwise cmp _vunote,x ;check if note changed beq .vu6 inc _vufrm,x ;increase frame if so sta _vunote,x bpl .vu6 .vu12 ;-----release ;check if frameskip reached 0 lda _vucnt,x bne .vu8 ;no lda shsr,x ;get Release value and #$0f ;sta $7c0,x ;<-debug tay ;Yreg = Release lda _drframes,y ;reload frame skip counter sta _vucnt,x lda _vufrm,x ;get animation frame sec sbc _drinc,y ;and subtract appropriate value sta _vufrm,x beq .vu13 ;reached 0 bpl .vu6 ;not yet lda #$00 sta _vufrm,x ;we were below 0 .vu13 dec _vustat,x ;go to idle state beq .vu6 .vu8 dec _vucnt,x .vu6 lda _vufrm,x clc adc #$d3 sta VUMETERS,x ;update sprite pointers dex bmi .vue jmp .vu5 .vue rts ;**** Update Playtime PTUpdate: dec _tframe bpl .pte lda #$31 ;Reset _tframe sta _tframe sed clc lda #$01 adc _tsecs cmp #$60 bne .ptu0 clc lda #$01 adc _tmins sta _tmins lda #$00 .ptu0 sta _tsecs cld .pte ;**** codeend: rts ;***** MUSIC ***** ;*=$1000 !source "uc-low_serotonin.s" ;***** Logo charset ***** !source "logo2_.asm" ;***** Sprites ***** *=$34C0 !bin "sprites2.bin" ;***** Main charset ***** *=$3800 !bin "Arlek-05b_7bit_fixed_woz.bin" ;"charset2.bin" ;***** Text ***** _SNameLabel: !scrxor $80,"4516 " !scrxor $80,"low serotonin" !scrxor $80," 0123" _SAuthorLabel: !scr "author: " !scr "uctumi" _SDateLabel: !scr "released: " !scr "08/03/16" _SPlayLabel: !scr "playtime: 00:00" _SGFXLabel: !scr "gfx: alakran" _SCharLabel: !scr "charset: arlequin" _SCodeLabel: !scr "code: the" !8 95 !scr "woz" _SChipLabel: !scr "chip: 8580" ;_SVULabel: ; !scrxor $80,"1 2 3"
; Disassembly of file: hello.o ; Wed Nov 29 10:56:31 2017 ; Mode: 32 bits ; Syntax: YASM/NASM ; Instruction set: 80386 global _main extern _printf ; near SECTION .text align=1 execute ; section number 1, code _main: ; Function begin push ebp ; 0000 _ 55 mov ebp, esp ; 0001 _ 89. E5 push msg ; 0003 _ 68, 00000000(d) call _printf ; 0008 _ E8, 00000000(rel) mov eax, 0 ; 000D _ B8, 00000000 leave ; 0012 _ C9 ret ; 0013 _ C3 ; _main End of function nop ; 0014 _ 90 nop ; 0015 _ 90 nop ; 0016 _ 90 nop ; 0017 _ 90 nop ; 0018 _ 90 nop ; 0019 _ 90 nop ; 001A _ 90 nop ; 001B _ 90 nop ; 001C _ 90 nop ; 001D _ 90 nop ; 001E _ 90 nop ; 001F _ 90 SECTION .data align=1 noexecute ; section number 2, data msg: ; byte db 48H, 65H, 6CH, 6CH, 6FH, 20H, 77H, 6FH ; 0000 _ Hello wo db 72H, 6CH, 64H, 21H, 20H, 0AH, 00H, 00H ; 0008 _ rld! ... SECTION .bss align=1 noexecute ; section number 3, bss
; A249769: Sequence of distinct least positive numbers such that the average of the first n terms is a factorial. ; 1,3,2,18,6,114,24,792,120,6120,720,52560,5040,498960,40320,5201280,362880,59149440,3628800,729388800,39916800,9699782400,479001600,138431462400,6227020800,2110960051200,87178291200,34261068441600,1307674368000,589761139968000,20922789888000 mov $3,2 mov $7,$0 lpb $3 mov $0,$7 sub $3,1 add $0,$3 sub $0,1 mov $5,$0 add $5,1 mov $4,$5 mov $6,1 mov $8,1 lpb $0 trn $0,2 add $6,$8 mul $4,$6 lpe mov $2,$3 mov $8,$4 lpb $2 mov $1,$8 sub $2,1 lpe lpe lpb $7 sub $1,$8 mov $7,0 lpe
; WARNING: Autogenerated file! Do not put extra data here; editor will not preserve it! .byte $02, $BD, $42, $42, $B4, $D7, $4B, $43, $43, $43, $4B, $D7, $E2, $42, $42, $02 .byte $02, $B4, $42, $B4, $42, $42, $42, $43, $43, $5E, $42, $42, $D7, $42, $42, $02 .byte $02, $49, $E5, $45, $47, $42, $42, $42, $D7, $D7, $D7, $D7, $D7, $60, $42, $02 .byte $02, $B4, $42, $BD, $46, $42, $42, $BE, $D7, $BB, $42, $42, $42, $42, $42, $02 .byte $02, $B4, $BC, $42, $03, $D7, $42, $D7, $D7, $BC, $84, $86, $BB, $BB, $42, $02 .byte $02, $B4, $42, $42, $46, $42, $BE, $42, $BB, $42, $8C, $8E, $D7, $42, $42, $02 .byte $02, $42, $42, $BE, $48, $E0, $D7, $D7, $42, $42, $8C, $8F, $85, $85, $85, $02 .byte $02, $42, $42, $42, $EA, $EA, $42, $42, $84, $85, $90, $8D, $8D, $8D, $8D, $02 .byte $02, $43, $42, $EA, $48, $D7, $BB, $D7, $4B, $8D, $8D, $8D, $8D, $8D, $8D, $02 .byte $FF
format binary as 'gba' include '../lib/macros.inc' macro m_exit test { mov r7, test bl tmain_end } header: include '../lib/header.asm' main: m_test_init adr r0, tmain + 1 bx r0 code16 align 2 tmain: ; Reset test register mov r7, 0 ; Tests start at 1 include 'logical.asm' ; Tests start at 50 include 'shifts.asm' ; Tests start at 100 include 'arithmetic.asm' ; Tests start at 150 include 'branches.asm' ; Tests start at 200 include 'memory.asm' tmain_end: adr r0, eval bx r0 code32 align 4 eval: m_vsync m_test_eval r7 idle: b idle include '../lib/text.asm'
; A024378: a(n) = 2nd elementary symmetric function of the first n+1 positive integers congruent to 1 mod 4. ; 5,59,254,730,1675,3325,5964,9924,15585,23375,33770,47294,64519,86065,112600,144840,183549,229539,283670,346850,420035,504229,600484,709900,833625,972855,1128834,1302854,1496255,1710425,1946800,2206864,2492149 mov $5,4 mov $7,$0 lpb $0 add $1,6 add $1,$0 add $5,$0 sub $0,1 add $5,3 add $1,$5 add $6,3 lpe add $1,$6 add $1,2 add $1,$6 add $1,3 mov $4,$7 mov $8,$7 lpb $4 add $2,$8 sub $4,1 lpe mov $3,20 mov $8,$2 lpb $3 add $1,$8 sub $3,1 lpe mov $2,0 mov $4,$7 lpb $4 add $2,$8 sub $4,1 lpe mov $3,11 mov $8,$2 lpb $3 add $1,$8 sub $3,1 lpe mov $2,0 mov $4,$7 lpb $4 add $2,$8 sub $4,1 lpe mov $3,2 mov $8,$2 lpb $3 add $1,$8 sub $3,1 lpe
dnl IA-64 mpn_sec_tabselect. dnl Copyright 2011 Free Software Foundation, Inc. dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or modify dnl it under the terms of either: dnl dnl * the GNU Lesser General Public License as published by the Free dnl Software Foundation; either version 3 of the License, or (at your dnl option) any later version. dnl dnl or dnl dnl * the GNU General Public License as published by the Free Software dnl Foundation; either version 2 of the License, or (at your option) any dnl later version. dnl dnl or both in parallel, as here. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License dnl for more details. dnl dnl You should have received copies of the GNU General Public License and the dnl GNU Lesser General Public License along with the GNU MP Library. If not, dnl see https://www.gnu.org/licenses/. include(`../config.m4') C cycles/limb C Itanium: ? C Itanium 2: 2.5 C NOTES C * Using software pipelining could trivially yield 2 c/l without unrolling, C or 1+epsilon with unrolling. (This code was modelled after the powerpc64 C code, for simplicity.) C mpn_sec_tabselect (mp_limb_t *rp, mp_limb_t *tp, mp_size_t n, mp_size_t nents, mp_size_t which) define(`rp', `r32') define(`tp', `r33') define(`n', `r34') define(`nents', `r35') define(`which', `r36') define(`mask', `r8') define(`rp1', `r32') define(`tp1', `r33') define(`rp2', `r14') define(`tp2', `r15') ASM_START() TEXT ALIGN(16) PROLOGUE(mpn_sec_tabselect) .prologue .save ar.lc, r2 .body ifdef(`HAVE_ABI_32',` .mmi; addp4 rp = 0, rp C M I addp4 tp = 0, tp C M I zxt4 n = n C I .mii; nop 0 zxt4 nents = nents C I zxt4 which = which C I ;; ') .mmi; add rp2 = 8, rp1 add tp2 = 8, tp1 add r6 = -2, n ;; .mmi; cmp.eq p10, p0 = 1, n and r9 = 1, n C set cr0 for use in inner loop shr.u r6 = r6, 1 C inner loop count ;; .mmi; cmp.eq p8, p0 = 0, r9 sub which = nents, which shl n = n, 3 ;; L(outer): .mmi cmp.eq p6, p7 = which, nents C are we at the selected table entry? nop 0 mov ar.lc = r6 C I0 ;; .mmb; (p6) mov mask = -1 (p7) mov mask = 0 (p8) br.dptk L(top) C branch to loop entry if n even ;; .mmi; ld8 r16 = [tp1], 8 add tp2 = 8, tp2 nop 0 ;; .mmi; ld8 r18 = [rp1] and r16 = r16, mask nop 0 ;; .mmi; andcm r18 = r18, mask ;; or r16 = r16, r18 nop 0 ;; .mmb; st8 [rp1] = r16, 8 add rp2 = 8, rp2 (p10) br.dpnt L(end) ALIGN(32) L(top): .mmi; ld8 r16 = [tp1], 16 ld8 r17 = [tp2], 16 nop 0 ;; .mmi; ld8 r18 = [rp1] and r16 = r16, mask nop 0 .mmi; ld8 r19 = [rp2] and r17 = r17, mask nop 0 ;; .mmi; andcm r18 = r18, mask andcm r19 = r19, mask nop 0 ;; .mmi; or r16 = r16, r18 or r17 = r17, r19 nop 0 ;; .mmb; st8 [rp1] = r16, 16 st8 [rp2] = r17, 16 br.cloop.dptk L(top) ;; L(end): .mmi; sub rp1 = rp1, n C move rp back to beginning sub rp2 = rp2, n C move rp back to beginning cmp.ne p9, p0 = 1, nents .mmb; add nents = -1, nents nop 0 (p9) br.dptk L(outer) ;; .mib; nop 0 nop 0 br.ret.sptk.many b0 EPILOGUE()
// Copyright 2020 Google LLC // // 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 "aistreams/base/packet.h" #include <memory> #include <string> #include "aistreams/base/types/eos.h" #include "aistreams/base/types/gstreamer_buffer.h" #include "aistreams/base/types/jpeg_frame.h" #include "aistreams/base/types/raw_image.h" #include "aistreams/port/gtest.h" #include "aistreams/port/logging.h" #include "aistreams/port/status.h" #include "aistreams/port/statusor.h" #include "aistreams/proto/packet.pb.h" #include "aistreams/proto/types/control_signal.pb.h" #include "aistreams/proto/types/raw_image.pb.h" #include "aistreams/proto/types/raw_image_packet_type_descriptor.pb.h" namespace aistreams { TEST(PacketTest, MakePacketStringTest) { { std::string s("hello!"); auto packet_status_or = MakePacket(s); EXPECT_TRUE(packet_status_or.ok()); auto packet = std::move(packet_status_or).ValueOrDie(); EXPECT_EQ(packet.header().type().type_id(), PACKET_TYPE_STRING); EXPECT_EQ(packet.payload(), s); } { std::string s("hello!"); std::string tmp(s); auto packet_status_or = MakePacket(std::move(tmp)); EXPECT_TRUE(packet_status_or.ok()); auto packet = std::move(packet_status_or).ValueOrDie(); EXPECT_EQ(packet.header().type().type_id(), PACKET_TYPE_STRING); EXPECT_EQ(packet.payload(), s); } } TEST(PacketTest, PacketAsStringTest) { { std::string src("hey!"); auto packet_status_or = MakePacket(src); EXPECT_TRUE(packet_status_or.ok()); PacketAs<std::string> packet_as(std::move(packet_status_or).ValueOrDie()); EXPECT_TRUE(packet_as.ok()); PacketHeader header = packet_as.header(); EXPECT_EQ(header.type().type_id(), PACKET_TYPE_STRING); std::string dst = std::move(packet_as).ValueOrDie(); EXPECT_EQ(dst, src); } } TEST(PacketTest, MakePacketRawImageTest) { { RawImage r(2, 3, RAW_IMAGE_FORMAT_SRGB); r(0) = 3; r(1) = 1; r(2) = 4; auto packet_status_or = MakePacket(r); EXPECT_TRUE(packet_status_or.ok()); auto packet = std::move(packet_status_or).ValueOrDie(); EXPECT_EQ(packet.header().type().type_id(), PACKET_TYPE_RAW_IMAGE); RawImagePacketTypeDescriptor raw_image_packet_type_desc; EXPECT_TRUE(packet.header().type().type_descriptor().UnpackTo( &raw_image_packet_type_desc)); RawImageDescriptor raw_image_descriptor = raw_image_packet_type_desc.raw_image_descriptor(); EXPECT_EQ(raw_image_descriptor.height(), 2); EXPECT_EQ(raw_image_descriptor.width(), 3); EXPECT_EQ(raw_image_descriptor.format(), RAW_IMAGE_FORMAT_SRGB); EXPECT_EQ(packet.payload()[0], 3); EXPECT_EQ(packet.payload()[1], 1); EXPECT_EQ(packet.payload()[2], 4); EXPECT_EQ(packet.payload().size(), 18); } } TEST(PacketTest, PacketAsRawImageTest) { { RawImage src(2, 3, RAW_IMAGE_FORMAT_SRGB); src(0) = 3; src(1) = 1; src(2) = 4; auto packet_status_or = MakePacket(src); EXPECT_TRUE(packet_status_or.ok()); PacketAs<RawImage> packet_as(std::move(packet_status_or).ValueOrDie()); EXPECT_TRUE(packet_as.ok()); PacketHeader header = packet_as.header(); EXPECT_EQ(header.type().type_id(), PACKET_TYPE_RAW_IMAGE); RawImagePacketTypeDescriptor raw_image_packet_type_desc; EXPECT_TRUE( header.type().type_descriptor().UnpackTo(&raw_image_packet_type_desc)); RawImageDescriptor raw_image_descriptor = raw_image_packet_type_desc.raw_image_descriptor(); EXPECT_EQ(raw_image_descriptor.height(), 2); EXPECT_EQ(raw_image_descriptor.width(), 3); EXPECT_EQ(raw_image_descriptor.format(), RAW_IMAGE_FORMAT_SRGB); RawImage dst = std::move(packet_as).ValueOrDie(); EXPECT_EQ(dst.height(), src.height()); EXPECT_EQ(dst.width(), src.width()); EXPECT_EQ(dst.channels(), src.channels()); EXPECT_EQ(dst.format(), src.format()); EXPECT_EQ(dst.size(), src.size()); for (size_t i = 0; i < dst.size(); ++i) { EXPECT_EQ(dst(i), src(i)); } } { RawImage src(2, 3, RAW_IMAGE_FORMAT_SRGB); auto packet_status_or = MakePacket(src); EXPECT_TRUE(packet_status_or.ok()); PacketAs<std::string> packet_as(std::move(packet_status_or).ValueOrDie()); EXPECT_FALSE(packet_as.ok()); ASSERT_DEATH(packet_as.ValueOrDie(), ""); } } TEST(PacketTest, MakePacketJpegFrameTest) { { std::string bytes(10, 2); auto packet_status_or = MakePacket(JpegFrame(bytes)); EXPECT_TRUE(packet_status_or.ok()); auto packet = std::move(packet_status_or).ValueOrDie(); EXPECT_EQ(packet.header().type().type_id(), PACKET_TYPE_JPEG); for (size_t i = 0; i < bytes.size(); ++i) { EXPECT_EQ(packet.payload()[i], bytes[i]); } EXPECT_EQ(packet.payload().size(), bytes.size()); } } TEST(PacketTest, PacketAsJpegFrameTest) { { std::string src(10, 2); auto packet_status_or = MakePacket(JpegFrame(src)); EXPECT_TRUE(packet_status_or.ok()); PacketAs<JpegFrame> packet_as(std::move(packet_status_or).ValueOrDie()); EXPECT_TRUE(packet_as.ok()); PacketHeader header = packet_as.header(); EXPECT_EQ(header.type().type_id(), PACKET_TYPE_JPEG); JpegFrame dst = std::move(packet_as).ValueOrDie(); EXPECT_EQ(dst.size(), src.size()); for (size_t i = 0; i < dst.size(); ++i) { EXPECT_EQ(dst.data()[i], src[i]); } } } TEST(PacketTest, ProtobufPacketTest) { { // Packing a string Packet into a protobuf Packet. Packet src_string_packet; { std::string s("hello!"); auto packet_status_or = MakePacket(s); EXPECT_TRUE(packet_status_or.ok()); src_string_packet = std::move(packet_status_or).ValueOrDie(); } auto packet_status_or = MakePacket(src_string_packet); EXPECT_TRUE(packet_status_or.ok()); auto protobuf_packet = std::move(packet_status_or).ValueOrDie(); EXPECT_EQ(protobuf_packet.header().type().type_id(), PACKET_TYPE_PROTOBUF); // Reading out the string Packet from the protobuf Packet. PacketAs<Packet> packet_as(protobuf_packet); EXPECT_TRUE(packet_as.ok()); Packet dst_string_packet = std::move(packet_as).ValueOrDie(); EXPECT_EQ(dst_string_packet.header().type().type_id(), PACKET_TYPE_STRING); EXPECT_EQ(dst_string_packet.payload(), src_string_packet.payload()); } { // Create a protobuf Packet containing a Packet protobuf. Packet string_packet; { std::string s("hello!"); auto packet_status_or = MakePacket(s); EXPECT_TRUE(packet_status_or.ok()); string_packet = std::move(packet_status_or).ValueOrDie(); } auto packet_status_or = MakePacket(string_packet); EXPECT_TRUE(packet_status_or.ok()); auto protobuf_packet = std::move(packet_status_or).ValueOrDie(); // Test that it is not possible to read it out as another protobuf message. PacketAs<RawImageDescriptor> packet_as(protobuf_packet); EXPECT_FALSE(packet_as.ok()); ASSERT_DEATH(packet_as.ValueOrDie(), ""); } { std::string s("hello!"); auto packet_status_or = MakePacket(s); EXPECT_TRUE(packet_status_or.ok()); const Packet string_packet = std::move(packet_status_or).ValueOrDie(); packet_status_or = MakePacket(string_packet); EXPECT_TRUE(packet_status_or.ok()); auto protobuf_packet = std::move(packet_status_or).ValueOrDie(); // Test that it is not possible to read it out as another protobuf // message. PacketAs<RawImageDescriptor> packet_as(protobuf_packet); EXPECT_FALSE(packet_as.ok()); ASSERT_DEATH(packet_as.ValueOrDie(), ""); } } TEST(PacketTest, MakePacketGstreamerBufferTest) { { std::string caps("video/x-raw"); std::string bytes(10, 2); GstreamerBuffer gstreamer_buffer; gstreamer_buffer.set_caps_string(caps); gstreamer_buffer.assign(bytes); auto packet_status_or = MakePacket(gstreamer_buffer); EXPECT_TRUE(packet_status_or.ok()); auto packet = std::move(packet_status_or).ValueOrDie(); EXPECT_EQ(packet.header().type().type_id(), PACKET_TYPE_GSTREAMER_BUFFER); for (size_t i = 0; i < bytes.size(); ++i) { EXPECT_EQ(packet.payload()[i], bytes[i]); } EXPECT_EQ(packet.payload().size(), bytes.size()); GstreamerBufferPacketTypeDescriptor gstreamer_buffer_packet_type_desc; EXPECT_TRUE(packet.header().type().type_descriptor().UnpackTo( &gstreamer_buffer_packet_type_desc)); EXPECT_EQ(gstreamer_buffer_packet_type_desc.caps_string(), caps); } { std::string caps("video/x-raw"); std::string bytes(10, 2); GstreamerBuffer gstreamer_buffer; gstreamer_buffer.set_caps_string(caps); gstreamer_buffer.assign(bytes); auto packet_status_or = MakePacket(std::move(gstreamer_buffer)); EXPECT_TRUE(packet_status_or.ok()); auto packet = std::move(packet_status_or).ValueOrDie(); EXPECT_EQ(packet.header().type().type_id(), PACKET_TYPE_GSTREAMER_BUFFER); for (size_t i = 0; i < bytes.size(); ++i) { EXPECT_EQ(packet.payload()[i], bytes[i]); } EXPECT_EQ(packet.payload().size(), bytes.size()); GstreamerBufferPacketTypeDescriptor gstreamer_buffer_packet_type_desc; EXPECT_TRUE(packet.header().type().type_descriptor().UnpackTo( &gstreamer_buffer_packet_type_desc)); EXPECT_EQ(gstreamer_buffer_packet_type_desc.caps_string(), caps); } } TEST(PacketTest, PacketAsGstreamerBufferTest) { { std::string caps("video/x-raw"); std::string bytes(10, 2); GstreamerBuffer src; src.set_caps_string(caps); src.assign(bytes); auto packet_status_or = MakePacket(src); EXPECT_TRUE(packet_status_or.ok()); PacketAs<GstreamerBuffer> packet_as( std::move(packet_status_or).ValueOrDie()); EXPECT_TRUE(packet_as.ok()); PacketHeader header = packet_as.header(); EXPECT_EQ(header.type().type_id(), PACKET_TYPE_GSTREAMER_BUFFER); GstreamerBuffer dst = std::move(packet_as).ValueOrDie(); EXPECT_EQ(caps, dst.get_caps()); EXPECT_EQ(bytes, std::string(dst.data(), dst.size())); } } TEST(PacketTest, MakePacketEosTest) { { std::string reason = "some reason"; EosValue eos_value; eos_value.set_reason(reason); Eos eos(eos_value); auto packet_status_or = MakePacket(eos); EXPECT_TRUE(packet_status_or.ok()); auto packet = std::move(packet_status_or).ValueOrDie(); EXPECT_EQ(packet.header().type().type_id(), PACKET_TYPE_CONTROL_SIGNAL); EosValue dst_eos_value; EXPECT_TRUE(dst_eos_value.ParseFromString(packet.payload())); EXPECT_EQ(eos_value.reason(), dst_eos_value.reason()); EXPECT_EQ(dst_eos_value.reason(), reason); } } TEST(PacketTest, PacketAsEosTest) { { std::string reason = "some reason"; Eos eos; eos.set_reason(reason); auto packet_status_or = MakePacket(eos); EXPECT_TRUE(packet_status_or.ok()); PacketAs<Eos> packet_as(std::move(packet_status_or).ValueOrDie()); EXPECT_TRUE(packet_as.ok()); PacketHeader header = packet_as.header(); EXPECT_EQ(header.type().type_id(), PACKET_TYPE_CONTROL_SIGNAL); eos = std::move(packet_as).ValueOrDie(); EXPECT_EQ(eos.reason(), reason); } { std::string src("hey!"); auto packet_status_or = MakePacket(src); PacketAs<Eos> packet_as(std::move(packet_status_or).ValueOrDie()); EXPECT_FALSE(packet_as.ok()); } } TEST(PacketTest, MakeEosPacketTest) { { std::string reason = "some reason"; auto packet_status_or = MakeEosPacket(reason); EXPECT_TRUE(packet_status_or.ok()); PacketAs<Eos> packet_as(std::move(packet_status_or).ValueOrDie()); EXPECT_TRUE(packet_as.ok()); PacketHeader header = packet_as.header(); EXPECT_EQ(header.type().type_id(), PACKET_TYPE_CONTROL_SIGNAL); Eos eos = std::move(packet_as).ValueOrDie(); EXPECT_EQ(eos.reason(), reason); } } } // namespace aistreams
; A024163: Number of integer-sided triangles with sides a,b,c, a<b<c, a+b+c=n such that c - b < b - a. ; 0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,3,1,3,3,3,3,6,3,6,6,6,6,10,6,10,10,10,10,15,10,15,15,15,15,21,15,21,21,21,21,28,21,28,28,28,28,36,28,36,36,36,36,45,36,45,45,45,45,55,45,55,55,55,55,66,55,66,66,66,66,78,66,78,78,78,78,91,78,91,91,91,91,105,91,105,105,105,105,120,105,120,120,120,120 trn $0,2 seq $0,8615 ; a(n) = floor(n/2) - floor(n/3). mov $1,$0 sub $0,1 mul $0,2 mul $0,$1 div $0,4
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // 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 "pass_ncnn.h" namespace pnnx { namespace ncnn { class torch_prod : public GraphRewriterPass { public: const char* match_pattern_graph() const { return R"PNNXIR(7767517 3 2 pnnx.Input input 0 1 input torch.prod op_0 1 1 input out dim=%dim keepdim=%keepdim pnnx.Output output 1 0 out )PNNXIR"; } const char* type_str() const { return "Reduction"; } const char* name_str() const { return "prod"; } void write(Operator* op, const std::map<std::string, Parameter>& captured_params) const { int dim = captured_params.at("dim").i; const int batch_index = op->inputs[0]->params["__batch_index"].i; if (dim == batch_index) { fprintf(stderr, "prod along batch axis is not supported\n"); return; } int new_dim = dim > batch_index ? dim - 1 : dim; op->params["0"] = 6; op->params["1"] = 0; op->params["3"] = std::vector<int>{new_dim}; op->params["4"] = captured_params.at("keepdim").b ? 1 : 0; } }; REGISTER_GLOBAL_PNNX_NCNN_GRAPH_REWRITER_PASS(torch_prod, 20) } // namespace ncnn } // namespace pnnx
.include "defaults_mod.asm" table_file_jp equ "exe4-utf8.tbl" table_file_en equ "bn4-utf8.tbl" game_code_len equ 3 game_code equ 0x4234574A // B4WJ game_code_2 equ 0x42345745 // B4WE game_code_3 equ 0x42345750 // B4WP card_type equ 1 card_id equ 124 card_no equ "124" card_sub equ "Mod Card 124" card_sub_x equ 64 card_desc_len equ 3 card_desc_1 equ "Address 0E" card_desc_2 equ "SearchSoul (Buggy)" card_desc_3 equ "Red Sun only" card_name_jp_full equ "サーチソウル" card_name_jp_game equ "サーチソウル" card_name_en_full equ "SearchSoul" card_name_en_game equ "SearchSoul" card_address equ "0E" card_address_id equ 4 card_bug equ 1 card_wrote_en equ "SearchSoul" card_wrote_jp equ "サーチソウル"
/*--------------------------------------------------------------------------*\ | | | Copyright (C) 2017 | | | | , __ , __ | | /|/ \ /|/ \ | | | __/ _ ,_ | __/ _ ,_ | | | \|/ / | | | | \|/ / | | | | | |(__/|__/ |_/ \_/|/|(__/|__/ |_/ \_/|/ | | /| /| | | \| \| | | | | Enrico Bertolazzi | | Dipartimento di Ingegneria Industriale | | Universita` degli Studi di Trento | | email: enrico.bertolazzi@unitn.it | | | \*--------------------------------------------------------------------------*/ #include "Line.hh" #include "Circle.hh" #include "Biarc.hh" #include "Clothoid.hh" #include "ClothoidList.hh" #include "PolyLine.hh" #include "CubicRootsFlocke.hh" // workaround for windows that defines max and min as macros! #ifdef max #undef max #endif #ifdef min #undef min #endif #include <cmath> #include <cfloat> #include <algorithm> namespace G2lib { using std::vector; using std::abs; using std::min; using std::max; using std::swap; using std::ceil; using std::floor; using std::isfinite; using std::numeric_limits; int_type ClothoidCurve::max_iter = 10; real_type ClothoidCurve::tolerance = 1e-9; // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ClothoidCurve::ClothoidCurve( BaseCurve const & C ) : BaseCurve(G2LIB_CLOTHOID) , aabb_done(false) { switch ( C.type() ) { case G2LIB_LINE: build( *static_cast<LineSegment const *>(&C) ); break; case G2LIB_CIRCLE: build( *static_cast<CircleArc const *>(&C) ); break; case G2LIB_CLOTHOID: copy( *static_cast<ClothoidCurve const *>(&C) ); break; case G2LIB_BIARC: case G2LIB_CLOTHOID_LIST: case G2LIB_POLYLINE: G2LIB_ASSERT( false, "ClothoidList constructor cannot convert from: " << CurveType_name[C.type()] ); } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . void ClothoidCurve::optimized_sample_internal( real_type s_begin, real_type s_end, real_type offs, real_type ds, real_type max_angle, vector<real_type> & s ) const { real_type ss = s_begin; real_type thh = theta(s_begin); for ( int_type npts = 0; ss < s_end; ++npts ) { G2LIB_ASSERT( npts < 1000000, "ClothoidCurve::optimized_sample_internal " << "is generating too much points (>1000000)\n" << "something is going wrong or parameters are not well set" ); // estimate angle variation and compute step accodingly real_type k = CD.kappa( ss ); real_type dss = ds/(1-k*offs); // scale length with offset real_type sss = ss + dss; if ( sss > s_end ) { sss = s_end; dss = s_end-ss; } if ( abs(k*dss) > max_angle ) { dss = abs(max_angle/k); sss = ss + dss; } // check and recompute if necessary real_type thhh = theta(sss); if ( abs(thh-thhh) > max_angle ) { k = CD.kappa( sss ); dss = abs(max_angle/k); sss = ss + dss; thhh = theta(sss); } ss = sss; thh = thhh; s.push_back(ss); } s.back() = s_end; } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . void ClothoidCurve::optimized_sample( real_type offs, int_type npts, real_type max_angle, vector<real_type> & s ) const { s.clear(); s.reserve( size_t(npts) ); s.push_back(0); real_type ds = L/npts; if ( CD.kappa0*CD.dk >= 0 || CD.kappa(L)*CD.dk <= 0 ) { optimized_sample_internal( 0, L, offs, ds, max_angle, s ); } else { // flex inside, split clothoid real_type sflex = -CD.kappa0/CD.dk; optimized_sample_internal( 0, sflex, offs, ds, max_angle, s ); optimized_sample_internal( sflex, L, offs, ds, max_angle, s ); } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /*\ | _ _ _____ _ _ | | |__| |_|_ _| _(_)__ _ _ _ __ _| |___ | | '_ \ '_ \| || '_| / _` | ' \/ _` | / -_) | |_.__/_.__/|_||_| |_\__,_|_||_\__, |_\___| | |___/ \*/ // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . void ClothoidCurve::bbTriangles_internal( real_type offs, vector<T2D> & tvec, real_type s_begin, real_type s_end, real_type max_angle, real_type max_size, int_type icurve ) const { static real_type const one_degree = m_pi/180; real_type ss = s_begin; real_type thh = CD.theta(ss); real_type MX = min( L, max_size ); for ( int_type npts = 0; ss < s_end; ++npts ) { G2LIB_ASSERT( npts < 1000000, "ClothoidCurve::bbTriangles_internal " << "is generating too much triangles (>1000000)\n" << "something is going wrong or parameters are not well set" ); // estimate angle variation and compute step accodingly real_type k = CD.kappa( ss ); real_type dss = MX/(1-k*offs); // scale length with offset real_type sss = ss + dss; if ( sss > s_end ) { sss = s_end; dss = s_end-ss; } if ( abs(k*dss) > max_angle ) { dss = abs(max_angle/k); sss = ss + dss; } // check and recompute if necessary real_type thhh = theta(sss); if ( abs(thh-thhh) > max_angle ) { k = CD.kappa( sss ); dss = abs(max_angle/k); sss = ss + dss; thhh = theta(sss); } real_type x0, y0, x1, y1; CD.eval( ss, offs, x0, y0 ); CD.eval( sss, offs, x1, y1 ); real_type tx0 = cos(thh); real_type ty0 = sin(thh); real_type alpha = sss-ss; // se angolo troppo piccolo uso approx piu rozza if ( abs(thh-thhh) > one_degree ) { real_type tx1 = cos(thhh); real_type ty1 = sin(thhh); real_type det = tx1 * ty0 - tx0 * ty1; real_type dx = x1-x0; real_type dy = y1-y0; alpha = (dy*tx1 - dx*ty1)/det; } real_type x2 = x0 + alpha*tx0; real_type y2 = y0 + alpha*ty0; T2D t( x0, y0, x2, y2, x1, y1, ss, sss, icurve ); tvec.push_back( t ); ss = sss; thh = thhh; } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . void ClothoidCurve::bbTriangles( real_type offs, vector<T2D> & tvec, real_type max_angle, real_type max_size, int_type icurve ) const { if ( CD.kappa0*CD.dk >= 0 || CD.kappa(L)*CD.dk <= 0 ) { bbTriangles_internal( offs, tvec, 0, L, max_angle, max_size, icurve ); } else { // flex inside, split clothoid real_type sflex = -CD.kappa0/CD.dk; bbTriangles_internal( offs, tvec, 0, sflex, max_angle, max_size, icurve ); bbTriangles_internal( offs, tvec, sflex, L, max_angle, max_size, icurve ); } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /*\ | ___ ___ | | _ ) _ ) _____ __ | | _ \ _ \/ _ \ \ / | |___/___/\___/_\_\ \*/ void ClothoidCurve::bbox( real_type offs, real_type & xmin, real_type & ymin, real_type & xmax, real_type & ymax ) const { vector<T2D> tvec; bbTriangles( offs, tvec, m_pi/18, 1e100 ); xmin = ymin = numeric_limits<real_type>::infinity(); xmax = ymax = -xmin; vector<T2D>::const_iterator it; for ( it = tvec.begin(); it != tvec.end(); ++it ) { // - - - - - - - - - - - - - - - - - - - - if ( it->x1() < xmin ) xmin = it->x1(); else if ( it->x1() > xmax ) xmax = it->x1(); if ( it->x2() < xmin ) xmin = it->x2(); else if ( it->x2() > xmax ) xmax = it->x2(); if ( it->x3() < xmin ) xmin = it->x3(); else if ( it->x3() > xmax ) xmax = it->x3(); // - - - - - - - - - - - - - - - - - - - - if ( it->y1() < ymin ) ymin = it->y1(); else if ( it->y1() > ymax ) ymax = it->y1(); if ( it->y2() < ymin ) ymin = it->y2(); else if ( it->y2() > ymax ) ymax = it->y2(); if ( it->y3() < ymin ) ymin = it->y3(); else if ( it->y3() > ymax ) ymax = it->y3(); } } // . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . /*\ | _ _ ____ ____ _ | / \ / \ | __ )| __ )| |_ _ __ ___ ___ | / _ \ / _ \ | _ \| _ \| __| '__/ _ \/ _ \ | / ___ \ / ___ \| |_) | |_) | |_| | | __/ __/ | /_/ \_\/_/ \_\____/|____/ \__|_| \___|\___| \*/ void ClothoidCurve::build_AABBtree( real_type offs, real_type max_angle, real_type max_size ) const { if ( aabb_done && isZero( offs-aabb_offs ) && isZero( max_angle-aabb_max_angle ) && isZero( max_size-aabb_max_size ) ) return; #ifdef G2LIB_USE_CXX11 vector<shared_ptr<BBox const> > bboxes; #else vector<BBox const *> bboxes; #endif bbTriangles( offs, aabb_tri, max_angle, max_size ); bboxes.reserve(aabb_tri.size()); vector<T2D>::const_iterator it; int_type ipos = 0; for ( it = aabb_tri.begin(); it != aabb_tri.end(); ++it, ++ipos ) { real_type xmin, ymin, xmax, ymax; it->bbox( xmin, ymin, xmax, ymax ); #ifdef G2LIB_USE_CXX11 bboxes.push_back( make_shared<BBox const>( xmin, ymin, xmax, ymax, G2LIB_CLOTHOID, ipos ) ); #else bboxes.push_back( new BBox( xmin, ymin, xmax, ymax, G2LIB_CLOTHOID, ipos ) ); #endif } aabb_tree.build(bboxes); aabb_done = true; aabb_offs = offs; aabb_max_angle = max_angle; aabb_max_size = max_size; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /*\ | _ _ _ _ | ___ ___ | | (_)___(_) ___ _ __ | / __/ _ \| | | / __| |/ _ \| '_ \ | | (_| (_) | | | \__ \ | (_) | | | | | \___\___/|_|_|_|___/_|\___/|_| |_| \*/ bool ClothoidCurve::collision( ClothoidCurve const & C ) const { this->build_AABBtree( 0 ); C.build_AABBtree( 0 ); T2D_collision fun( this, 0, &C, 0 ); return aabb_tree.collision( C.aabb_tree, fun, false ); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - bool ClothoidCurve::collision( real_type offs, ClothoidCurve const & C, real_type offs_C ) const { this->build_AABBtree( offs ); C.build_AABBtree( offs_C ); T2D_collision fun( this, offs, &C, offs_C ); return aabb_tree.collision( C.aabb_tree, fun, false ); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // collision detection bool ClothoidCurve::approximate_collision( real_type offs, ClothoidCurve const & C, real_type offs_C, real_type max_angle, real_type max_size ) const { this->build_AABBtree( offs, max_angle, max_size ); C.build_AABBtree( offs_C, max_angle, max_size ); T2D_approximate_collision fun( this, &C ); return aabb_tree.collision( C.aabb_tree, fun, false ); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /*\ | _ _ _ | (_)_ __ | |_ ___ _ __ ___ ___ ___| |_ | | | '_ \| __/ _ \ '__/ __|/ _ \/ __| __| | | | | | | || __/ | \__ \ __/ (__| |_ | |_|_| |_|\__\___|_| |___/\___|\___|\__| \*/ bool ClothoidCurve::aabb_intersect( T2D const & T1, real_type offs, ClothoidCurve const * pC, T2D const & T2, real_type offs_C, real_type & ss1, real_type & ss2 ) const { real_type eps1 = machepsi1000*L; real_type eps2 = machepsi1000*pC->L; real_type s1_min = T1.S0()-eps1; real_type s1_max = T1.S1()+eps1; real_type s2_min = T2.S0()-eps2; real_type s2_max = T2.S1()+eps2; int_type nout = 0; bool converged = false; ss1 = (s1_min+s1_max)/2; ss2 = (s2_min+s2_max)/2; for ( int_type i = 0; i < max_iter && !converged; ++i ) { real_type t1[2], t2[2], p1[2], p2[2]; CD.eval ( ss1, offs, p1[0], p1[1] ); CD.eval_D( ss1, offs, t1[0], t1[1] ); pC->CD.eval ( ss2, offs_C, p2[0], p2[1] ); pC->CD.eval_D( ss2, offs_C, t2[0], t2[1] ); /* // risolvo il sistema // p1 + alpha * t1 = p2 + beta * t2 // alpha * t1 - beta * t2 = p2 - p1 // // / t1[0] -t2[0] \ / alpha \ = / p2[0] - p1[0] \ // \ t1[1] -t2[1] / \ beta / \ p2[1] - p1[1] / */ real_type det = t2[0]*t1[1]-t1[0]*t2[1]; real_type px = p2[0]-p1[0]; real_type py = p2[1]-p1[1]; ss1 += (py*t2[0] - px*t2[1])/det; ss2 += (t1[0]*py - t1[1]*px)/det; if ( ! ( isfinite(ss1) && isfinite(ss1) ) ) break; bool out = false; if ( ss1 < s1_min ) { out = true; ss1 = s1_min; } else if ( ss1 > s1_max ) { out = true; ss1 = s1_max; } if ( ss2 < s2_min ) { out = true; ss2 = s2_min; } else if ( ss2 > s2_max ) { out = true; ss2 = s2_max; } if ( out ) { if ( ++nout > 3 ) break; } else { converged = abs(px) <= tolerance && abs(py) <= tolerance; } } if ( converged ) { if ( ss1 < T1.S0() ) ss1 = T1.S0(); else if ( ss1 > T1.S1() ) ss1 = T1.S1(); if ( ss2 < T2.S0() ) ss2 = T2.S0(); else if ( ss2 > T2.S1() ) ss2 = T2.S1(); } return converged; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - void ClothoidCurve::intersect( real_type offs, ClothoidCurve const & C, real_type offs_C, IntersectList & ilist, bool swap_s_vals ) const { this->build_AABBtree( offs ); C.build_AABBtree( offs_C ); AABBtree::VecPairPtrBBox iList; aabb_tree.intersect( C.aabb_tree, iList ); AABBtree::VecPairPtrBBox::const_iterator ip; for ( ip = iList.begin(); ip != iList.end(); ++ip ) { size_t ipos1 = size_t(ip->first->Ipos()); size_t ipos2 = size_t(ip->second->Ipos()); T2D const & T1 = aabb_tri[ipos1]; T2D const & T2 = C.aabb_tri[ipos2]; real_type ss1, ss2; bool converged = aabb_intersect( T1, offs, &C, T2, offs_C, ss1, ss2 ); if ( converged ) { if ( swap_s_vals ) swap( ss1, ss2 ); ilist.push_back( Ipair( ss1, ss2 ) ); } } } /*\ | _ _ ____ _ _ | ___| | ___ ___ ___ ___| |_| _ \ ___ (_)_ __ | |_ | / __| |/ _ \/ __|/ _ \/ __| __| |_) / _ \| | '_ \| __| | | (__| | (_) \__ \ __/\__ \ |_| __/ (_) | | | | | |_ | \___|_|\___/|___/\___||___/\__|_| \___/|_|_| |_|\__| \*/ void ClothoidCurve::closestPoint_internal( real_type s_begin, real_type s_end, real_type qx, real_type qy, real_type offs, real_type & x, real_type & y, real_type & s, real_type & dst ) const { #if 1 // minimize using circle approximation s = (s_begin + s_end)/2; int_type nout = 0; for ( int_type iter = 0; iter < max_iter; ++iter ) { // osculating circle CD.eval( s, offs, x, y ); real_type th = CD.theta( s ); real_type kk = CD.kappa( s ); real_type sc = 1-kk*offs; real_type ds = projectPointOnArc( x, y, th, kk/sc, qx, qy )/sc; s += ds; bool out = false; if ( s <= s_begin ) { out = true; s = s_begin; } else if ( s >= s_end ) { out = true; s = s_end; } if ( out ) { if ( ++nout > 3 ) break; } else { if ( abs(ds) <= tolerance ) break; } } dst = hypot( qx-x, qy-y ); #else real_type ds = (s_end-s_begin)/10; for ( int_type iter = 0; iter <= 10 ; ++iter ) { real_type ss = s_begin + iter * ds; real_type xx, yy; CD.eval( ss, offs, xx, yy ); real_type dx = xx-qx; real_type dy = yy-qy; real_type dst1 = hypot( dx, dy ); if ( dst1 < dst ) { s = ss; x = xx; y = yy; dst = dst1; } } #endif } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - int_type ClothoidCurve::closestPoint( real_type qx, real_type qy, real_type offs, real_type & x, real_type & y, real_type & s, real_type & t, real_type & DST ) const { DST = numeric_limits<real_type>::infinity(); this->build_AABBtree( offs ); AABBtree::VecPtrBBox candidateList; aabb_tree.min_distance( qx, qy, candidateList ); AABBtree::VecPtrBBox::const_iterator ic; G2LIB_ASSERT( candidateList.size() > 0, "ClothoidCurve::closestPoint no candidate" ); for ( ic = candidateList.begin(); ic != candidateList.end(); ++ic ) { size_t ipos = size_t((*ic)->Ipos()); T2D const & T = aabb_tri[ipos]; real_type dst = T.distMin( qx, qy ); if ( dst < DST ) { // refine distance real_type xx, yy, ss; closestPoint_internal( T.S0(), T.S1(), qx, qy, offs, xx, yy, ss, dst ); if ( dst < DST ) { DST = dst; s = ss; x = xx; y = yy; } } } real_type nx, ny; nor( s, nx, ny ); t = (qx-x) * nx + (qy-y) * ny - offs; real_type err = abs( abs(t) - DST ); if ( err > DST*machepsi1000 ) return -1; return 1; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - real_type ClothoidCurve::thetaTotalVariation() const { // cerco punto minimo parabola // root = -k/dk; real_type kL = CD.kappa0; real_type kR = CD.kappa(L); real_type thL = 0; real_type thR = CD.deltaTheta(L); if ( kL*kR < 0 ) { real_type root = -CD.kappa0/CD.dk; if ( root > 0 && root < L ) { real_type thM = CD.deltaTheta(root); return abs( thR - thM ) + abs( thM - thL ); } } return abs( thR - thL ); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - real_type ClothoidCurve::thetaMinMax( real_type & thMin, real_type & thMax ) const { // cerco punto minimo parabola // root = -k/dk; real_type kL = CD.kappa0; real_type kR = CD.kappa(L); real_type thL = 0; real_type thR = CD.deltaTheta(L); if ( thL < thR ) { thMin = thL; thMax = thR; } else { thMin = thR; thMax = thL; } if ( kL*kR < 0 ) { real_type root = -CD.kappa0/CD.dk; if ( root > 0 && root < L ) { real_type thM = CD.deltaTheta(root); if ( thM < thMin ) thMin = thM; else if ( thM > thMax ) thMax = thM; } } return thMax - thMin; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - real_type ClothoidCurve::curvatureMinMax( real_type & kMin, real_type & kMax ) const { // cerco punto minimo parabola // root = -k/dk; kMin = CD.kappa0; kMax = CD.kappa(L); if ( kMax < kMin ) swap( kMax, kMin ); return kMax - kMin; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - real_type ClothoidCurve::curvatureTotalVariation() const { // cerco punto minimo parabola // root = -k/dk; real_type km = CD.kappa0; real_type kp = CD.kappa(L); return abs(kp-km); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - real_type ClothoidCurve::integralCurvature2() const { return L*( CD.kappa0*(CD.kappa0+L*CD.dk) + (L*L)*CD.dk*CD.dk/3 ); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - real_type ClothoidCurve::integralJerk2() const { real_type k2 = CD.kappa0*CD.kappa0; real_type k3 = CD.kappa0*k2; real_type k4 = k2*k2; real_type t1 = L; real_type t2 = L*t1; real_type t3 = L*t2; real_type t4 = L*t3; return ((((t4/5*CD.dk+t3*CD.kappa0)*CD.dk+(1+2*t2)*k2)*CD.dk+2*t1*k3)*CD.dk+k4)*L; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - real_type ClothoidCurve::integralSnap2() const { real_type k2 = CD.kappa0*CD.kappa0; real_type k3 = CD.kappa0*k2; real_type k4 = k2*k2; real_type k5 = k4*CD.kappa0; real_type k6 = k4*k2; real_type dk2 = CD.dk*CD.dk; real_type dk3 = CD.dk*dk2; real_type dk4 = dk2*dk2; real_type dk5 = dk4*CD.dk; real_type dk6 = dk4*dk2; real_type t2 = L; real_type t3 = L*t2; real_type t4 = L*t3; real_type t5 = L*t4; real_type t6 = L*t5; real_type t7 = L*t6; return ( (t7/7)*dk6 + dk5*CD.kappa0*t6 + 3*dk4*k2*t5 + 5*dk3*k3*t4 + 5*dk2*k4*t3 + 3*dk3*t3 + 3*CD.dk*k5*t2 + 9*dk2*CD.kappa0*t2 + k6+9*k2*CD.dk ) * L; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ostream_type & operator << ( ostream_type & stream, ClothoidCurve const & c ) { stream << "x0 = " << c.CD.x0 << "\ny0 = " << c.CD.y0 << "\ntheta0 = " << c.CD.theta0 << "\nkappa0 = " << c.CD.kappa0 << "\ndk = " << c.CD.dk << "\nL = " << c.L << "\n"; return stream; } } // EOF: Clothoid.cc
; =============================================================== ; Feb 2014 ; =============================================================== ; ; void bv_stack_clear(bv_stack_t *s) ; ; Clear the stack to empty. ; ; =============================================================== SECTION code_adt_bv_stack PUBLIC asm_bv_stack_clear EXTERN l_zeroword_hl defc asm_bv_stack_clear = l_zeroword_hl - 2 ; enter : hl = stack * ; ; exit : hl = & stack.size ; ; uses : hl
; ; Load a whole file by the BASIC driver ; ; Stefano - 28/06/2007 ; ; int zx_save_block(char *name, void *addr, size_t len) ; ; $Id: zx_save_block.asm,v 1.1 2007/07/03 07:32:03 stefano Exp $ XLIB zx_save_block LIB zx_setint LIB zx_goto LIB zxgetfname ; BASIC variable name .avar defb 'A',0 .lvar defb 'L',0 .zx_save_block pop af pop bc pop hl pop de push de push hl push bc push af push hl push bc ld hl,lvar ; BASIC variable L push hl push de ; size call zx_setint pop de pop hl pop bc ld hl,avar ; BASIC variable A push hl push bc ; ptr to address call zx_setint pop bc pop hl call zxgetfname ; HL is pointing to file name pop hl ;7650 - SAVE block ;a=addess ;l=length ;d=drive number ;n$=file name ld hl,7650 call zx_goto ld a,l ld hl,0 and a ret z dec hl ret
Route16GateUpstairsObject: db $a ; border block db $1 ; warps db $7, $7, $8, ROUTE_16_GATE_1F db $2 ; signs db $2, $1, $3 ; Route16GateUpstairsText3 db $2, $6, $4 ; Route16GateUpstairsText4 db $2 ; objects object SPRITE_YOUNG_BOY, $4, $2, STAY, NONE, $1 ; person object SPRITE_LITTLE_GIRL, $2, $5, WALK, $2, $2 ; person ; warp-to EVENT_DISP ROUTE_16_GATE_2F_WIDTH, $7, $7 ; ROUTE_16_GATE_1F
; A152948: a(n) = (n^2 - 3*n + 6)/2. ; 2,2,3,5,8,12,17,23,30,38,47,57,68,80,93,107,122,138,155,173,192,212,233,255,278,302,327,353,380,408,437,467,498,530,563,597,632,668,705,743,782,822,863,905,948,992,1037,1083,1130,1178,1227,1277,1328,1380 bin $0,2 mov $1,$0 add $1,2
/* * Copyright (C) 2013-2015 Open Source Robotics Foundation * * 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 "gazebo/gui/model/ModelEditorEvents.hh" using namespace gazebo; using namespace gui; event::EventT<void ()> model::Events::finishModel; event::EventT<bool ()> model::Events::saveAsModelEditor; event::EventT<bool ()> model::Events::saveModelEditor; event::EventT<void ()> model::Events::newModelEditor; event::EventT<void ()> model::Events::exitModelEditor; event::EventT<void ()> model::Events::modelChanged; event::EventT<void (std::string)> model::Events::modelNameChanged; event::EventT<void (bool, bool, const math::Pose &, const std::string &)> model::Events::modelPropertiesChanged; event::EventT<void (std::string)> model::Events::saveModel; event::EventT<void ()> model::Events::newModel; event::EventT<void (std::string)> model::Events::linkInserted; event::EventT<void (std::string, std::string, std::string, std::string)> model::Events::jointInserted; event::EventT<void (std::string)> model::Events::linkRemoved; event::EventT<void (std::string)> model::Events::jointRemoved; event::EventT<void (std::string)> model::Events::openLinkInspector; event::EventT<void (std::string)> model::Events::openJointInspector; event::EventT<void (std::string, std::string)> model::Events::jointNameChanged; event::EventT<void (std::string)> model::Events::showLinkContextMenu; event::EventT<void (std::string)> model::Events::showJointContextMenu; event::EventT<void (std::string, bool)> model::Events::setSelectedLink; event::EventT<void (std::string, bool)> model::Events::setSelectedJoint;
; unsigned char mkstemp_ex(char *template) ; returns file descriptor instead of FILE* INCLUDE "config_private.inc" SECTION code_env PUBLIC asm_mkstemp_ex EXTERN asm_env_mkstemp defc asm_mkstemp_ex = asm_env_mkstemp ; Create a temporary file using a filename formed by replacing the ; last four 'XXXX' in the supplied filename with random characters. ; ; Open the file for rw and return a file descriptor. ; ; enter : hl = char *template ; (extension: if 0, make a temp file in the system's tmp dir) ; ; exit : success ; ; hl = file handle ; carry reset ; ; fail ; ; hl = -1 ; carry set ; ; uses : af, bc, de, hl, bc', de', hl', ix
#include <QXmlStreamWriter> #include <set> #include <QGuiApplication> #include <QtCore/qbuffer.h> #include "documentsaver.h" #include "imageforever.h" #include "ds3file.h" #include "snapshotxml.h" #include "variablesxml.h" #include "fileforever.h" #include "objectXml.h" DocumentSaver::DocumentSaver(const QString *filename, Snapshot *snapshot, Object *object, DocumentSaver::Textures *textures, QByteArray *turnaroundPngByteArray, QString *script, std::map<QString, std::map<QString, QString>> *variables) : m_filename(filename), m_snapshot(snapshot), m_object(object), m_textures(textures), m_turnaroundPngByteArray(turnaroundPngByteArray), m_script(script), m_variables(variables) { } DocumentSaver::~DocumentSaver() { delete m_snapshot; delete m_object; delete m_textures; delete m_turnaroundPngByteArray; delete m_script; delete m_variables; } void DocumentSaver::process() { save(m_filename, m_snapshot, m_object, m_textures, m_turnaroundPngByteArray, m_script, m_variables); emit finished(); } void DocumentSaver::collectUsedResourceIds(const Snapshot *snapshot, std::set<QUuid> &imageIds, std::set<QUuid> &fileIds) { for (const auto &material: snapshot->materials) { for (auto &layer: material.second) { for (auto &mapItem: layer.second) { auto findImageIdString = mapItem.find("linkData"); if (findImageIdString == mapItem.end()) continue; QUuid imageId = QUuid(findImageIdString->second); imageIds.insert(imageId); } } } for (const auto &part: snapshot->parts) { auto findImageIdString = part.second.find("deformMapImageId"); if (findImageIdString == part.second.end()) continue; QUuid imageId = QUuid(findImageIdString->second); imageIds.insert(imageId); } for (const auto &part: snapshot->parts) { auto fillMeshLinkedIdString = part.second.find("fillMesh"); if (fillMeshLinkedIdString == part.second.end()) continue; QUuid fileId = QUuid(fillMeshLinkedIdString->second); if (fileId.isNull()) continue; fileIds.insert(fileId); const QByteArray *byteArray = FileForever::getContent(fileId); if (nullptr == byteArray) continue; QXmlStreamReader stream(*byteArray); Snapshot fileSnapshot; loadSkeletonFromXmlStream(&fileSnapshot, stream, SNAPSHOT_ITEM_CANVAS | SNAPSHOT_ITEM_COMPONENT); collectUsedResourceIds(&fileSnapshot, imageIds, fileIds); } } bool DocumentSaver::save(const QString *filename, Snapshot *snapshot, const Object *object, Textures *textures, const QByteArray *turnaroundPngByteArray, const QString *script, const std::map<QString, std::map<QString, QString>> *variables) { Ds3FileWriter ds3Writer; { QByteArray modelXml; QXmlStreamWriter stream(&modelXml); saveSkeletonToXmlStream(snapshot, &stream); if (modelXml.size() > 0) ds3Writer.add("model.xml", "model", &modelXml); } if (nullptr != object) { QByteArray objectXml; QXmlStreamWriter stream(&objectXml); saveObjectToXmlStream(object, &stream); if (objectXml.size() > 0) ds3Writer.add("object.xml", "object", &objectXml); } if (nullptr != object && nullptr != textures) { if (nullptr != textures->textureImage && !textures->textureImage->isNull()) { if (nullptr == textures->textureImageByteArray) { textures->textureImageByteArray = new QByteArray; QBuffer pngBuffer(textures->textureImageByteArray); pngBuffer.open(QIODevice::WriteOnly); textures->textureImage->save(&pngBuffer, "PNG"); } if (textures->textureImageByteArray->size() > 0) ds3Writer.add("object_color.png", "asset", textures->textureImageByteArray); } if (nullptr != textures->textureNormalImage && !textures->textureNormalImage->isNull()) { if (nullptr == textures->textureNormalImageByteArray) { textures->textureNormalImageByteArray = new QByteArray; QBuffer pngBuffer(textures->textureNormalImageByteArray); pngBuffer.open(QIODevice::WriteOnly); textures->textureNormalImage->save(&pngBuffer, "PNG"); } if (textures->textureNormalImageByteArray->size() > 0) ds3Writer.add("object_normal.png", "asset", textures->textureNormalImageByteArray); } if (nullptr != textures->textureMetalnessImage && !textures->textureMetalnessImage->isNull()) { if (nullptr == textures->textureMetalnessImageByteArray) { textures->textureMetalnessImageByteArray = new QByteArray; QBuffer pngBuffer(textures->textureMetalnessImageByteArray); pngBuffer.open(QIODevice::WriteOnly); textures->textureMetalnessImage->save(&pngBuffer, "PNG"); } if (textures->textureMetalnessImageByteArray->size() > 0) ds3Writer.add("object_metallic.png", "asset", textures->textureMetalnessImageByteArray); } if (nullptr != textures->textureRoughnessImage && !textures->textureRoughnessImage->isNull()) { if (nullptr == textures->textureRoughnessImageByteArray) { textures->textureRoughnessImageByteArray = new QByteArray; QBuffer pngBuffer(textures->textureRoughnessImageByteArray); pngBuffer.open(QIODevice::WriteOnly); textures->textureRoughnessImage->save(&pngBuffer, "PNG"); } if (textures->textureRoughnessImageByteArray->size() > 0) ds3Writer.add("object_roughness.png", "asset", textures->textureRoughnessImageByteArray); } if (nullptr != textures->textureAmbientOcclusionImage && !textures->textureAmbientOcclusionImage->isNull()) { if (nullptr == textures->textureAmbientOcclusionImageByteArray) { textures->textureAmbientOcclusionImageByteArray = new QByteArray; QBuffer pngBuffer(textures->textureAmbientOcclusionImageByteArray); pngBuffer.open(QIODevice::WriteOnly); textures->textureAmbientOcclusionImage->save(&pngBuffer, "PNG"); } if (textures->textureAmbientOcclusionImageByteArray->size() > 0) ds3Writer.add("object_ao.png", "asset", textures->textureAmbientOcclusionImageByteArray); } } if (nullptr != turnaroundPngByteArray && turnaroundPngByteArray->size() > 0) ds3Writer.add("canvas.png", "asset", turnaroundPngByteArray); if (nullptr != script && !script->isEmpty()) { auto scriptByteArray = script->toUtf8(); ds3Writer.add("model.js", "script", &scriptByteArray); } if (nullptr != variables && !variables->empty()) { QByteArray variablesXml; QXmlStreamWriter variablesXmlStream(&variablesXml); saveVariablesToXmlStream(*variables, &variablesXmlStream); if (variablesXml.size() > 0) ds3Writer.add("variables.xml", "variable", &variablesXml); } std::set<QUuid> imageIds; std::set<QUuid> fileIds; collectUsedResourceIds(snapshot, imageIds, fileIds); for (const auto &imageId: imageIds) { const QByteArray *pngByteArray = ImageForever::getPngByteArray(imageId); if (nullptr == pngByteArray) continue; if (pngByteArray->size() > 0) ds3Writer.add("images/" + imageId.toString() + ".png", "asset", pngByteArray); } for (const auto &fileId: fileIds) { const QByteArray *byteArray = FileForever::getContent(fileId); if (nullptr == byteArray) continue; QString suffix = ".bin"; const QString *name = FileForever::getName(fileId); if (nullptr != name) { int suffixBegin = name->lastIndexOf("."); if (-1 != suffixBegin) suffix = name->mid(suffixBegin); } if (byteArray->size() > 0) ds3Writer.add("files/" + fileId.toString() + suffix, "asset", byteArray); } return ds3Writer.save(*filename); }
############################################################################### # Copyright 2018 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # You may not use this file except in compliance with the License. You may # obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### .text .p2align 4, 0x90 CODE_DATA: PSHUFFLE_BYTE_FLIP_MASK: .byte 3,2,1,0, 7,6,5,4, 11,10,9,8, 15,14,13,12 .p2align 4, 0x90 .globl _UpdateSHA256ni _UpdateSHA256ni: push %ebp mov %esp, %ebp push %ebx push %esi push %edi sub $(64), %esp lea (16)(%esp), %eax and $(-16), %eax movl (16)(%ebp), %edx test %edx, %edx jz .Lquitgas_1 movl (8)(%ebp), %edi movl (12)(%ebp), %esi movl (20)(%ebp), %ebx movdqu (%edi), %xmm1 movdqu (16)(%edi), %xmm2 pshufd $(177), %xmm1, %xmm1 pshufd $(27), %xmm2, %xmm2 movdqa %xmm1, %xmm7 palignr $(8), %xmm2, %xmm1 pblendw $(240), %xmm7, %xmm2 mov $(66051), %ecx movl %ecx, (%eax) mov $(67438087), %ecx movl %ecx, (4)(%eax) mov $(134810123), %ecx movl %ecx, (8)(%eax) mov $(202182159), %ecx movl %ecx, (12)(%eax) .Lsha256_block_loopgas_1: movdqa %xmm1, (16)(%eax) movdqa %xmm2, (32)(%eax) movdqu (%esi), %xmm0 pshufb (%eax), %xmm0 movdqa %xmm0, %xmm3 paddd (%ebx), %xmm0 sha256rnds2 %xmm1, %xmm2 pshufd $(14), %xmm0, %xmm0 sha256rnds2 %xmm2, %xmm1 movdqu (16)(%esi), %xmm0 pshufb (%eax), %xmm0 movdqa %xmm0, %xmm4 paddd (16)(%ebx), %xmm0 sha256rnds2 %xmm1, %xmm2 pshufd $(14), %xmm0, %xmm0 sha256rnds2 %xmm2, %xmm1 sha256msg1 %xmm4, %xmm3 movdqu (32)(%esi), %xmm0 pshufb (%eax), %xmm0 movdqa %xmm0, %xmm5 paddd (32)(%ebx), %xmm0 sha256rnds2 %xmm1, %xmm2 pshufd $(14), %xmm0, %xmm0 sha256rnds2 %xmm2, %xmm1 sha256msg1 %xmm5, %xmm4 movdqu (48)(%esi), %xmm0 pshufb (%eax), %xmm0 movdqa %xmm0, %xmm6 paddd (48)(%ebx), %xmm0 sha256rnds2 %xmm1, %xmm2 movdqa %xmm6, %xmm7 palignr $(4), %xmm5, %xmm7 paddd %xmm7, %xmm3 sha256msg2 %xmm6, %xmm3 pshufd $(14), %xmm0, %xmm0 sha256rnds2 %xmm2, %xmm1 sha256msg1 %xmm6, %xmm5 movdqa %xmm3, %xmm0 paddd (64)(%ebx), %xmm0 sha256rnds2 %xmm1, %xmm2 movdqa %xmm3, %xmm7 palignr $(4), %xmm6, %xmm7 paddd %xmm7, %xmm4 sha256msg2 %xmm3, %xmm4 pshufd $(14), %xmm0, %xmm0 sha256rnds2 %xmm2, %xmm1 sha256msg1 %xmm3, %xmm6 movdqa %xmm4, %xmm0 paddd (80)(%ebx), %xmm0 sha256rnds2 %xmm1, %xmm2 movdqa %xmm4, %xmm7 palignr $(4), %xmm3, %xmm7 paddd %xmm7, %xmm5 sha256msg2 %xmm4, %xmm5 pshufd $(14), %xmm0, %xmm0 sha256rnds2 %xmm2, %xmm1 sha256msg1 %xmm4, %xmm3 movdqa %xmm5, %xmm0 paddd (96)(%ebx), %xmm0 sha256rnds2 %xmm1, %xmm2 movdqa %xmm5, %xmm7 palignr $(4), %xmm4, %xmm7 paddd %xmm7, %xmm6 sha256msg2 %xmm5, %xmm6 pshufd $(14), %xmm0, %xmm0 sha256rnds2 %xmm2, %xmm1 sha256msg1 %xmm5, %xmm4 movdqa %xmm6, %xmm0 paddd (112)(%ebx), %xmm0 sha256rnds2 %xmm1, %xmm2 movdqa %xmm6, %xmm7 palignr $(4), %xmm5, %xmm7 paddd %xmm7, %xmm3 sha256msg2 %xmm6, %xmm3 pshufd $(14), %xmm0, %xmm0 sha256rnds2 %xmm2, %xmm1 sha256msg1 %xmm6, %xmm5 movdqa %xmm3, %xmm0 paddd (128)(%ebx), %xmm0 sha256rnds2 %xmm1, %xmm2 movdqa %xmm3, %xmm7 palignr $(4), %xmm6, %xmm7 paddd %xmm7, %xmm4 sha256msg2 %xmm3, %xmm4 pshufd $(14), %xmm0, %xmm0 sha256rnds2 %xmm2, %xmm1 sha256msg1 %xmm3, %xmm6 movdqa %xmm4, %xmm0 paddd (144)(%ebx), %xmm0 sha256rnds2 %xmm1, %xmm2 movdqa %xmm4, %xmm7 palignr $(4), %xmm3, %xmm7 paddd %xmm7, %xmm5 sha256msg2 %xmm4, %xmm5 pshufd $(14), %xmm0, %xmm0 sha256rnds2 %xmm2, %xmm1 sha256msg1 %xmm4, %xmm3 movdqa %xmm5, %xmm0 paddd (160)(%ebx), %xmm0 sha256rnds2 %xmm1, %xmm2 movdqa %xmm5, %xmm7 palignr $(4), %xmm4, %xmm7 paddd %xmm7, %xmm6 sha256msg2 %xmm5, %xmm6 pshufd $(14), %xmm0, %xmm0 sha256rnds2 %xmm2, %xmm1 sha256msg1 %xmm5, %xmm4 movdqa %xmm6, %xmm0 paddd (176)(%ebx), %xmm0 sha256rnds2 %xmm1, %xmm2 movdqa %xmm6, %xmm7 palignr $(4), %xmm5, %xmm7 paddd %xmm7, %xmm3 sha256msg2 %xmm6, %xmm3 pshufd $(14), %xmm0, %xmm0 sha256rnds2 %xmm2, %xmm1 sha256msg1 %xmm6, %xmm5 movdqa %xmm3, %xmm0 paddd (192)(%ebx), %xmm0 sha256rnds2 %xmm1, %xmm2 movdqa %xmm3, %xmm7 palignr $(4), %xmm6, %xmm7 paddd %xmm7, %xmm4 sha256msg2 %xmm3, %xmm4 pshufd $(14), %xmm0, %xmm0 sha256rnds2 %xmm2, %xmm1 sha256msg1 %xmm3, %xmm6 movdqa %xmm4, %xmm0 paddd (208)(%ebx), %xmm0 sha256rnds2 %xmm1, %xmm2 movdqa %xmm4, %xmm7 palignr $(4), %xmm3, %xmm7 paddd %xmm7, %xmm5 sha256msg2 %xmm4, %xmm5 pshufd $(14), %xmm0, %xmm0 sha256rnds2 %xmm2, %xmm1 movdqa %xmm5, %xmm0 paddd (224)(%ebx), %xmm0 sha256rnds2 %xmm1, %xmm2 movdqa %xmm5, %xmm7 palignr $(4), %xmm4, %xmm7 paddd %xmm7, %xmm6 sha256msg2 %xmm5, %xmm6 pshufd $(14), %xmm0, %xmm0 sha256rnds2 %xmm2, %xmm1 movdqa %xmm6, %xmm0 paddd (240)(%ebx), %xmm0 sha256rnds2 %xmm1, %xmm2 pshufd $(14), %xmm0, %xmm0 sha256rnds2 %xmm2, %xmm1 paddd (16)(%eax), %xmm1 paddd (32)(%eax), %xmm2 add $(64), %esi sub $(64), %edx jg .Lsha256_block_loopgas_1 pshufd $(27), %xmm1, %xmm1 pshufd $(177), %xmm2, %xmm2 movdqa %xmm1, %xmm7 pblendw $(240), %xmm2, %xmm1 palignr $(8), %xmm7, %xmm2 movdqu %xmm1, (%edi) movdqu %xmm2, (16)(%edi) .Lquitgas_1: add $(64), %esp pop %edi pop %esi pop %ebx pop %ebp ret
; A204327: a(n) = Pell(n^2). ; Submitted by Christian Krause ; 1,12,985,470832,1311738121,21300003689580,2015874949414289041,1111984844349868137938112,3575077977948634627394046618865,66992092050551637663438906713182313772,7316660981177400006023755031791634132229378601 add $0,1 pow $0,2 seq $0,163271 ; Numerators of fractions in a 'zero-transform' approximation of sqrt(2) by means of a(n) = (a(n-1) + c)/(a(n-1) + 1) with c=2 and a(1)=0. div $0,2
/* * * Created on: 2019年10月1日 * Author: Lzy */ #include "macaddr.h" MacAddr::MacAddr() { mMac = sDataPacket::bulid()->mac; } MacAddr *MacAddr::bulid() { static MacAddr* sington = nullptr; if(sington == nullptr) sington = new MacAddr(); return sington; } uint MacAddr::macToInt(QString str) { bool ok; str = str.replace(MAC_ADDR_PREFIX, QString("")); str = str.replace(QString(":"), QString("")); uint ret = str.toUInt(&ok, 16); if(!ok) ret = 0; return ret; } QByteArray MacAddr::intToByte(uint number) { QByteArray abyte0; abyte0.resize(3); abyte0[2] = (uchar) (0x000000ff & number); abyte0[1] = (uchar) ((0x0000ff00 & number) >> 8); abyte0[0] = (uchar) ((0x00ff0000 & number) >> 16); return abyte0; } QString MacAddr::intToMac(uint v) { QByteArray array = intToByte(v); QString str = cm_ByteArrayToHexStr(array); QString mac = MAC_ADDR_PREFIX + str.left(str.size()-1); return mac.replace(QString(" "), QString(":")); } uint MacAddr::macHasCounts(sMacUnit &unit) { uint rtn = macToInt(unit.end); unit.counts = rtn - macToInt(unit.mac); return unit.counts; } uint MacAddr::macUsedCounts(sMacUnit &unit) { uint rtn = macToInt(unit.start); unit.used = macToInt(unit.mac)-rtn; return unit.used; } bool MacAddr::createMac(sMacUnit &unit) { bool ret = true; unit.counts = macHasCounts(unit); if(unit.counts > 0) { unit.value = macToInt(unit.mac) + 1; unit.mac = intToMac(unit.value); unit.counts--; } else { ret = false; } return ret; } bool MacAddr::revokeMac(sMacUnit &unit) { bool ret = true; unit.used = macUsedCounts(unit); if(unit.used > 0) { unit.value = macToInt(unit.mac) - 1; unit.mac = intToMac(unit.value); unit.counts++; } else { ret = false; } return ret; } QList<sMacUnit> MacAddr::createMacList(sMacUnit &unit, int num) { bool ret; QList<sMacUnit> list; for(int i=0; i<num; ++i) { ret = createMac(unit); if(ret) { list << unit; } else { break; } } return list; } bool MacAddr::revokeMacList(sMacUnit &it, QList<sMacUnit> &units) { for(int i=units.size()-1; i>=0; --i) { it = units.at(i); revokeMac(it); } return true; } /** * 函数功能:将格式如"EA-EB-EC-AA-AB-AC"的MAC QString字符串转换成6字节的数组, * 数组的元素对应为{0xEA,0xEB,0xEC,0xAA,0xAB,0xAC} */ QByteArray MacAddr::get_mac_array_from_QString(const QString &in) { QByteArray array; unsigned char out[6]; uint8_t next_ip_separate_symbol_index = 0; uint8_t now_ip_separate_symbol_index = 0; for(uint8_t i=0;i<6;i++){ next_ip_separate_symbol_index = (i!=5)? (in.indexOf("-",next_ip_separate_symbol_index+1)):(in.length()); if((next_ip_separate_symbol_index-now_ip_separate_symbol_index>0)&&(next_ip_separate_symbol_index-now_ip_separate_symbol_index<= 3)){ *(out+i) = in.mid((i==0)? now_ip_separate_symbol_index:(now_ip_separate_symbol_index+1), \ (i==0)? next_ip_separate_symbol_index: \ (next_ip_separate_symbol_index-now_ip_separate_symbol_index-1)).toInt(0,16); now_ip_separate_symbol_index = next_ip_separate_symbol_index; }else{ return array; } } array.resize(sizeof(out));//重置数据大小 memcpy(array.data(), out, sizeof(out));//copy数据 return array; } bool MacAddr::isMacAddress(QString mac) { mac = mac.replace(QString(":"), QString("-")); QRegExp rx("^([A-Fa-f0-9]{2}[-,:]){5}[A-Fa-f0-9]{2}$"); QRegExpValidator v(rx, 0); int pos = 0; if(v.validate(mac, pos) == QValidator::Acceptable) return true; return false; }
include uXmx86asm.inc option casemap:none ifndef __X64__ .686P .xmm .model flat, c else .X64P .xmm option win64:11 option stackbase:rsp endif option frame:auto .code align 16 uXm_has_enabled_ZMM proto VECCALL (byte) align 16 uXm_has_enabled_ZMM proc VECCALL (byte) mov eax, 1 cpuid and ecx, bit_OSXSAVE cmp ecx, bit_OSXSAVE ; OSXSAVE support by microprocessor jne not_supported ; processor supports XGETBV is enabled by OS mov ecx, 0 ; specify 0 for XCR0 register xgetbv ; result in edx:eax and eax, 0E6h cmp eax, 0E6h ; check OS has enabled both XMM and YMM and ZMM state support jne not_supported mov al, true jmp done not_supported: mov al, false done: ret uXm_has_enabled_ZMM endp end ;.code
#include "robotoc/riccati/backward_riccati_recursion_factorizer.hpp" namespace robotoc { BackwardRiccatiRecursionFactorizer::BackwardRiccatiRecursionFactorizer( const Robot& robot) : dimv_(robot.dimv()), dimu_(robot.dimu()), AtP_(MatrixXdRowMajor::Zero(2*robot.dimv(), 2*robot.dimv())), BtP_(MatrixXdRowMajor::Zero(robot.dimu(), 2*robot.dimv())), GK_(Eigen::MatrixXd::Zero(robot.dimu(), 2*robot.dimv())), Pf_(Eigen::VectorXd::Zero(2*robot.dimv())) { } BackwardRiccatiRecursionFactorizer::BackwardRiccatiRecursionFactorizer() : dimv_(0), dimu_(0), AtP_(), BtP_(), GK_(), Pf_() { } BackwardRiccatiRecursionFactorizer::~BackwardRiccatiRecursionFactorizer() { } void BackwardRiccatiRecursionFactorizer::factorizeKKTMatrix( const SplitRiccatiFactorization& riccati_next, SplitKKTMatrix& kkt_matrix, SplitKKTResidual& kkt_residual) { AtP_.noalias() = kkt_matrix.Fxx.transpose() * riccati_next.P; BtP_.noalias() = kkt_matrix.Fvu.transpose() * riccati_next.P.bottomRows(dimv_); // Factorize F kkt_matrix.Qxx.noalias() += AtP_ * kkt_matrix.Fxx; // Factorize H kkt_matrix.Qxu.noalias() += AtP_.rightCols(dimv_) * kkt_matrix.Fvu; // Factorize G kkt_matrix.Quu.noalias() += BtP_.rightCols(dimv_) * kkt_matrix.Fvu; // Factorize vector term kkt_residual.lu.noalias() += BtP_ * kkt_residual.Fx; kkt_residual.lu.noalias() -= kkt_matrix.Fvu.transpose() * riccati_next.sv(); } void BackwardRiccatiRecursionFactorizer::factorizeHamiltonian( const SplitRiccatiFactorization& riccati_next, const SplitKKTMatrix& kkt_matrix, SplitRiccatiFactorization& riccati, const bool has_next_sto_phase) const { riccati.psi_x.noalias() = AtP_ * kkt_matrix.fx; riccati.psi_u.noalias() = BtP_ * kkt_matrix.fx; riccati.psi_x.noalias() += kkt_matrix.hx; riccati.psi_u.noalias() += kkt_matrix.hu; riccati.psi_x.noalias() += kkt_matrix.Fxx.transpose() * riccati_next.Psi; riccati.psi_u.noalias() += kkt_matrix.Fvu.transpose() * riccati_next.Psi.tail(dimv_); if (has_next_sto_phase) { riccati.phi_x.noalias() = kkt_matrix.Fxx.transpose() * riccati_next.Phi; riccati.phi_u.noalias() = kkt_matrix.Fvu.transpose() * riccati_next.Phi.tail(dimv_); } else { riccati.phi_x.setZero(); riccati.phi_u.setZero(); } } void BackwardRiccatiRecursionFactorizer::factorizeKKTMatrix( const SplitRiccatiFactorization& riccati_next, ImpulseSplitKKTMatrix& kkt_matrix) { AtP_.noalias() = kkt_matrix.Fxx.transpose() * riccati_next.P; // Factorize F kkt_matrix.Qxx.noalias() += AtP_ * kkt_matrix.Fxx; } void BackwardRiccatiRecursionFactorizer::factorizeRiccatiFactorization( const SplitRiccatiFactorization& riccati_next, SplitKKTMatrix& kkt_matrix, const SplitKKTResidual& kkt_residual, const LQRPolicy& lqr_policy, SplitRiccatiFactorization& riccati) { GK_.noalias() = kkt_matrix.Quu * lqr_policy.K; kkt_matrix.Qxx.noalias() -= lqr_policy.K.transpose() * GK_; // Riccati factorization matrix with preserving the symmetry riccati.P = 0.5 * (kkt_matrix.Qxx + kkt_matrix.Qxx.transpose()); // Riccati factorization vector riccati.s.noalias() = kkt_matrix.Fxx.transpose() * riccati_next.s; riccati.s.noalias() -= AtP_ * kkt_residual.Fx; riccati.s.noalias() -= kkt_residual.lx; riccati.s.noalias() -= kkt_matrix.Qxu * lqr_policy.k; } void BackwardRiccatiRecursionFactorizer::factorizeSTOFactorization( const SplitRiccatiFactorization& riccati_next, const SplitKKTMatrix& kkt_matrix, const SplitKKTResidual& kkt_residual, const LQRPolicy& lqr_policy, SplitRiccatiFactorization& riccati, const bool has_next_sto_phase) { // Qtx riccati.Psi = riccati.psi_x; riccati.Psi.noalias() += lqr_policy.K.transpose() * riccati.psi_u; if (has_next_sto_phase) { riccati.Phi.noalias() = riccati.phi_x; riccati.Phi.noalias() += lqr_policy.K.transpose() * riccati.phi_u; } else { riccati.Phi.setZero(); } // Qtt Pf_.noalias() = riccati_next.P * kkt_matrix.fx; riccati.xi = kkt_matrix.fx.dot(Pf_); riccati.xi += kkt_matrix.Qtt; riccati.xi += 2 * riccati_next.Psi.dot(kkt_matrix.fx); riccati.xi += lqr_policy.T.dot(riccati.psi_u); riccati.xi += riccati_next.xi; if (has_next_sto_phase) { riccati.chi = kkt_matrix.Qtt_prev; riccati.chi += riccati_next.Phi.dot(kkt_matrix.fx); riccati.chi += lqr_policy.T.dot(riccati.phi_u); riccati.chi += riccati_next.chi; riccati.rho = lqr_policy.W.dot(riccati.phi_u); riccati.rho += riccati_next.rho; } else { riccati.chi = 0.0; riccati.rho = 0.0; } // h Pf_.noalias() = riccati_next.P * kkt_residual.Fx - riccati_next.s; riccati.eta = kkt_matrix.fx.dot(Pf_); riccati.eta += kkt_residual.h; riccati.eta += riccati_next.Psi.dot(kkt_residual.Fx); riccati.eta += riccati.psi_u.dot(lqr_policy.k); riccati.eta += riccati_next.eta; if (has_next_sto_phase) { riccati.iota = riccati_next.Phi.dot(kkt_residual.Fx); riccati.iota += riccati.phi_u.dot(lqr_policy.k); riccati.iota += riccati_next.iota; } else { riccati.iota = 0.0; } } void BackwardRiccatiRecursionFactorizer::factorizeRiccatiFactorization( const SplitRiccatiFactorization& riccati_next, const ImpulseSplitKKTMatrix& kkt_matrix, const ImpulseSplitKKTResidual& kkt_residual, SplitRiccatiFactorization& riccati) { // Riccati factorization matrix with preserving the symmetry riccati.P = 0.5 * (kkt_matrix.Qxx + kkt_matrix.Qxx.transpose()); // Riccati factorization vector riccati.s.noalias() = kkt_matrix.Fxx.transpose() * riccati_next.s; riccati.s.noalias() -= AtP_ * kkt_residual.Fx; riccati.s.noalias() -= kkt_residual.lx; } void BackwardRiccatiRecursionFactorizer::factorizeSTOFactorization( const SplitRiccatiFactorization& riccati_next, const ImpulseSplitKKTMatrix& kkt_matrix, const ImpulseSplitKKTResidual& kkt_residual, SplitRiccatiFactorization& riccati) { // Qtx riccati.Psi.setZero(); riccati.Phi.noalias() = kkt_matrix.Fxx.transpose() * riccati_next.Phi; riccati.xi = 0.0; riccati.chi = 0.0; riccati.rho = riccati_next.rho; riccati.eta = 0.0; riccati.iota = riccati_next.iota; riccati.iota += riccati_next.Phi.dot(kkt_residual.Fx); } } // namespace robotoc
; A232228: a(1)=1; thereafter a(n) = 2^(number of bits in binary expansion of a(n-1)) + 1 + a(n-1). ; 1,4,13,30,63,128,385,898,1923,3972,8069,16262,32647,65416,130953,262026,524171,1048460,2097037,4194190,8388495,16777104,33554321,67108754,134217619,268435348,536870805,1073741718,2147483543,4294967192,8589934489,17179869082,34359738267,68719476636,137438953373,274877906846,549755813791,1099511627680,2199023255457,4398046511010,8796093022115,17592186044324,35184372088741,70368744177574,140737488355239,281474976710568,562949953421225,1125899906842538,2251799813685163,4503599627370412,9007199254740909,18014398509481902,36028797018963887,72057594037927856,144115188075855793,288230376151711666,576460752303423411,1152921504606846900,2305843009213693877,4611686018427387830,9223372036854775735,18446744073709551544,36893488147419103161,73786976294838206394,147573952589676412859,295147905179352825788,590295810358705651645,1180591620717411303358,2361183241434822606783,4722366482869645213632,9444732965739290427329,18889465931478580854722,37778931862957161709507,75557863725914323419076,151115727451828646838213,302231454903657293676486,604462909807314587353031,1208925819614629174706120,2417851639229258349412297,4835703278458516698824650,9671406556917033397649355,19342813113834066795298764,38685626227668133590597581,77371252455336267181195214,154742504910672534362390479,309485009821345068724781008,618970019642690137449562065,1237940039285380274899124178,2475880078570760549798248403,4951760157141521099596496852,9903520314283042199192993749,19807040628566084398385987542,39614081257132168796771975127,79228162514264337593543950296,158456325028528675187087900633,316912650057057350374175801306,633825300114114700748351602651,1267650600228229401496703205340,2535301200456458802993406410717,5070602400912917605986812821470 mov $4,$0 mov $6,$0 add $6,1 lpb $6 mov $0,$4 sub $6,1 sub $0,$6 mov $3,$0 mov $0,7 mov $2,$3 add $2,2 lpb $0 div $0,$2 sub $2,$0 mov $5,2 pow $5,$2 add $5,1 lpe add $1,$5 lpe mov $0,$1
; A144943: a(n) = number of divisors of n^3 (excluding 1 and n^3). ; Submitted by Jamie Morken(s3) ; 0,2,2,5,2,14,2,8,5,14,2,26,2,14,14,11,2,26,2,26,14,14,2,38,5,14,8,26,2,62,2,14,14,14,14,47,2,14,14,38,2,62,2,26,26,14,2,50,5,26,14,26,2,38,14,38,14,14,2,110,2,14,26,17,14,62,2,26,14,62,2,68,2,14,26,26,14,62,2,50,11,14,2,110,14,14,14,38,2,110,14,26,14,14,14,62,2,26,26,47 seq $0,15995 ; a(n) = (tau(n^3)+2)/3. mov $2,4 mul $2,$0 sub $2,$0 mov $3,$2 mov $4,$0 cmp $4,1 add $3,$4 mov $0,$3 sub $0,4
; A132813: Triangle read by rows: A001263 * A127648 as infinite lower triangular matrices. ; Submitted by Christian Krause ; 1,1,2,1,6,3,1,12,18,4,1,20,60,40,5,1,30,150,200,75,6,1,42,315,700,525,126,7,1,56,588,1960,2450,1176,196,8,1,72,1008,4704,8820,7056,2352,288,9,1,90,1620,10080,26460,31752,17640,4320,405,10,1,110,2475,19800,69300,116424,97020,39600,7425,550,11,1,132,3630,36300,163350,365904,426888,261360,81675,12100,726,12,1,156,5148,62920,353925,1019304,1585584,1359072,637065,157300,18876,936,13,1,182,7098,104104,715715,2576574,5153148,5889312,3864861 mov $1,1 lpb $0 add $2,1 sub $0,$2 add $1,1 lpe bin $1,$0 bin $2,$0 mul $1,$2 mov $0,$1
; A124350: a(n) = 4*n*(floor(n^2/2)+1). For n>=3, this is the number of directed Hamiltonian paths on the n-prism graph. ; 0,4,24,60,144,260,456,700,1056,1476,2040,2684,3504,4420,5544,6780,8256,9860,11736,13756,16080,18564,21384,24380,27744,31300,35256,39420,44016,48836,54120,59644,65664,71940,78744,85820,93456,101380,109896,118716 mov $1,$0 mul $1,$0 add $1,2 div $1,2 mul $1,$0 mul $1,4
; A072265: Variant of Lucas numbers: a(n) = a(n-1) + 4*a(n-2) starting with a(0)=2 and a(1)=1. ; Submitted by Jon Maiga ; 2,1,9,13,49,101,297,701,1889,4693,12249,31021,80017,204101,524169,1340573,3437249,8799541,22548537,57746701,147940849,378927653,970691049,2486401661,6369165857,16314772501,41791435929,107050525933,274216269649,702418373381,1799283451977,4608956945501,11806090753409,30241918535413,77466281549049,198433955690701,508299081886897,1302034904649701,3335231232197289,8543370850796093,21884295779585249,56057779182769621,143594962301110617,367826079032189101,942205928236631569,2413510244365387973 mov $2,1 mov $4,2 lpb $0 sub $0,1 mov $3,$4 mul $3,4 mov $4,$2 add $2,$3 lpe mov $0,$4
LABEL stdlib_strlen AUTO LABEL stdlib_strupr AUTO LABEL stdlib_putchar AUTO LABEL stdlib_getchar AUTO LABEL stdlib_puts AUTO LABEL stdlib_shutdown AUTO ;****************************************************************************** ; strlen LABEL stdlib_strlen_loop AUTO LABEL stdlib_strlen_done AUTO stdlib_strlen: PUSH G.H0 CLR A stdlib_strlen_loop: CMPIND $00 @G.H0 JZ stdlib_strlen_done INC A.H0 INC G.H0 JMP stdlib_strlen_loop stdlib_strlen_done: POP G.H0 RET ;****************************************************************************** ; strupr LABEL stdlib_strupr_loop AUTO LABEL stdlib_strupr_done AUTO LABEL stdlib_strupr_continue AUTO stdlib_strupr: PUSH G.H0 CLR A stdlib_strupr_loop: CMPIND $00 @G.H0 JZ stdlib_strupr_done CMPIND $61 @G.H0 JB stdlib_strupr_continue CMPIND $7A @G.H0 JA stdlib_strupr_continue LD @G.H0 A.B0 SUB $20 A.B0 ST A.B0 @G.H0 stdlib_strupr_continue: INC G.H0 JMP stdlib_strupr_loop stdlib_strupr_done: POP G.H0 LD G.H0 A RET ;****************************************************************************** ; strlwr LABEL stdlib_strlwr_loop AUTO LABEL stdlib_strlwr_done AUTO LABEL stdlib_strlwr_continue AUTO stdlib_strlwr: PUSH G.H0 CLR A stdlib_strlwr_loop: CMPIND $00 @G.H0 JZ stdlib_strlwr_done CMPIND $41 @G.H0 JB stdlib_strlwr_continue CMPIND $5A @G.H0 JA stdlib_strlwr_continue LD @G.H0 A.B0 ADD $20 A.B0 ST A.B0 @G.H0 stdlib_strlwr_continue: INC G.H0 JMP stdlib_strlwr_loop stdlib_strlwr_done: POP G.H0 LD G.H0 A RET ;****************************************************************************** ; puts stdlib_puts: PUSH A LD $0002 A INT $40 POP A RET ;****************************************************************************** ; putchar stdlib_putchar: CLR A LD $0003 A INT $40 CLR A LD G.B0 A.B0 RET ;****************************************************************************** ; getchar stdlib_getchar: RET ;****************************************************************************** ; shutdown stdlib_shutdown: LD $0000 A INT $40 ; In case an error occurs... RET
//************************************************************************ // Copyright (C) 2020 Massachusetts Institute of Technology // // File Name: cep_crypto.cc/h // Program: Common Evaluation Platform (CEP) // Description: crypto test for CEP // Notes: //************************************************************************ #ifndef BARE_MODE #include <string.h> #endif #include "v2c_cmds.h" #include "cep_apis.h" #include "cep_crypto.h" #include "simdiag_global.h" #include "portable_io.h" #include "CEP.h" #include "cepregression.h" #include "random48.h" void cep_crypto::init(void) { #ifndef BARE_MODE mFd = 0; #endif mCapture = 0; mC2C_Capture = 0; mErrCnt = 0; mCount = 0; mSingle = 0; mWordCnt = 0; mAdrBase = 0; mAdrSize = 0x10000; // default } void cep_crypto::freeMe(void) { #ifndef BARE_MODE if (mCapture) { // terminate fprintf(mFd,"};\n\n"); fprintf(mFd,"#define %s_adrBase 0x%010lx\n", mTestName, mAdrBase); fprintf(mFd,"#define %s_adrSize 0x%0lx\n", mTestName, mAdrSize); fprintf(mFd,"#define %s_size %d\n", mTestName,mWordCnt); fprintf(mFd,"#define %s_cmdCnt4Single %d\n", mTestName, mSingle); fprintf(mFd,"#define %s_totalCommands %d\n#endif\n", mTestName, mCount); // fclose(mFd); } // turn off the capturing if (mC2C_Capture) { writeDvt(mC2C_Capture, mC2C_Capture, 0); if (mC2C_Capture == DVTF_DFT_CAPTURE_EN_BIT) { // also stop IDFT writeDvt(DVTF_IDFT_CAPTURE_EN_BIT, DVTF_IDFT_CAPTURE_EN_BIT, 0); } } #endif } // // // void cep_crypto::SetSeed (int seed) { mSeed=seed; Random48_srand48(seed); } // void cep_crypto::RandomGen(uint8_t *buf, int size) { // random uint32_t rand = Random48_rand(); for (int j=0;j<size;j++) { if ((j % 4)==0) rand = Random48_rand(); // pick up new number buf[j] = rand & 0xFF; rand = rand >> 8; } } // int cep_crypto::CheckCipherText(void) { for (int i=0;i<GetBlockSize();i++) { if (mHwCp[i] != mSwCp[i]) mErrCnt++; } return mErrCnt; } int cep_crypto::CheckPlainText(void) { for (int i=0;i<GetBlockSize();i++) { if (mHwPt[i] != mSwPt[i]) mErrCnt++; } return mErrCnt; } // // Print // void cep_crypto::PrintMe(const char *name, uint8_t *buf, int size) { //if (GetVerbose()==0) return; // char str[128]; //printf("Printing packet\n"); // print every 32 bytes?? int bC = 0; int first=1; str[0] = 0; // empty for (int i=0;i<size;i++) { if (bC == 0) { if (first) { sprintf(str,"%s: %02x",name,*(buf+i) & 0xff); first = 0; } else { sprintf(str," %02x",*(buf+i) & 0xff); } } // start of line else if (bC & 0x1) { sprintf(str,"%s%02x",str,*(buf+i) & 0xff); } // add 1 byte else { sprintf(str,"%s_%02x",str,*(buf+i) & 0xff); } // add 1 byte // print every 32 bytes in a line if ((bC == 31) || (i == (size-1))) { // 16 bytes or end LOGI("%s\n",str); bC = 0; } else { bC++; } } } void cep_crypto::PrintMe(const char *name, double *buf1, double *buf2, int size) { // //if (GetVerbose()==0) return; char str[128]; //printf("Printing packet\n"); // print every 32 bytes?? int bC = 0; int first=1; str[0] = 0; // empty for (int i=0;i<size;i++) { if (bC == 0) { if (first) { sprintf(str,"%s: %f %f",name,*(buf1+i),*(buf2+i)); first = 0; } else { sprintf(str," %f %f",*(buf1+i),*(buf2+i)); } } // start of line else if (bC & 0x1) { sprintf(str,"%s%f %f ",str,*(buf1+i),*(buf2+i) ); } // add 1 byte else { sprintf(str,"%s_%f_%f ",str,*(buf1+i),*(buf2+i)); } // add 1 byte // print every 32 bytes in a line if ((bC == 0) || (i == (size-1))) { // 16 bytes or end LOGI("%s\n",str); bC = 0; } else { bC++; } } } // // To support bareMetal and unit level testbench // void cep_crypto::SetCaptureMode(int mode, const char *path, const char *testName) { #ifndef BARE_MODE // char fName[512]; // init(); // // Sim Only // if (Get_C2C_Capture()) { if (strcmp(testName,"aes") == 0) { mC2C_Capture = DVTF_AES_CAPTURE_EN_BIT; } else if (strcmp(testName,"sha256") == 0) { mC2C_Capture = DVTF_SHA256_CAPTURE_EN_BIT; } else if (strcmp(testName,"md5") == 0) { mC2C_Capture = DVTF_MD5_CAPTURE_EN_BIT; } else if (strcmp(testName,"rsa") == 0) { mC2C_Capture = DVTF_RSA_CAPTURE_EN_BIT; } else if (strcmp(testName,"des3") == 0) { mC2C_Capture = DVTF_DES3_CAPTURE_EN_BIT; } else if (strcmp(testName,"gps") == 0) { mC2C_Capture = DVTF_GPS_CAPTURE_EN_BIT; } else if (strcmp(testName,"dft") == 0) { // both in one test mC2C_Capture = DVTF_DFT_CAPTURE_EN_BIT; // also the IDFT since it is in same test writeDvt(DVTF_IDFT_CAPTURE_EN_BIT, DVTF_IDFT_CAPTURE_EN_BIT, 1); } else if (strcmp(testName,"idft") == 0) { mC2C_Capture = DVTF_IDFT_CAPTURE_EN_BIT; } else if (strcmp(testName,"iir") == 0) { mC2C_Capture = DVTF_IIR_CAPTURE_EN_BIT; } else if (strcmp(testName,"fir") == 0) { mC2C_Capture = DVTF_FIR_CAPTURE_EN_BIT; } // writeDvt(mC2C_Capture, mC2C_Capture, 1); } // // mCapture = mode; //strcpy(mPath,path); strcpy(mTestName,testName); // open file if on if (mCapture) { // for input sprintf(fName,"%s/%s_playback.h",path,testName); mFd = fopen(fName,"w"); if (mFd == NULL) { LOGI("%s: ERROR: Can't open file %s\n",__FUNCTION__,fName); mCapture = 0; // turn off } else { LOGI("%s: Opening file %s for sequence capturing\n",__FUNCTION__,fName); // print CopyRigth fprintf(mFd,"//************************************************************************\n"); fprintf(mFd,"// Copyright (C) 2020 Massachusetts Institute of Technology\n"); fprintf(mFd,"//\n"); fprintf(mFd,"// This file is auto-generated for test: %s. Do not modify!!!\n", testName); fprintf(mFd,"//\n"); fprintf(mFd,"// Generated on: %s %s\n",__DATE__, __TIME__); fprintf(mFd,"//************************************************************************\n"); // // print Header // fprintf(mFd,"#ifndef %s_playback_H\n",testName); fprintf(mFd,"#define %s_playback_H\n\n",testName); // command encoding fprintf(mFd,"#ifndef PLAYBACK_CMD_H\n"); fprintf(mFd,"#define PLAYBACK_CMD_H\n"); fprintf(mFd,"// Write to : <physicalAdr> <writeData>\n"); fprintf(mFd,"#define WRITE__CMD 1\n"); fprintf(mFd,"// Read and compare: <physicalAdr> <Data2Compare>\n"); fprintf(mFd,"#define RDnCMP_CMD 2\n"); fprintf(mFd,"// Read and spin until match : <physicalAdr> <Data2Match> <mask> <timeout>\n"); fprintf(mFd,"#define RDSPIN_CMD 3\n\n"); fprintf(mFd,"#define WRITE__CMD_SIZE 3\n"); fprintf(mFd,"#define RDnCMP_CMD_SIZE 3\n"); fprintf(mFd,"#define RDSPIN_CMD_SIZE 5\n"); fprintf(mFd,"#endif\n\n"); fprintf(mFd,"// %s command sequences to playback\n",testName); fprintf(mFd,"uint64_t %s_playback[] = { \n",testName); } } #endif } void cep_crypto::cep_writeNcapture(int device, uint32_t pAddress, uint64_t pData) { cep_write(device, pAddress, pData); // // save to file in captured mode (BFM only) // #ifndef BARE_MODE if (mCapture) { if (mCount++ == 0) { fprintf(mFd,"\t WRITE__CMD, 0x%08x, 0x%016lx // %d\n", (uint32_t)get_physical_adr(device,pAddress), pData, mCount); } else { fprintf(mFd,"\t, WRITE__CMD, 0x%08x, 0x%016lx // %d\n", (uint32_t)get_physical_adr(device,pAddress), pData, mCount); } // save this away if (mAdrBase == 0) { mAdrBase = get_physical_adr(device,pAddress) & ~(mAdrSize-1); } mWordCnt += 3; } #endif } // // // uint64_t cep_crypto::cep_readNcapture(int device, uint32_t pAddress) { uint64_t pData = cep_read(device, pAddress); // // save to file in captured mode (BFM only) // #ifndef BARE_MODE if (mCapture) { if (mCount++ == 0) { fprintf(mFd,"\t RDnCMP_CMD, 0x%08x, 0x%016lx // %d\n", (uint32_t)get_physical_adr(device,pAddress), pData, mCount); } else { fprintf(mFd,"\t, RDnCMP_CMD, 0x%08x, 0x%016lx // %d\n", (uint32_t)get_physical_adr(device,pAddress), pData, mCount); } mWordCnt += 3; } #endif // return pData; } // int cep_crypto::cep_readNspin(int device, uint32_t pAddress, uint64_t pData,int timeOut) { return cep_readNspin(device, pAddress,pData,(uint64_t)(-1), timeOut) ; } int cep_crypto::cep_readNspin(int device, uint32_t pAddress,uint64_t pData,uint64_t mask, int timeOut) { if (GetVerbose()) { LOGI("%s: expData=0x%016lx mask=0x%016lx\n",__FUNCTION__,pData,mask); } uint64_t rdDat; // #ifndef BARE_MODE if (mCapture) { if (mCount++ == 0) { fprintf(mFd,"\t RDSPIN_CMD, 0x%08x, 0x%016lx, 0x%lx, 0x%x // %d\n", (uint32_t)get_physical_adr(device,pAddress), pData,mask,timeOut, mCount); } else { fprintf(mFd,"\t, RDSPIN_CMD, 0x%08x, 0x%016lx, 0x%lx, 0x%x // %d\n", (uint32_t)get_physical_adr(device,pAddress), pData,mask,timeOut, mCount); } mWordCnt += 5; } #endif // while (timeOut > 0) { rdDat = cep_read(device, pAddress); if (((rdDat ^ pData) & mask) == 0) { break; } timeOut--; }; return (timeOut <= 0) ? 1 : 0; } void cep_crypto::MarkSingle(int loop) { if ((loop >= mCapture) && (mSingle==0)) { mSingle = mCount; } }
DATA SEGMENT AT 0E000H ; 数据段的位置从 0E000H 开始 ARRAY_B LABEL BYTE ; 不同类型同一起始地址 ARRAY_W DW 50 DUP (?) DATA ENDS STACK SEGMENT PARA STACK 'STACK' TOP LABEL BYTE BASE DB 100 DUP (?) STACK ENDS CODE SEGMENT ASSUME CS:CODE, DS:DATA, SS:STACK ; 段指定 ORG 1000H ; 指定主程序从 1000H 开始 START: MOV AX, DATA MOV DS, AX ; your code here MOV AX, 4C00H INT 21H CODE ENDS END START
// Perf and stress test framework for blobfuse. // There are many existing benchmarks for file systems, and those are useful, but it's also useful to have something // purposefully designed to test and validate the expected behavior of blobfuse. // For the purposes of this file, "stress" refers to validating that there is no data corruption or data loss at high scale, and // "perf" or "performance" refers to measuring throughput, latency, etc. // We should run these tests for some static set of input parameters for every release. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdexcept> #include <string> #include <iostream> #include <sstream> #include <iomanip> #include <fstream> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <dirent.h> #include <vector> #include <sys/sendfile.h> #include <errno.h> #include <ftw.h> #include <chrono> #include <functional> #include <algorithm> #include <deque> #include <mutex> #include <condition_variable> #include <thread> #include <random> #include <csignal> #include <uuid/uuid.h> void signalHandler( int signum ) { exit(signum); } // Config std::string perf_source_dir("/home/vikas/stress_test/src"); // Source directory for test data. This is an SSD on my machine. Should not be a blobfuse directory. All contents will be wiped. std::string perf_dest_dir_1("/home/vikas/blob_mnt/stress"); // blobfuse directory to copy to. All contents will be wiped. std::string perf_dest_dir_2("/home/vikas/stress_test/dst"); // Local destination directory. This is an SSD on my machine. Should not be a blobfuse directory. All contents will be wiped. // There isn't really a built-in C++11 threadpool, and it ended up not being too difficult to code one up, with the specific behavior we need. // Basically, we start a bunch (constant number) of std::thread threads, and store them in m_threads. // We also store a deque (double-ended queue) of work to do, where a unit of work is some arbitrary std::function<void()>. Work is performed in roughly FIFO order. // Each thread runs one work item at a time. When it finished it tries to get another unit of work, or goes to sleep. // Work is added to the queue via the add_task method. // Note that there is only one queue of work, and all operations to it (pushing new work and popping work off to perform it) require mutex operations. // This may be a significant amount of overhead if the size of the work is very small and the number of work items is very large. So for example, if the work is to copy // a million very small files, it will be very bad to push the copy of each file to the threadpool as a separate item. Much better to chunk it externally. class thread_pool { public: // Loop that each thread runs, to pop work off the queue and execute it. void run_thread(int thread_id) { // m_finished is set during threadpool destruction, allowing the threads to all exit gracefully. while (!m_finished) { std::function<void()> work; { // Lock the mutex for the duration of the queue operations, but not performing the actual work. std::unique_lock<std::mutex> lk(m_mutex); m_wait_count++; // Release the mutex and perhaps sleep until woken up and there is work to be done (or tearing down the threadpool.) m_cv.wait(lk, [this] {return (!m_task_list.empty()) || m_finished;}); m_wait_count--; if (!m_finished) { // Pop a unit of work from the queue; we still hold the mutex at this point. work = m_task_list.front(); m_task_list.pop_front(); } } // Actually do the work. if (!m_finished) { work(); } } } // Spins up the desired number of threads, each of which will immediately wait on the condition variable. thread_pool(int size) : m_threads(), m_task_list(), m_mutex(), m_cv(), m_wait_count(0), m_finished(0) { for (int i = 0; i < size; i++) { m_threads.push_back(std::thread(&thread_pool::run_thread, this, i)); } } // Locks the work queue, adds a task to it, and then wakes up a worker thread to do the work. // If no worker threads are waiting, notify_one is a no-op. void add_task(std::function<void()> task) { std::lock_guard<std::mutex> lk(m_mutex); { m_task_list.push_back(task); } m_cv.notify_one(); } // Blocks until all work in the queue has been completed. // This condition is detected void drain() { while (true) { { std::lock_guard<std::mutex> lk(m_mutex); if ((m_wait_count == m_threads.size()) && (m_task_list.empty())) { return; } } std::this_thread::sleep_for(std::chrono::seconds(1)); } } // Drains all the work from the pool, instructs all worker threads to wake up and exit gracefully. ~thread_pool() { drain(); m_finished = true; m_cv.notify_all(); for (auto it = m_threads.begin(); it != m_threads.end(); it++) { it->join(); } } std::vector<std::thread> m_threads; std::deque<std::function<void()>> m_task_list; std::mutex m_mutex; std::condition_variable m_cv; int m_wait_count; bool m_finished; }; // Callback function for destroy_path (below). int rm_helper(const char *fpath, const struct stat * /*sb*/, int tflag, struct FTW * /*ftwbuf*/) { if (tflag == FTW_DP) { errno = 0; int ret = rmdir(fpath); return ret; } else { errno = 0; int ret = unlink(fpath); return ret; } } // Delete the entire contents of a path. FTW is a simple library for walking a directory structure. It's fairly limited in what it can do, but it works for deletion. void destroy_path(std::string path_to_destroy) { errno = 0; // FTW_DEPTH instructs FTW to do a post-order traversal (children of a directory before the actual directory.) nftw(path_to_destroy.c_str(), rm_helper, 20, FTW_DEPTH); } // Class used for running a single perf test. // At the moment, a single perf test consists of copying the entire (recursive) contents of a directory to the service, and then copying it back. // There are other interesting stress & performance analyses we could run as well (many writers / readers to // one file, for example), but we don't have infra for that yet. // // Parameters for a single test are defined by the "populate" function, input in the constructor. This // function is expected to create some directory structure, to use as a source directory. // The populate method is called in the constructor. This is because it's not really part of the actual test, although we could move it into run(). // // run() runs the actual test. That consists of the following steps: // - Run a recursive copy from the source directory to the cloud directory, and time this operation. // - Run a recusrive copy from the cloud directory to the local destination directory, and time this operation. // - Print the relevant performance metrics // - Validate that the contents of both the cloud and the local destination directory match the source. // Note: There are some important blobfuse-related parameters that are not captured here, but can have a large impact on performace: // - blobfuse cache timeout - if the files are still cached during download, download will be much faster. // - location of the blobfuse tmp directory (local SSD? Azure Disk? etc) // - Size of the VM on which blobfuse is mounted and this test runs - CPUs, Memory, etc // For any perf tests where we save the results for later comparison, we should document as many of these as possible. // We could also test multiple versions of blobfuse at the same time, if there are concerns that it might be hard to repro an environment. class perf_test { public: perf_test(int parallel_count, std::function<std::pair<size_t, size_t>(std::string, thread_pool&)> populate, std::string source_dir, std::string dest_dir_1, std::string dest_dir_2) : m_thread_pool(parallel_count), m_source_dir(source_dir), m_dest_dir_1(dest_dir_1), m_dest_dir_2(dest_dir_2) { std::pair<size_t, size_t> totals = populate(source_dir, m_thread_pool); m_total_size = totals.first; m_total_files = totals.second; } // We can remove the cleanup temporarily to help debugging, if necessary. ~perf_test() { std::cout << "Deleting test files." << std::endl; destroy_path(m_source_dir); destroy_path(m_dest_dir_1); destroy_path(m_dest_dir_2); } thread_pool m_thread_pool; std::string m_source_dir; std::string m_dest_dir_1; std::string m_dest_dir_2; size_t m_total_size; size_t m_total_files; // Print currnt time to the command line. // Helpful for keeping track of perf tests - if you expect a test to take an hour, come back in a while and don't remember when you started it, for example. void print_now() { std::time_t start = std::chrono::high_resolution_clock::to_time_t(std::chrono::high_resolution_clock::now()); std::cout << "Now = " << std::ctime(&start) << std::endl; } // Run the test, end-to-end. void run() { std::cout << "About to call copy_recursive to upload." << std::endl; std::chrono::time_point<std::chrono::high_resolution_clock> start_upload = std::chrono::high_resolution_clock::now(); copy_recursive(m_source_dir, m_dest_dir_1); m_thread_pool.drain(); // Note that we have to wait for the pool to drain before stopping the clock. std::chrono::time_point<std::chrono::high_resolution_clock> end_upload = std::chrono::high_resolution_clock::now(); double upload_time = std::chrono::duration_cast<std::chrono::microseconds>(end_upload - start_upload).count() / (1000000.0); std::cout << "Upload finished." << std::endl; print_now(); std::cout << "About to call copy_recursive to download." << std::endl; std::chrono::time_point<std::chrono::high_resolution_clock> start_download = std::chrono::high_resolution_clock::now(); copy_recursive(m_dest_dir_1, m_dest_dir_2); m_thread_pool.drain(); std::chrono::time_point<std::chrono::high_resolution_clock> end_download = std::chrono::high_resolution_clock::now(); double download_time = std::chrono::duration_cast<std::chrono::microseconds>(end_download - start_download).count() / (1000000.0); std::cout << "Download finished." << std::endl; double mbps_up = (m_total_size * 8) / (upload_time * 1024 * 1024); // Note we calculate Mb, not MB. double mbps_down = (m_total_size * 8) / (download_time * 1024 * 1024); std::cout << "Upload took " << upload_time << " seconds, averaging " << mbps_up << "Mb per second." << std::endl; std::cout << "Download took " << download_time << " seconds, averaging " << mbps_down << "Mb per second." << std::endl; print_now(); std::cout << "Now validating." << std::endl; validate_directory(m_source_dir, m_dest_dir_1); m_thread_pool.drain(); validate_directory(m_source_dir, m_dest_dir_2); m_thread_pool.drain(); std::cout << "Contents validated." << std::endl; } // Helper function to copy a file. // sendfile() is used to avoid having to copy data into userspace (other than in blobfuse, of course) - read() and write() would have additional user-space copies. void copy_file(std::string input, std::string output) { // std::cout << "Operate file called with " << input << " and " << output << std::endl; int input_fd = open(input.c_str(), O_RDONLY); if (input_fd < 0) { std::stringstream error; error << "Failed to open input file. errno = " << errno << ", input = " << input; throw std::runtime_error(error.str()); } int output_fd = open(output.c_str(), O_WRONLY | O_CREAT | O_EXCL, 0777); if (input_fd < 0) { std::stringstream error; error << "Failed to open output file. errno = " << errno << ", output = " << output; throw std::runtime_error(error.str()); } struct stat st; stat(input.c_str(), &st); size_t count = st.st_size; size_t initial_size = count; while (count > 0) { ssize_t copied = sendfile(output_fd, input_fd, NULL, count); if (copied < 0) { std::stringstream error; error << "Failed to copy file. errno = " << errno << ", input = " << input << ", initial size = " << initial_size << ", bytes remaining = " << count; throw std::runtime_error(error.str()); } else { count -= copied; } } close(input_fd); close(output_fd); } // Helper function to list all files in a directory, and call some other function for each file. // Used during directory validation. void list_in_directory(std::string dir_to_list, std::function<void (struct dirent*)> dir_ent_op) { DIR *dir_stream = opendir(dir_to_list.c_str()); if (dir_stream != NULL) { struct dirent* dir_ent = readdir(dir_stream); while (dir_ent != NULL) { if (dir_ent->d_name[0] != '.') { dir_ent_op(dir_ent); } dir_ent = readdir(dir_stream); } closedir(dir_stream); } else { std::stringstream error; error << "Failed to open directory. errno = " << errno << ", directory = " << dir_to_list; throw std::runtime_error(error.str()); } } // Validate that the contents of two files match. void validate_file(std::string input, std::string output) { std::ifstream input_file(input, std::ifstream::ate | std::ifstream::binary); std::ifstream output_file(output, std::ifstream::ate | std::ifstream::binary); if (input_file.tellg() != output_file.tellg()) { std::stringstream error; error << "Files are not the same size. File " << input << " has size " << input_file.tellg() << ", file " << output << " has size " << output_file.tellg(); throw std::runtime_error(error.str()); } size_t count = input_file.tellg(); input_file.seekg(0, std::ifstream::beg); output_file.seekg(0, std::ifstream::beg); uint read_buf_size = 1*1024*1024; char inputbuf[read_buf_size]; char outputbuf[read_buf_size]; while (count > 0) { uint size_to_read = read_buf_size < count ? read_buf_size : count; input_file.read(inputbuf, size_to_read); output_file.read(outputbuf, size_to_read); if (0 != memcmp(inputbuf, outputbuf, size_to_read)) { std::stringstream error; error << "File contents do not match. Files are " << input << " and " << output; throw std::runtime_error(error.str()); } count -= size_to_read; } } // Recursively copy one directory to another directory. // Note that file copies are done serially, as they come up, while directory copies are added to the threadpool. // This must be kept in mind when designing file structures to copy. void copy_recursive(std::string input_dir, std::string output_dir) { struct stat st; if (stat(output_dir.c_str(), &st) != 0) { int mkdirret = mkdir(output_dir.c_str(), 0777); if (mkdirret < 0) { //std::stringstream error; //error << "Failed to make directory. errno = " << errno << ", directory = " << output_dir; //throw std::runtime_error(error.str()); } } DIR *dir_stream = opendir(input_dir.c_str()); if (dir_stream != NULL) { struct dirent* dir_ent = readdir(dir_stream); while (dir_ent != NULL) { if (dir_ent->d_name[0] != '.') { std::string input(input_dir + "/" + dir_ent->d_name); std::string output(output_dir + "/" + dir_ent->d_name); if (dir_ent->d_type == DT_DIR) { m_thread_pool.add_task([this, input, output] () { copy_recursive(input, output); }); } else { copy_file(input, output); } } dir_ent = readdir(dir_stream); } closedir(dir_stream); } else { std::stringstream error; error << "Failed to open directory. errno = " << errno << ", directory = " << input_dir; throw std::runtime_error(error.str()); } } // Validate that the contents of two directories are equal. // Does file comparisons serially; adds directory comparisons to the threadpool. void validate_directory(std::string input_dir, std::string output_dir) { std::vector<std::string> input_file_list; std::vector<std::string> input_directory_list; std::vector<std::string> output_file_list; std::vector<std::string> output_directory_list; list_in_directory(input_dir, [&input_file_list, &input_directory_list] (struct dirent* dir_ent) { std::string name(dir_ent->d_name); if (dir_ent->d_type == DT_DIR) { input_directory_list.push_back(name); } else { input_file_list.push_back(name); } }); list_in_directory(output_dir, [&output_file_list, &output_directory_list] (struct dirent* dir_ent) { if (dir_ent->d_type == DT_DIR) { output_directory_list.push_back(dir_ent->d_name); } else { output_file_list.push_back(dir_ent->d_name); } }); std::sort(input_file_list.begin(), input_file_list.end()); std::sort(input_directory_list.begin(), input_directory_list.end()); std::sort(output_file_list.begin(), output_file_list.end()); std::sort(output_directory_list.begin(), output_directory_list.end()); if (input_file_list != output_file_list) { std::stringstream error; error << "List of files in directories do not match. Left dir = " << input_dir << ", right dir = " << output_dir; throw std::runtime_error(error.str()); } if (input_directory_list != output_directory_list) { std::stringstream error; error << "List of subdirectories in directories do not match. Left parent dir = " << input_dir << ", right parent dir = " << output_dir; throw std::runtime_error(error.str()); } for (int i = 0; i < input_directory_list.size(); i++) { std::string input_subdir(input_dir + "/" + input_directory_list[i]); std::string output_subdir(output_dir + "/" + output_directory_list[i]); m_thread_pool.add_task([this, input_subdir, output_subdir] () { validate_directory(input_subdir, output_subdir); }); } for (int i = 0; i < input_file_list.size(); i++) { std::string input_file(input_dir + "/" + input_file_list[i]); std::string output_file(output_dir + "/" + output_file_list[i]); validate_file(input_file, output_file); } } }; // Helper method to print out relevant information for each test run. // May need to change as additional scenarios are added. void print_test_initial_stats(int total_dir_count, int file_per_dir_count, size_t file_size_base, long unsigned int additional_size_jitter) { std::cout << "Total directory count = " << total_dir_count << ", files per directory = " << file_per_dir_count << "." << std::endl; std::cout << "File sizes chosen from roughly random uniform distribution between " << file_size_base << " and " << file_size_base + additional_size_jitter << " bytes." << std::endl; std::cout << "This adds up to around " << total_dir_count * file_per_dir_count * (file_size_base + (additional_size_jitter/2)) << " bytes total, across " << total_dir_count * file_per_dir_count << " files." << std::endl; } // Creates a directory structure for testing copies of large files. // Creates one file per directory, so that each file is copied in parallel. // TODO: remove duplicated logic between populate_* methods. std::pair<size_t, size_t> populate_large(std::string source_dir, thread_pool& pool) { #if 0 int total_dir_count = 30; size_t file_size_base = 50*1024*1024; // Each file will be roughly 50 MB in size (increase this for actual perf testing) long unsigned int additional_size_jitter = 1024 * 1024; // Each file will have between 0-1MB added to it (on top of the 500 MB)) #else int total_dir_count = 10; size_t file_size_base = 10*1024*1024; long unsigned int additional_size_jitter = 100; // Each file will have between 0-1MB added to it (on top of the 500 MB)) #endif int seed = 4; // We use a constant seed here to make each run identical; this probably doesn't matter a ton. std::minstd_rand r(seed); // minstd_rand has terrible randomness properties, but it's more than good enough for our purposes here, and is far faster than better options. size_t total_size = 0; std::cout << "Running large file stress test." << std::endl; print_test_initial_stats(total_dir_count, 1, file_size_base, additional_size_jitter); for (int i = 0; i < total_dir_count; i++) { std::string dir = source_dir + "/" + std::to_string(i); int mkdirret = mkdir(dir.c_str(), 0777); if (mkdirret < 0) { //std::stringstream error; //error << "Failed to make directory. errno = " << errno << ", directory = " << dir; //throw std::runtime_error(error.str()); } std::string file = dir + "/file"; uint_fast32_t start = r(); size_t file_size = file_size_base + (r() % additional_size_jitter); total_size += file_size; pool.add_task([=] () { uint_fast32_t current = start; std::ofstream file_stream(file, std::ios::binary); for (size_t i = 0; i < file_size; i += 4 /* sizeof uint_fast32_t */) { file_stream.write(reinterpret_cast<char*>(&current), 4); current++; } }); } pool.drain(); return std::make_pair(total_size, total_dir_count); } // Creates a directory structure for testing copying large numbers of small files. // Directories are copied in parallel to each other, while files in a directory are copied serially. This must be considered when choosing parameters. std::pair<size_t, size_t> populate_small(std::string source_dir, thread_pool& pool) { int seed = 4; std::minstd_rand r(seed); #if 0 size_t file_size_base = 1024; // Each file has a base size of 1 KB. long unsigned int additional_size_jitter = 1024; // Each file will have between 0-1KB added to it, randomly. int total_dir_count = 60; int file_per_dir_count = 10000; #else size_t file_size_base = 1024; // Each file has a base size of 1 KB. long unsigned int additional_size_jitter = 10; // Each file will have between 0-1KB added to it, randomly. int total_dir_count = 10; int file_per_dir_count = 100; #endif size_t total_size = total_dir_count * file_per_dir_count * (file_size_base + (additional_size_jitter/2)); // Here we just estimate the total size, more than close enough. std::cout << "Running small file stress test." << std::endl; print_test_initial_stats(total_dir_count, file_per_dir_count, file_size_base, additional_size_jitter); for (int i = 0; i < total_dir_count; i++) { std::string dir = source_dir + "/" + std::to_string(i); int mkdirret = mkdir(dir.c_str(), 0777); if (mkdirret < 0) { //std::stringstream error; //error << "Failed to make directory. errno = " << errno << ", directory = " << dir; //throw std::runtime_error(error.str()); } std::string file = dir + "/file"; uint_fast32_t r_local_seed = r(); pool.add_task([=] () { std::minstd_rand r_local(r_local_seed); for (int j = 0; j < file_per_dir_count; j++) { std::stringstream file_name_stream; file_name_stream << file << std::setfill('0') << std::setw(8) << j; size_t file_size = file_size_base + (r_local() % additional_size_jitter); uint_fast32_t current = r_local(); std::ofstream file_stream(file_name_stream.str(), std::ios::binary); for (size_t i = 0; i < file_size; i += 4 /* sizeof uint_fast32_t */) { file_stream.write(reinterpret_cast<char*>(&current), 4); current++; } } }); } pool.drain(); return std::make_pair(total_size, total_dir_count * file_per_dir_count); } int main(int argc, char *argv[]) { signal(SIGINT, signalHandler); if (argc >= 3) { uuid_t dir_uuid; uuid_generate( (unsigned char *)&dir_uuid ); char dir_name_uuid[37]; uuid_unparse_lower(dir_uuid, dir_name_uuid); std::string dir_name_prefix = "stresstest"; std::string dir_name = dir_name_prefix + dir_name_uuid; perf_source_dir = std::string(argv[2]) + "/src"; perf_dest_dir_1 = std::string(argv[1]) + "/" + dir_name; perf_dest_dir_2 = std::string(argv[2]) + "/dst"; printf("Running with : MNT : %s, SRC : %s, DST : %s\n", \ perf_dest_dir_1.c_str(), perf_source_dir.c_str(), perf_dest_dir_2.c_str()); //return 0; } else { printf("\nUsage : blobfusestress <mounted-dir> <tmp-download-dir>\n\n"); return 0; } try { std::vector<std::function<std::pair<size_t, size_t>(std::string, thread_pool&)>> populate_fns { populate_small, populate_large, }; std::cout << populate_fns.size() << " tests to run in total." << std::endl << std::endl; for (int i = 0; i < populate_fns.size(); i++) { std::cout << std::endl << "Starting test " << i << "." << std::endl; std::function<std::pair<size_t, size_t>(std::string, thread_pool&)> populate_func = populate_fns[i]; std::time_t start = std::chrono::high_resolution_clock::to_time_t(std::chrono::high_resolution_clock::now()); std::cout << "Start time = " << std::ctime(&start) << std::endl; struct stat st; if (stat(perf_source_dir.c_str(), &st) != 0) { int mkdirret = mkdir(perf_source_dir.c_str(), 0777); /*if (mkdirret < 0) { std::stringstream error; error << "Failed to make directory. errno = " << errno << ", directory = " << perf_source_dir; throw std::runtime_error(error.str()); }*/ } int parallel = 8; // Run 8 threads in parallel. std::cout << "Parallel count = " << parallel << std::endl; std::cout << "Starting generating test files." << std::endl; perf_test test(parallel, populate_func, perf_source_dir, perf_dest_dir_1, perf_dest_dir_2); std::cout << "Now running test." << std::endl; test.run(); std::time_t end = std::chrono::high_resolution_clock::to_time_t(std::chrono::high_resolution_clock::now()); std::cout << "End time = " << std::ctime(&end) << std::endl; rmdir(perf_source_dir.c_str()); } } catch (const std::exception& e) { std::cout << "Critical error encountered. e.what() = " << e.what() << std::endl; } return 0; }
INCLUDE Irvine32.inc INCLUDE Macros.inc .data array DWORD 4 DUP(?) rowSize = ($ - array) DWORD 4 DUP(?) DWORD 4 DUP(?) DWORD 4 DUP(?) siz WORD 4 overhund DWORD 16 DUP(?) rowIndex DWORD ? colIndex DWORD ? sum DWORD 0 cout DWORD 0; count DWORD 1 num DWORD 0 .code ;================M A I N======================== main PROC mWrite <"This program manipulates a two-dimensional array"> call crlf call run exit main endp ;================================================= run PROC mWrite<" Enter 16 values: (0-200)"> call crlf call fillarray call crlf mWrite"=========================================" call crlf mWrite " Right-Justified Values in 4X4 Matrix" call crlf call print call crlf mWrite"=========================================" call crlf call readR mov ecx, rowSize call sumRow call crlf mWrite"=========================================" call crlf call readC mov ecx, rowSize call sumCol call crlf call readChar mWrite"=========================================" call crlf mWrite" There are " push eax mov eax, cout call writedec mWrite" values >= 100" pop eax call crlf mWritespace call printHund call crlf call readchar mWrite"=========================================" call crlf mWrite<" Press any key to exchange rows 1 and 3"> call readchar call exchange mWrite"=========================================" call crlf ret run endp ;========================================== fillarray PROC xor eax, eax mov edi, OFFSET overhund mov ecx, LENGTHOF array*4 mov esi, OFFSET array l1: push eax mWritespace inc num mov eax, num call writedec mWrite ": " pop eax call readInt .IF eax > 200 || eax < 0 mWrite "ERROR: 0 < Value <= 200" call crlf dec num jmp l1 .ENDIF .IF eax >= 100 call addsum .ENDIF mov [esi], eax add esi, TYPE array loop l1 ret fillarray endp ;========================================== readR PROC mWritespace mWrite <"Enter a row (0-3): "> call readInt mov rowIndex, eax ret readR endp ;========================================== readC PROC mWritespace mWrite <"Enter a column (0-3): "> call readInt mov colIndex, eax ret readC endp ;============================================== print PROC push eax xor eax, eax mov ecx, LENGTHOF array*4 mov esi, OFFSET array l1: mWritespace mov eax, [esi] .IF eax < 10 mWriteSpace .ENDIF .IF eax < 100 mWritespace .ENDIF call writedec inc count .IF count > 4 call crlf call crlf sub count, 4 .ENDIF add esi, TYPE array loop l1 pop eax ret print endp ;===============================================; exchange PROC ; mov edi, OFFSET array mov esi, OFFSET array mov ebx, 16 add edi, ebx mov ecx, 48 add esi, ecx label1: .IF count > 4 jmp exs .ENDIF mov eax, [edi] mov ebp, [esi] xchg eax, ebp mov [edi], eax mov [esi], ebp add edi, 4 add esi, 4 inc count jmp label1 ; exs: call crlf mov count, 1 call print ; ret ; exchange endp ; ;===============================================; sumRow PROC USES ebx ecx esi mul ecx ; rowIndex*rowSize = eax*Ecx push eax mov eax, ecx mov edx, 0 div siz mov ecx, eax pop eax mov ebx, OFFSET array add ebx, eax mov eax, 0 mov esi, 0 l1: mov edx, [ebx+esi] add eax, edx add esi, 4 loop l1 push eax mWrite " The sum of row " mov eax, rowIndex call writedec mWrite " is: " pop eax call writedec call crlf ret sumRow endp ;================================================ sumCol PROC USES ebx ecx esi add ecx, eax ; rowIndex*rowSize = eax*Ecx push eax mov eax, ecx mov edx, 0 div siz mov ecx, eax pop eax mov ebx, OFFSET array mov eax, colIndex imul eax, 4 add ebx, eax mov eax, 0 mov esi, 0 l1: mov edx, [ebx+esi] add eax, edx add esi, rowSize loop l1 push eax mWrite " The sum of column " mov eax, colIndex call writedec mWrite " is: " pop eax call writedec call crlf ret sumCol endp ;================================= addsum PROC mov [edi], eax add edi, TYPE array inc cout ret addsum endp printHund PROC mov edi, OFFSET overhund mov ecx, cout l1: .IF eax == 0 jmp exs .ENDIF mov eax, [edi] add edi, TYPE overhund call writedec mWritespace loop l1 exs: ret printHund endp ;================================== end main
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Client side implementation of the airboat. // // - Dampens motion of driver's view to reduce nausea. // - Autocenters driver's view after a period of inactivity. // - Controls headlights. // - Controls curve parameters for pitch/roll blending. // //=============================================================================// #include "cbase.h" #include "c_prop_vehicle.h" #include "datacache/imdlcache.h" #include "flashlighteffect.h" #include "movevars_shared.h" #include "ammodef.h" #include "SpriteTrail.h" #include "beamdraw.h" #include "enginesprite.h" #include "fx_quad.h" #include "fx.h" #include "fx_water.h" #include "engine/ivdebugoverlay.h" #include "view.h" #include "clienteffectprecachesystem.h" #include "c_basehlplayer.h" #include "vgui_controls/Controls.h" #include "vgui/ISurface.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" ConVar r_AirboatViewBlendTo( "r_AirboatViewBlendTo", "1", FCVAR_CHEAT ); ConVar r_AirboatViewBlendToScale( "r_AirboatViewBlendToScale", "0.03", FCVAR_CHEAT ); ConVar r_AirboatViewBlendToTime( "r_AirboatViewBlendToTime", "1.5", FCVAR_CHEAT ); ConVar cl_draw_airboat_wake( "cl_draw_airboat_wake", "1", FCVAR_CHEAT ); // Curve parameters for pitch/roll blending. // NOTE: Must restart (or create a new airboat) after changing these cvars! ConVar r_AirboatRollCurveZero( "r_AirboatRollCurveZero", "90.0", FCVAR_CHEAT ); // Roll less than this is clamped to zero. ConVar r_AirboatRollCurveLinear( "r_AirboatRollCurveLinear", "120.0", FCVAR_CHEAT ); // Roll greater than this is mapped directly. // Spline in between. ConVar r_AirboatPitchCurveZero( "r_AirboatPitchCurveZero", "25.0", FCVAR_CHEAT ); // Pitch less than this is clamped to zero. ConVar r_AirboatPitchCurveLinear( "r_AirboatPitchCurveLinear", "60.0", FCVAR_CHEAT ); // Pitch greater than this is mapped directly. // Spline in between. ConVar airboat_joy_response_move( "airboat_joy_response_move", "1" ); // Quadratic steering response #define AIRBOAT_DELTA_LENGTH_MAX 12.0f // 1 foot #define AIRBOAT_FRAMETIME_MIN 1e-6 #define HEADLIGHT_DISTANCE 1000 #define MAX_WAKE_POINTS 16 #define WAKE_POINT_MASK (MAX_WAKE_POINTS-1) #define WAKE_LIFETIME 0.5f //============================================================================= // // Client-side Airboat Class // class C_PropAirboat : public C_PropVehicleDriveable { DECLARE_CLASS( C_PropAirboat, C_PropVehicleDriveable ); public: DECLARE_CLIENTCLASS(); DECLARE_INTERPOLATION(); DECLARE_DATADESC(); C_PropAirboat(); ~C_PropAirboat(); public: // C_BaseEntity virtual void Simulate(); // IClientVehicle virtual void UpdateViewAngles( C_BasePlayer *pLocalPlayer, CUserCmd *pCmd ); virtual void OnEnteredVehicle( C_BasePlayer *pPlayer ); virtual int GetPrimaryAmmoType() const; virtual int GetPrimaryAmmoClip() const; virtual bool PrimaryAmmoUsesClips() const; virtual int GetPrimaryAmmoCount() const; virtual int GetJoystickResponseCurve() const; int DrawModel( int flags ); // Draws crosshair in the forward direction of the boat void DrawHudElements( ); private: void DrawPropWake( Vector origin, float speed ); void DrawPontoonSplash( Vector position, Vector direction, float speed ); void DrawPontoonWake( Vector startPos, Vector wakeDir, float wakeLength, float speed); void DampenEyePosition( Vector &vecVehicleEyePos, QAngle &vecVehicleEyeAngles ); void DampenForwardMotion( Vector &vecVehicleEyePos, QAngle &vecVehicleEyeAngles, float flFrameTime ); void DampenUpMotion( Vector &vecVehicleEyePos, QAngle &vecVehicleEyeAngles, float flFrameTime ); void ComputePDControllerCoefficients( float *pCoefficientsOut, float flFrequency, float flDampening, float flDeltaTime ); void UpdateHeadlight( void ); void UpdateWake( void ); int DrawWake( void ); void DrawSegment( const BeamSeg_t &beamSeg, const Vector &vNormal ); TrailPoint_t *GetTrailPoint( int n ) { int nIndex = (n + m_nFirstStep) & WAKE_POINT_MASK; return &m_vecSteps[nIndex]; } private: Vector m_vecLastEyePos; Vector m_vecLastEyeTarget; Vector m_vecEyeSpeed; Vector m_vecTargetSpeed; float m_flViewAngleDeltaTime; bool m_bHeadlightIsOn; int m_nAmmoCount; CHeadlightEffect *m_pHeadlight; int m_nExactWaterLevel; TrailPoint_t m_vecSteps[MAX_WAKE_POINTS]; int m_nFirstStep; int m_nStepCount; float m_flUpdateTime; TimedEvent m_SplashTime; CMeshBuilder m_Mesh; Vector m_vecPhysVelocity; }; IMPLEMENT_CLIENTCLASS_DT( C_PropAirboat, DT_PropAirboat, CPropAirboat ) RecvPropBool( RECVINFO( m_bHeadlightIsOn ) ), RecvPropInt( RECVINFO( m_nAmmoCount ) ), RecvPropInt( RECVINFO( m_nExactWaterLevel ) ), RecvPropInt( RECVINFO( m_nWaterLevel ) ), RecvPropVector( RECVINFO( m_vecPhysVelocity ) ), END_RECV_TABLE() BEGIN_DATADESC( C_PropAirboat ) DEFINE_FIELD( m_vecLastEyePos, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_vecLastEyeTarget, FIELD_POSITION_VECTOR ), DEFINE_FIELD( m_vecEyeSpeed, FIELD_VECTOR ), DEFINE_FIELD( m_vecTargetSpeed, FIELD_VECTOR ), //DEFINE_FIELD( m_flViewAngleDeltaTime, FIELD_FLOAT ), END_DATADESC() //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- C_PropAirboat::C_PropAirboat() { m_vecEyeSpeed.Init(); m_flViewAngleDeltaTime = 0.0f; m_pHeadlight = NULL; m_ViewSmoothingData.flPitchCurveZero = r_AirboatPitchCurveZero.GetFloat(); m_ViewSmoothingData.flPitchCurveLinear = r_AirboatPitchCurveLinear.GetFloat(); m_ViewSmoothingData.flRollCurveZero = r_AirboatRollCurveZero.GetFloat(); m_ViewSmoothingData.flRollCurveLinear = r_AirboatRollCurveLinear.GetFloat(); m_ViewSmoothingData.rollLockData.flLockInterval = 1.5; m_ViewSmoothingData.rollLockData.flUnlockBlendInterval = 1.0; m_ViewSmoothingData.pitchLockData.flLockInterval = 1.5; m_ViewSmoothingData.pitchLockData.flUnlockBlendInterval = 1.0; m_nFirstStep = 0; m_nStepCount = 0; m_SplashTime.Init( 60 ); } //----------------------------------------------------------------------------- // Purpose: Deconstructor //----------------------------------------------------------------------------- C_PropAirboat::~C_PropAirboat() { if (m_pHeadlight) { delete m_pHeadlight; } } //----------------------------------------------------------------------------- // Draws the ammo for the airboat //----------------------------------------------------------------------------- int C_PropAirboat::GetPrimaryAmmoType() const { if ( m_nAmmoCount < 0 ) return -1; int nAmmoType = GetAmmoDef()->Index( "AirboatGun" ); return nAmmoType; } int C_PropAirboat::GetPrimaryAmmoCount() const { return m_nAmmoCount; } bool C_PropAirboat::PrimaryAmmoUsesClips() const { return false; } int C_PropAirboat::GetPrimaryAmmoClip() const { return -1; } //----------------------------------------------------------------------------- // The airboat prefers a more peppy response curve for joystick control. //----------------------------------------------------------------------------- int C_PropAirboat::GetJoystickResponseCurve() const { return airboat_joy_response_move.GetInt(); } //----------------------------------------------------------------------------- // Draws crosshair in the forward direction of the boat //----------------------------------------------------------------------------- void C_PropAirboat::DrawHudElements( ) { BaseClass::DrawHudElements(); MDLCACHE_CRITICAL_SECTION(); CHudTexture *pIcon = gHUD.GetIcon( IsX360() ? "crosshair_default" : "plushair" ); if ( pIcon != NULL ) { float x, y; Vector screen; int vx, vy, vw, vh; vgui::surface()->GetFullscreenViewport( vx, vy, vw, vh ); float screenWidth = vw; float screenHeight = vh; x = screenWidth/2; y = screenHeight/2; int eyeAttachmentIndex = LookupAttachment( "vehicle_driver_eyes" ); Vector vehicleEyeOrigin; QAngle vehicleEyeAngles; GetAttachment( eyeAttachmentIndex, vehicleEyeOrigin, vehicleEyeAngles ); // Only worry about yaw. vehicleEyeAngles.x = vehicleEyeAngles.z = 0.0f; Vector vecForward; AngleVectors( vehicleEyeAngles, &vecForward ); VectorMA( vehicleEyeOrigin, 100.0f, vecForward, vehicleEyeOrigin ); ScreenTransform( vehicleEyeOrigin, screen ); x += 0.5 * screen[0] * screenWidth + 0.5; y -= 0.5 * screen[1] * screenHeight + 0.5; x -= pIcon->Width() / 2; y -= pIcon->Height() / 2; pIcon->DrawSelf( x, y, gHUD.m_clrNormal ); } } //----------------------------------------------------------------------------- // Purpose: Blend view angles. //----------------------------------------------------------------------------- void C_PropAirboat::UpdateViewAngles( C_BasePlayer *pLocalPlayer, CUserCmd *pCmd ) { if ( r_AirboatViewBlendTo.GetInt() ) { // // Autocenter the view after a period of no mouse movement while throttling. // bool bResetViewAngleTime = false; if ( ( pCmd->mousedx != 0 || pCmd->mousedy != 0 ) || ( fabsf( m_flThrottle ) < 0.01f ) ) { if ( IsX360() ) { // Only reset this if there isn't an autoaim target! C_BaseHLPlayer *pLocalHLPlayer = (C_BaseHLPlayer *)pLocalPlayer; if ( pLocalHLPlayer ) { // Get the autoaim target. CBaseEntity *pTarget = pLocalHLPlayer->m_HL2Local.m_hAutoAimTarget.Get(); if( !pTarget ) { bResetViewAngleTime = true; } } } else { bResetViewAngleTime = true; } } if( bResetViewAngleTime ) { m_flViewAngleDeltaTime = 0.0f; } else { m_flViewAngleDeltaTime += gpGlobals->frametime; } if ( m_flViewAngleDeltaTime > r_AirboatViewBlendToTime.GetFloat() ) { // Blend the view angles. int eyeAttachmentIndex = LookupAttachment( "vehicle_driver_eyes" ); Vector vehicleEyeOrigin; QAngle vehicleEyeAngles; GetAttachmentLocal( eyeAttachmentIndex, vehicleEyeOrigin, vehicleEyeAngles ); QAngle outAngles; InterpolateAngles( pCmd->viewangles, vehicleEyeAngles, outAngles, r_AirboatViewBlendToScale.GetFloat() ); pCmd->viewangles = outAngles; } } BaseClass::UpdateViewAngles( pLocalPlayer, pCmd ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_PropAirboat::DampenEyePosition( Vector &vecVehicleEyePos, QAngle &vecVehicleEyeAngles ) { // Get the frametime. (Check to see if enough time has passed to warrent dampening). float flFrameTime = gpGlobals->frametime; if ( flFrameTime < AIRBOAT_FRAMETIME_MIN ) { vecVehicleEyePos = m_vecLastEyePos; DampenUpMotion( vecVehicleEyePos, vecVehicleEyeAngles, 0.0f ); return; } // Keep static the sideways motion. // Dampen forward/backward motion. DampenForwardMotion( vecVehicleEyePos, vecVehicleEyeAngles, flFrameTime ); // Blend up/down motion. DampenUpMotion( vecVehicleEyePos, vecVehicleEyeAngles, flFrameTime ); } //----------------------------------------------------------------------------- // Use the controller as follows: // speed += ( pCoefficientsOut[0] * ( targetPos - currentPos ) + pCoefficientsOut[1] * ( targetSpeed - currentSpeed ) ) * flDeltaTime; //----------------------------------------------------------------------------- void C_PropAirboat::ComputePDControllerCoefficients( float *pCoefficientsOut, float flFrequency, float flDampening, float flDeltaTime ) { float flKs = 9.0f * flFrequency * flFrequency; float flKd = 4.5f * flFrequency * flDampening; float flScale = 1.0f / ( 1.0f + flKd * flDeltaTime + flKs * flDeltaTime * flDeltaTime ); pCoefficientsOut[0] = flKs * flScale; pCoefficientsOut[1] = ( flKd + flKs * flDeltaTime ) * flScale; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_PropAirboat::DampenForwardMotion( Vector &vecVehicleEyePos, QAngle &vecVehicleEyeAngles, float flFrameTime ) { // vecVehicleEyePos = real eye position this frame // m_vecLastEyePos = eye position last frame // m_vecEyeSpeed = eye speed last frame // vecPredEyePos = predicted eye position this frame (assuming no acceleration - it will get that from the pd controller). // vecPredEyeSpeed = predicted eye speed Vector vecPredEyePos = m_vecLastEyePos + m_vecEyeSpeed * flFrameTime; Vector vecPredEyeSpeed = m_vecEyeSpeed; // m_vecLastEyeTarget = real eye position last frame (used for speed calculation). // Calculate the approximate speed based on the current vehicle eye position and the eye position last frame. Vector vecVehicleEyeSpeed = ( vecVehicleEyePos - m_vecLastEyeTarget ) / flFrameTime; m_vecLastEyeTarget = vecVehicleEyePos; if (vecVehicleEyeSpeed.Length() == 0.0) { return; } // Calculate the delta between the predicted eye position and speed and the current eye position and speed. Vector vecDeltaSpeed = vecVehicleEyeSpeed - vecPredEyeSpeed; Vector vecDeltaPos = vecVehicleEyePos - vecPredEyePos; // Forward vector. Vector vecForward; AngleVectors( vecVehicleEyeAngles, &vecForward ); float flDeltaLength = vecDeltaPos.Length(); if ( flDeltaLength > AIRBOAT_DELTA_LENGTH_MAX ) { // Clamp. float flDelta = flDeltaLength - AIRBOAT_DELTA_LENGTH_MAX; if ( flDelta > 40.0f ) { // This part is a bit of a hack to get rid of large deltas (at level load, etc.). m_vecLastEyePos = vecVehicleEyePos; m_vecEyeSpeed = vecVehicleEyeSpeed; } else { // Position clamp. float flRatio = AIRBOAT_DELTA_LENGTH_MAX / flDeltaLength; vecDeltaPos *= flRatio; Vector vecForwardOffset = vecForward * ( vecForward.Dot( vecDeltaPos ) ); vecVehicleEyePos -= vecForwardOffset; m_vecLastEyePos = vecVehicleEyePos; // Speed clamp. vecDeltaSpeed *= flRatio; float flCoefficients[2]; ComputePDControllerCoefficients( flCoefficients, r_AirboatViewDampenFreq.GetFloat(), r_AirboatViewDampenDamp.GetFloat(), flFrameTime ); m_vecEyeSpeed += ( ( flCoefficients[0] * vecDeltaPos + flCoefficients[1] * vecDeltaSpeed ) * flFrameTime ); } } else { // Generate an updated (dampening) speed for use in next frames position prediction. float flCoefficients[2]; ComputePDControllerCoefficients( flCoefficients, r_AirboatViewDampenFreq.GetFloat(), r_AirboatViewDampenDamp.GetFloat(), flFrameTime ); m_vecEyeSpeed += ( ( flCoefficients[0] * vecDeltaPos + flCoefficients[1] * vecDeltaSpeed ) * flFrameTime ); // Save off data for next frame. m_vecLastEyePos = vecPredEyePos; // Move eye forward/backward. Vector vecForwardOffset = vecForward * ( vecForward.Dot( vecDeltaPos ) ); vecVehicleEyePos -= vecForwardOffset; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_PropAirboat::DampenUpMotion( Vector &vecVehicleEyePos, QAngle &vecVehicleEyeAngles, float flFrameTime ) { // Get up vector. Vector vecUp; AngleVectors( vecVehicleEyeAngles, NULL, NULL, &vecUp ); vecUp.z = clamp( vecUp.z, 0.0f, vecUp.z ); vecVehicleEyePos.z += r_AirboatViewZHeight.GetFloat() * vecUp.z; // NOTE: Should probably use some damped equation here. } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_PropAirboat::OnEnteredVehicle( C_BasePlayer *pPlayer ) { int eyeAttachmentIndex = LookupAttachment( "vehicle_driver_eyes" ); Vector vehicleEyeOrigin; QAngle vehicleEyeAngles; GetAttachment( eyeAttachmentIndex, vehicleEyeOrigin, vehicleEyeAngles ); m_vecLastEyeTarget = vehicleEyeOrigin; m_vecLastEyePos = vehicleEyeOrigin; m_vecEyeSpeed = vec3_origin; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_PropAirboat::Simulate() { UpdateHeadlight(); UpdateWake(); BaseClass::Simulate(); } //----------------------------------------------------------------------------- // Purpose: Creates, destroys, and updates the headlight effect as needed. //----------------------------------------------------------------------------- void C_PropAirboat::UpdateHeadlight() { if (m_bHeadlightIsOn) { if (!m_pHeadlight) { // Turned on the headlight; create it. m_pHeadlight = new CHeadlightEffect(); if (!m_pHeadlight) return; m_pHeadlight->TurnOn(); } // The headlight is emitted from an attachment point so that it can move // as we turn the handlebars. int nHeadlightIndex = LookupAttachment( "vehicle_headlight" ); Vector vecLightPos; QAngle angLightDir; GetAttachment(nHeadlightIndex, vecLightPos, angLightDir); Vector vecLightDir, vecLightRight, vecLightUp; AngleVectors( angLightDir, &vecLightDir, &vecLightRight, &vecLightUp ); // Update the light with the new position and direction. m_pHeadlight->UpdateLight( vecLightPos, vecLightDir, vecLightRight, vecLightUp, HEADLIGHT_DISTANCE ); } else if (m_pHeadlight) { // Turned off the headlight; delete it. delete m_pHeadlight; m_pHeadlight = NULL; } } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_PropAirboat::UpdateWake( void ) { if ( gpGlobals->frametime <= 0.0f ) return; // Can't update too quickly if ( m_flUpdateTime > gpGlobals->curtime ) return; Vector screenPos = GetRenderOrigin(); screenPos.z = m_nExactWaterLevel; TrailPoint_t *pLast = m_nStepCount ? GetTrailPoint( m_nStepCount-1 ) : NULL; if ( ( pLast == NULL ) || ( pLast->m_vecScreenPos.DistToSqr( screenPos ) > 4.0f ) ) { // If we're over our limit, steal the last point and put it up front if ( m_nStepCount >= MAX_WAKE_POINTS ) { --m_nStepCount; ++m_nFirstStep; } // Save off its screen position, not its world position TrailPoint_t *pNewPoint = GetTrailPoint( m_nStepCount ); pNewPoint->m_vecScreenPos = screenPos + Vector( 0, 0, 2 ); pNewPoint->m_flDieTime = gpGlobals->curtime + WAKE_LIFETIME; pNewPoint->m_flWidthVariance = random->RandomFloat( -16, 16 ); if ( pLast ) { pNewPoint->m_flTexCoord = pLast->m_flTexCoord + pLast->m_vecScreenPos.DistTo( screenPos ); pNewPoint->m_flTexCoord = fmod( pNewPoint->m_flTexCoord, 1 ); } else { pNewPoint->m_flTexCoord = 0.0f; } ++m_nStepCount; } // Don't update again for a bit m_flUpdateTime = gpGlobals->curtime + ( 0.5f / (float) MAX_WAKE_POINTS ); } //----------------------------------------------------------------------------- // Purpose: // Input : &beamSeg - //----------------------------------------------------------------------------- void C_PropAirboat::DrawSegment( const BeamSeg_t &beamSeg, const Vector &vNormal ) { // Build the endpoints. Vector vPoint1, vPoint2; VectorMA( beamSeg.m_vPos, beamSeg.m_flWidth*0.5f, vNormal, vPoint1 ); VectorMA( beamSeg.m_vPos, -beamSeg.m_flWidth*0.5f, vNormal, vPoint2 ); // Specify the points. m_Mesh.Position3fv( vPoint1.Base() ); m_Mesh.Color4f( VectorExpand( beamSeg.m_vColor ), beamSeg.m_flAlpha ); m_Mesh.TexCoord2f( 0, 0, beamSeg.m_flTexCoord ); m_Mesh.TexCoord2f( 1, 0, beamSeg.m_flTexCoord ); m_Mesh.AdvanceVertex(); m_Mesh.Position3fv( vPoint2.Base() ); m_Mesh.Color4f( VectorExpand( beamSeg.m_vColor ), beamSeg.m_flAlpha ); m_Mesh.TexCoord2f( 0, 1, beamSeg.m_flTexCoord ); m_Mesh.TexCoord2f( 1, 1, beamSeg.m_flTexCoord ); m_Mesh.AdvanceVertex(); } //----------------------------------------------------------------------------- // Purpose: // Input : position - //----------------------------------------------------------------------------- void C_PropAirboat::DrawPontoonSplash( Vector origin, Vector direction, float speed ) { Vector offset; CSmartPtr<CSplashParticle> pSimple = CSplashParticle::Create( "splish" ); pSimple->SetSortOrigin( origin ); SimpleParticle *pParticle; Vector color = Vector( 0.8f, 0.8f, 0.75f ); float colorRamp; float flScale = RemapVal( speed, 64, 256, 0.75f, 1.0f ); PMaterialHandle hMaterial; float tempDelta = gpGlobals->frametime; while( m_SplashTime.NextEvent( tempDelta ) ) { if ( random->RandomInt( 0, 1 ) ) { hMaterial = ParticleMgr()->GetPMaterial( "effects/splash1" ); } else { hMaterial = ParticleMgr()->GetPMaterial( "effects/splash2" ); } offset = RandomVector( -8.0f * flScale, 8.0f * flScale ); offset[2] = 0.0f; offset += origin; pParticle = (SimpleParticle *) pSimple->AddParticle( sizeof( SimpleParticle ), hMaterial, offset ); if ( pParticle == NULL ) continue; pParticle->m_flLifetime = 0.0f; pParticle->m_flDieTime = 0.25f; pParticle->m_vecVelocity.Random( -0.4f, 0.4f ); pParticle->m_vecVelocity += (direction*5.0f+Vector(0,0,1)); VectorNormalize( pParticle->m_vecVelocity ); pParticle->m_vecVelocity *= speed + random->RandomFloat( -128.0f, 128.0f ); colorRamp = random->RandomFloat( 0.75f, 1.25f ); pParticle->m_uchColor[0] = MIN( 1.0f, color[0] * colorRamp ) * 255.0f; pParticle->m_uchColor[1] = MIN( 1.0f, color[1] * colorRamp ) * 255.0f; pParticle->m_uchColor[2] = MIN( 1.0f, color[2] * colorRamp ) * 255.0f; pParticle->m_uchStartSize = random->RandomFloat( 8, 16 ) * flScale; pParticle->m_uchEndSize = pParticle->m_uchStartSize * 2; pParticle->m_uchStartAlpha = 255; pParticle->m_uchEndAlpha = 0; pParticle->m_flRoll = random->RandomInt( 0, 360 ); pParticle->m_flRollDelta = random->RandomFloat( -4.0f, 4.0f ); } } //----------------------------------------------------------------------------- // Purpose: // Input : Vector startPos - // wakeDir - // wakeLength - //----------------------------------------------------------------------------- void C_PropAirboat::DrawPontoonWake( Vector startPos, Vector wakeDir, float wakeLength, float speed ) { #define WAKE_STEPS 6 Vector wakeStep = wakeDir * ( wakeLength / (float) WAKE_STEPS ); Vector origin; float scale; IMaterial *pMaterial = materials->FindMaterial( "effects/splashwake1", NULL, false ); CMatRenderContextPtr pRenderContext( materials ); IMesh* pMesh = pRenderContext->GetDynamicMesh( 0, 0, 0, pMaterial ); CMeshBuilder meshBuilder; meshBuilder.Begin( pMesh, MATERIAL_QUADS, WAKE_STEPS ); for ( int i = 0; i < WAKE_STEPS; i++ ) { origin = startPos + ( wakeStep * i ); origin[0] += random->RandomFloat( -4.0f, 4.0f ); origin[1] += random->RandomFloat( -4.0f, 4.0f ); origin[2] = m_nExactWaterLevel + 2.0f; float scaleRange = RemapVal( i, 0, WAKE_STEPS-1, 32, 64 ); scale = scaleRange + ( 8.0f * sin( gpGlobals->curtime * 5 * i ) ); float alpha = RemapValClamped( speed, 128, 600, 0.05f, 0.25f ); float color[4] = { 1.0f, 1.0f, 1.0f, alpha }; // Needs to be time based so it'll freeze when the game is frozen float yaw = random->RandomFloat( 0, 360 ); Vector rRight = ( Vector(1,0,0) * cos( DEG2RAD( yaw ) ) ) - ( Vector(0,1,0) * sin( DEG2RAD( yaw ) ) ); Vector rUp = ( Vector(1,0,0) * cos( DEG2RAD( yaw+90.0f ) ) ) - ( Vector(0,1,0) * sin( DEG2RAD( yaw+90.0f ) ) ); Vector point; meshBuilder.Color4fv (color); meshBuilder.TexCoord2f (0, 0, 1); VectorMA (origin, -scale, rRight, point); VectorMA (point, -scale, rUp, point); meshBuilder.Position3fv (point.Base()); meshBuilder.AdvanceVertex(); meshBuilder.Color4fv (color); meshBuilder.TexCoord2f (0, 0, 0); VectorMA (origin, scale, rRight, point); VectorMA (point, -scale, rUp, point); meshBuilder.Position3fv (point.Base()); meshBuilder.AdvanceVertex(); meshBuilder.Color4fv (color); meshBuilder.TexCoord2f (0, 1, 0); VectorMA (origin, scale, rRight, point); VectorMA (point, scale, rUp, point); meshBuilder.Position3fv (point.Base()); meshBuilder.AdvanceVertex(); meshBuilder.Color4fv (color); meshBuilder.TexCoord2f (0, 1, 1); VectorMA (origin, -scale, rRight, point); VectorMA (point, scale, rUp, point); meshBuilder.Position3fv (point.Base()); meshBuilder.AdvanceVertex(); } meshBuilder.End(); pMesh->Draw(); } //----------------------------------------------------------------------------- // Purpose: // Output : int //----------------------------------------------------------------------------- int C_PropAirboat::DrawWake( void ) { if ( cl_draw_airboat_wake.GetBool() == false ) return 0; // Make sure we're in water... if ( GetWaterLevel() == 0 ) return 0; //FIXME: For now, we don't draw slime this way if ( GetWaterLevel() == 2 ) return 0; bool bDriven = ( GetPassenger( VEHICLE_ROLE_DRIVER ) != NULL ); Vector vehicleDir = m_vecPhysVelocity; float vehicleSpeed = VectorNormalize( vehicleDir ); Vector vecPontoonFrontLeft; Vector vecPontoonFrontRight; Vector vecPontoonRearLeft; Vector vecPontoonRearRight; Vector vecSplashPoint; QAngle fooAngles; //FIXME: This lookup should be cached off // Get all attachments GetAttachment( LookupAttachment( "raytrace_fl" ), vecPontoonFrontLeft, fooAngles ); GetAttachment( LookupAttachment( "raytrace_fr" ), vecPontoonFrontRight, fooAngles ); GetAttachment( LookupAttachment( "raytrace_rl" ), vecPontoonRearLeft, fooAngles ); GetAttachment( LookupAttachment( "raytrace_rr" ), vecPontoonRearRight, fooAngles ); GetAttachment( LookupAttachment( "splash_pt" ), vecSplashPoint, fooAngles ); // Find the direction of the pontoons Vector vecLeftWakeDir = ( vecPontoonRearLeft - vecPontoonFrontLeft ); Vector vecRightWakeDir = ( vecPontoonRearRight - vecPontoonFrontRight ); // Find the pontoon's size float flWakeLeftLength = VectorNormalize( vecLeftWakeDir ); float flWakeRightLength = VectorNormalize( vecRightWakeDir ); vecPontoonFrontLeft.z = m_nExactWaterLevel; vecPontoonFrontRight.z = m_nExactWaterLevel; if ( bDriven && vehicleSpeed > 128.0f ) { DrawPontoonWake( vecPontoonFrontLeft, vecLeftWakeDir, flWakeLeftLength, vehicleSpeed ); DrawPontoonWake( vecPontoonFrontRight, vecRightWakeDir, flWakeRightLength, vehicleSpeed ); Vector vecSplashDir; Vector vForward; GetVectors( &vForward, NULL, NULL ); if ( m_vecPhysVelocity.x < -64.0f ) { vecSplashDir = vecLeftWakeDir - vForward; VectorNormalize( vecSplashDir ); // Don't do this if we're going backwards if ( m_vecPhysVelocity.y > 0.0f ) { DrawPontoonSplash( vecPontoonFrontLeft + ( vecLeftWakeDir * 1.0f ), vecSplashDir, m_vecPhysVelocity.y ); } } else if ( m_vecPhysVelocity.x > 64.0f ) { vecSplashDir = vecRightWakeDir + vForward; VectorNormalize( vecSplashDir ); // Don't do this if we're going backwards if ( m_vecPhysVelocity.y > 0.0f ) { DrawPontoonSplash( vecPontoonFrontRight + ( vecRightWakeDir * 1.0f ), vecSplashDir, m_vecPhysVelocity.y ); } } } // Must have at least one point if ( m_nStepCount <= 1 ) return 1; IMaterial *pMaterial = materials->FindMaterial( "effects/splashwake4", 0); //Bind the material CMatRenderContextPtr pRenderContext( materials ); IMesh *pMesh = pRenderContext->GetDynamicMesh( true, NULL, NULL, pMaterial ); m_Mesh.Begin( pMesh, MATERIAL_TRIANGLE_STRIP, (m_nStepCount-1) * 2 ); TrailPoint_t *pLast = GetTrailPoint( m_nStepCount - 1 ); TrailPoint_t currentPoint; currentPoint.m_flDieTime = gpGlobals->curtime + 0.5f; currentPoint.m_vecScreenPos = GetAbsOrigin(); currentPoint.m_vecScreenPos[2] = m_nExactWaterLevel + 16; currentPoint.m_flTexCoord = pLast->m_flTexCoord + currentPoint.m_vecScreenPos.DistTo(pLast->m_vecScreenPos); currentPoint.m_flTexCoord = fmod( currentPoint.m_flTexCoord, 1 ); currentPoint.m_flWidthVariance = 0.0f; TrailPoint_t *pPrevPoint = NULL; Vector segDir, normal; for ( int i = 0; i <= m_nStepCount; ++i ) { // This makes it so that we're always drawing to the current location TrailPoint_t *pPoint = (i != m_nStepCount) ? GetTrailPoint(i) : &currentPoint; float flLifePerc = RemapValClamped( ( pPoint->m_flDieTime - gpGlobals->curtime ), 0, WAKE_LIFETIME, 0.0f, 1.0f ); BeamSeg_t curSeg; curSeg.m_vColor.x = curSeg.m_vColor.y = curSeg.m_vColor.z = 1.0f; float flAlphaFade = flLifePerc; float alpha = RemapValClamped( fabs( m_vecPhysVelocity.y ), 128, 600, 0.0f, 1.0f ); curSeg.m_flAlpha = 0.25f; curSeg.m_flAlpha *= flAlphaFade * alpha; curSeg.m_vPos = pPoint->m_vecScreenPos; float widthBase = SimpleSplineRemapVal( fabs( m_vecPhysVelocity.y ), 128, 600, 32, 48 ); curSeg.m_flWidth = Lerp( flLifePerc, widthBase*6, widthBase ); curSeg.m_flWidth += pPoint->m_flWidthVariance; if ( curSeg.m_flWidth < 0.0f ) { curSeg.m_flWidth = 0.0f; } curSeg.m_flTexCoord = pPoint->m_flTexCoord; if ( pPrevPoint != NULL ) { segDir = ( pPrevPoint->m_vecScreenPos - pPoint->m_vecScreenPos ); VectorNormalize( segDir ); normal = CrossProduct( segDir, Vector( 0, 0, -1 ) ); DrawSegment( curSeg, normal ); } pPrevPoint = pPoint; } m_Mesh.End(); pMesh->Draw(); return 1; } //----------------------------------------------------------------------------- // Purpose: // Input : flags - // Output : int //----------------------------------------------------------------------------- int C_PropAirboat::DrawModel( int flags ) { if ( BaseClass::DrawModel( flags ) == false ) return 0; if ( !m_bReadyToDraw ) return 0; return DrawWake(); }
; =============================================================== ; Jan 2014 ; =============================================================== ; ; int mtx_lock(mtx_t *m) ; ; Block until the mutex is acquired. ; ; =============================================================== SECTION code_threads_mutex PUBLIC asm_mtx_lock EXTERN asm_mtx_timedlock asm_mtx_lock: ; enter : hl = mtx_t *m ; ; exit : success ; ; hl = thrd_success ; carry reset ; ; fail if recursive lock count exceeded ; or scheduler unblocks thread (unusual) ; ; hl = thrd_error ; carry set ; ; fail if mutex invalid ; ; hl = -1 ; carry set, errno = EINVAL ; ; uses : af, bc, de, hl ld bc,0 ; no timeout jp asm_mtx_timedlock
; ; ANSI Video handling for the MSX ; ; Handles colors ; ; Scrollup ; ; Stefano Bodrato - Oct. 2017 ; ; $Id: f_ansi_scrollup.asm $ ; SECTION code_clib PUBLIC ansi_SCROLLUP PUBLIC __tms9918_scroll_buffer EXTERN __tms9918_attribute IF FORmsx EXTERN msxbios INCLUDE "target/msx/def/msxbios.def" ELSE IF FORsvi EXTERN msxbios INCLUDE "target/svi/def/svibios.def" ENDIF ENDIF .ansi_SCROLLUP push ix ld b,23 ld hl,256 .scloop push bc push hl ld de,__tms9918_scroll_buffer ld bc,256 ld ix,LDIRMV call msxbios pop hl push hl ld de,-256 add hl,de ld de,__tms9918_scroll_buffer ld bc,256 ex de,hl ld ix,LDIRVM call msxbios pop hl push hl ld de,8192 add hl,de push hl ld de,__tms9918_scroll_buffer ld bc,256 ;ex de,hl ld ix,LDIRMV call msxbios pop hl ld de,-256 add hl,de ld de,__tms9918_scroll_buffer ld bc,256 ex de,hl ld ix,LDIRVM call msxbios pop hl inc h pop bc djnz scloop dec h xor a ld bc,256 ld ix,FILVRM call msxbios pop ix ret SECTION bss_clib __tms9918_scroll_buffer: defs 256
_resetAll: ;ExstoKit.c,60 :: void resetAll(){ ;ExstoKit.c,61 :: display1 = 1; BSF PORTA+0, 5 ;ExstoKit.c,62 :: display2 = 1; BSF PORTA+0, 2 ;ExstoKit.c,63 :: display3 = 1; BSF PORTE+0, 0 ;ExstoKit.c,64 :: display4 = 1; BSF PORTE+0, 2 ;ExstoKit.c,65 :: pinoA = 0; BCF PORTD+0, 0 ;ExstoKit.c,66 :: pinoB = 0; BCF PORTD+0, 1 ;ExstoKit.c,67 :: pinoC = 0; BCF PORTD+0, 2 ;ExstoKit.c,68 :: pinoD = 0; BCF PORTD+0, 3 ;ExstoKit.c,69 :: pinoE = 0; BCF PORTD+0, 4 ;ExstoKit.c,70 :: pinoF = 0; BCF PORTD+0, 5 ;ExstoKit.c,71 :: pinoG = 0; BCF PORTD+0, 6 ;ExstoKit.c,72 :: pinoDP = 0; BCF PORTD+0, 7 ;ExstoKit.c,73 :: display1 = 0; BCF PORTA+0, 5 ;ExstoKit.c,74 :: display2 = 0; BCF PORTA+0, 2 ;ExstoKit.c,75 :: display3 = 0; BCF PORTE+0, 0 ;ExstoKit.c,76 :: display4 = 0; BCF PORTE+0, 2 ;ExstoKit.c,77 :: } L_end_resetAll: RETURN 0 ; end of _resetAll _resetDisplays: ;ExstoKit.c,79 :: void resetDisplays(){ ;ExstoKit.c,80 :: display1 = 0; BCF PORTA+0, 5 ;ExstoKit.c,81 :: display2 = 0; BCF PORTA+0, 2 ;ExstoKit.c,82 :: display3 = 0; BCF PORTE+0, 0 ;ExstoKit.c,83 :: display4 = 0; BCF PORTE+0, 2 ;ExstoKit.c,84 :: } L_end_resetDisplays: RETURN 0 ; end of _resetDisplays _setNumber: ;ExstoKit.c,86 :: void setNumber(int _display, int _number){ ;ExstoKit.c,87 :: switch(_display){ GOTO L_setNumber0 ;ExstoKit.c,88 :: case 1: L_setNumber2: ;ExstoKit.c,89 :: display1 = 1; BSF PORTA+0, 5 ;ExstoKit.c,90 :: break; GOTO L_setNumber1 ;ExstoKit.c,92 :: case 2: L_setNumber3: ;ExstoKit.c,93 :: display2 = 1; BSF PORTA+0, 2 ;ExstoKit.c,94 :: break; GOTO L_setNumber1 ;ExstoKit.c,96 :: case 3: L_setNumber4: ;ExstoKit.c,97 :: display3 = 1; BSF PORTE+0, 0 ;ExstoKit.c,98 :: break; GOTO L_setNumber1 ;ExstoKit.c,100 :: case 4: L_setNumber5: ;ExstoKit.c,101 :: display4 = 1; BSF PORTE+0, 2 ;ExstoKit.c,102 :: break; GOTO L_setNumber1 ;ExstoKit.c,104 :: default: L_setNumber6: ;ExstoKit.c,105 :: return; GOTO L_end_setNumber ;ExstoKit.c,106 :: } L_setNumber0: MOVLW 0 XORWF FARG_setNumber__display+1, 0 BTFSS STATUS+0, 2 GOTO L__setNumber30 MOVLW 1 XORWF FARG_setNumber__display+0, 0 L__setNumber30: BTFSC STATUS+0, 2 GOTO L_setNumber2 MOVLW 0 XORWF FARG_setNumber__display+1, 0 BTFSS STATUS+0, 2 GOTO L__setNumber31 MOVLW 2 XORWF FARG_setNumber__display+0, 0 L__setNumber31: BTFSC STATUS+0, 2 GOTO L_setNumber3 MOVLW 0 XORWF FARG_setNumber__display+1, 0 BTFSS STATUS+0, 2 GOTO L__setNumber32 MOVLW 3 XORWF FARG_setNumber__display+0, 0 L__setNumber32: BTFSC STATUS+0, 2 GOTO L_setNumber4 MOVLW 0 XORWF FARG_setNumber__display+1, 0 BTFSS STATUS+0, 2 GOTO L__setNumber33 MOVLW 4 XORWF FARG_setNumber__display+0, 0 L__setNumber33: BTFSC STATUS+0, 2 GOTO L_setNumber5 GOTO L_setNumber6 L_setNumber1: ;ExstoKit.c,107 :: PORTD = numbers[_number]; MOVF FARG_setNumber__number+0, 0 MOVWF R0 MOVF FARG_setNumber__number+1, 0 MOVWF R1 RLCF R0, 1 BCF R0, 0 RLCF R1, 1 MOVLW _numbers+0 ADDWF R0, 0 MOVWF FSR0L+0 MOVLW hi_addr(_numbers+0) ADDWFC R1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF PORTD+0 ;ExstoKit.c,108 :: delay_ms(1); MOVLW 7 MOVWF R12, 0 MOVLW 125 MOVWF R13, 0 L_setNumber7: DECFSZ R13, 1, 1 BRA L_setNumber7 DECFSZ R12, 1, 1 BRA L_setNumber7 ;ExstoKit.c,109 :: resetDisplays(); CALL _resetDisplays+0, 0 ;ExstoKit.c,110 :: } L_end_setNumber: RETURN 0 ; end of _setNumber _setNumbers: ;ExstoKit.c,112 :: void setNumbers(int _numbers[4], int _timer){ ;ExstoKit.c,113 :: int c = 0; CLRF setNumbers_c_L0+0 CLRF setNumbers_c_L0+1 ;ExstoKit.c,114 :: for (c; c<=_timer; c++){ L_setNumbers8: MOVLW 128 XORWF FARG_setNumbers__timer+1, 0 MOVWF R0 MOVLW 128 XORWF setNumbers_c_L0+1, 0 SUBWF R0, 0 BTFSS STATUS+0, 2 GOTO L__setNumbers35 MOVF setNumbers_c_L0+0, 0 SUBWF FARG_setNumbers__timer+0, 0 L__setNumbers35: BTFSS STATUS+0, 0 GOTO L_setNumbers9 ;ExstoKit.c,115 :: setNumber(1, _numbers[0]); MOVLW 1 MOVWF FARG_setNumber__display+0 MOVLW 0 MOVWF FARG_setNumber__display+1 MOVFF FARG_setNumbers__numbers+0, FSR0L+0 MOVFF FARG_setNumbers__numbers+1, FSR0H+0 MOVF POSTINC0+0, 0 MOVWF FARG_setNumber__number+0 MOVF POSTINC0+0, 0 MOVWF FARG_setNumber__number+1 CALL _setNumber+0, 0 ;ExstoKit.c,116 :: setNumber(2, _numbers[1]); MOVLW 2 MOVWF FARG_setNumber__display+0 MOVLW 0 MOVWF FARG_setNumber__display+1 MOVLW 2 ADDWF FARG_setNumbers__numbers+0, 0 MOVWF FSR0L+0 MOVLW 0 ADDWFC FARG_setNumbers__numbers+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF FARG_setNumber__number+0 MOVF POSTINC0+0, 0 MOVWF FARG_setNumber__number+1 CALL _setNumber+0, 0 ;ExstoKit.c,117 :: setNumber(3, _numbers[2]); MOVLW 3 MOVWF FARG_setNumber__display+0 MOVLW 0 MOVWF FARG_setNumber__display+1 MOVLW 4 ADDWF FARG_setNumbers__numbers+0, 0 MOVWF FSR0L+0 MOVLW 0 ADDWFC FARG_setNumbers__numbers+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF FARG_setNumber__number+0 MOVF POSTINC0+0, 0 MOVWF FARG_setNumber__number+1 CALL _setNumber+0, 0 ;ExstoKit.c,118 :: setNumber(4, _numbers[3]); MOVLW 4 MOVWF FARG_setNumber__display+0 MOVLW 0 MOVWF FARG_setNumber__display+1 MOVLW 6 ADDWF FARG_setNumbers__numbers+0, 0 MOVWF FSR0L+0 MOVLW 0 ADDWFC FARG_setNumbers__numbers+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF FARG_setNumber__number+0 MOVF POSTINC0+0, 0 MOVWF FARG_setNumber__number+1 CALL _setNumber+0, 0 ;ExstoKit.c,114 :: for (c; c<=_timer; c++){ INFSNZ setNumbers_c_L0+0, 1 INCF setNumbers_c_L0+1, 1 ;ExstoKit.c,119 :: } GOTO L_setNumbers8 L_setNumbers9: ;ExstoKit.c,120 :: } L_end_setNumbers: RETURN 0 ; end of _setNumbers _setLetter: ;ExstoKit.c,122 :: void setLetter(int _display, int _letterIndex){ ;ExstoKit.c,123 :: switch(_display){ GOTO L_setLetter11 ;ExstoKit.c,124 :: case 1: L_setLetter13: ;ExstoKit.c,125 :: display1 = 1; BSF PORTA+0, 5 ;ExstoKit.c,126 :: break; GOTO L_setLetter12 ;ExstoKit.c,128 :: case 2: L_setLetter14: ;ExstoKit.c,129 :: display2 = 1; BSF PORTA+0, 2 ;ExstoKit.c,130 :: break; GOTO L_setLetter12 ;ExstoKit.c,132 :: case 3: L_setLetter15: ;ExstoKit.c,133 :: display3 = 1; BSF PORTE+0, 0 ;ExstoKit.c,134 :: break; GOTO L_setLetter12 ;ExstoKit.c,136 :: case 4: L_setLetter16: ;ExstoKit.c,137 :: display4 = 1; BSF PORTE+0, 2 ;ExstoKit.c,138 :: break; GOTO L_setLetter12 ;ExstoKit.c,140 :: default: L_setLetter17: ;ExstoKit.c,141 :: return; GOTO L_end_setLetter ;ExstoKit.c,142 :: } L_setLetter11: MOVLW 0 XORWF FARG_setLetter__display+1, 0 BTFSS STATUS+0, 2 GOTO L__setLetter37 MOVLW 1 XORWF FARG_setLetter__display+0, 0 L__setLetter37: BTFSC STATUS+0, 2 GOTO L_setLetter13 MOVLW 0 XORWF FARG_setLetter__display+1, 0 BTFSS STATUS+0, 2 GOTO L__setLetter38 MOVLW 2 XORWF FARG_setLetter__display+0, 0 L__setLetter38: BTFSC STATUS+0, 2 GOTO L_setLetter14 MOVLW 0 XORWF FARG_setLetter__display+1, 0 BTFSS STATUS+0, 2 GOTO L__setLetter39 MOVLW 3 XORWF FARG_setLetter__display+0, 0 L__setLetter39: BTFSC STATUS+0, 2 GOTO L_setLetter15 MOVLW 0 XORWF FARG_setLetter__display+1, 0 BTFSS STATUS+0, 2 GOTO L__setLetter40 MOVLW 4 XORWF FARG_setLetter__display+0, 0 L__setLetter40: BTFSC STATUS+0, 2 GOTO L_setLetter16 GOTO L_setLetter17 L_setLetter12: ;ExstoKit.c,143 :: PORTD = letters[_letterIndex]; MOVF FARG_setLetter__letterIndex+0, 0 MOVWF R0 MOVF FARG_setLetter__letterIndex+1, 0 MOVWF R1 RLCF R0, 1 BCF R0, 0 RLCF R1, 1 MOVLW _letters+0 ADDWF R0, 0 MOVWF FSR0L+0 MOVLW hi_addr(_letters+0) ADDWFC R1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF PORTD+0 ;ExstoKit.c,144 :: delay_ms(1); MOVLW 7 MOVWF R12, 0 MOVLW 125 MOVWF R13, 0 L_setLetter18: DECFSZ R13, 1, 1 BRA L_setLetter18 DECFSZ R12, 1, 1 BRA L_setLetter18 ;ExstoKit.c,145 :: resetDisplays(); CALL _resetDisplays+0, 0 ;ExstoKit.c,146 :: } L_end_setLetter: RETURN 0 ; end of _setLetter _setWord: ;ExstoKit.c,148 :: void setWord(int _letters[4], int _timer){ ;ExstoKit.c,149 :: int c = 0; CLRF setWord_c_L0+0 CLRF setWord_c_L0+1 ;ExstoKit.c,150 :: for (c; c<=_timer; c++){ L_setWord19: MOVLW 128 XORWF FARG_setWord__timer+1, 0 MOVWF R0 MOVLW 128 XORWF setWord_c_L0+1, 0 SUBWF R0, 0 BTFSS STATUS+0, 2 GOTO L__setWord42 MOVF setWord_c_L0+0, 0 SUBWF FARG_setWord__timer+0, 0 L__setWord42: BTFSS STATUS+0, 0 GOTO L_setWord20 ;ExstoKit.c,151 :: setLetter(1, _letters[0]); MOVLW 1 MOVWF FARG_setLetter__display+0 MOVLW 0 MOVWF FARG_setLetter__display+1 MOVFF FARG_setWord__letters+0, FSR0L+0 MOVFF FARG_setWord__letters+1, FSR0H+0 MOVF POSTINC0+0, 0 MOVWF FARG_setLetter__letterIndex+0 MOVF POSTINC0+0, 0 MOVWF FARG_setLetter__letterIndex+1 CALL _setLetter+0, 0 ;ExstoKit.c,152 :: setLetter(2, _letters[1]); MOVLW 2 MOVWF FARG_setLetter__display+0 MOVLW 0 MOVWF FARG_setLetter__display+1 MOVLW 2 ADDWF FARG_setWord__letters+0, 0 MOVWF FSR0L+0 MOVLW 0 ADDWFC FARG_setWord__letters+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF FARG_setLetter__letterIndex+0 MOVF POSTINC0+0, 0 MOVWF FARG_setLetter__letterIndex+1 CALL _setLetter+0, 0 ;ExstoKit.c,153 :: setLetter(3, _letters[2]); MOVLW 3 MOVWF FARG_setLetter__display+0 MOVLW 0 MOVWF FARG_setLetter__display+1 MOVLW 4 ADDWF FARG_setWord__letters+0, 0 MOVWF FSR0L+0 MOVLW 0 ADDWFC FARG_setWord__letters+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF FARG_setLetter__letterIndex+0 MOVF POSTINC0+0, 0 MOVWF FARG_setLetter__letterIndex+1 CALL _setLetter+0, 0 ;ExstoKit.c,154 :: setLetter(4, _letters[3]); MOVLW 4 MOVWF FARG_setLetter__display+0 MOVLW 0 MOVWF FARG_setLetter__display+1 MOVLW 6 ADDWF FARG_setWord__letters+0, 0 MOVWF FSR0L+0 MOVLW 0 ADDWFC FARG_setWord__letters+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF FARG_setLetter__letterIndex+0 MOVF POSTINC0+0, 0 MOVWF FARG_setLetter__letterIndex+1 CALL _setLetter+0, 0 ;ExstoKit.c,150 :: for (c; c<=_timer; c++){ INFSNZ setWord_c_L0+0, 1 INCF setWord_c_L0+1, 1 ;ExstoKit.c,155 :: } GOTO L_setWord19 L_setWord20: ;ExstoKit.c,156 :: } L_end_setWord: RETURN 0 ; end of _setWord _slideWord: ;ExstoKit.c,158 :: void slideWord(int _letters[8], int _timer){ ;ExstoKit.c,162 :: for(counter=0; counter<8; counter++){ CLRF slideWord_counter_L0+0 CLRF slideWord_counter_L0+1 L_slideWord22: MOVLW 128 XORWF slideWord_counter_L0+1, 0 MOVWF R0 MOVLW 128 SUBWF R0, 0 BTFSS STATUS+0, 2 GOTO L__slideWord44 MOVLW 8 SUBWF slideWord_counter_L0+0, 0 L__slideWord44: BTFSC STATUS+0, 0 GOTO L_slideWord23 ;ExstoKit.c,163 :: _letters[0] = _letters[counter-7]; MOVLW 7 SUBWF slideWord_counter_L0+0, 0 MOVWF R3 MOVLW 0 SUBWFB slideWord_counter_L0+1, 0 MOVWF R4 MOVF R3, 0 MOVWF R0 MOVF R4, 0 MOVWF R1 RLCF R0, 1 BCF R0, 0 RLCF R1, 1 MOVF FARG_slideWord__letters+0, 0 ADDWF R0, 1 MOVF FARG_slideWord__letters+1, 0 ADDWFC R1, 1 MOVFF FARG_slideWord__letters+0, FSR1L+0 MOVFF FARG_slideWord__letters+1, FSR1H+0 MOVFF R0, FSR0L+0 MOVFF R1, FSR0H+0 MOVF POSTINC0+0, 0 MOVWF POSTINC1+0 MOVF POSTINC0+0, 0 MOVWF POSTINC1+0 ;ExstoKit.c,164 :: _letters[1] = _letters[counter-6]; MOVLW 2 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR1L+0 MOVLW 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR1L+1 MOVLW 6 SUBWF slideWord_counter_L0+0, 0 MOVWF R3 MOVLW 0 SUBWFB slideWord_counter_L0+1, 0 MOVWF R4 MOVF R3, 0 MOVWF R0 MOVF R4, 0 MOVWF R1 RLCF R0, 1 BCF R0, 0 RLCF R1, 1 MOVF R0, 0 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR0L+0 MOVF R1, 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF POSTINC1+0 MOVF POSTINC0+0, 0 MOVWF POSTINC1+0 ;ExstoKit.c,165 :: _letters[2] = _letters[counter-5]; MOVLW 4 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR1L+0 MOVLW 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR1L+1 MOVLW 5 SUBWF slideWord_counter_L0+0, 0 MOVWF R3 MOVLW 0 SUBWFB slideWord_counter_L0+1, 0 MOVWF R4 MOVF R3, 0 MOVWF R0 MOVF R4, 0 MOVWF R1 RLCF R0, 1 BCF R0, 0 RLCF R1, 1 MOVF R0, 0 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR0L+0 MOVF R1, 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF POSTINC1+0 MOVF POSTINC0+0, 0 MOVWF POSTINC1+0 ;ExstoKit.c,166 :: _letters[3] = _letters[counter-4]; MOVLW 6 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR1L+0 MOVLW 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR1L+1 MOVLW 4 SUBWF slideWord_counter_L0+0, 0 MOVWF R3 MOVLW 0 SUBWFB slideWord_counter_L0+1, 0 MOVWF R4 MOVF R3, 0 MOVWF R0 MOVF R4, 0 MOVWF R1 RLCF R0, 1 BCF R0, 0 RLCF R1, 1 MOVF R0, 0 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR0L+0 MOVF R1, 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF POSTINC1+0 MOVF POSTINC0+0, 0 MOVWF POSTINC1+0 ;ExstoKit.c,167 :: _letters[4] = _letters[counter-3]; MOVLW 8 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR1L+0 MOVLW 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR1L+1 MOVLW 3 SUBWF slideWord_counter_L0+0, 0 MOVWF R3 MOVLW 0 SUBWFB slideWord_counter_L0+1, 0 MOVWF R4 MOVF R3, 0 MOVWF R0 MOVF R4, 0 MOVWF R1 RLCF R0, 1 BCF R0, 0 RLCF R1, 1 MOVF R0, 0 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR0L+0 MOVF R1, 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF POSTINC1+0 MOVF POSTINC0+0, 0 MOVWF POSTINC1+0 ;ExstoKit.c,168 :: _letters[5] = _letters[counter-2]; MOVLW 10 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR1L+0 MOVLW 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR1L+1 MOVLW 2 SUBWF slideWord_counter_L0+0, 0 MOVWF R3 MOVLW 0 SUBWFB slideWord_counter_L0+1, 0 MOVWF R4 MOVF R3, 0 MOVWF R0 MOVF R4, 0 MOVWF R1 RLCF R0, 1 BCF R0, 0 RLCF R1, 1 MOVF R0, 0 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR0L+0 MOVF R1, 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF POSTINC1+0 MOVF POSTINC0+0, 0 MOVWF POSTINC1+0 ;ExstoKit.c,169 :: _letters[6] = _letters[counter-1]; MOVLW 12 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR1L+0 MOVLW 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR1L+1 MOVLW 1 SUBWF slideWord_counter_L0+0, 0 MOVWF R3 MOVLW 0 SUBWFB slideWord_counter_L0+1, 0 MOVWF R4 MOVF R3, 0 MOVWF R0 MOVF R4, 0 MOVWF R1 RLCF R0, 1 BCF R0, 0 RLCF R1, 1 MOVF R0, 0 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR0L+0 MOVF R1, 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF POSTINC1+0 MOVF POSTINC0+0, 0 MOVWF POSTINC1+0 ;ExstoKit.c,170 :: _letters[7] = _letters[counter]; MOVLW 14 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR1L+0 MOVLW 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR1L+1 MOVF slideWord_counter_L0+0, 0 MOVWF R0 MOVF slideWord_counter_L0+1, 0 MOVWF R1 RLCF R0, 1 BCF R0, 0 RLCF R1, 1 MOVF R0, 0 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR0L+0 MOVF R1, 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF POSTINC1+0 MOVF POSTINC0+0, 0 MOVWF POSTINC1+0 ;ExstoKit.c,172 :: wordOne[0] = _letters[0]; MOVFF FARG_slideWord__letters+0, FSR0L+0 MOVFF FARG_slideWord__letters+1, FSR0H+0 MOVF POSTINC0+0, 0 MOVWF slideWord_wordOne_L0+0 MOVF POSTINC0+0, 0 MOVWF slideWord_wordOne_L0+1 ;ExstoKit.c,173 :: wordOne[1] = _letters[1]; MOVLW 2 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR0L+0 MOVLW 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF slideWord_wordOne_L0+2 MOVF POSTINC0+0, 0 MOVWF slideWord_wordOne_L0+3 ;ExstoKit.c,174 :: wordOne[2] = _letters[2]; MOVLW 4 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR0L+0 MOVLW 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF slideWord_wordOne_L0+4 MOVF POSTINC0+0, 0 MOVWF slideWord_wordOne_L0+5 ;ExstoKit.c,175 :: wordOne[3] = _letters[3]; MOVLW 6 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR0L+0 MOVLW 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF slideWord_wordOne_L0+6 MOVF POSTINC0+0, 0 MOVWF slideWord_wordOne_L0+7 ;ExstoKit.c,177 :: wordTwo[0] = _letters[4]; MOVLW 8 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR0L+0 MOVLW 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF slideWord_wordTwo_L0+0 MOVF POSTINC0+0, 0 MOVWF slideWord_wordTwo_L0+1 ;ExstoKit.c,178 :: wordTwo[1] = _letters[5]; MOVLW 10 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR0L+0 MOVLW 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF slideWord_wordTwo_L0+2 MOVF POSTINC0+0, 0 MOVWF slideWord_wordTwo_L0+3 ;ExstoKit.c,179 :: wordTwo[2] = _letters[6]; MOVLW 12 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR0L+0 MOVLW 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF slideWord_wordTwo_L0+4 MOVF POSTINC0+0, 0 MOVWF slideWord_wordTwo_L0+5 ;ExstoKit.c,180 :: wordTwo[3] = _letters[7]; MOVLW 14 ADDWF FARG_slideWord__letters+0, 0 MOVWF FSR0L+0 MOVLW 0 ADDWFC FARG_slideWord__letters+1, 0 MOVWF FSR0L+1 MOVF POSTINC0+0, 0 MOVWF slideWord_wordTwo_L0+6 MOVF POSTINC0+0, 0 MOVWF slideWord_wordTwo_L0+7 ;ExstoKit.c,181 :: setWord(wordOne, _timer); MOVLW slideWord_wordOne_L0+0 MOVWF FARG_setWord__letters+0 MOVLW hi_addr(slideWord_wordOne_L0+0) MOVWF FARG_setWord__letters+1 MOVF FARG_slideWord__timer+0, 0 MOVWF FARG_setWord__timer+0 MOVF FARG_slideWord__timer+1, 0 MOVWF FARG_setWord__timer+1 CALL _setWord+0, 0 ;ExstoKit.c,182 :: setWord(wordTwo, _timer); MOVLW slideWord_wordTwo_L0+0 MOVWF FARG_setWord__letters+0 MOVLW hi_addr(slideWord_wordTwo_L0+0) MOVWF FARG_setWord__letters+1 MOVF FARG_slideWord__timer+0, 0 MOVWF FARG_setWord__timer+0 MOVF FARG_slideWord__timer+1, 0 MOVWF FARG_setWord__timer+1 CALL _setWord+0, 0 ;ExstoKit.c,162 :: for(counter=0; counter<8; counter++){ INFSNZ slideWord_counter_L0+0, 1 INCF slideWord_counter_L0+1, 1 ;ExstoKit.c,183 :: } GOTO L_slideWord22 L_slideWord23: ;ExstoKit.c,184 :: } L_end_slideWord: RETURN 0 ; end of _slideWord _main: ;ExstoKit.c,186 :: void main() { ;ExstoKit.c,187 :: int sexshop[8] = {18, 4, 23, 26, 18, 7, 14, 15}; MOVLW ?ICSmain_sexshop_L0+0 MOVWF TBLPTRL+0 MOVLW hi_addr(?ICSmain_sexshop_L0+0) MOVWF TBLPTRL+1 MOVLW higher_addr(?ICSmain_sexshop_L0+0) MOVWF TBLPTRL+2 MOVLW main_sexshop_L0+0 MOVWF FSR1L+0 MOVLW hi_addr(main_sexshop_L0+0) MOVWF FSR1L+1 MOVLW 16 MOVWF R0 MOVLW 1 MOVWF R1 CALL ___CC2DW+0, 0 ;ExstoKit.c,188 :: ADCON1 = 0b00001111; MOVLW 15 MOVWF ADCON1+0 ;ExstoKit.c,189 :: TRISD = 0b00000000; CLRF TRISD+0 ;ExstoKit.c,190 :: TRISA.B5 = 0; BCF TRISA+0, 5 ;ExstoKit.c,191 :: TRISA.B2 = 0; BCF TRISA+0, 2 ;ExstoKit.c,192 :: TRISE.B2 = 0; BCF TRISE+0, 2 ;ExstoKit.c,193 :: TRISE.B0 = 0; BCF TRISE+0, 0 ;ExstoKit.c,195 :: resetAll(); CALL _resetAll+0, 0 ;ExstoKit.c,197 :: while(1){ L_main25: ;ExstoKit.c,198 :: slideWord(sexshop, 300); MOVLW main_sexshop_L0+0 MOVWF FARG_slideWord__letters+0 MOVLW hi_addr(main_sexshop_L0+0) MOVWF FARG_slideWord__letters+1 MOVLW 44 MOVWF FARG_slideWord__timer+0 MOVLW 1 MOVWF FARG_slideWord__timer+1 CALL _slideWord+0, 0 ;ExstoKit.c,199 :: } GOTO L_main25 ;ExstoKit.c,203 :: } L_end_main: GOTO $+0 ; end of _main
; A010811: 23rd powers: a(n) = n^23. ; 0,1,8388608,94143178827,70368744177664,11920928955078125,789730223053602816,27368747340080916343,590295810358705651712,8862938119652501095929,100000000000000000000000,895430243255237372246531,6624737266949237011120128,41753905413413116367045797,229585692886981495482220544,1122274146401882171630859375,4951760157141521099596496896,19967568900859523802559065713,74347713614021927913318776832,257829627945307727248226067259,838860800000000000000000000000,2576580875108218291929075869661,7511413302012830262726227918848,20880467999847912034355032910567,55572324035428505185378394701824,142108547152020037174224853515625,350257144982200575261531309080576,834385168331080533771857328695283,1925904380037276068854119113162752,4316720717749415770740818372739989,9414317882700000000000000000000000,20013311644049280264138724244295391,41538374868278621028243970633760768,84298649517881922539738734663399137,167500108222301408246337399112597504,326260892630588011062145233154296875,623673825204293256669089197883129856 pow $0,23
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r15 push %r8 push %rax push %rbp push %rdx push %rsi lea addresses_normal_ht+0x75d7, %rbp nop and %r8, %r8 mov $0x6162636465666768, %rsi movq %rsi, %xmm5 vmovups %ymm5, (%rbp) nop nop nop nop nop xor $27112, %rax lea addresses_UC_ht+0x1a8c7, %r11 dec %rdx mov $0x6162636465666768, %rax movq %rax, %xmm6 movups %xmm6, (%r11) nop nop nop nop nop xor %r11, %r11 lea addresses_UC_ht+0x19b27, %rbp nop nop nop add $58857, %r15 mov (%rbp), %esi nop nop nop nop xor $17637, %rsi lea addresses_WT_ht+0x1c94f, %r15 nop cmp $26083, %rbp movb (%r15), %r11b nop nop nop xor $32321, %rax lea addresses_WT_ht+0xc69f, %rdx nop nop nop dec %rax movb $0x61, (%rdx) nop nop nop nop sub %r15, %r15 lea addresses_WC_ht+0xc04e, %r8 nop xor %rbp, %rbp mov (%r8), %rdx nop nop nop nop nop and $61212, %rsi lea addresses_WT_ht+0x1d0e7, %r15 nop nop nop nop add $37431, %rbp movb (%r15), %al nop xor $47596, %r11 lea addresses_UC_ht+0x1551f, %r8 nop nop add $23712, %rax vmovups (%r8), %ymm7 vextracti128 $0, %ymm7, %xmm7 vpextrq $1, %xmm7, %r15 nop nop add $50305, %rbp lea addresses_WT_ht+0x1ce3f, %rsi nop add $52265, %rdx mov (%rsi), %rax nop nop and %r11, %r11 lea addresses_D_ht+0x1599f, %r8 nop nop nop sub $4611, %rsi mov $0x6162636465666768, %rbp movq %rbp, (%r8) add %rbp, %rbp lea addresses_D_ht+0x1b71f, %r15 clflush (%r15) nop nop nop nop sub $11598, %rax mov (%r15), %r8d nop nop nop nop nop xor %rax, %rax lea addresses_WC_ht+0x1719f, %rsi nop nop nop nop dec %rax mov (%rsi), %bp and $38600, %rdx lea addresses_WC_ht+0x5d9f, %r8 nop sub %rax, %rax mov $0x6162636465666768, %r11 movq %r11, %xmm0 and $0xffffffffffffffc0, %r8 vmovaps %ymm0, (%r8) nop nop nop nop sub $46050, %rsi lea addresses_WT_ht+0xab9f, %r11 nop nop nop and %rsi, %rsi mov $0x6162636465666768, %r15 movq %r15, %xmm0 movups %xmm0, (%r11) nop nop nop nop cmp %r15, %r15 pop %rsi pop %rdx pop %rbp pop %rax pop %r8 pop %r15 pop %r11 ret .global s_faulty_load s_faulty_load: push %r12 push %r8 push %r9 push %rax push %rdi push %rdx push %rsi // Store lea addresses_normal+0x1abd, %rsi nop nop nop nop and %rdx, %rdx mov $0x5152535455565758, %r8 movq %r8, %xmm7 vmovups %ymm7, (%rsi) nop nop xor %rdx, %rdx // Load lea addresses_PSE+0xd39f, %r12 nop nop nop inc %rdi mov (%r12), %dx nop nop nop nop nop sub $36782, %r9 // Faulty Load lea addresses_A+0x99f, %rsi nop nop nop nop nop inc %rdx mov (%rsi), %r12w lea oracles, %r9 and $0xff, %r12 shlq $12, %r12 mov (%r9,%r12,1), %r12 pop %rsi pop %rdx pop %rdi pop %rax pop %r9 pop %r8 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'NT': True, 'AVXalign': False, 'size': 4, 'congruent': 0, 'same': False, 'type': 'addresses_A'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 1, 'same': False, 'type': 'addresses_normal'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 9, 'same': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'} [Faulty Load] {'src': {'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0, 'same': True, 'type': 'addresses_A'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'dst': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 2, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 3, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 3, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 4, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': True, 'size': 1, 'congruent': 8, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'} {'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 0, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 3, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 7, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 5, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 11, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'STOR'} {'src': {'NT': True, 'AVXalign': True, 'size': 4, 'congruent': 5, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'src': {'NT': True, 'AVXalign': True, 'size': 2, 'congruent': 10, 'same': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'dst': {'NT': False, 'AVXalign': True, 'size': 32, 'congruent': 9, 'same': True, 'type': 'addresses_WC_ht'}, 'OP': 'STOR'} {'dst': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 9, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'} {'00': 1, '35': 21828} 00 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 */
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Berkeley Softworks 1990 -- All Rights Reserved PROJECT: PC GEOS MODULE: print drivers FILE: uiGetNoMain.asm AUTHOR: Dave Durran ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 5/92 Initial revision DESCRIPTION: $Id: uiGetNoMain.asm,v 1.1 97/04/18 11:50:28 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% PrintEvalOptionsUI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: called to pass no object tree for the main dialog box. CALLED BY: PASS: RETURN: nothing DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: none REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 01/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ PrintGetMainUI proc far clc ret PrintGetMainUI endp