text
stringlengths
1
1.05M
; A165326: a(0)=a(1)=1, a(n) = -a(n-1) for n > 1. ; 1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1 trn $0,1 mov $1,-1 pow $1,$0 mov $0,$1
;***************************************************************************** ;* x86-optimized functions for yadif filter ;* ;* Copyright (C) 2006 Michael Niedermayer <michaelni@gmx.at> ;* Copyright (c) 2013 Daniel Kang <daniel.d.kang@gmail.com> ;* Copyright (c) 2011-2013 James Darnley <james.darnley@gmail.com> ;* ;* This file is part of FFmpeg. ;* ;* FFmpeg is free software; you can redistribute it and/or modify ;* it under the terms of the GNU General Public License as published by ;* the Free Software Foundation; either version 2 of the License, or ;* (at your option) any later version. ;* ;* FFmpeg is distributed in the hope that it will be useful, ;* but WITHOUT ANY WARRANTY; without even the implied warranty of ;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;* GNU General Public License for more details. ;* ;* You should have received a copy of the GNU General Public License along ;* with FFmpeg; if not, write to the Free Software Foundation, Inc., ;* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ;****************************************************************************** %include "libavutil/x86/x86util.asm" SECTION_RODATA pw_1: times 8 dw 1 SECTION .text %macro PABS 2 %if cpuflag(ssse3) pabsw %1, %1 %else pxor %2, %2 pcmpgtw %2, %1 pxor %1, %2 psubw %1, %2 %endif %endmacro %macro PMAXUW 2 %if cpuflag(sse4) pmaxuw %1, %2 %else psubusw %1, %2 paddusw %1, %2 %endif %endmacro %macro CHECK 2 movu m2, [curq+t1+%1*2] movu m3, [curq+t0+%2*2] mova m4, m2 mova m5, m2 pxor m4, m3 pavgw m5, m3 pand m4, [pw_1] psubusw m5, m4 %if mmsize == 16 psrldq m5, 2 %else psrlq m5, 16 %endif mova m4, m2 psubusw m2, m3 psubusw m3, m4 PMAXUW m2, m3 mova m3, m2 mova m4, m2 %if mmsize == 16 psrldq m3, 2 psrldq m4, 4 %else psrlq m3, 16 psrlq m4, 32 %endif paddw m2, m3 paddw m2, m4 %endmacro %macro CHECK1 0 mova m3, m0 pcmpgtw m3, m2 pminsw m0, m2 mova m6, m3 pand m5, m3 pandn m3, m1 por m3, m5 mova m1, m3 %endmacro ; %macro CHECK2 0 ; paddw m6, [pw_1] ; psllw m6, 14 ; paddsw m2, m6 ; mova m3, m0 ; pcmpgtw m3, m2 ; pminsw m0, m2 ; pand m5, m3 ; pandn m3, m1 ; por m3, m5 ; mova m1, m3 ; %endmacro ; This version of CHECK2 is required for 14-bit samples. The left-shift trick ; in the old code is not large enough to correctly select pixels or scores. %macro CHECK2 0 mova m3, m0 pcmpgtw m0, m2 pand m0, m6 mova m6, m0 pand m5, m6 pand m2, m0 pandn m6, m1 pandn m0, m3 por m6, m5 por m0, m2 mova m1, m6 %endmacro %macro LOAD 2 movu %1, %2 %endmacro %macro FILTER 3 .loop%1: pxor m7, m7 LOAD m0, [curq+t1] LOAD m1, [curq+t0] LOAD m2, [%2] LOAD m3, [%3] mova m4, m3 paddw m3, m2 psraw m3, 1 mova [rsp+ 0], m0 mova [rsp+16], m3 mova [rsp+32], m1 psubw m2, m4 PABS m2, m4 LOAD m3, [prevq+t1] LOAD m4, [prevq+t0] psubw m3, m0 psubw m4, m1 PABS m3, m5 PABS m4, m5 paddw m3, m4 psrlw m2, 1 psrlw m3, 1 pmaxsw m2, m3 LOAD m3, [nextq+t1] LOAD m4, [nextq+t0] psubw m3, m0 psubw m4, m1 PABS m3, m5 PABS m4, m5 paddw m3, m4 psrlw m3, 1 pmaxsw m2, m3 mova [rsp+48], m2 paddw m1, m0 paddw m0, m0 psubw m0, m1 psrlw m1, 1 PABS m0, m2 movu m2, [curq+t1-1*2] movu m3, [curq+t0-1*2] mova m4, m2 psubusw m2, m3 psubusw m3, m4 PMAXUW m2, m3 %if mmsize == 16 mova m3, m2 psrldq m3, 4 %else mova m3, m2 psrlq m3, 32 %endif paddw m0, m2 paddw m0, m3 psubw m0, [pw_1] CHECK -2, 0 CHECK1 CHECK -3, 1 CHECK2 CHECK 0, -2 CHECK1 CHECK 1, -3 CHECK2 mova m6, [rsp+48] cmp DWORD r8m, 2 jge .end%1 LOAD m2, [%2+t1*2] LOAD m4, [%3+t1*2] LOAD m3, [%2+t0*2] LOAD m5, [%3+t0*2] paddw m2, m4 paddw m3, m5 psrlw m2, 1 psrlw m3, 1 mova m4, [rsp+ 0] mova m5, [rsp+16] mova m7, [rsp+32] psubw m2, m4 psubw m3, m7 mova m0, m5 psubw m5, m4 psubw m0, m7 mova m4, m2 pminsw m2, m3 pmaxsw m3, m4 pmaxsw m2, m5 pminsw m3, m5 pmaxsw m2, m0 pminsw m3, m0 pxor m4, m4 pmaxsw m6, m3 psubw m4, m2 pmaxsw m6, m4 .end%1: mova m2, [rsp+16] mova m3, m2 psubw m2, m6 paddw m3, m6 pmaxsw m1, m2 pminsw m1, m3 movu [dstq], m1 add dstq, mmsize-4 add prevq, mmsize-4 add curq, mmsize-4 add nextq, mmsize-4 sub DWORD r4m, mmsize/2-2 jg .loop%1 %endmacro %macro YADIF 0 %if ARCH_X86_32 cglobal yadif_filter_line_10bit, 4, 6, 8, 80, dst, prev, cur, next, w, \ prefs, mrefs, parity, mode %else cglobal yadif_filter_line_10bit, 4, 7, 8, 80, dst, prev, cur, next, w, \ prefs, mrefs, parity, mode %endif %if ARCH_X86_32 mov r4, r5mp mov r5, r6mp DECLARE_REG_TMP 4,5 %else movsxd r5, DWORD r5m movsxd r6, DWORD r6m DECLARE_REG_TMP 5,6 %endif cmp DWORD paritym, 0 je .parity0 FILTER 1, prevq, curq jmp .ret .parity0: FILTER 0, curq, nextq .ret: RET %endmacro INIT_XMM ssse3 YADIF INIT_XMM sse2 YADIF %if ARCH_X86_32 INIT_MMX mmxext YADIF %endif
; wInputType:: ; c2c7 AUTO_INPUT EQU $ff ; wDebugFlags:: ; c2cc const_def const DEBUG_BATTLE_F const DEBUG_FIELD_F ; wCurDexMode:: ; c7d4 const_def const DEXMODE_NEW const DEXMODE_OLD const DEXMODE_ABC const DEXMODE_UNOWN ; wMonType:: ; cf5f const_def const PARTYMON ; 0 const OTPARTYMON ; 1 const BOXMON ; 2 const TEMPMON ; 3 const WILDMON ; 4 ; wGameTimerPause:: ; cfbc GAMETIMERPAUSE_TIMER_PAUSED_F EQU 0 GAMETIMERPAUSE_MOBILE_7_F EQU 7 ; wOptions:: ; cfcc TEXT_DELAY_MASK EQU %111 const_def 4 const NO_TEXT_SCROLL ; 4 const STEREO ; 5 const BATTLE_SHIFT ; 6 const BATTLE_SCENE ; 7 TEXT_DELAY_FAST EQU %001 ; 1 TEXT_DELAY_MED EQU %011 ; 3 TEXT_DELAY_SLOW EQU %101 ; 5 ; wTextboxFrame:: ; cfce const_def const FRAME_1 ; 0 const FRAME_2 ; 1 const FRAME_3 ; 2 const FRAME_4 ; 3 const FRAME_5 ; 4 const FRAME_6 ; 5 const FRAME_7 ; 6 const FRAME_8 ; 7 NUM_FRAMES EQU const_value ; wTextboxFlags:: ; cfcf const_def const FAST_TEXT_DELAY_F ; 0 const NO_TEXT_DELAY_F ; 1 ; wGBPrinterBrightness:: ; cfd0 GBPRINTER_LIGHTEST EQU $00 GBPRINTER_LIGHTER EQU $20 GBPRINTER_NORMAL EQU $40 GBPRINTER_DARKER EQU $60 GBPRINTER_DARKEST EQU $7f ; wOptions2:: ; cfd1 const_def const MENU_ACCOUNT ; 0 ; wWalkingDirection:: ; d043 const_def -1 const STANDING ; -1 const DOWN ; 0 const UP ; 1 const LEFT ; 2 const RIGHT ; 3 NUM_DIRECTIONS EQU const_value DOWN_MASK EQU 1 << DOWN UP_MASK EQU 1 << UP LEFT_MASK EQU 1 << LEFT RIGHT_MASK EQU 1 << RIGHT ; wFacingDirection:: ; d044 FACE_CURRENT EQU 0 FACE_DOWN EQU 8 FACE_UP EQU 4 FACE_LEFT EQU 2 FACE_RIGHT EQU 1 ; wPokemonWithdrawDepositParameter:: ; d10b PC_WITHDRAW EQU 0 PC_DEPOSIT EQU 1 REMOVE_PARTY EQU 0 REMOVE_BOX EQU 1 DAY_CARE_WITHDRAW EQU 2 DAY_CARE_DEPOSIT EQU 3 ; wPlayerStepFlags:: ; d150 const_def 4 const PLAYERSTEP_MIDAIR_F ; 4 const PLAYERSTEP_CONTINUE_F ; 5 const PLAYERSTEP_STOP_F ; 6 const PLAYERSTEP_START_F ; 7 ; wInitListType:: ; d263 INIT_ENEMYOT_LIST EQU 1 INIT_BAG_ITEM_LIST EQU 2 INIT_OTHER_ITEM_LIST EQU 3 INIT_PLAYEROT_LIST EQU 4 INIT_MON_LIST EQU 5 ; wTimeOfDay:: ; d269 const_def const MORN_F ; 0 const DAY_F ; 1 const NITE_F ; 2 const DARKNESS_F ; 3 NUM_DAYTIMES EQU const_value MORN EQU 1 << MORN_F DAY EQU 1 << DAY_F NITE EQU 1 << NITE_F DARKNESS EQU 1 << DARKNESS_F ANYTIME EQU MORN | DAY | NITE ; wBattleAnimFlags:: ; d40f const_def const BATTLEANIM_STOP_F ; 0 const BATTLEANIM_IN_SUBROUTINE_F ; 1 const BATTLEANIM_IN_LOOP_F ; 2 const BATTLEANIM_KEEPSPRITES_F ; 3 ; wPlayerSpriteSetupFlags:: ; d45b PLAYERSPRITESETUP_FACING_MASK EQU %11 PLAYERSPRITESETUP_FEMALE_TO_MALE_F EQU 2 PLAYERSPRITESETUP_CUSTOM_FACING_F EQU 5 PLAYERSPRITESETUP_SKIP_RELOAD_GFX_F EQU 6 PLAYERSPRITESETUP_RESET_ACTION_F EQU 7 ; wPlayerGender:: ; d472 PLAYERGENDER_FEMALE_F EQU 0 ; wMapStatus:: ; d432 const_def const MAPSTATUS_START ; 0 const MAPSTATUS_ENTER ; 1 const MAPSTATUS_HANDLE ; 2 const MAPSTATUS_DONE ; 3 ; wMapEventStatus:: ; d433 const_def const MAPEVENTS_ON ; 0 const MAPEVENTS_OFF ; 1 ; wScriptFlags:: ; d434 SCRIPT_RUNNING EQU 2 ; wScriptMode:: ; d437 const_def const SCRIPT_OFF const SCRIPT_READ const SCRIPT_WAIT_MOVEMENT const SCRIPT_WAIT ; wSpawnAfterChampion:: ; d4b5 SPAWN_LANCE EQU 1 SPAWN_RED EQU 2 ; wCurDay:: ; d4cb const_def const SUNDAY ; 0 const MONDAY ; 1 const TUESDAY ; 2 const WEDNESDAY ; 3 const THURSDAY ; 4 const FRIDAY ; 5 const SATURDAY ; 6 ; wMapObjects:: ; d71e PLAYER_OBJECT EQU 0 NUM_OBJECTS EQU 16 ; wStatusFlags:: ; d84c const_def const STATUSFLAGS_POKEDEX_F ; 0 const STATUSFLAGS_UNOWN_DEX_F ; 1 const STATUSFLAGS_FLASH_F ; 2 const STATUSFLAGS_CAUGHT_POKERUS_F ; 3 const STATUSFLAGS_ROCKET_SIGNAL_F ; 4 const STATUSFLAGS_NO_WILD_ENCOUNTERS_F ; 5 const STATUSFLAGS_HALL_OF_FAME_F ; 6 const STATUSFLAGS_MAIN_MENU_MOBILE_CHOICES_F ; 7 ; wStatusFlags2:: ; d84d const_def const STATUSFLAGS2_ROCKETS_IN_RADIO_TOWER_F ; 0 const STATUSFLAGS2_SAFARI_GAME_F ; 1 const STATUSFLAGS2_BUG_CONTEST_TIMER_F ; 2 const STATUSFLAGS2_NATIONAL_DEX_F ; 3 const STATUSFLAGS2_BIKE_SHOP_CALL_F ; 4 const STATUSFLAGS2_MET_BEBE_F ; 5 const STATUSFLAGS2_REACHED_GOLDENROD_F ; 6 const STATUSFLAGS2_ROCKETS_IN_MAHOGANY_F ; 7 ; wMomSavingMoney:: ; d854 MOM_SAVING_SOME_MONEY_F EQU 0 MOM_SAVING_HALF_MONEY_F EQU 1 MOM_SAVING_ALL_MONEY_F EQU 2 MOM_ACTIVE_F EQU 7 MOM_SAVING_MONEY_MASK EQU (1 << MOM_SAVING_SOME_MONEY_F) | (1 << MOM_SAVING_HALF_MONEY_F) | (1 << MOM_SAVING_ALL_MONEY_F) ; wJohtoBadges:: ; d857 const_def const ZEPHYRBADGE const HIVEBADGE const PLAINBADGE const FOGBADGE const MINERALBADGE const STORMBADGE const GLACIERBADGE const RISINGBADGE NUM_JOHTO_BADGES EQU const_value ; wKantoBadges:: ; d858 const_def const BOULDERBADGE const CASCADEBADGE const THUNDERBADGE const RAINBOWBADGE const SOULBADGE const MARSHBADGE const VOLCANOBADGE const EARTHBADGE NUM_KANTO_BADGES EQU const_value NUM_BADGES EQU NUM_JOHTO_BADGES + NUM_KANTO_BADGES ; wPokegearFlags:: ; d957 const_def const POKEGEAR_MAP_CARD_F ; 0 const POKEGEAR_RADIO_CARD_F ; 1 const POKEGEAR_PHONE_CARD_F ; 2 const POKEGEAR_EXPN_CARD_F ; 3 POKEGEAR_OBTAINED_F EQU 7 ; wWhichRegisteredItem:: ; d95b REGISTERED_POCKET EQU %11100000 REGISTERED_NUMBER EQU %00011111 ; wPlayerState:: ; d95d PLAYER_NORMAL EQU 0 PLAYER_BIKE EQU 1 PLAYER_SKATE EQU 2 PLAYER_SURF EQU 4 PLAYER_SURF_PIKA EQU 8 ; wCelebiEvent:: ; dbf3 CELEBIEVENT_FOREST_IS_RESTLESS_F EQU 2 ; wBikeFlags:: ; dbf5 const_def const BIKEFLAGS_STRENGTH_ACTIVE_F ; 0 const BIKEFLAGS_ALWAYS_ON_BIKE_F ; 1 const BIKEFLAGS_DOWNHILL_F ; 2 ; wDailyFlags1:: ; dc1e const_def const DAILYFLAGS1_KURT_MAKING_BALLS_F ; 0 const DAILYFLAGS1_BUG_CONTEST_F ; 1 const DAILYFLAGS1_FISH_SWARM_F ; 2 const DAILYFLAGS1_TIME_CAPSULE_F ; 3 const DAILYFLAGS1_ALL_FRUIT_TREES_F ; 4 const DAILYFLAGS1_GOT_SHUCKIE_TODAY_F ; 5 const DAILYFLAGS1_GOLDENROD_UNDERGROUND_BARGAIN_F ; 6 const DAILYFLAGS1_TRAINER_HOUSE_F ; 7 ; wDailyFlags2:: ; dc1f const_def const DAILYFLAGS2_MT_MOON_SQUARE_CLEFAIRY_F ; 0 const DAILYFLAGS2_UNION_CAVE_LAPRAS_F ; 1 const DAILYFLAGS2_GOLDENROD_UNDERGROUND_GOT_HAIRCUT_F ; 2 const DAILYFLAGS2_GOLDENROD_DEPT_STORE_TM27_RETURN_F ; 3 const DAILYFLAGS2_DAISYS_GROOMING_F ; 4 const DAILYFLAGS2_INDIGO_PLATEAU_RIVAL_FIGHT_F ; 5 const DAILYFLAGS2_MOVE_TUTOR_F ; 6 const DAILYFLAGS2_BUENAS_PASSWORD_F ; 7 ; wSwarmFlags:: ; dc20 const_def const SWARMFLAGS_BUENAS_PASSWORD_F ; 0 const SWARMFLAGS_GOLDENROD_DEPT_STORE_SALE_F ; 1 const SWARMFLAGS_DUNSPARCE_SWARM_F ; 2 const SWARMFLAGS_YANMA_SWARM_F ; 3 const SWARMFLAGS_MOBILE_4_F ; 4 ; wLuckyNumberShowFlag:: ; dc9d LUCKYNUMBERSHOW_GAME_OVER_F EQU 0 ; wDayCareMan:: ; def5 DAYCAREMAN_HAS_MON_F EQU 0 DAYCAREMAN_MONS_COMPATIBLE_F EQU 5 DAYCAREMAN_HAS_EGG_F EQU 6 DAYCAREMAN_ACTIVE_F EQU 7 ; wDayCareLady:: ; df2c DAYCARELADY_HAS_MON_F EQU 0 DAYCARELADY_ACTIVE_F EQU 7
/* * CMP.asm * * Created: 5/13/2018 3:19:37 PM * Author: ROTP */ CMP_immediate: swapPCwithTEMPPC ADIW ZH:ZL, 1 dereferencer r22 cp AR, r22 BRLT CMP_immediate_lt BREQ CMP_immediate_eq CMP_immediate_gt: ;AR > R22 => Z = 0, C = 1 CBR SR, ZERO_FLAG SBR SR, CARRY_FLAG ;JMP CMP_immediate_ret ADIW ZH:ZL, 1 RET CMP_immediate_lt: ;AR < r22 => Z = 0, C = 0 CBR SR, ZERO_FLAG CBR SR, CARRY_FLAG ;JMP CMP_immediate_ret ADIW ZH:ZL, 1 RET CMP_immediate_eq: ;AR = R22 => Z = 1, C = 1 SBR SR, ZERO_FLAG SBR SR, CARRY_FLAG ;JMP CMP_immediate_ret CMP_immediate_ret: ADIW ZH:ZL, 1 RET CMP_zpg: swapPCwithTEMPPC ADIW ZH:ZL, 1 MOV R22, ZL MOV R23, ZH dereferencer r24 MOV ZL, R24 CLR ZH dereferencer R25 cp AR, r25 BRLT CMP_zpg_lt BREQ CMP_zpg_eq CMP_zpg_gt: ;AR > R22 => Z = 0, C = 1 CBR SR, ZERO_FLAG SBR SR, CARRY_FLAG JMP CMP_zpg_ret CMP_zpg_lt: ;AR < r22 => Z = 0, C = 0 CBR SR, ZERO_FLAG CBR SR, CARRY_FLAG JMP CMP_zpg_ret CMP_zpg_eq: ;AR = R22 => Z = 1, C = 1 SBR SR, ZERO_FLAG SBR SR, CARRY_FLAG ;JMP CMP_zpg_ret CMP_zpg_ret: MOV ZL, R22 MOV ZH, R23 ADIW ZH:ZL, 1 RET CMP_zpg_X: ;UNTESTED swapPCwithTEMPPC ADIW ZH:ZL, 1 MOV R22, ZL MOV R23, ZH dereferencer r24 MOV ZL, R24 CLR ZH dereferencer R25 add R25, XR cp AR, r25 BRLT CMP_zpg_X_lt BREQ CMP_zpg_X_eq CMP_zpg_X_gt: ;AR > R22 => Z = 0, C = 1 CBR SR, ZERO_FLAG SBR SR, CARRY_FLAG JMP CMP_zpg_X_ret CMP_zpg_X_lt: ;AR < r22 => Z = 0, C = 0 CBR SR, ZERO_FLAG CBR SR, CARRY_FLAG JMP CMP_zpg_X_ret CMP_zpg_X_eq: ;AR = R22 => Z = 1, C = 1 SBR SR, ZERO_FLAG SBR SR, CARRY_FLAG ;JMP CMP_zpg_X_ret CMP_zpg_X_ret: MOV ZL, R22 MOV ZH, R23 ADIW ZH:ZL, 1 RET CMP_absolute: swapPCwithTEMPPC ADIW ZH:ZL, 1 dereferencer r23 ;grab LO ADIW ZH:ZL, 1 dereferencer r22 ;grab HI mov r24, ZL ;preserve Z mov r25, ZH MOV ZH, R22 ;put new data in Z MOV ZL, R23 dereferencer r26 cp AR, r26 BRLT CMP_absolute_lt BREQ CMP_absolute_eq CMP_absolute_gt: ;AR > R22 => Z = 0, C = 1 CBR SR, ZERO_FLAG SBR SR, CARRY_FLAG JMP CMP_absolute_ret CMP_absolute_lt: ;AR < r22 => Z = 0, C = 0 CBR SR, ZERO_FLAG CBR SR, CARRY_FLAG JMP CMP_absolute_ret CMP_absolute_eq: ;AR = R22 => Z = 1, C = 1 SBR SR, ZERO_FLAG SBR SR, CARRY_FLAG ;JMP CMP_absolute_ret CMP_absolute_ret: mov ZL, R24 ;restore Z mov ZH, R25 ADIW ZH:ZL, 1 RET CMP_absolute_X: ;UNTESTED swapPCwithTEMPPC ADIW ZH:ZL, 1 dereferencer r23 ;grab LO ADIW ZH:ZL, 1 dereferencer r22 ;grab HI mov r24, ZL ;preserve Z mov r25, ZH MOV ZH, R22 ;put new data in Z MOV ZL, R23 CLR R26 ADD ZL, XR ADC ZH, R26 dereferencer r26 cp AR, r26 BRLT CMP_absolute_X_lt BREQ CMP_absolute_X_eq CMP_absolute_X_gt: ;AR > R22 => Z = 0, C = 1 CBR SR, ZERO_FLAG SBR SR, CARRY_FLAG JMP CMP_absolute_X_ret CMP_absolute_X_lt: ;AR < r22 => Z = 0, C = 0 CBR SR, ZERO_FLAG CBR SR, CARRY_FLAG JMP CMP_absolute_X_ret CMP_absolute_X_eq: ;AR = R22 => Z = 1, C = 1 SBR SR, ZERO_FLAG SBR SR, CARRY_FLAG ;JMP CMP_absolute_X_ret CMP_absolute_X_ret: mov ZL, R24 ;restore Z mov ZH, R25 ADIW ZH:ZL, 1 RET CMP_absolute_Y: ;UNTESTED swapPCwithTEMPPC ADIW ZH:ZL, 1 dereferencer r23 ;grab LO ADIW ZH:ZL, 1 dereferencer r22 ;grab HI mov r24, ZL ;preserve Z mov r25, ZH MOV ZH, R22 ;put new data in Z MOV ZL, R23 CLR R26 ADD ZL, YR ADC ZH, R26 dereferencer r26 cp AR, r26 BRLT CMP_absolute_Y_lt BREQ CMP_absolute_Y_eq CMP_absolute_Y_gt: ;AR > R22 => Z = 0, C = 1 CBR SR, ZERO_FLAG SBR SR, CARRY_FLAG JMP CMP_absolute_Y_ret CMP_absolute_Y_lt: ;AR < r22 => Z = 0, C = 0 CBR SR, ZERO_FLAG CBR SR, CARRY_FLAG JMP CMP_absolute_Y_ret CMP_absolute_Y_eq: ;AR = R22 => Z = 1, C = 1 SBR SR, ZERO_FLAG SBR SR, CARRY_FLAG ;JMP CMP_absolute_Y_ret CMP_absolute_Y_ret: mov ZL, R24 ;restore Z mov ZH, R25 ADIW ZH:ZL, 1 RET
;******************************************************************************* ;* ;* ASM_002: LED Intermitente ;* ;******************************************************************************* ;* FileName: main.asm ;* Processor: PIC16F84A ;* Complier: MPASM v5.55 ;* Author: Pedro Sánchez (MrChunckuee) ;* Blog: http://mrchunckuee.blogspot.com/ ;* Email: mrchunckuee.psr@gmail.com ;* Description: Cambiar el estado del LED conectado en RB0 cada 1 segundo ;* Oscilador XT=4MHz ;******************************************************************************* ;* Rev. Date Comment ;* v1.00 08/06/2015 Creación del firmware ;******************************************************************************* ;********** C A B E C E R A **************************************************** list p=16F84A ;Identifica el PIC a usar #include <P16F84A.INC> ;Libreria del PIC ;********** F U S E S ********************************************************** ; _CP_OFF Se desactiva proteccion de codigo ; _WDT_OFF Se desactiva el Watchdog Timer ; _PWRTE_ON Se activa el Power-Up Timer ; _XT_OSC Se usa oscilador externo XT __CONFIG _CP_OFF & _WDT_OFF & _PWRTE_ON & _XT_OSC ;********** V A R I A B L E S ************************************************** ContadorA EQU 0x0C ; Seleccionamos posicion de la RAM y guardamos ; ContadorA usado para el retardo ; 0x0C es donde inicia la SRAM del PIC ContadorB EQU 0x0D ; Guardamos ContadorB usado para el retardo ContadorC EQU 0x0E ; Guardamos ContadorC usado para el retardo Led EQU 0 ; Definimos Led como RB0 ;********** C O N F I G * P U E R T O S **************************************** RESET org 0x00 ; Aqui comienza el micro despues del reset goto Inicio ; Salto a la etiqueta Inicio org 0x05 ; Origen del codigo de programa Inicio bsf STATUS,RP0 ; Pasamos de Banco 0 a Banco 1 movlw b'11111110' ; Cargamos 11111110 a W movwf TRISB ; Cargamos W en TRISB, RB0 como salida bcf STATUS,RP0 ; Paso del Banco 1 al Banco 0 bcf PORTB,Led ; Comienza con el LED apagado ;********** C O D I G O * P R I N C I P A L ************************************ Bucle bsf PORTB,Led ; Encendemos Led call Retardo_1s bcf PORTB,Led ; Apagamos Led call Retardo_1s goto Bucle ; Regresamos para repetir tareas ;********** C O D I G O * R E T A R D O S ************************************** ; Considerando Fosc=4MHz, ciclo maquina (cm) = 1uS ; Time = 2 + 1 + 1 + N + N + MN + MN + KMN + (K-1)MN + 2MN + 2(K-1)MN + (M-1)N ; + 2N + (M-1)2N + (N-1) + 2 + 2(N-1) + 2 ; Time = (5 + 4M + 4MN + 4KM) ciclos máquina. Para K=249, M=100 y N=10 ; Time = 5 + 40 + 4000 + 996000 ciclos maquina ; Time = 1000045 uS = 1 segundo Retardo_1s ; 2 ciclo máquina movlw d'10' ; 1 ciclo máquina. Este es el valor de "N" movwf ContadorC ; 1 ciclo máquina. Retardo_BucleExterno2 movlw d'100' ; Nx1 ciclos máquina. Este es el valor de "M". movwf ContadorB ; Nx1 ciclos máquina. Retardo_BucleExterno movlw d'249' ; MxNx1 ciclos máquina. Este es el valor de "K". movwf ContadorA ; MxNx1 ciclos máquina. Retardo_BucleInterno nop ; KxMxNx1 ciclos máquina. decfsz ContadorA,F ; (K-1)xMxNx1 cm (si no salta) + MxNx2 cm (al saltar). goto Retardo_BucleInterno ; (K-1)xMxNx2 ciclos máquina. decfsz ContadorB,F ; (M-1)xNx1 cm (si no salta) + Nx2 cm (al saltar). goto Retardo_BucleExterno ; (M-1)xNx2 ciclos máquina. decfsz ContadorC,F ; (N-1)x1 cm (si no salta) + 2 cm (al saltar). goto Retardo_BucleExterno2 ; (N-1)x2 ciclos máquina. return ; 2 ciclos máquina. end //Fin del codigo
SECTION code_clib PUBLIC xor_MODE1 .xor_MODE1 defc NEEDxor = 1 INCLUDE "target/spc1000/graphics/pixel_MODE1.inc"
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/grappler/optimizers/constant_folding.h" #include "tensorflow/cc/ops/array_ops_internal.h" #include "tensorflow/cc/ops/standard_ops.h" #include "tensorflow/core/framework/node_def.pb.h" #include "tensorflow/core/framework/tensor_testutil.h" #include "tensorflow/core/grappler/grappler_item.h" #include "tensorflow/core/grappler/utils.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/lib/strings/strcat.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/public/session.h" namespace tensorflow { namespace grappler { namespace { class ConstantFoldingTest : public ::testing::Test { protected: std::vector<Tensor> EvaluateNodes(const GraphDef& graph, const std::vector<string>& fetch) { SessionOptions options; std::unique_ptr<tensorflow::Session> session(NewSession(options)); TF_CHECK_OK(session->Create(graph)); RunOptions run_options; std::vector<Tensor> output_tensors; TF_CHECK_OK( session->Run(run_options, {}, fetch, fetch, &output_tensors, nullptr)); TF_CHECK_OK(session->Close()); return output_tensors; } }; TEST_F(ConstantFoldingTest, SimpleFolding) { // Build a simple graph with a few trivially prunable ops. tensorflow::Scope s = tensorflow::Scope::NewRootScope(); Output a = ops::Const(s.WithOpName("a"), 1.0f, {1}); Output b = ops::Const(s.WithOpName("b"), 2.0f, {1}); Output c = ops::AddN(s.WithOpName("c").WithDevice("/CPU:0"), {a, b}); Output d = ops::AddN(s.WithOpName("d"), {b, c}); GrapplerItem item; item.fetch.push_back("d"); TF_CHECK_OK(s.ToGraphDef(&item.graph)); ConstantFolding fold(nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); EXPECT_EQ(1, output.node_size()); const NodeDef& node_d = output.node(0); EXPECT_EQ("d", node_d.name()); EXPECT_EQ("Const", node_d.op()); std::vector<string> fetch = {"d"}; auto tensors_expected = EvaluateNodes(item.graph, fetch); auto tensors = EvaluateNodes(output, fetch); EXPECT_EQ(1, tensors_expected.size()); EXPECT_EQ(1, tensors.size()); test::ExpectTensorEqual<float>(tensors_expected[0], tensors[0]); } TEST_F(ConstantFoldingTest, NeutralElement) { for (bool use_const : {true, false}) { tensorflow::Scope s = tensorflow::Scope::NewRootScope(); Output x = ops::Placeholder(s.WithOpName("x"), DT_FLOAT, ops::Placeholder::Shape(TensorShape({2, 2}))); Output y = ops::Placeholder(s.WithOpName("y"), DT_FLOAT, ops::Placeholder::Shape(TensorShape({2, 2}))); Output a = ops::Placeholder(s.WithOpName("a"), DT_FLOAT, ops::Placeholder::Shape(TensorShape({3, 2}))); Output b = ops::Placeholder(s.WithOpName("b"), DT_FLOAT, ops::Placeholder::Shape(TensorShape({2, 3}))); Output zeros = !use_const ? ops::ZerosLike(s.WithOpName("zeros"), x) : ops::Const(s.WithOpName("zeros"), 0.0f, {2, 2}); Output zeros_broadcast = ops::Const(s.WithOpName("zeros_broadcast"), 0.0f, {1, 1}); Output ones = !use_const ? ops::OnesLike(s.WithOpName("ones"), x) : ops::Const(s.WithOpName("ones"), 1.0f, {2, 2}); Output mul1 = ops::Mul(s.WithOpName("mul1"), x, zeros); Output mul2 = ops::Mul(s.WithOpName("mul2"), zeros, y); Output mul3 = ops::Mul(s.WithOpName("mul3"), x, ones); Output mul4 = ops::Mul(s.WithOpName("mul4"), ones, y); Output mul5 = ops::Mul(s.WithOpName("mul5"), x, zeros_broadcast); Output mul6 = ops::Mul(s.WithOpName("mul6"), zeros_broadcast, y); Output matmul1 = ops::MatMul(s.WithOpName("matmul1"), x, zeros); Output matmul2 = ops::MatMul(s.WithOpName("matmul2"), zeros, y); Output matmul3 = ops::MatMul(s.WithOpName("matmul3"), a, zeros); Output matmul4 = ops::MatMul(s.WithOpName("matmul4"), zeros, b); Output add1 = ops::Add(s.WithOpName("add1"), x, zeros); Output add2 = ops::Add(s.WithOpName("add2"), zeros, y); Output addn = ops::AddN( s.WithOpName("addn"), {mul1, mul2, mul3, mul4, mul5, mul6, matmul1, matmul2, add1, add2}); GrapplerItem item; TF_CHECK_OK(s.ToGraphDef(&item.graph)); item.fetch = {"addn", "matmul3", "matmul4"}; ConstantFolding optimizer(RewriterConfig::AGGRESSIVE, nullptr /* cpu_device */); GraphDef output; Status status = optimizer.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); EXPECT_EQ(20, output.node_size()); for (int i = 0; i < output.node_size(); ++i) { const NodeDef& node = output.node(i); const string& name = node.name(); if (name == "mul1") { EXPECT_EQ("Const", node.op()); EXPECT_EQ("^x", node.input(0)); EXPECT_EQ("^zeros", node.input(1)); } else if (name == "mul2") { EXPECT_EQ("Const", node.op()); EXPECT_EQ("^zeros", node.input(0)); EXPECT_EQ("^y", node.input(1)); } else if (name == "mul3") { EXPECT_EQ("Identity", node.op()); EXPECT_EQ("x", node.input(0)); EXPECT_EQ("^ones", node.input(1)); } else if (name == "mul4") { EXPECT_EQ("Identity", node.op()); EXPECT_EQ("y", node.input(0)); EXPECT_EQ("^ones", node.input(1)); } else if (name == "mul5") { EXPECT_EQ("Const", node.op()); EXPECT_EQ("^x", node.input(0)); EXPECT_EQ("^zeros_broadcast", node.input(1)); } else if (name == "mul6") { EXPECT_EQ("Const", node.op()); EXPECT_EQ("^zeros_broadcast", node.input(0)); EXPECT_EQ("^y", node.input(1)); } else if (name == "matmul1") { EXPECT_EQ("Const", node.op()); EXPECT_EQ("^x", node.input(0)); EXPECT_EQ("^zeros", node.input(1)); } else if (name == "matmul2") { EXPECT_EQ("Const", node.op()); EXPECT_EQ("^zeros", node.input(0)); EXPECT_EQ("^y", node.input(1)); } else if (name == "matmul3") { EXPECT_EQ("Const", node.op()); EXPECT_EQ("^a", node.input(0)); EXPECT_EQ("^zeros", node.input(1)); TensorProto t = node.attr().at("value").tensor(); EXPECT_EQ(1, t.float_val_size()); EXPECT_EQ(0, t.float_val(0)); EXPECT_EQ(2, t.tensor_shape().dim_size()); EXPECT_EQ(3, t.tensor_shape().dim(0).size()); EXPECT_EQ(2, t.tensor_shape().dim(1).size()); } else if (name == "matmul4") { EXPECT_EQ("Const", node.op()); EXPECT_EQ("^zeros", node.input(0)); EXPECT_EQ("^b", node.input(1)); TensorProto t = node.attr().at("value").tensor(); EXPECT_EQ(1, t.float_val_size()); EXPECT_EQ(0, t.float_val(0)); EXPECT_EQ(2, t.tensor_shape().dim_size()); EXPECT_EQ(2, t.tensor_shape().dim(0).size()); EXPECT_EQ(3, t.tensor_shape().dim(1).size()); } else if (name == "add1") { EXPECT_EQ("Identity", node.op()); EXPECT_EQ("x", node.input(0)); EXPECT_EQ("^zeros", node.input(1)); } else if (name == "add2") { EXPECT_EQ("Identity", node.op()); EXPECT_EQ("y", node.input(0)); EXPECT_EQ("^zeros", node.input(1)); } const std::set<string> square_zero_const{"mul1", "mul2", "mul5", "mul6", "matmul1", "matmul2"}; if (square_zero_const.count(name) > 0) { TensorProto t = node.attr().at("value").tensor(); EXPECT_EQ(1, t.float_val_size()); EXPECT_EQ(0, t.float_val(0)); EXPECT_EQ(2, t.tensor_shape().dim_size()); EXPECT_EQ(2, t.tensor_shape().dim(0).size()); EXPECT_EQ(2, t.tensor_shape().dim(1).size()); } } } } TEST_F(ConstantFoldingTest, CreateConstNodes) { tensorflow::Scope s = tensorflow::Scope::NewRootScope(); #define MAKE_TEST_GRAPH(TYPE) \ Output TYPE##_const = \ ops::Const(s.WithOpName(#TYPE "_const"), static_cast<TYPE>(10), {5}); \ Output TYPE##_mul = \ ops::Mul(s.WithOpName(#TYPE "_mul"), TYPE##_const, TYPE##_const); \ Output TYPE##_id = ops::Identity(s.WithOpName(#TYPE "_id"), TYPE##_mul) MAKE_TEST_GRAPH(float); MAKE_TEST_GRAPH(double); MAKE_TEST_GRAPH(int64); MAKE_TEST_GRAPH(int32); MAKE_TEST_GRAPH(int16); MAKE_TEST_GRAPH(int8); MAKE_TEST_GRAPH(uint8); #undef MAKE_TEST_GRAPH Output bool_const = ops::Const(s.WithOpName("bool_const"), true, {5}); Output bool_and = ops::LogicalAnd(s.WithOpName("bool_and"), bool_const, bool_const); Output bool_id = ops::Identity(s.WithOpName("bool_id"), bool_and); GrapplerItem item; TF_CHECK_OK(s.ToGraphDef(&item.graph)); ConstantFolding fold(nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); EXPECT_EQ(24, output.node_size()); for (const NodeDef& node : output.node()) { #define CHECK_RESULT(TYPE, FIELD) \ if (node.name() == #TYPE "_mul") { \ EXPECT_EQ(5, \ node.attr().at("value").tensor().tensor_shape().dim(0).size()); \ EXPECT_EQ(1, node.attr().at("value").tensor().FIELD##_val_size()); \ EXPECT_EQ(10 * 10, node.attr().at("value").tensor().FIELD##_val(0)); \ } CHECK_RESULT(float, float); CHECK_RESULT(double, double); CHECK_RESULT(int64, int64); CHECK_RESULT(int32, int); CHECK_RESULT(int16, int); CHECK_RESULT(int8, int); CHECK_RESULT(uint8, int); #undef CHECK_RESULT if (node.name() == "bool_and") { EXPECT_EQ(5, node.attr().at("value").tensor().tensor_shape().dim(0).size()); EXPECT_EQ(1, node.attr().at("value").tensor().bool_val_size()); EXPECT_EQ(true && true, node.attr().at("value").tensor().bool_val(0)); } } } TEST_F(ConstantFoldingTest, FoldingNodeWithTwoOutputs) { // Build a simple graph with a few trivially prunable ops. tensorflow::Scope s = tensorflow::Scope::NewRootScope(); Output a = ops::Const(s.WithOpName("a"), 10, {5}); auto b = ops::Unique(s.WithOpName("b"), {a}); Output c = ops::Identity(s.WithOpName("c"), {b.y}); Output d = ops::Identity(s.WithOpName("d"), {b.idx}); Output e = ops::Identity(s.WithOpName("e"), {c}); Output f = ops::Identity(s.WithOpName("f"), {d}); GrapplerItem item; item.fetch.push_back("e"); item.fetch.push_back("f"); TF_CHECK_OK(s.ToGraphDef(&item.graph)); ConstantFolding fold(nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); EXPECT_EQ(2, output.node_size()); const NodeDef& new_c = output.node(0); EXPECT_EQ("e", new_c.name()); EXPECT_EQ("Const", new_c.op()); const NodeDef& new_d = output.node(1); EXPECT_EQ("f", new_d.name()); EXPECT_EQ("Const", new_d.op()); std::vector<string> fetch = {"e", "f"}; auto tensors_expected = EvaluateNodes(item.graph, fetch); auto tensors = EvaluateNodes(output, fetch); EXPECT_EQ(fetch.size(), tensors_expected.size()); EXPECT_EQ(fetch.size(), tensors.size()); for (int i = 0; i < fetch.size(); i++) { test::ExpectTensorEqual<int>(tensors_expected[i], tensors[i]); } } TEST_F(ConstantFoldingTest, ControlDependencies) { tensorflow::Scope scope = tensorflow::Scope::NewRootScope(); Output dflt = ops::Const(scope.WithOpName("dflt"), 3.14f, {1}); Output p1 = ops::PlaceholderWithDefault(scope.WithOpName("p1"), dflt, {1}); Output p2 = ops::PlaceholderWithDefault(scope.WithOpName("p2"), dflt, {1}); Output c = ops::Const(scope.WithOpName("c").WithControlDependencies(p1), 10, {3}); Output i1 = ops::Identity(scope.WithOpName("i1"), {c}); Output i2 = ops::Identity(scope.WithOpName("i2").WithControlDependencies(p2), {i1}); Output i3 = ops::Identity(scope.WithOpName("e"), {i2}); GrapplerItem item; item.fetch.push_back("e"); TF_CHECK_OK(scope.ToGraphDef(&item.graph)); ConstantFolding fold(nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); std::vector<string> expected_nodes = {"dflt", "p1", "p2", "e"}; EXPECT_EQ(output.node_size(), expected_nodes.size()); int i = 0; int found = 0; for (const auto& node : output.node()) { EXPECT_EQ(expected_nodes[i], output.node(i).name()); i++; if (node.name() == "e") { EXPECT_EQ("Const", node.op()); ++found; auto folded = EvaluateNodes(output, {"e"}); auto expected = EvaluateNodes(item.graph, {"e"}); EXPECT_EQ(1, expected.size()); EXPECT_EQ(1, folded.size()); test::ExpectTensorEqual<int>(folded[0], expected[0]); EXPECT_EQ(2, node.input_size()); EXPECT_EQ("^p1", node.input(0)); EXPECT_EQ("^p2", node.input(1)); } } EXPECT_EQ(1, found); } TEST_F(ConstantFoldingTest, ControlDependenciesEmptyFetch) { tensorflow::Scope scope = tensorflow::Scope::NewRootScope(); Output dflt = ops::Const(scope.WithOpName("dflt"), 3.14f, {1}); Output p1 = ops::PlaceholderWithDefault(scope.WithOpName("p1"), dflt, {1}); Output p2 = ops::PlaceholderWithDefault(scope.WithOpName("p2"), dflt, {1}); Output c = ops::Const(scope.WithOpName("c").WithControlDependencies(p1), 10, {3}); Output i1 = ops::Identity(scope.WithOpName("i1"), {c}); Output i2 = ops::Identity(scope.WithOpName("i2").WithControlDependencies(p2), {i1}); Output i3 = ops::Identity(scope.WithOpName("e"), {i2}); GrapplerItem item; TF_CHECK_OK(scope.ToGraphDef(&item.graph)); ConstantFolding fold(nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); std::vector<string> expected_nodes = {"dflt", "p1", "p2", "c", "i1", "i2", "e"}; EXPECT_EQ(output.node_size(), expected_nodes.size()); int i = 0; int found = 0; for (const auto& node : output.node()) { EXPECT_EQ(expected_nodes[i], output.node(i).name()); i++; if (node.name() == "i1") { EXPECT_EQ("Const", node.op()); ++found; auto folded = EvaluateNodes(output, {"i1"}); auto expected = EvaluateNodes(item.graph, {"i1"}); EXPECT_EQ(1, expected.size()); EXPECT_EQ(1, folded.size()); test::ExpectTensorEqual<int>(folded[0], expected[0]); EXPECT_EQ(1, node.input_size()); EXPECT_EQ("^p1", node.input(0)); } if (node.name() == "i2") { EXPECT_EQ("Const", node.op()); ++found; auto folded = EvaluateNodes(output, {"i2"}); auto expected = EvaluateNodes(item.graph, {"i2"}); EXPECT_EQ(1, expected.size()); EXPECT_EQ(1, folded.size()); test::ExpectTensorEqual<int>(folded[0], expected[0]); EXPECT_EQ(2, node.input_size()); EXPECT_EQ("^p1", node.input(0)); EXPECT_EQ("^p2", node.input(1)); } } EXPECT_EQ(2, found); } TEST_F(ConstantFoldingTest, ControlDependenciesDeduplicate) { tensorflow::Scope scope = tensorflow::Scope::NewRootScope(); Output dflt = ops::Const(scope.WithOpName("dflt"), 3.14f, {1}); Output p1 = ops::PlaceholderWithDefault(scope.WithOpName("p1"), dflt, {1}); Output p2 = ops::PlaceholderWithDefault(scope.WithOpName("p2"), dflt, {1}); Output c = ops::Const(scope.WithOpName("c").WithControlDependencies(p1), 10, {3}); Output i1 = ops::Identity(scope.WithOpName("i1") .WithControlDependencies(p2) .WithControlDependencies(p1), {c}); Output i2 = ops::Identity(scope.WithOpName("i2"), {i1}); GrapplerItem item; item.fetch.push_back("i2"); TF_CHECK_OK(scope.ToGraphDef(&item.graph)); ConstantFolding fold(nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); std::vector<string> expected_nodes = {"dflt", "p1", "p2", "i2"}; EXPECT_EQ(output.node_size(), expected_nodes.size()); int i = 0; for (const auto& node : output.node()) { EXPECT_EQ(expected_nodes[i], output.node(i).name()); i++; if (node.name() == "i2") { EXPECT_EQ("Const", node.op()); EXPECT_EQ(2, node.input_size()); EXPECT_EQ("^p1", node.input(0)); EXPECT_EQ("^p2", node.input(1)); } } } TEST_F(ConstantFoldingTest, VariableNumberOfOutputs) { tensorflow::Scope scope = tensorflow::Scope::NewRootScope(); // Add a DynamicPartition node to the graph Output input = ops::Const(scope.WithOpName("in0"), 314, {3, 4, 5}); Output indices = ops::Const(scope.WithOpName("indices"), 1, {3, 4}); int num_partitions = 4; ops::DynamicPartition part(scope.WithOpName("partition"), input, indices, num_partitions); std::vector<string> outputs; for (int i = 0; i < num_partitions; ++i) { string part_out_name = strings::StrCat("part_out", i); ops::Identity partition_out(scope.WithOpName(part_out_name), {part.outputs[i]}); outputs.push_back(part_out_name); } GrapplerItem item; TF_CHECK_OK(scope.ToGraphDef(&item.graph)); // Add a ConcatOffset node to the graph Tensor initial_val(DT_INT32, TensorShape({3})); test::FillIota<int>(&initial_val, 7); for (int i = 1; i < 5; ++i) { TF_CHECK_OK(NodeDefBuilder(strings::StrCat("in", i), "Const") .Attr("dtype", DT_INT32) .Attr("value", initial_val) .Finalize(item.graph.add_node())); } Tensor concat_dim(DT_INT32, TensorShape({})); test::FillIota<int>(&concat_dim, 0); TF_CHECK_OK(NodeDefBuilder("concat_dim", "Const") .Attr("dtype", DT_INT32) .Attr("value", concat_dim) .Finalize(item.graph.add_node())); TF_CHECK_OK(NodeDefBuilder("concat_offsets", "ConcatOffset") .Input("concat_dim", 0, DT_INT32) .Input({NodeDefBuilder::NodeOut("in1", 0, DT_INT32), NodeDefBuilder::NodeOut("in2", 0, DT_INT32), NodeDefBuilder::NodeOut("in3", 0, DT_INT32), NodeDefBuilder::NodeOut("in4", 0, DT_INT32)}) .Finalize(item.graph.add_node())); for (int i = 0; i < 4; ++i) { string concat_offset_out_name = strings::StrCat("concat_offset_out", i); TF_CHECK_OK(NodeDefBuilder(concat_offset_out_name, "Identity") .Attr("T", DT_INT32) .Input("concat_offsets", i, DT_INT32) .Finalize(item.graph.add_node())); outputs.push_back(concat_offset_out_name); } item.fetch = outputs; ConstantFolding fold(nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); int constant_folded = 0; for (const auto& node : output.node()) { if (node.name().find("part_out") != string::npos || node.name().find("concat_offset_out") != string::npos) { ++constant_folded; EXPECT_EQ("Const", node.op()); } } EXPECT_EQ(8, constant_folded); auto expected = EvaluateNodes(item.graph, outputs); auto optimized = EvaluateNodes(output, outputs); ASSERT_EQ(expected.size(), optimized.size()); for (int i = 0; i < expected.size(); ++i) { test::ExpectTensorEqual<int>(expected[i], optimized[i]); } } TEST_F(ConstantFoldingTest, ShapeMaterialization) { tensorflow::Scope scope = tensorflow::Scope::NewRootScope(); Output v1 = ops::Variable(scope.WithOpName("v1"), {3}, DT_FLOAT); Output v2 = ops::Variable(scope.WithOpName("v2"), {5, 7}, DT_FLOAT); Output v3 = ops::Variable(scope.WithOpName("v3"), {11, 13}, DT_FLOAT); Output rank = ops::Rank(scope.WithOpName("rank"), v1); Output shape = ops::Shape(scope.WithOpName("shape"), v2); Output size = ops::Size(scope.WithOpName("size"), v3); Output p1 = ops::Multiply(scope.WithOpName("p1"), size, rank); Output p2 = ops::Multiply(scope.WithOpName("p2"), p1, shape); GrapplerItem item; item.fetch.push_back("p2"); TF_CHECK_OK(scope.ToGraphDef(&item.graph)); ConstantFolding fold(nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); int found = 0; for (const auto& node : output.node()) { if (node.name() == "p2") { ++found; EXPECT_EQ("Const", node.op()); EXPECT_EQ(3, node.input_size()); EXPECT_EQ("^v3", node.input(0)); EXPECT_EQ("^v1", node.input(1)); EXPECT_EQ("^v2", node.input(2)); Tensor value; CHECK(value.FromProto(node.attr().at("value").tensor())); // rank = 1, shape = (5, 7), size = 143 = 11*13 // p2 = (715, 1001) = (5*143, 7*143) EXPECT_EQ(715, value.flat<int>()(0)); EXPECT_EQ(1001, value.flat<int>()(1)); } } EXPECT_EQ(1, found); } TEST_F(ConstantFoldingTest, ShapeMaterializationEmptyFetch) { tensorflow::Scope scope = tensorflow::Scope::NewRootScope(); Output v1 = ops::Variable(scope.WithOpName("v1"), {3}, DT_FLOAT); Output v2 = ops::Variable(scope.WithOpName("v2"), {5, 7}, DT_FLOAT); Output v3 = ops::Variable(scope.WithOpName("v3"), {11, 13}, DT_FLOAT); Output rank = ops::Rank(scope.WithOpName("rank"), v1); Output shape = ops::Shape(scope.WithOpName("shape"), v2); Output size = ops::Size(scope.WithOpName("size"), v3); Output p1 = ops::Multiply(scope.WithOpName("p1"), size, rank); Output p2 = ops::Multiply(scope.WithOpName("p2"), p1, shape); GrapplerItem item; TF_CHECK_OK(scope.ToGraphDef(&item.graph)); ConstantFolding fold(nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); int found = 0; for (const auto& node : output.node()) { if (node.name() == "size") { ++found; EXPECT_EQ("Const", node.op()); EXPECT_EQ(1, node.input_size()); EXPECT_EQ("^v3", node.input(0)); Tensor value; CHECK(value.FromProto(node.attr().at("value").tensor())); EXPECT_EQ(11 * 13, value.flat<int>()(0)); } else if (node.name() == "rank") { ++found; EXPECT_EQ("Const", node.op()); EXPECT_EQ(1, node.input_size()); EXPECT_EQ("^v1", node.input(0)); Tensor value; CHECK(value.FromProto(node.attr().at("value").tensor())); EXPECT_EQ(1, value.flat<int>()(0)); } else if (node.name() == "shape") { ++found; EXPECT_EQ("Const", node.op()); EXPECT_EQ(1, node.input_size()); EXPECT_EQ("^v2", node.input(0)); Tensor value; CHECK(value.FromProto(node.attr().at("value").tensor())); EXPECT_EQ(5, value.flat<int>()(0)); EXPECT_EQ(7, value.flat<int>()(1)); } } EXPECT_EQ(3, found); } TEST_F(ConstantFoldingTest, ShapeMaterializationShapeN) { tensorflow::Scope scope = tensorflow::Scope::NewRootScope(); Output v1 = ops::Variable(scope.WithOpName("v1"), {3, -1}, DT_FLOAT); Output v2 = ops::Variable(scope.WithOpName("v2"), {}, DT_FLOAT); Output v3 = ops::Variable(scope.WithOpName("v3"), {4, 6}, DT_FLOAT); auto s = ops::ShapeN(scope.WithOpName("s"), {v1, v2, v3}); Output i1a = ops::Identity(scope.WithOpName("i1a"), s[0]); Output i1b = ops::Identity(scope.WithOpName("i1b"), s[0]); Output i2a = ops::Identity(scope.WithOpName("i2a"), s[1]); Output i2b = ops::Identity(scope.WithOpName("i2b"), s[1]); Output i2c = ops::Identity(scope.WithOpName("i2c"), s[1]); Output i3a = ops::Identity(scope.WithOpName("i3a"), s[2]); Output i3b = ops::Identity(scope.WithOpName("i3b"), s[2]); GrapplerItem item; TF_CHECK_OK(scope.ToGraphDef(&item.graph)); ConstantFolding fold(nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); int found = 0; for (const auto& node : output.node()) { EXPECT_NE(AddPrefixToNodeName("s-0", kConstantFoldingConst), node.name()); EXPECT_NE(AddPrefixToNodeName("s-1", kConstantFoldingConst), node.name()); if (node.name() == "i1a" || node.name() == "i1b") { ++found; EXPECT_EQ("s", node.input(0)); } if (node.name() == "i2a" || node.name() == "i2b" || node.name() == "i2c") { ++found; EXPECT_EQ("s:1", node.input(0)); } if (node.name() == "i3a" || node.name() == "i3b") { ++found; EXPECT_EQ(AddPrefixToNodeName("s-2", kConstantFoldingConst), node.input(0)); } if (node.name() == "s") { ++found; EXPECT_EQ("ShapeN", node.op()); EXPECT_EQ("v1", node.input(0)); EXPECT_EQ("v2", node.input(1)); EXPECT_EQ("v3", node.input(2)); } if (node.name() == AddPrefixToNodeName("s-2", kConstantFoldingConst)) { ++found; EXPECT_EQ("Const", node.op()); EXPECT_EQ("^s", node.input(0)); Tensor value; CHECK(value.FromProto(node.attr().at("value").tensor())); EXPECT_EQ(4, value.flat<int>()(0)); EXPECT_EQ(6, value.flat<int>()(1)); } } EXPECT_EQ(9, found); } TEST_F(ConstantFoldingTest, SwitchNodesEmptyFetch) { tensorflow::Scope scope = tensorflow::Scope::NewRootScope(); ops::Variable v_in(scope.WithOpName("v_in"), {3}, DT_FLOAT); ops::Variable v_ctrl(scope.WithOpName("v_ctrl"), {}, DT_BOOL); ops::Switch s1(scope.WithOpName("switch"), v_in, v_ctrl); ops::Rank rank(scope.WithOpName("rank"), s1.output_false); ops::Identity i(scope.WithOpName("i"), s1.output_true); ops::Size size(scope.WithOpName("size"), i); ops::Square p1(scope.WithOpName("p1"), rank); ops::Square p2(scope.WithOpName("p2"), size); ops::Merge m(scope.WithOpName("m"), {p1.y, p2.y}); Output predicate = ops::Const(scope.WithOpName("false"), false, TensorShape({})); Output constant = ops::Const(scope.WithOpName("constant"), 1.0f, TensorShape({1})); ops::Switch s2(scope.WithOpName("switch2"), constant, predicate); ops::Identity statically_known(scope.WithOpName("i2"), s2.output_false); ops::Identity never_generated(scope.WithOpName("i3"), s2.output_true); ops::Merge m2(scope.WithOpName("m2"), {statically_known.output, never_generated.output}); GrapplerItem item; TF_CHECK_OK(scope.ToGraphDef(&item.graph)); ConstantFolding fold(nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); std::set<string> present_nodes = {"v_in", "v_ctrl", "switch", "i", "p1", "p2", "m", "false", "constant", "switch2", "i2", "i3", "m2", "ConstantFoldingCtrl/switch_0", "rank", "size"}; std::set<string> not_present_nodes = {"ConstantFolding/switch2-0"}; EXPECT_EQ(present_nodes.size(), output.node_size()); int found = 0; for (const auto& node : output.node()) { EXPECT_TRUE(present_nodes.find(node.name()) != present_nodes.end()); EXPECT_TRUE(not_present_nodes.find(node.name()) == not_present_nodes.end()); present_nodes.erase(node.name()); not_present_nodes.erase(node.name()); if (node.name() == "rank") { ++found; EXPECT_EQ("Const", node.op()); EXPECT_EQ(1, node.input_size()); EXPECT_EQ("^ConstantFoldingCtrl/switch_0", node.input(0)); } if (node.name() == "size") { ++found; EXPECT_EQ("Const", node.op()); EXPECT_EQ(1, node.input_size()); EXPECT_EQ("^i", node.input(0)); } if (node.name() == "i2") { ++found; EXPECT_EQ("Const", node.op()); EXPECT_EQ(0, node.input_size()); } if (node.name() == "i3") { ++found; EXPECT_EQ("Identity", node.op()); EXPECT_EQ(1, node.input_size()); EXPECT_EQ("switch2:1", node.input(0)); } } EXPECT_EQ(4, found); } TEST_F(ConstantFoldingTest, SwitchNodes) { tensorflow::Scope scope = tensorflow::Scope::NewRootScope(); ops::Variable v_in(scope.WithOpName("v_in"), {3}, DT_FLOAT); ops::Variable v_ctrl(scope.WithOpName("v_ctrl"), {}, DT_BOOL); ops::Switch s1(scope.WithOpName("switch"), v_in, v_ctrl); ops::Rank rank(scope.WithOpName("rank"), s1.output_false); ops::Identity i(scope.WithOpName("i"), s1.output_true); ops::Size size(scope.WithOpName("size"), i); ops::Square p1(scope.WithOpName("p1"), rank); ops::Square p2(scope.WithOpName("p2"), size); ops::Merge m(scope.WithOpName("m"), {p1.y, p2.y}); Output predicate = ops::Const(scope.WithOpName("false"), false, TensorShape({})); Output constant = ops::Const(scope.WithOpName("constant"), 1.0f, TensorShape({1})); ops::Switch s2(scope.WithOpName("switch2"), constant, predicate); ops::Identity statically_known(scope.WithOpName("i2"), s2.output_false); ops::Identity never_generated(scope.WithOpName("i3"), s2.output_true); ops::Merge m2(scope.WithOpName("m2"), {statically_known.output, never_generated.output}); GrapplerItem item; item.fetch.push_back("m"); item.fetch.push_back("m2"); TF_CHECK_OK(scope.ToGraphDef(&item.graph)); ConstantFolding fold(nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); std::set<string> present_nodes = {"v_in", "v_ctrl", "switch", "i", "p1", "p2", "m", "false", "constant", "switch2", "i2", "i3", "m2", "ConstantFoldingCtrl/switch_0"}; std::set<string> not_present_nodes = {"rank", "size", "ConstantFolding/switch2-0"}; EXPECT_EQ(present_nodes.size(), output.node_size()); int found = 0; for (const auto& node : output.node()) { EXPECT_TRUE(present_nodes.find(node.name()) != present_nodes.end()); EXPECT_TRUE(not_present_nodes.find(node.name()) == not_present_nodes.end()); present_nodes.erase(node.name()); not_present_nodes.erase(node.name()); if (node.name() == "i2") { ++found; EXPECT_EQ("Const", node.op()); EXPECT_EQ(0, node.input_size()); } if (node.name() == "i3") { ++found; EXPECT_EQ("Identity", node.op()); EXPECT_EQ(1, node.input_size()); EXPECT_EQ("switch2:1", node.input(0)); } } EXPECT_EQ(2, found); } TEST_F(ConstantFoldingTest, MergeNodes) { tensorflow::Scope scope = tensorflow::Scope::NewRootScope(); Output x = ops::RandomNormal(scope.WithOpName("x"), {3, 5}, DataType::DT_FLOAT); Output y = ops::RandomNormal(scope.WithOpName("y"), {3, 5}, DataType::DT_FLOAT); Output const1 = ops::Const(scope.WithOpName("const1").WithControlDependencies(x), 2.7f, TensorShape({3, 5})); Output const2 = ops::Const(scope.WithOpName("const2"), 3.14f, TensorShape({3, 5})); Output const3 = ops::Const(scope.WithOpName("const3").WithControlDependencies(x), 3.14f, TensorShape({3, 5})); // Create 3 merge nodes: m1 is foldable, m2 and m3 aren't. ops::Merge m1(scope.WithOpName("m1"), {x, const1, const2}); ops::Merge m2(scope.WithOpName("m2"), {const1, const3}); ops::Merge m3(scope.WithOpName("m3"), {x, y}); ops::Identity out1(scope.WithOpName("out1"), m1.output); ops::Identity idx1(scope.WithOpName("idx1"), m1.value_index); ops::Identity out2(scope.WithOpName("out2"), m2.output); ops::Identity idx2(scope.WithOpName("idx2"), m2.value_index); ops::Identity out3(scope.WithOpName("out3"), m3.output); ops::Identity idx3(scope.WithOpName("idx3"), m3.value_index); GrapplerItem item; item.fetch = {"out1", "idx1", "out2", "idx2", "out3", "idx3"}; TF_CHECK_OK(scope.ToGraphDef(&item.graph)); ConstantFolding fold(nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); int found_nodes = 0; for (const auto& node : output.node()) { if (node.name() == "out1") { EXPECT_EQ(1, node.input_size()); EXPECT_EQ("^m1", node.input(0)); ++found_nodes; } else if (node.name() == "idx1") { EXPECT_EQ(1, node.input_size()); EXPECT_EQ("^m1", node.input(0)); ++found_nodes; } else if (node.name() == "ConstantFolding/m1") { EXPECT_EQ("Const", node.op()); EXPECT_EQ(1, node.input_size()); EXPECT_EQ("^m1", node.input(0)); ++found_nodes; } else if (node.name() == "ConstantFolding/m1_index") { EXPECT_EQ("Const", node.op()); EXPECT_EQ(1, node.input_size()); EXPECT_EQ("^m1", node.input(0)); ++found_nodes; } else if (node.name() == "out2") { EXPECT_EQ(1, node.input_size()); EXPECT_EQ("m2", node.input(0)); ++found_nodes; } else if (node.name() == "idx2") { EXPECT_EQ(1, node.input_size()); EXPECT_EQ("m2:1", node.input(0)); ++found_nodes; } else if (node.name() == "out3") { EXPECT_EQ(1, node.input_size()); EXPECT_EQ("m3", node.input(0)); ++found_nodes; } else if (node.name() == "idx3") { EXPECT_EQ(1, node.input_size()); EXPECT_EQ("m3:1", node.input(0)); ++found_nodes; } } // Make sure the graph contains all the nodes we're expecting. EXPECT_EQ(6, found_nodes); std::vector<string> fetch = {"out1", "idx1"}; auto tensors = EvaluateNodes(output, fetch); EXPECT_EQ(2, tensors.size()); const Tensor& out_value = tensors[0]; EXPECT_EQ(3 * 5, out_value.NumElements()); for (int i = 0; i < 3 * 5; ++i) { EXPECT_EQ(3.14f, out_value.flat<float>()(i)); } const Tensor& out_idx = tensors[1]; EXPECT_EQ(1, out_idx.NumElements()); EXPECT_EQ(2, out_idx.flat<int32>()(0)); } TEST_F(ConstantFoldingTest, NoOpReduction) { // Build a simple graph with a reduction that can be reduced to the identity. tensorflow::Scope scope = tensorflow::Scope::NewRootScope(); Output v = ops::Variable(scope.WithOpName("v"), {3, 5, 7}, DT_FLOAT); Output c = ops::Const(scope.WithOpName("c").WithControlDependencies(v), 0, {0}); Output i = ops::Identity(scope.WithOpName("i"), c); Output p = ops::Prod(scope.WithOpName("p"), v, i); Output s = ops::Square(scope.WithOpName("s"), p); GrapplerItem item; item.fetch.push_back("s"); TF_CHECK_OK(scope.ToGraphDef(&item.graph)); ConstantFolding fold(nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); bool found = false; for (const auto& node : output.node()) { if (node.name() == "p") { found = true; EXPECT_EQ("Identity", node.op()); EXPECT_EQ(2, node.input_size()); EXPECT_EQ("v", node.input(0)); EXPECT_EQ("^i", node.input(1)); } } EXPECT_TRUE(found); } TEST_F(ConstantFoldingTest, NoOpReshape) { // Build a simple graph with a reshape that can be reduced to the identity. tensorflow::Scope scope = tensorflow::Scope::NewRootScope(); // A reshape than can be optimized Output d1 = ops::Const(scope.WithOpName("d1"), 3.14f, {17}); Output v1 = ops::Variable(scope.WithOpName("v1"), {17}, DT_FLOAT); Output c1 = ops::Const(scope.WithOpName("c1").WithControlDependencies(v1), 17, {1}); Output i1 = ops::Identity(scope.WithOpName("i1"), c1); Output r1 = ops::Reshape(scope.WithOpName("r1").WithControlDependencies(d1), v1, i1); Output s1 = ops::Square(scope.WithOpName("s1"), r1); // A multi dimensional reshape than can be optimized Output v3 = ops::Variable(scope.WithOpName("v3"), {5, 5, 5}, DT_FLOAT); Output c3 = ops::Const(scope.WithOpName("c3").WithControlDependencies(v3), 5, {3}); Output i3 = ops::Identity(scope.WithOpName("i3"), c3); Output r3 = ops::Reshape(scope.WithOpName("r3"), v3, i3); Output s3 = ops::Square(scope.WithOpName("s3"), r3); // A multi dimensional partially defined reshape than can be optimized Output v4 = ops::Variable(scope.WithOpName("v4"), {5, 5, 5}, DT_FLOAT); Output c4 = ops::Const(scope.WithOpName("c4").WithControlDependencies(v4), {5, -1, 5}, {3}); Output i4 = ops::Identity(scope.WithOpName("i4"), c4); Output r4 = ops::Reshape(scope.WithOpName("r4"), v4, i4); Output s4 = ops::Square(scope.WithOpName("s4"), r4); // A reshape that can't be optimized Output v2 = ops::Variable(scope.WithOpName("v2"), {17, 1}, DT_FLOAT); Output c2 = ops::Const(scope.WithOpName("c2").WithControlDependencies(v2), 17, {1}); Output r2 = ops::Reshape(scope.WithOpName("r2"), v2, c2); Output s2 = ops::Square(scope.WithOpName("s2"), r2); GrapplerItem item; item.fetch = {"s1", "s2", "s3", "s4"}; TF_CHECK_OK(scope.ToGraphDef(&item.graph)); ConstantFolding fold(nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); int found = 0; for (const auto& node : output.node()) { if (node.name() == "r1") { ++found; EXPECT_EQ("Identity", node.op()); ASSERT_EQ(3, node.input_size()); EXPECT_EQ("v1", node.input(0)); EXPECT_EQ("^i1", node.input(1)); EXPECT_EQ("^d1", node.input(2)); } else if (node.name() == "r3") { ++found; EXPECT_EQ("Identity", node.op()); ASSERT_EQ(2, node.input_size()); EXPECT_EQ("v3", node.input(0)); EXPECT_EQ("^i3", node.input(1)); } else if (node.name() == "r4") { ++found; EXPECT_EQ("Identity", node.op()); ASSERT_EQ(2, node.input_size()); EXPECT_EQ("v4", node.input(0)); EXPECT_EQ("^i4", node.input(1)); } else if (node.name() == "r2") { ++found; EXPECT_EQ("Reshape", node.op()); ASSERT_EQ(2, node.input_size()); EXPECT_EQ("v2", node.input(0)); EXPECT_EQ("c2", node.input(1)); } } EXPECT_EQ(4, found); } TEST_F(ConstantFoldingTest, Packing) { // Build a simple graph with a large constant that can be folded. tensorflow::Scope scope = tensorflow::Scope::NewRootScope(); Output c = ops::Const(scope.WithOpName("c"), 3.14f, {1000}); Output i1 = ops::Identity(scope.WithOpName("i1"), c); Output i2 = ops::Identity(scope.WithOpName("i2"), c); GrapplerItem item; TF_CHECK_OK(scope.ToGraphDef(&item.graph)); ConstantFolding fold(nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); // Make sure that the representation of the folded constant is space // efficient: in particular, the whole message should be smaller than 8k (the // size needed to naively encode 1000 floats folded twice). EXPECT_GT(8000, output.ByteSizeLong()); } TEST_F(ConstantFoldingTest, MaterializeBroadcastGradientArgs) { tensorflow::Scope s = tensorflow::Scope::NewRootScope(); Output a = ops::Placeholder(s.WithOpName("a"), DT_FLOAT, ops::Placeholder::Shape(PartialTensorShape({-1, -1}))); Output b = ops::Square(s.WithOpName("b"), a); Output c = ops::Mul(s.WithOpName("c"), a, b); Output d = ops::Shape(s.WithOpName("d"), a); Output e = ops::Shape(s.WithOpName("e"), b); auto f = ops::internal::BroadcastGradientArgs(s.WithOpName("f"), d, e); Output o1 = ops::Identity(s.WithOpName("o1"), f.r0); Output o2 = ops::Identity(s.WithOpName("o2"), f.r1); Output g = ops::Placeholder(s.WithOpName("g"), DT_FLOAT, ops::Placeholder::Shape(PartialTensorShape({1}))); Output h = ops::Shape(s.WithOpName("h"), g); auto i = ops::internal::BroadcastGradientArgs(s.WithOpName("i"), d, h); Output p1 = ops::Identity(s.WithOpName("p1"), i.r0); Output p2 = ops::Identity(s.WithOpName("p2"), i.r1); GrapplerItem item; TF_CHECK_OK(s.ToGraphDef(&item.graph)); ConstantFolding fold(RewriterConfig::AGGRESSIVE, nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); // Run a second time to make sure the optimization is idempotent. item.graph.Swap(&output); status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); int found = 0; for (const auto& node : output.node()) { if (node.name() == "o1") { ++found; EXPECT_EQ(1, node.input_size()); EXPECT_EQ("ConstantFolding/f-0", node.input(0)); } else if (node.name() == "o2") { ++found; EXPECT_EQ(1, node.input_size()); EXPECT_EQ("ConstantFolding/f-1", node.input(0)); } else if (node.name() == "ConstantFolding/f-0") { ++found; EXPECT_EQ("Const", node.op()); EXPECT_EQ(1, node.input_size()); EXPECT_EQ("^f", node.input(0)); EXPECT_EQ(0, TensorShape(node.attr().at("value").tensor().tensor_shape()) .num_elements()); } else if (node.name() == "ConstantFolding/f-1") { ++found; EXPECT_EQ("Const", node.op()); EXPECT_EQ(1, node.input_size()); EXPECT_EQ("^f", node.input(0)); EXPECT_EQ(0, TensorShape(node.attr().at("value").tensor().tensor_shape()) .num_elements()); } else if (node.name() == "p1") { ++found; EXPECT_EQ(1, node.input_size()); EXPECT_EQ("ConstantFolding/i-0", node.input(0)); } else if (node.name() == "p2") { ++found; EXPECT_EQ(1, node.input_size()); EXPECT_EQ("i:1", node.input(0)); } else if (node.name() == "ConstantFolding/i-0") { ++found; EXPECT_EQ("Const", node.op()); EXPECT_EQ(1, node.input_size()); EXPECT_EQ("^i", node.input(0)); EXPECT_EQ(0, TensorShape(node.attr().at("value").tensor().tensor_shape()) .num_elements()); } } EXPECT_EQ(7, found); } TEST_F(ConstantFoldingTest, MaterializeReductionIndices) { tensorflow::Scope s = tensorflow::Scope::NewRootScope(); Output input = ops::Placeholder(s.WithOpName("input"), DT_FLOAT, ops::Placeholder::Shape(PartialTensorShape({-1, -1}))); Output indices = ops::Placeholder(s.WithOpName("indices"), DT_INT32); Output sum = ops::Sum(s.WithOpName("sum"), input, indices); Output size = ops::Const(s.WithOpName("size"), 1, {1}); Output reshape = ops::Reshape(s.WithOpName("reshape"), sum, size); GrapplerItem item; TF_CHECK_OK(s.ToGraphDef(&item.graph)); item.fetch.push_back("reshape"); ConstantFolding fold(RewriterConfig::AGGRESSIVE, nullptr /* cpu_device */); GraphDef output; Status status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); // Run a second time to make sure the optimization is idempotent. item.graph.Swap(&output); status = fold.Optimize(nullptr, item, &output); TF_EXPECT_OK(status); int found = 0; for (const auto& node : output.node()) { if (node.name() == "ConstantFolding/sum-reduction_indices") { ++found; EXPECT_EQ("Const", node.op()); EXPECT_EQ("^indices", node.input(0)); EXPECT_EQ(2, TensorShape(node.attr().at("value").tensor().tensor_shape()) .num_elements()); } else if (node.name() == "sum") { ++found; EXPECT_EQ("ConstantFolding/sum-reduction_indices", node.input(1)); } else if (node.name() == "indices") { ++found; } } EXPECT_EQ(3, found); } } // namespace } // namespace grappler } // namespace tensorflow // LocalWords: NewRootScope
.global s_prepare_buffers s_prepare_buffers: push %r12 push %r13 push %r8 push %rax push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0x6ed6, %r12 sub $47749, %rax mov $0x6162636465666768, %rdx movq %rdx, %xmm2 vmovups %ymm2, (%r12) nop nop add %r13, %r13 lea addresses_A_ht+0x6496, %rsi lea addresses_D_ht+0x7f56, %rdi nop nop sub %r8, %r8 mov $47, %rcx rep movsq nop nop nop add $32199, %rsi lea addresses_D_ht+0x90d6, %rdx nop nop nop nop add $24598, %rsi mov $0x6162636465666768, %rdi movq %rdi, (%rdx) nop nop nop nop sub %r8, %r8 pop %rsi pop %rdx pop %rdi pop %rcx pop %rax pop %r8 pop %r13 pop %r12 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r14 push %r15 push %rax push %rdx // Store lea addresses_A+0x1056, %rax nop nop nop nop xor $10127, %r14 mov $0x5152535455565758, %r15 movq %r15, %xmm2 movups %xmm2, (%rax) add $15413, %r14 // Faulty Load lea addresses_WT+0x1f796, %rdx nop nop nop nop nop inc %r15 vmovups (%rdx), %ymm7 vextracti128 $0, %ymm7, %xmm7 vpextrq $1, %xmm7, %r14 lea oracles, %r12 and $0xff, %r14 shlq $12, %r14 mov (%r12,%r14,1), %r14 pop %rdx pop %rax pop %r15 pop %r14 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'NT': False, 'AVXalign': False, 'size': 2, 'type': 'addresses_WT', 'congruent': 0}} {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 16, 'type': 'addresses_A', 'congruent': 0}, 'OP': 'STOR'} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_WT', 'congruent': 0}} <gen_prepare_buffer> {'dst': {'same': False, 'NT': False, 'AVXalign': False, 'size': 32, 'type': 'addresses_WT_ht', 'congruent': 6}, 'OP': 'STOR'} {'dst': {'same': False, 'congruent': 4, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'src': {'same': False, 'congruent': 7, 'type': 'addresses_A_ht'}} {'dst': {'same': True, 'NT': False, 'AVXalign': False, 'size': 8, 'type': 'addresses_D_ht', 'congruent': 6}, 'OP': 'STOR'} {'39': 21829} 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 39 */
; A007401: Add n-1 to n-th term of 'n appears n times' sequence (A002024). ; 1,3,4,6,7,8,10,11,12,13,15,16,17,18,19,21,22,23,24,25,26,28,29,30,31,32,33,34,36,37,38,39,40,41,42,43,45,46,47,48,49,50,51,52,53,55,56,57,58,59,60,61,62,63,64,66,67,68,69,70,71,72,73,74,75,76,78,79,80,81,82,83,84,85,86,87,88,89,91,92,93,94,95,96,97,98,99,100,101,102,103,105,106,107,108,109,110,111,112,113,114,115,116,117,118,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,136,137,138,139,140,141,142,143,144,145,146,147,148,149,150,151,153,154,155,156,157,158,159,160,161,162,163,164,165,166,167,168,169,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271 mov $1,1 mov $2,$0 lpb $0 add $1,1 trn $0,$1 lpe add $1,$2
; A143157: Partial sums of A091512. ; 0,1,5,8,20,25,37,44,76,85,105,116,152,165,193,208,288,305,341,360,420,441,485,508,604,629,681,708,792,821,881,912,1104,1137,1205,1240,1348,1385,1461,1500,1660,1701,1785,1828,1960,2005,2097,2144,2384,2433,2533,2584,2740,2793,2901,2956,3180,3237,3353,3412,3592,3653,3777,3840,4288,4353,4485,4552,4756,4825,4965,5036,5324,5397,5545,5620,5848,5925,6081,6160,6560,6641,6805,6888,7140,7225,7397,7484,7836,7925,8105,8196,8472,8565,8753,8848,9424,9521,9717,9816,10116,10217,10421,10524,10940,11045,11257,11364,11688,11797,12017,12128,12688,12801,13029,13144,13492,13609,13845,13964,14444,14565,14809,14932,15304,15429,15681,15808,16832,16961,17221,17352,17748,17881,18149,18284,18828,18965,19241,19380,19800,19941,20225,20368,21088,21233,21525,21672,22116,22265,22565,22716,23324,23477,23785,23940,24408,24565,24881,25040,26000,26161,26485,26648,27140,27305,27637,27804,28476,28645,28985,29156,29672,29845,30193,30368,31248,31425,31781,31960,32500,32681,33045,33228,33964,34149,34521,34708,35272,35461,35841,36032,37376,37569,37957,38152,38740,38937,39333,39532,40332,40533,40937,41140,41752,41957,42369,42576,43616,43825,44245,44456,45092,45305,45733,45948,46812,47029,47465,47684,48344,48565,49009,49232,50576,50801,51253,51480,52164,52393,52853,53084,54012,54245,54713,54948,55656,55893,56369,56608,57808,58049,58533,58776,59508,59753,60245,60492,61484,61733 mov $18,$0 mov $20,$0 lpb $20,1 clr $0,18 mov $0,$18 sub $20,1 sub $0,$20 mov $1,$0 mul $0,1331 add $1,$0 pow $0,2 gcd $0,281474976710656 add $3,$0 lpb $3,1 div $3,4 add $17,$1 lpe mov $1,$17 div $1,1332 add $19,$1 lpe mov $1,$19
; A067471: n-th root of A067470(n). ; 1,4,5,6,7,7,8,8,8,8,9,9,9,9,9,9,9,9,9,9,9 mov $1,$0 mul $0,9 div $0,2 mov $3,17 lpb $3 add $2,$1 add $0,$2 sub $3,3 lpe div $0,2 add $1,2 div $0,$1 add $0,1
; ; Copyright (c) 2008-2020 Stefan Krah. All rights reserved. ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions ; are met: ; ; 1. Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; ; 2. Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in the ; documentation and/or other materials provided with the distribution. ; ; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. ; PUBLIC _mpd_div_words _TEXT SEGMENT q$ = 8 r$ = 16 hi$ = 24 lo$ = 32 d$ = 40 _mpd_div_words PROC mov r10, rdx mov rdx, r8 mov rax, r9 div QWORD PTR d$[rsp] mov QWORD PTR [r10], rdx mov QWORD PTR [rcx], rax ret 0 _mpd_div_words ENDP _TEXT ENDS END
;-----------------------------------------------------------------------------; ; Author: Stephen Fewer (stephen_fewer[at]harmonysecurity[dot]com) ; Compatible: Windows 7, 2003 ; Size: 505 bytes ; Build: >build.py single_shell_bind_tcp ;-----------------------------------------------------------------------------; [BITS 64] [ORG 0] cld ; Clear the direction flag. and rsp, 0xFFFFFFFFFFFFFFF0 ; Ensure RSP is 16 byte aligned call start ; Call start, this pushes the address of 'api_call' onto the stack. %include "./src/block/block_api.asm" start: ; pop rbp ; Pop off the address of 'api_call' for calling later. %include "./src/block/block_bind_tcp.asm" ; By here we will have performed the bind_tcp connection and EDI will be out socket. %include "./src/block/block_shell.asm" ; Finish up with the EXITFUNK. %include "./src/block/block_exitfunk.asm"
#include "gtest/gtest.h" #include <Core/Matrix/Matrix.hpp> using namespace CubbyFlow; TEST(Vector, Constructors) { Vector<double, 5> vec1; EXPECT_DOUBLE_EQ(0.0, vec1[0]); EXPECT_DOUBLE_EQ(0.0, vec1[1]); EXPECT_DOUBLE_EQ(0.0, vec1[2]); EXPECT_DOUBLE_EQ(0.0, vec1[3]); EXPECT_DOUBLE_EQ(0.0, vec1[4]); Vector<double, 5> vec2({ 1.0, 2.0, 3.0, 4.0, 5.0 }); EXPECT_DOUBLE_EQ(1.0, vec2[0]); EXPECT_DOUBLE_EQ(2.0, vec2[1]); EXPECT_DOUBLE_EQ(3.0, vec2[2]); EXPECT_DOUBLE_EQ(4.0, vec2[3]); EXPECT_DOUBLE_EQ(5.0, vec2[4]); Vector<double, 5> vec3(vec2); EXPECT_DOUBLE_EQ(1.0, vec3[0]); EXPECT_DOUBLE_EQ(2.0, vec3[1]); EXPECT_DOUBLE_EQ(3.0, vec3[2]); EXPECT_DOUBLE_EQ(4.0, vec3[3]); EXPECT_DOUBLE_EQ(5.0, vec3[4]); } TEST(Vector, BasicSetters) { Vector<double, 5> vec{ 1.0, 2.0, 3.0, 4.0, 5.0 }; vec.Fill(0.0); for (int i = 0; i < 5; ++i) { EXPECT_DOUBLE_EQ(0.0, vec[i]); } vec.Fill(4.0); for (int i = 0; i < 5; ++i) { EXPECT_DOUBLE_EQ(4.0, vec[i]); } vec.Fill([](size_t i) -> double { return i * 5.0; }); for (int i = 0; i < 5; ++i) { EXPECT_DOUBLE_EQ(i * 5.0, vec[i]); } vec.Fill([](size_t i, size_t j) -> double { return i + 8.0 * (j + 1); }); for (int i = 0; i < 5; ++i) { EXPECT_DOUBLE_EQ(i + 8.0, vec[i]); } Vector<double, 5> vec2{ 5.0, 4.0, 3.0, 2.0, 1.0 }; vec.Swap(vec2); for (int i = 0; i < 5; ++i) { EXPECT_DOUBLE_EQ(5.0 - i, vec[i]); EXPECT_DOUBLE_EQ(i + 8.0, vec2[i]); } vec.Normalize(); double len = 0.0; for (int i = 0; i < 5; ++i) { len += vec[i] * vec[i]; } EXPECT_NEAR(1.0, len, 1e-10); } TEST(Vector, BasicGetters) { Vector<double, 4> vecA = { +3.0, -1.0, +2.0, 5.0 }; EXPECT_EQ(4u, vecA.GetRows()); EXPECT_EQ(1u, vecA.GetCols()); const double* data = vecA.data(); EXPECT_EQ(3.0, data[0]); EXPECT_EQ(-1.0, data[1]); EXPECT_EQ(2.0, data[2]); EXPECT_EQ(5.0, data[3]); double* data2 = vecA.data(); data2[0] = 6.0; data2[1] = 2.5; data2[2] = -9.0; data2[3] = 8.0; EXPECT_EQ(+6.0, vecA[0]); EXPECT_EQ(+2.5, vecA[1]); EXPECT_EQ(-9.0, vecA[2]); EXPECT_EQ(+8.0, vecA[3]); const auto iter = vecA.begin(); EXPECT_EQ(+6.0, iter[0]); EXPECT_EQ(+2.5, iter[1]); EXPECT_EQ(-9.0, iter[2]); EXPECT_EQ(+8.0, iter[3]); vecA = { +3.0, -1.0, +2.0, 5.0 }; auto iter2 = vecA.begin(); iter2[0] = 6.0; iter2[1] = 2.5; iter2[2] = -9.0; iter2[3] = 8.0; EXPECT_EQ(+6.0, iter2[0]); EXPECT_EQ(+2.5, iter2[1]); EXPECT_EQ(-9.0, iter2[2]); EXPECT_EQ(+8.0, iter2[3]); auto d = vecA.end() - vecA.begin(); EXPECT_EQ(4, d); EXPECT_EQ(7.5, vecA.Sum()); EXPECT_EQ(7.5 / 4.0, vecA.Avg()); EXPECT_EQ(-9.0, vecA.Min()); EXPECT_EQ(8.0, vecA.Max()); EXPECT_EQ(2.5, vecA.AbsMin()); EXPECT_EQ(-9.0, vecA.AbsMax()); EXPECT_EQ(2u, vecA.DominantAxis()); EXPECT_EQ(1u, vecA.SubdominantAxis()); auto vecB = vecA; Vector<double, 4> vecC = vecB.Normalized(); vecA.Normalize(); for (size_t i = 0; i < vecA.GetRows(); ++i) { EXPECT_EQ(vecA[i], vecC[i]); } vecA[0] = 6.0; vecA[1] = 2.5; vecA[2] = -9.0; vecA[3] = 8.0; double lenSqr = vecA.LengthSquared(); EXPECT_EQ(187.25, lenSqr); double len = vecA.Length(); EXPECT_EQ(std::sqrt(187.25), len); vecA = { +3.0, -1.0, +2.0, 5.0 }; vecB = { +6.0, +2.5, -9.0, 8.0 }; double distSq = vecA.DistanceSquaredTo(vecB); EXPECT_EQ(151.25, distSq); double dist = vecA.DistanceTo(vecB); EXPECT_EQ(std::sqrt(151.25), dist); Vector<float, 4> vecD = vecA.CastTo<float>(); EXPECT_EQ(+3.f, vecD[0]); EXPECT_EQ(-1.f, vecD[1]); EXPECT_EQ(+2.f, vecD[2]); EXPECT_EQ(+5.f, vecD[3]); } TEST(Vector, BinaryOperators) { Vector<double, 4> vecA = { +3.0, -1.0, +2.0, 5.0 }; Vector<double, 4> vecB = { +6.0, +2.5, -9.0, 8.0 }; Vector<double, 4> vecC = vecA + vecB; EXPECT_EQ(+9.0, vecC[0]); EXPECT_EQ(+1.5, vecC[1]); EXPECT_EQ(-7.0, vecC[2]); EXPECT_EQ(13.0, vecC[3]); vecC = vecA + 3.0; EXPECT_EQ(+6.0, vecC[0]); EXPECT_EQ(+2.0, vecC[1]); EXPECT_EQ(+5.0, vecC[2]); EXPECT_EQ(+8.0, vecC[3]); vecC = 2.0 + vecA; EXPECT_EQ(+5.0, vecC[0]); EXPECT_EQ(+1.0, vecC[1]); EXPECT_EQ(+4.0, vecC[2]); EXPECT_EQ(+7.0, vecC[3]); vecC = vecA - vecB; EXPECT_EQ(-3.0, vecC[0]); EXPECT_EQ(-3.5, vecC[1]); EXPECT_EQ(11.0, vecC[2]); EXPECT_EQ(-3.0, vecC[3]); vecC = 6.0 - vecA; EXPECT_EQ(+3.0, vecC[0]); EXPECT_EQ(+7.0, vecC[1]); EXPECT_EQ(+4.0, vecC[2]); EXPECT_EQ(+1.0, vecC[3]); vecC = vecA - 4.0; EXPECT_EQ(-1.0, vecC[0]); EXPECT_EQ(-5.0, vecC[1]); EXPECT_EQ(-2.0, vecC[2]); EXPECT_EQ(+1.0, vecC[3]); vecC = ElemMul(vecA, vecB); EXPECT_EQ(18.0, vecC[0]); EXPECT_EQ(-2.5, vecC[1]); EXPECT_EQ(-18.0, vecC[2]); EXPECT_EQ(40.0, vecC[3]); vecC = vecA * 2.0; EXPECT_EQ(+6.0, vecC[0]); EXPECT_EQ(-2.0, vecC[1]); EXPECT_EQ(+4.0, vecC[2]); EXPECT_EQ(10.0, vecC[3]); vecC = ElemDiv(vecA, vecB); EXPECT_EQ(+0.5, vecC[0]); EXPECT_EQ(-0.4, vecC[1]); EXPECT_EQ(-2.0 / 9.0, vecC[2]); EXPECT_EQ(0.625, vecC[3]); vecC = vecA / 0.5; EXPECT_EQ(+6.0, vecC[0]); EXPECT_EQ(-2.0, vecC[1]); EXPECT_EQ(+4.0, vecC[2]); EXPECT_EQ(10.0, vecC[3]); vecC = 2.0 / vecA; EXPECT_EQ(+2.0 / 3.0, vecC[0]); EXPECT_EQ(-2.0, vecC[1]); EXPECT_EQ(+1.0, vecC[2]); EXPECT_EQ(+0.4, vecC[3]); vecC = 3.0 / (0.5 * vecA + 2.0 * vecB); EXPECT_EQ(3.0 / 13.5, vecC[0]); EXPECT_EQ(2.0 / 3.0, vecC[1]); EXPECT_EQ(3.0 / -17.0, vecC[2]); EXPECT_EQ(3.0 / 18.5, vecC[3]); }
export Com_Clamp code proc Com_Clamp 0 0 ADDRFP4 8 ADDRFP4 8 INDIRF4 ASGNF4 ADDRFP4 8 INDIRF4 ADDRFP4 0 INDIRF4 GEF4 $24 ADDRFP4 0 INDIRF4 RETF4 ADDRGP4 $23 JUMPV LABELV $24 ADDRFP4 8 INDIRF4 ADDRFP4 4 INDIRF4 LEF4 $26 ADDRFP4 4 INDIRF4 RETF4 ADDRGP4 $23 JUMPV LABELV $26 ADDRFP4 8 INDIRF4 RETF4 LABELV $23 endproc Com_Clamp 0 0 export COM_SkipPath proc COM_SkipPath 4 0 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRLP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRGP4 $30 JUMPV LABELV $29 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 47 NEI4 $32 ADDRLP4 0 ADDRFP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $32 ADDRFP4 0 ADDRFP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $30 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $29 ADDRLP4 0 INDIRP4 RETP4 LABELV $28 endproc COM_SkipPath 4 0 export COM_GetExtension proc COM_GetExtension 16 8 ADDRFP4 0 INDIRP4 ARGP4 CNSTI4 46 ARGI4 ADDRLP4 8 ADDRGP4 qk_strrchr CALLP4 ASGNP4 ADDRLP4 0 ADDRLP4 8 INDIRP4 ASGNP4 ADDRLP4 0 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $35 ADDRFP4 0 INDIRP4 ARGP4 CNSTI4 47 ARGI4 ADDRLP4 12 ADDRGP4 qk_strrchr CALLP4 ASGNP4 ADDRLP4 4 ADDRLP4 12 INDIRP4 ASGNP4 ADDRLP4 12 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $37 ADDRLP4 4 INDIRP4 CVPU4 4 ADDRLP4 0 INDIRP4 CVPU4 4 GEU4 $35 LABELV $37 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 RETP4 ADDRGP4 $34 JUMPV LABELV $35 ADDRGP4 $38 RETP4 LABELV $34 endproc COM_GetExtension 16 8 export COM_StripExtension proc COM_StripExtension 20 12 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 8 ADDRFP4 8 INDIRI4 ASGNI4 ADDRFP4 0 INDIRP4 ARGP4 CNSTI4 46 ARGI4 ADDRLP4 8 ADDRGP4 qk_strrchr CALLP4 ASGNP4 ADDRLP4 0 ADDRLP4 8 INDIRP4 ASGNP4 ADDRLP4 0 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $40 ADDRFP4 0 INDIRP4 ARGP4 CNSTI4 47 ARGI4 ADDRLP4 12 ADDRGP4 qk_strrchr CALLP4 ASGNP4 ADDRLP4 4 ADDRLP4 12 INDIRP4 ASGNP4 ADDRLP4 12 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $42 ADDRLP4 4 INDIRP4 CVPU4 4 ADDRLP4 0 INDIRP4 CVPU4 4 GEU4 $40 LABELV $42 ADDRFP4 8 INDIRI4 ADDRLP4 0 INDIRP4 CVPU4 4 ADDRFP4 0 INDIRP4 CVPU4 4 SUBU4 CVUI4 4 CNSTI4 1 ADDI4 GEI4 $44 ADDRLP4 16 ADDRFP4 8 INDIRI4 ASGNI4 ADDRGP4 $45 JUMPV LABELV $44 ADDRLP4 16 ADDRLP4 0 INDIRP4 CVPU4 4 ADDRFP4 0 INDIRP4 CVPU4 4 SUBU4 CVUI4 4 CNSTI4 1 ADDI4 ASGNI4 LABELV $45 ADDRFP4 8 ADDRLP4 16 INDIRI4 ASGNI4 LABELV $40 ADDRFP4 0 INDIRP4 CVPU4 4 ADDRFP4 4 INDIRP4 CVPU4 4 NEU4 $46 ADDRFP4 8 INDIRI4 CNSTI4 1 LEI4 $46 ADDRFP4 8 INDIRI4 CNSTI4 1 SUBI4 ADDRFP4 4 INDIRP4 ADDP4 CNSTI1 0 ASGNI1 ADDRGP4 $47 JUMPV LABELV $46 ADDRFP4 4 INDIRP4 ARGP4 ADDRFP4 0 INDIRP4 ARGP4 ADDRFP4 8 INDIRI4 ARGI4 ADDRGP4 Q_strncpyz CALLV pop LABELV $47 LABELV $39 endproc COM_StripExtension 20 12 export COM_CompareExtension proc COM_CompareExtension 20 8 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 8 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRLP4 0 ADDRLP4 8 INDIRU4 CVUI4 4 ASGNI4 ADDRFP4 4 INDIRP4 ARGP4 ADDRLP4 12 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRLP4 4 ADDRLP4 12 INDIRU4 CVUI4 4 ASGNI4 ADDRLP4 4 INDIRI4 ADDRLP4 0 INDIRI4 GTI4 $49 ADDRFP4 0 ADDRLP4 0 INDIRI4 ADDRLP4 4 INDIRI4 SUBI4 ADDRFP4 0 INDIRP4 ADDP4 ASGNP4 ADDRFP4 0 INDIRP4 ARGP4 ADDRFP4 4 INDIRP4 ARGP4 ADDRLP4 16 ADDRGP4 Q_stricmp CALLI4 ASGNI4 ADDRLP4 16 INDIRI4 CNSTI4 0 NEI4 $51 CNSTI4 1 RETI4 ADDRGP4 $48 JUMPV LABELV $51 LABELV $49 CNSTI4 0 RETI4 LABELV $48 endproc COM_CompareExtension 20 8 export COM_DefaultExtension proc COM_DefaultExtension 16 12 ADDRFP4 0 INDIRP4 ARGP4 CNSTI4 46 ARGI4 ADDRLP4 8 ADDRGP4 qk_strrchr CALLP4 ASGNP4 ADDRLP4 0 ADDRLP4 8 INDIRP4 ASGNP4 ADDRLP4 0 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $54 ADDRFP4 0 INDIRP4 ARGP4 CNSTI4 47 ARGI4 ADDRLP4 12 ADDRGP4 qk_strrchr CALLP4 ASGNP4 ADDRLP4 4 ADDRLP4 12 INDIRP4 ASGNP4 ADDRLP4 12 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $56 ADDRLP4 4 INDIRP4 CVPU4 4 ADDRLP4 0 INDIRP4 CVPU4 4 GEU4 $54 LABELV $56 ADDRGP4 $53 JUMPV LABELV $54 ADDRFP4 0 INDIRP4 ARGP4 ADDRFP4 4 INDIRI4 ARGI4 ADDRFP4 8 INDIRP4 ARGP4 ADDRGP4 Q_strcat CALLV pop LABELV $53 endproc COM_DefaultExtension 16 12 export CopyShortSwap proc CopyShortSwap 8 0 ADDRLP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRLP4 4 ADDRFP4 4 INDIRP4 ASGNP4 ADDRLP4 0 INDIRP4 ADDRLP4 4 INDIRP4 CNSTI4 1 ADDP4 INDIRU1 ASGNU1 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ADDRLP4 4 INDIRP4 INDIRU1 ASGNU1 LABELV $57 endproc CopyShortSwap 8 0 export CopyLongSwap proc CopyLongSwap 8 0 ADDRLP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRLP4 4 ADDRFP4 4 INDIRP4 ASGNP4 ADDRLP4 0 INDIRP4 ADDRLP4 4 INDIRP4 CNSTI4 3 ADDP4 INDIRU1 ASGNU1 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ADDRLP4 4 INDIRP4 CNSTI4 2 ADDP4 INDIRU1 ASGNU1 ADDRLP4 0 INDIRP4 CNSTI4 2 ADDP4 ADDRLP4 4 INDIRP4 CNSTI4 1 ADDP4 INDIRU1 ASGNU1 ADDRLP4 0 INDIRP4 CNSTI4 3 ADDP4 ADDRLP4 4 INDIRP4 INDIRU1 ASGNU1 LABELV $58 endproc CopyLongSwap 8 0 export ShortSwap proc ShortSwap 16 0 ADDRFP4 0 ADDRFP4 0 INDIRI4 CVII2 4 ASGNI2 ADDRLP4 4 ADDRFP4 0 INDIRI2 CVII4 2 ASGNI4 ADDRLP4 8 CNSTI4 255 ASGNI4 ADDRLP4 0 ADDRLP4 4 INDIRI4 ADDRLP4 8 INDIRI4 BANDI4 CVIU4 4 CVUU1 4 ASGNU1 ADDRLP4 12 CNSTI4 8 ASGNI4 ADDRLP4 1 ADDRLP4 4 INDIRI4 ADDRLP4 12 INDIRI4 RSHI4 ADDRLP4 8 INDIRI4 BANDI4 CVIU4 4 CVUU1 4 ASGNU1 ADDRLP4 0 INDIRU1 CVUI4 1 ADDRLP4 12 INDIRI4 LSHI4 ADDRLP4 1 INDIRU1 CVUI4 1 ADDI4 CVII2 4 CVII4 2 RETI4 LABELV $59 endproc ShortSwap 16 0 export ShortNoSwap proc ShortNoSwap 0 0 ADDRFP4 0 ADDRFP4 0 INDIRI4 CVII2 4 ASGNI2 ADDRFP4 0 INDIRI2 CVII4 2 RETI4 LABELV $60 endproc ShortNoSwap 0 0 export LongSwap proc LongSwap 24 0 ADDRFP4 0 ADDRFP4 0 INDIRI4 ASGNI4 ADDRLP4 8 CNSTI4 255 ASGNI4 ADDRLP4 0 ADDRFP4 0 INDIRI4 ADDRLP4 8 INDIRI4 BANDI4 CVIU4 4 CVUU1 4 ASGNU1 ADDRLP4 12 CNSTI4 8 ASGNI4 ADDRLP4 1 ADDRFP4 0 INDIRI4 ADDRLP4 12 INDIRI4 RSHI4 ADDRLP4 8 INDIRI4 BANDI4 CVIU4 4 CVUU1 4 ASGNU1 ADDRLP4 16 CNSTI4 16 ASGNI4 ADDRLP4 2 ADDRFP4 0 INDIRI4 ADDRLP4 16 INDIRI4 RSHI4 ADDRLP4 8 INDIRI4 BANDI4 CVIU4 4 CVUU1 4 ASGNU1 ADDRLP4 20 CNSTI4 24 ASGNI4 ADDRLP4 3 ADDRFP4 0 INDIRI4 ADDRLP4 20 INDIRI4 RSHI4 ADDRLP4 8 INDIRI4 BANDI4 CVIU4 4 CVUU1 4 ASGNU1 ADDRLP4 0 INDIRU1 CVUI4 1 ADDRLP4 20 INDIRI4 LSHI4 ADDRLP4 1 INDIRU1 CVUI4 1 ADDRLP4 16 INDIRI4 LSHI4 ADDI4 ADDRLP4 2 INDIRU1 CVUI4 1 ADDRLP4 12 INDIRI4 LSHI4 ADDI4 ADDRLP4 3 INDIRU1 CVUI4 1 ADDI4 RETI4 LABELV $61 endproc LongSwap 24 0 export LongNoSwap proc LongNoSwap 0 0 ADDRFP4 0 INDIRI4 RETI4 LABELV $62 endproc LongNoSwap 0 0 export Long64Swap proc Long64Swap 12 0 ADDRLP4 8 ADDRFP4 4 INDIRP4 ASGNP4 ADDRLP4 0 ADDRLP4 8 INDIRP4 CNSTI4 7 ADDP4 INDIRU1 ASGNU1 ADDRLP4 0+1 ADDRLP4 8 INDIRP4 CNSTI4 6 ADDP4 INDIRU1 ASGNU1 ADDRLP4 0+2 ADDRFP4 4 INDIRP4 CNSTI4 5 ADDP4 INDIRU1 ASGNU1 ADDRLP4 0+3 ADDRFP4 4 INDIRP4 CNSTI4 4 ADDP4 INDIRU1 ASGNU1 ADDRLP4 0+4 ADDRFP4 4 INDIRP4 CNSTI4 3 ADDP4 INDIRU1 ASGNU1 ADDRLP4 0+5 ADDRFP4 4 INDIRP4 CNSTI4 2 ADDP4 INDIRU1 ASGNU1 ADDRLP4 0+6 ADDRFP4 4 INDIRP4 CNSTI4 1 ADDP4 INDIRU1 ASGNU1 ADDRLP4 0+7 ADDRFP4 4 INDIRP4 INDIRU1 ASGNU1 ADDRFP4 0 INDIRP4 ADDRLP4 0 INDIRB ASGNB 8 LABELV $63 endproc Long64Swap 12 0 export Long64NoSwap proc Long64NoSwap 0 0 ADDRFP4 0 INDIRP4 ADDRFP4 4 INDIRP4 INDIRB ASGNB 8 LABELV $72 endproc Long64NoSwap 0 0 export FloatSwap proc FloatSwap 8 4 ADDRLP4 0 ADDRFP4 0 INDIRP4 INDIRF4 ASGNF4 ADDRLP4 0 INDIRU4 CVUI4 4 ARGI4 ADDRLP4 4 ADDRGP4 LongSwap CALLI4 ASGNI4 ADDRLP4 0 ADDRLP4 4 INDIRI4 CVIU4 4 ASGNU4 ADDRLP4 0 INDIRF4 RETF4 LABELV $74 endproc FloatSwap 8 4 export FloatNoSwap proc FloatNoSwap 0 0 ADDRFP4 0 INDIRP4 INDIRF4 RETF4 LABELV $75 endproc FloatNoSwap 0 0 export COM_BeginParseSession proc COM_BeginParseSession 0 16 ADDRGP4 com_lines CNSTI4 1 ASGNI4 ADDRGP4 com_tokenline CNSTI4 0 ASGNI4 ADDRGP4 com_parsename ARGP4 CNSTI4 1024 ARGI4 ADDRGP4 $77 ARGP4 ADDRFP4 0 INDIRP4 ARGP4 ADDRGP4 Com_sprintf CALLI4 pop LABELV $76 endproc COM_BeginParseSession 0 16 export COM_GetCurrentParseLine proc COM_GetCurrentParseLine 0 0 ADDRGP4 com_tokenline INDIRI4 CNSTI4 0 EQI4 $79 ADDRGP4 com_tokenline INDIRI4 RETI4 ADDRGP4 $78 JUMPV LABELV $79 ADDRGP4 com_lines INDIRI4 RETI4 LABELV $78 endproc COM_GetCurrentParseLine 0 0 export COM_Parse proc COM_Parse 4 8 ADDRFP4 0 INDIRP4 ARGP4 CNSTI4 1 ARGI4 ADDRLP4 0 ADDRGP4 COM_ParseExt CALLP4 ASGNP4 ADDRLP4 0 INDIRP4 RETP4 LABELV $81 endproc COM_Parse 4 8 bss align 1 LABELV $83 skip 4096 export COM_ParseError code proc COM_ParseError 8 16 ADDRLP4 0 ADDRFP4 0+4 ASGNP4 ADDRGP4 $83 ARGP4 CNSTU4 4096 ARGU4 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 0 INDIRP4 ARGP4 ADDRGP4 qk_vsnprintf CALLI4 pop ADDRLP4 0 CNSTP4 0 ASGNP4 ADDRLP4 4 ADDRGP4 COM_GetCurrentParseLine CALLI4 ASGNI4 ADDRGP4 $85 ARGP4 ADDRGP4 com_parsename ARGP4 ADDRLP4 4 INDIRI4 ARGI4 ADDRGP4 $83 ARGP4 ADDRGP4 Com_Printf CALLV pop LABELV $82 endproc COM_ParseError 8 16 bss align 1 LABELV $87 skip 4096 export COM_ParseWarning code proc COM_ParseWarning 8 16 ADDRLP4 0 ADDRFP4 0+4 ASGNP4 ADDRGP4 $87 ARGP4 CNSTU4 4096 ARGU4 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 0 INDIRP4 ARGP4 ADDRGP4 qk_vsnprintf CALLI4 pop ADDRLP4 0 CNSTP4 0 ASGNP4 ADDRLP4 4 ADDRGP4 COM_GetCurrentParseLine CALLI4 ASGNI4 ADDRGP4 $89 ARGP4 ADDRGP4 com_parsename ARGP4 ADDRLP4 4 INDIRI4 ARGI4 ADDRGP4 $87 ARGP4 ADDRGP4 Com_Printf CALLV pop LABELV $86 endproc COM_ParseWarning 8 16 proc SkipWhitespace 12 0 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 4 ADDRFP4 4 INDIRP4 ASGNP4 ADDRGP4 $92 JUMPV LABELV $91 ADDRLP4 0 INDIRI4 CNSTI4 0 NEI4 $94 CNSTP4 0 RETP4 ADDRGP4 $90 JUMPV LABELV $94 ADDRLP4 0 INDIRI4 CNSTI4 10 NEI4 $96 ADDRLP4 4 ADDRGP4 com_lines ASGNP4 ADDRLP4 8 CNSTI4 1 ASGNI4 ADDRLP4 4 INDIRP4 ADDRLP4 4 INDIRP4 INDIRI4 ADDRLP4 8 INDIRI4 ADDI4 ASGNI4 ADDRFP4 4 INDIRP4 ADDRLP4 8 INDIRI4 ASGNI4 LABELV $96 ADDRFP4 0 ADDRFP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $92 ADDRLP4 4 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 0 ADDRLP4 4 INDIRI4 ASGNI4 ADDRLP4 4 INDIRI4 CNSTI4 32 LEI4 $91 ADDRFP4 0 INDIRP4 RETP4 LABELV $90 endproc SkipWhitespace 12 0 export COM_Compress proc COM_Compress 48 0 ADDRLP4 12 CNSTI4 0 ASGNI4 ADDRLP4 16 CNSTI4 0 ASGNI4 ADDRLP4 20 ADDRFP4 0 INDIRP4 ASGNP4 ADDRLP4 8 ADDRLP4 20 INDIRP4 ASGNP4 ADDRLP4 0 ADDRLP4 20 INDIRP4 ASGNP4 ADDRLP4 0 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $99 ADDRGP4 $102 JUMPV LABELV $101 ADDRLP4 24 CNSTI4 47 ASGNI4 ADDRLP4 4 INDIRI4 ADDRLP4 24 INDIRI4 NEI4 $104 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 INDIRI1 CVII4 1 ADDRLP4 24 INDIRI4 NEI4 $104 ADDRGP4 $107 JUMPV LABELV $106 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $107 ADDRLP4 28 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 28 INDIRI4 CNSTI4 0 EQI4 $109 ADDRLP4 28 INDIRI4 CNSTI4 10 NEI4 $106 LABELV $109 ADDRGP4 $105 JUMPV LABELV $104 ADDRLP4 4 INDIRI4 CNSTI4 47 NEI4 $110 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 INDIRI1 CVII4 1 CNSTI4 42 NEI4 $110 ADDRGP4 $113 JUMPV LABELV $112 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $113 ADDRLP4 32 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 32 INDIRI4 CNSTI4 0 EQI4 $115 ADDRLP4 32 INDIRI4 CNSTI4 42 NEI4 $112 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 INDIRI1 CVII4 1 CNSTI4 47 NEI4 $112 LABELV $115 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 EQI4 $111 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 2 ADDP4 ASGNP4 ADDRGP4 $111 JUMPV LABELV $110 ADDRLP4 4 INDIRI4 CNSTI4 10 EQI4 $120 ADDRLP4 4 INDIRI4 CNSTI4 13 NEI4 $118 LABELV $120 ADDRLP4 32 CNSTI4 1 ASGNI4 ADDRLP4 12 ADDRLP4 32 INDIRI4 ASGNI4 ADDRLP4 0 ADDRLP4 0 INDIRP4 ADDRLP4 32 INDIRI4 ADDP4 ASGNP4 ADDRGP4 $119 JUMPV LABELV $118 ADDRLP4 4 INDIRI4 CNSTI4 32 EQI4 $123 ADDRLP4 4 INDIRI4 CNSTI4 9 NEI4 $121 LABELV $123 ADDRLP4 36 CNSTI4 1 ASGNI4 ADDRLP4 16 ADDRLP4 36 INDIRI4 ASGNI4 ADDRLP4 0 ADDRLP4 0 INDIRP4 ADDRLP4 36 INDIRI4 ADDP4 ASGNP4 ADDRGP4 $122 JUMPV LABELV $121 ADDRLP4 12 INDIRI4 CNSTI4 0 EQI4 $124 ADDRLP4 36 ADDRLP4 8 INDIRP4 ASGNP4 ADDRLP4 8 ADDRLP4 36 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 36 INDIRP4 CNSTI1 10 ASGNI1 ADDRLP4 40 CNSTI4 0 ASGNI4 ADDRLP4 12 ADDRLP4 40 INDIRI4 ASGNI4 ADDRLP4 16 ADDRLP4 40 INDIRI4 ASGNI4 LABELV $124 ADDRLP4 16 INDIRI4 CNSTI4 0 EQI4 $126 ADDRLP4 36 ADDRLP4 8 INDIRP4 ASGNP4 ADDRLP4 8 ADDRLP4 36 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 36 INDIRP4 CNSTI1 32 ASGNI1 ADDRLP4 16 CNSTI4 0 ASGNI4 LABELV $126 ADDRLP4 4 INDIRI4 CNSTI4 34 NEI4 $128 ADDRLP4 36 ADDRLP4 8 INDIRP4 ASGNP4 ADDRLP4 8 ADDRLP4 36 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 36 INDIRP4 ADDRLP4 4 INDIRI4 CVII1 4 ASGNI1 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRGP4 $131 JUMPV LABELV $130 ADDRLP4 4 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 4 INDIRI4 CNSTI4 0 EQI4 $132 ADDRLP4 4 INDIRI4 CNSTI4 34 EQI4 $132 ADDRLP4 44 ADDRLP4 8 INDIRP4 ASGNP4 ADDRLP4 8 ADDRLP4 44 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 44 INDIRP4 ADDRLP4 4 INDIRI4 CVII1 4 ASGNI1 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $134 LABELV $131 ADDRGP4 $130 JUMPV LABELV $132 ADDRLP4 4 INDIRI4 CNSTI4 34 NEI4 $129 ADDRLP4 40 ADDRLP4 8 INDIRP4 ASGNP4 ADDRLP4 8 ADDRLP4 40 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 40 INDIRP4 ADDRLP4 4 INDIRI4 CVII1 4 ASGNI1 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRGP4 $129 JUMPV LABELV $128 ADDRLP4 8 INDIRP4 ADDRLP4 4 INDIRI4 CVII1 4 ASGNI1 ADDRLP4 36 CNSTI4 1 ASGNI4 ADDRLP4 8 ADDRLP4 8 INDIRP4 ADDRLP4 36 INDIRI4 ADDP4 ASGNP4 ADDRLP4 0 ADDRLP4 0 INDIRP4 ADDRLP4 36 INDIRI4 ADDP4 ASGNP4 LABELV $129 LABELV $122 LABELV $119 LABELV $111 LABELV $105 LABELV $102 ADDRLP4 24 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 4 ADDRLP4 24 INDIRI4 ASGNI4 ADDRLP4 24 INDIRI4 CNSTI4 0 NEI4 $101 ADDRLP4 8 INDIRP4 CNSTI1 0 ASGNI1 LABELV $99 ADDRLP4 8 INDIRP4 CVPU4 4 ADDRFP4 0 INDIRP4 CVPU4 4 SUBU4 CVUI4 4 RETI4 LABELV $98 endproc COM_Compress 48 0 export COM_ParseExt proc COM_ParseExt 40 8 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 4 ADDRFP4 4 INDIRI4 ASGNI4 ADDRLP4 4 CNSTI4 0 ASGNI4 ADDRLP4 12 CNSTI4 0 ASGNI4 ADDRLP4 0 ADDRFP4 0 INDIRP4 INDIRP4 ASGNP4 ADDRLP4 16 CNSTI4 0 ASGNI4 ADDRLP4 8 ADDRLP4 16 INDIRI4 ASGNI4 ADDRGP4 com_token CNSTI1 0 ASGNI1 ADDRGP4 com_tokenline ADDRLP4 16 INDIRI4 ASGNI4 ADDRLP4 0 INDIRP4 CVPU4 4 CNSTU4 0 NEU4 $141 ADDRFP4 0 INDIRP4 CNSTP4 0 ASGNP4 ADDRGP4 com_token RETP4 ADDRGP4 $137 JUMPV LABELV $140 ADDRLP4 0 INDIRP4 ARGP4 ADDRLP4 12 ARGP4 ADDRLP4 20 ADDRGP4 SkipWhitespace CALLP4 ASGNP4 ADDRLP4 0 ADDRLP4 20 INDIRP4 ASGNP4 ADDRLP4 0 INDIRP4 CVPU4 4 CNSTU4 0 NEU4 $143 ADDRFP4 0 INDIRP4 CNSTP4 0 ASGNP4 ADDRGP4 com_token RETP4 ADDRGP4 $137 JUMPV LABELV $143 ADDRLP4 24 CNSTI4 0 ASGNI4 ADDRLP4 12 INDIRI4 ADDRLP4 24 INDIRI4 EQI4 $145 ADDRFP4 4 INDIRI4 ADDRLP4 24 INDIRI4 NEI4 $145 ADDRFP4 0 INDIRP4 ADDRLP4 0 INDIRP4 ASGNP4 ADDRGP4 com_token RETP4 ADDRGP4 $137 JUMPV LABELV $145 ADDRLP4 4 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 28 CNSTI4 47 ASGNI4 ADDRLP4 4 INDIRI4 ADDRLP4 28 INDIRI4 NEI4 $147 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 INDIRI1 CVII4 1 ADDRLP4 28 INDIRI4 NEI4 $147 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 2 ADDP4 ASGNP4 ADDRGP4 $150 JUMPV LABELV $149 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $150 ADDRLP4 32 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 32 INDIRI4 CNSTI4 0 EQI4 $152 ADDRLP4 32 INDIRI4 CNSTI4 10 NEI4 $149 LABELV $152 ADDRGP4 $148 JUMPV LABELV $147 ADDRLP4 4 INDIRI4 CNSTI4 47 NEI4 $142 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 INDIRI1 CVII4 1 CNSTI4 42 NEI4 $142 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 2 ADDP4 ASGNP4 ADDRGP4 $156 JUMPV LABELV $155 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 10 NEI4 $158 ADDRLP4 32 ADDRGP4 com_lines ASGNP4 ADDRLP4 32 INDIRP4 ADDRLP4 32 INDIRP4 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 LABELV $158 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $156 ADDRLP4 36 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 36 INDIRI4 CNSTI4 0 EQI4 $160 ADDRLP4 36 INDIRI4 CNSTI4 42 NEI4 $155 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 INDIRI1 CVII4 1 CNSTI4 47 NEI4 $155 LABELV $160 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 EQI4 $154 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 2 ADDP4 ASGNP4 LABELV $154 LABELV $148 LABELV $141 ADDRGP4 $140 JUMPV LABELV $142 ADDRGP4 com_tokenline ADDRGP4 com_lines INDIRI4 ASGNI4 ADDRLP4 4 INDIRI4 CNSTI4 34 NEI4 $163 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRGP4 $166 JUMPV LABELV $165 ADDRLP4 20 ADDRLP4 0 INDIRP4 ASGNP4 ADDRLP4 0 ADDRLP4 20 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 4 ADDRLP4 20 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 4 INDIRI4 CNSTI4 34 EQI4 $170 ADDRLP4 4 INDIRI4 CNSTI4 0 NEI4 $168 LABELV $170 ADDRLP4 8 INDIRI4 ADDRGP4 com_token ADDP4 CNSTI1 0 ASGNI1 ADDRFP4 0 INDIRP4 ADDRLP4 0 INDIRP4 ASGNP4 ADDRGP4 com_token RETP4 ADDRGP4 $137 JUMPV LABELV $168 ADDRLP4 4 INDIRI4 CNSTI4 10 NEI4 $171 ADDRLP4 28 ADDRGP4 com_lines ASGNP4 ADDRLP4 28 INDIRP4 ADDRLP4 28 INDIRP4 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 LABELV $171 ADDRLP4 8 INDIRI4 CNSTI4 1023 GEI4 $173 ADDRLP4 8 INDIRI4 ADDRGP4 com_token ADDP4 ADDRLP4 4 INDIRI4 CVII1 4 ASGNI1 ADDRLP4 8 ADDRLP4 8 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 LABELV $173 LABELV $166 ADDRGP4 $165 JUMPV LABELV $163 LABELV $175 ADDRLP4 8 INDIRI4 CNSTI4 1023 GEI4 $178 ADDRLP4 8 INDIRI4 ADDRGP4 com_token ADDP4 ADDRLP4 4 INDIRI4 CVII1 4 ASGNI1 ADDRLP4 8 ADDRLP4 8 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 LABELV $178 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 4 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ASGNI4 LABELV $176 ADDRLP4 4 INDIRI4 CNSTI4 32 GTI4 $175 ADDRLP4 8 INDIRI4 ADDRGP4 com_token ADDP4 CNSTI1 0 ASGNI1 ADDRFP4 0 INDIRP4 ADDRLP4 0 INDIRP4 ASGNP4 ADDRGP4 com_token RETP4 LABELV $137 endproc COM_ParseExt 40 8 export COM_MatchToken proc COM_MatchToken 12 16 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 4 ADDRGP4 COM_Parse CALLP4 ASGNP4 ADDRLP4 0 ADDRLP4 4 INDIRP4 ASGNP4 ADDRLP4 0 INDIRP4 ARGP4 ADDRFP4 4 INDIRP4 ARGP4 ADDRLP4 8 ADDRGP4 qk_strcmp CALLI4 ASGNI4 ADDRLP4 8 INDIRI4 CNSTI4 0 EQI4 $181 CNSTI4 1 ARGI4 ADDRGP4 $183 ARGP4 ADDRLP4 0 INDIRP4 ARGP4 ADDRFP4 4 INDIRP4 ARGP4 ADDRGP4 Com_Error CALLV pop LABELV $181 LABELV $180 endproc COM_MatchToken 12 16 export SkipBracedSection proc SkipBracedSection 8 8 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 4 ADDRFP4 4 INDIRI4 ASGNI4 LABELV $185 ADDRFP4 0 INDIRP4 ARGP4 CNSTI4 1 ARGI4 ADDRLP4 4 ADDRGP4 COM_ParseExt CALLP4 ASGNP4 ADDRLP4 0 ADDRLP4 4 INDIRP4 ASGNP4 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $188 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 123 NEI4 $190 ADDRFP4 4 ADDRFP4 4 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 ADDRGP4 $191 JUMPV LABELV $190 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 125 NEI4 $192 ADDRFP4 4 ADDRFP4 4 INDIRI4 CNSTI4 1 SUBI4 ASGNI4 LABELV $192 LABELV $191 LABELV $188 LABELV $186 ADDRFP4 4 INDIRI4 CNSTI4 0 EQI4 $194 ADDRFP4 0 INDIRP4 INDIRP4 CVPU4 4 CNSTU4 0 NEU4 $185 LABELV $194 ADDRFP4 4 INDIRI4 CNSTI4 0 NEI4 $196 ADDRLP4 4 CNSTI4 1 ASGNI4 ADDRGP4 $197 JUMPV LABELV $196 ADDRLP4 4 CNSTI4 0 ASGNI4 LABELV $197 ADDRLP4 4 INDIRI4 RETI4 LABELV $184 endproc SkipBracedSection 8 8 export SkipRestOfLine proc SkipRestOfLine 16 0 ADDRLP4 4 ADDRFP4 0 INDIRP4 INDIRP4 ASGNP4 ADDRGP4 $200 JUMPV LABELV $199 ADDRLP4 0 INDIRI4 CNSTI4 10 NEI4 $202 ADDRLP4 8 ADDRGP4 com_lines ASGNP4 ADDRLP4 8 INDIRP4 ADDRLP4 8 INDIRP4 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 ADDRGP4 $201 JUMPV LABELV $202 LABELV $200 ADDRLP4 8 ADDRLP4 4 INDIRP4 ASGNP4 ADDRLP4 4 ADDRLP4 8 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 12 ADDRLP4 8 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 0 ADDRLP4 12 INDIRI4 ASGNI4 ADDRLP4 12 INDIRI4 CNSTI4 0 NEI4 $199 LABELV $201 ADDRFP4 0 INDIRP4 ADDRLP4 4 INDIRP4 ASGNP4 LABELV $198 endproc SkipRestOfLine 16 0 export Parse1DMatrix proc Parse1DMatrix 16 8 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 4 ADDRFP4 4 INDIRI4 ASGNI4 ADDRFP4 8 ADDRFP4 8 INDIRP4 ASGNP4 ADDRFP4 0 INDIRP4 ARGP4 ADDRGP4 $205 ARGP4 ADDRGP4 COM_MatchToken CALLV pop ADDRLP4 0 CNSTI4 0 ASGNI4 ADDRGP4 $209 JUMPV LABELV $206 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 8 ADDRGP4 COM_Parse CALLP4 ASGNP4 ADDRLP4 4 ADDRLP4 8 INDIRP4 ASGNP4 ADDRLP4 4 INDIRP4 ARGP4 ADDRLP4 12 ADDRGP4 qk_atof CALLF4 ASGNF4 ADDRLP4 0 INDIRI4 CNSTI4 2 LSHI4 ADDRFP4 8 INDIRP4 ADDP4 ADDRLP4 12 INDIRF4 ASGNF4 LABELV $207 ADDRLP4 0 ADDRLP4 0 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 LABELV $209 ADDRLP4 0 INDIRI4 ADDRFP4 4 INDIRI4 LTI4 $206 ADDRFP4 0 INDIRP4 ARGP4 ADDRGP4 $210 ARGP4 ADDRGP4 COM_MatchToken CALLV pop LABELV $204 endproc Parse1DMatrix 16 8 export Parse2DMatrix proc Parse2DMatrix 8 12 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 4 ADDRFP4 4 INDIRI4 ASGNI4 ADDRFP4 8 ADDRFP4 8 INDIRI4 ASGNI4 ADDRFP4 12 ADDRFP4 12 INDIRP4 ASGNP4 ADDRFP4 0 INDIRP4 ARGP4 ADDRGP4 $205 ARGP4 ADDRGP4 COM_MatchToken CALLV pop ADDRLP4 0 CNSTI4 0 ASGNI4 ADDRGP4 $215 JUMPV LABELV $212 ADDRFP4 0 INDIRP4 ARGP4 ADDRFP4 8 INDIRI4 ARGI4 ADDRLP4 0 INDIRI4 ADDRFP4 8 INDIRI4 MULI4 CNSTI4 2 LSHI4 ADDRFP4 12 INDIRP4 ADDP4 ARGP4 ADDRGP4 Parse1DMatrix CALLV pop LABELV $213 ADDRLP4 0 ADDRLP4 0 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 LABELV $215 ADDRLP4 0 INDIRI4 ADDRFP4 4 INDIRI4 LTI4 $212 ADDRFP4 0 INDIRP4 ARGP4 ADDRGP4 $210 ARGP4 ADDRGP4 COM_MatchToken CALLV pop LABELV $211 endproc Parse2DMatrix 8 12 export Parse3DMatrix proc Parse3DMatrix 12 16 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 4 ADDRFP4 4 INDIRI4 ASGNI4 ADDRFP4 8 ADDRFP4 8 INDIRI4 ASGNI4 ADDRFP4 12 ADDRFP4 12 INDIRI4 ASGNI4 ADDRFP4 16 ADDRFP4 16 INDIRP4 ASGNP4 ADDRFP4 0 INDIRP4 ARGP4 ADDRGP4 $205 ARGP4 ADDRGP4 COM_MatchToken CALLV pop ADDRLP4 0 CNSTI4 0 ASGNI4 ADDRGP4 $220 JUMPV LABELV $217 ADDRFP4 0 INDIRP4 ARGP4 ADDRFP4 8 INDIRI4 ARGI4 ADDRFP4 12 INDIRI4 ARGI4 ADDRLP4 0 INDIRI4 ADDRFP4 12 INDIRI4 MULI4 ADDRFP4 8 INDIRI4 MULI4 CNSTI4 2 LSHI4 ADDRFP4 16 INDIRP4 ADDP4 ARGP4 ADDRGP4 Parse2DMatrix CALLV pop LABELV $218 ADDRLP4 0 ADDRLP4 0 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 LABELV $220 ADDRLP4 0 INDIRI4 ADDRFP4 4 INDIRI4 LTI4 $217 ADDRFP4 0 INDIRP4 ARGP4 ADDRGP4 $210 ARGP4 ADDRGP4 COM_MatchToken CALLV pop LABELV $216 endproc Parse3DMatrix 12 16 export Com_HexStrToInt proc Com_HexStrToInt 32 4 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 0 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $224 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $222 LABELV $224 CNSTI4 -1 RETI4 ADDRGP4 $221 JUMPV LABELV $222 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 48 NEI4 $225 ADDRFP4 0 INDIRP4 CNSTI4 1 ADDP4 INDIRI1 CVII4 1 CNSTI4 120 NEI4 $225 ADDRLP4 12 CNSTI4 0 ASGNI4 ADDRLP4 8 CNSTI4 2 ASGNI4 ADDRGP4 $230 JUMPV LABELV $227 ADDRLP4 12 ADDRLP4 12 INDIRI4 CNSTI4 4 LSHI4 ASGNI4 ADDRLP4 8 INDIRI4 ADDRFP4 0 INDIRP4 ADDP4 INDIRI1 CVII4 1 ARGI4 ADDRLP4 20 ADDRGP4 qk_tolower CALLI4 ASGNI4 ADDRLP4 16 ADDRLP4 20 INDIRI4 CVII1 4 ASGNI1 ADDRLP4 24 ADDRLP4 16 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 24 INDIRI4 CNSTI4 48 LTI4 $231 ADDRLP4 24 INDIRI4 CNSTI4 57 GTI4 $231 ADDRLP4 16 ADDRLP4 16 INDIRI1 CVII4 1 CNSTI4 48 SUBI4 CVII1 4 ASGNI1 ADDRGP4 $232 JUMPV LABELV $231 ADDRLP4 28 ADDRLP4 16 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 28 INDIRI4 CNSTI4 97 LTI4 $233 ADDRLP4 28 INDIRI4 CNSTI4 102 GTI4 $233 ADDRLP4 16 ADDRLP4 16 INDIRI1 CVII4 1 CNSTI4 97 SUBI4 CNSTI4 10 ADDI4 CVII1 4 ASGNI1 ADDRGP4 $234 JUMPV LABELV $233 CNSTI4 -1 RETI4 ADDRGP4 $221 JUMPV LABELV $234 LABELV $232 ADDRLP4 12 ADDRLP4 12 INDIRI4 ADDRLP4 16 INDIRI1 CVII4 1 ADDI4 ASGNI4 LABELV $228 ADDRLP4 8 ADDRLP4 8 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 LABELV $230 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 16 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRLP4 8 INDIRI4 CVIU4 4 ADDRLP4 16 INDIRU4 LTU4 $227 ADDRLP4 12 INDIRI4 RETI4 ADDRGP4 $221 JUMPV LABELV $225 CNSTI4 -1 RETI4 LABELV $221 endproc Com_HexStrToInt 32 4 export Q_isprint proc Q_isprint 4 0 ADDRLP4 0 ADDRFP4 0 INDIRI4 ASGNI4 ADDRLP4 0 INDIRI4 CNSTI4 32 LTI4 $236 ADDRLP4 0 INDIRI4 CNSTI4 126 GTI4 $236 CNSTI4 1 RETI4 ADDRGP4 $235 JUMPV LABELV $236 CNSTI4 0 RETI4 LABELV $235 endproc Q_isprint 4 0 export Q_islower proc Q_islower 4 0 ADDRLP4 0 ADDRFP4 0 INDIRI4 ASGNI4 ADDRLP4 0 INDIRI4 CNSTI4 97 LTI4 $239 ADDRLP4 0 INDIRI4 CNSTI4 122 GTI4 $239 CNSTI4 1 RETI4 ADDRGP4 $238 JUMPV LABELV $239 CNSTI4 0 RETI4 LABELV $238 endproc Q_islower 4 0 export Q_isupper proc Q_isupper 4 0 ADDRLP4 0 ADDRFP4 0 INDIRI4 ASGNI4 ADDRLP4 0 INDIRI4 CNSTI4 65 LTI4 $242 ADDRLP4 0 INDIRI4 CNSTI4 90 GTI4 $242 CNSTI4 1 RETI4 ADDRGP4 $241 JUMPV LABELV $242 CNSTI4 0 RETI4 LABELV $241 endproc Q_isupper 4 0 export Q_isalpha proc Q_isalpha 8 0 ADDRFP4 0 ADDRFP4 0 INDIRI4 ASGNI4 ADDRFP4 0 INDIRI4 CNSTI4 97 LTI4 $248 ADDRFP4 0 INDIRI4 CNSTI4 122 LEI4 $247 LABELV $248 ADDRFP4 0 INDIRI4 CNSTI4 65 LTI4 $245 ADDRFP4 0 INDIRI4 CNSTI4 90 GTI4 $245 LABELV $247 CNSTI4 1 RETI4 ADDRGP4 $244 JUMPV LABELV $245 CNSTI4 0 RETI4 LABELV $244 endproc Q_isalpha 8 0 export Q_isanumber proc Q_isanumber 16 8 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $250 CNSTI4 0 RETI4 ADDRGP4 $249 JUMPV LABELV $250 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 0 ARGP4 ADDRLP4 8 ADDRGP4 qk_strtod CALLF4 ASGNF4 ADDRLP4 4 ADDRLP4 8 INDIRF4 ASGNF4 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $253 ADDRLP4 12 CNSTI4 1 ASGNI4 ADDRGP4 $254 JUMPV LABELV $253 ADDRLP4 12 CNSTI4 0 ASGNI4 LABELV $254 ADDRLP4 12 INDIRI4 RETI4 LABELV $249 endproc Q_isanumber 16 8 export Q_isintegral proc Q_isintegral 8 0 ADDRLP4 4 ADDRFP4 0 INDIRF4 ASGNF4 ADDRLP4 4 INDIRF4 CVFI4 4 CVIF4 4 ADDRLP4 4 INDIRF4 NEF4 $257 ADDRLP4 0 CNSTI4 1 ASGNI4 ADDRGP4 $258 JUMPV LABELV $257 ADDRLP4 0 CNSTI4 0 ASGNI4 LABELV $258 ADDRLP4 0 INDIRI4 RETI4 LABELV $255 endproc Q_isintegral 8 0 export Q_strncpyz proc Q_strncpyz 0 12 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 8 ADDRFP4 8 INDIRI4 ASGNI4 ADDRFP4 0 INDIRP4 CVPU4 4 CNSTU4 0 NEU4 $260 CNSTI4 0 ARGI4 ADDRGP4 $262 ARGP4 ADDRGP4 Com_Error CALLV pop LABELV $260 ADDRFP4 4 INDIRP4 CVPU4 4 CNSTU4 0 NEU4 $263 CNSTI4 0 ARGI4 ADDRGP4 $265 ARGP4 ADDRGP4 Com_Error CALLV pop LABELV $263 ADDRFP4 8 INDIRI4 CNSTI4 1 GEI4 $266 CNSTI4 0 ARGI4 ADDRGP4 $268 ARGP4 ADDRGP4 Com_Error CALLV pop LABELV $266 ADDRFP4 0 INDIRP4 ARGP4 ADDRFP4 4 INDIRP4 ARGP4 ADDRFP4 8 INDIRI4 CNSTI4 1 SUBI4 CVIU4 4 ARGU4 ADDRGP4 qk_strncpy CALLP4 pop ADDRFP4 8 INDIRI4 CNSTI4 1 SUBI4 ADDRFP4 0 INDIRP4 ADDP4 CNSTI1 0 ASGNI1 LABELV $259 endproc Q_strncpyz 0 12 export Q_stricmpn proc Q_stricmpn 36 0 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 4 ADDRFP4 4 INDIRP4 ASGNP4 ADDRFP4 8 ADDRFP4 8 INDIRI4 ASGNI4 ADDRFP4 0 INDIRP4 CVPU4 4 CNSTU4 0 NEU4 $270 ADDRFP4 4 INDIRP4 CVPU4 4 CNSTU4 0 NEU4 $272 CNSTI4 0 RETI4 ADDRGP4 $269 JUMPV LABELV $272 CNSTI4 -1 RETI4 ADDRGP4 $269 JUMPV LABELV $270 ADDRFP4 4 INDIRP4 CVPU4 4 CNSTU4 0 NEU4 $274 CNSTI4 1 RETI4 ADDRGP4 $269 JUMPV LABELV $274 LABELV $276 ADDRLP4 8 ADDRFP4 0 INDIRP4 ASGNP4 ADDRLP4 20 CNSTI4 1 ASGNI4 ADDRFP4 0 ADDRLP4 8 INDIRP4 ADDRLP4 20 INDIRI4 ADDP4 ASGNP4 ADDRLP4 0 ADDRLP4 8 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 12 ADDRFP4 4 INDIRP4 ASGNP4 ADDRFP4 4 ADDRLP4 12 INDIRP4 ADDRLP4 20 INDIRI4 ADDP4 ASGNP4 ADDRLP4 4 ADDRLP4 12 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 16 ADDRFP4 8 INDIRI4 ASGNI4 ADDRFP4 8 ADDRLP4 16 INDIRI4 ADDRLP4 20 INDIRI4 SUBI4 ASGNI4 ADDRLP4 16 INDIRI4 CNSTI4 0 NEI4 $279 CNSTI4 0 RETI4 ADDRGP4 $269 JUMPV LABELV $279 ADDRLP4 0 INDIRI4 ADDRLP4 4 INDIRI4 EQI4 $281 ADDRLP4 0 INDIRI4 CNSTI4 97 LTI4 $283 ADDRLP4 0 INDIRI4 CNSTI4 122 GTI4 $283 ADDRLP4 0 ADDRLP4 0 INDIRI4 CNSTI4 32 SUBI4 ASGNI4 LABELV $283 ADDRLP4 4 INDIRI4 CNSTI4 97 LTI4 $285 ADDRLP4 4 INDIRI4 CNSTI4 122 GTI4 $285 ADDRLP4 4 ADDRLP4 4 INDIRI4 CNSTI4 32 SUBI4 ASGNI4 LABELV $285 ADDRLP4 0 INDIRI4 ADDRLP4 4 INDIRI4 EQI4 $287 ADDRLP4 0 INDIRI4 ADDRLP4 4 INDIRI4 GEI4 $290 ADDRLP4 32 CNSTI4 -1 ASGNI4 ADDRGP4 $291 JUMPV LABELV $290 ADDRLP4 32 CNSTI4 1 ASGNI4 LABELV $291 ADDRLP4 32 INDIRI4 RETI4 ADDRGP4 $269 JUMPV LABELV $287 LABELV $281 LABELV $277 ADDRLP4 0 INDIRI4 CNSTI4 0 NEI4 $276 CNSTI4 0 RETI4 LABELV $269 endproc Q_stricmpn 36 0 export Q_strncmp proc Q_strncmp 28 0 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 4 ADDRFP4 4 INDIRP4 ASGNP4 ADDRFP4 8 ADDRFP4 8 INDIRI4 ASGNI4 LABELV $293 ADDRLP4 8 ADDRFP4 0 INDIRP4 ASGNP4 ADDRLP4 20 CNSTI4 1 ASGNI4 ADDRFP4 0 ADDRLP4 8 INDIRP4 ADDRLP4 20 INDIRI4 ADDP4 ASGNP4 ADDRLP4 0 ADDRLP4 8 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 12 ADDRFP4 4 INDIRP4 ASGNP4 ADDRFP4 4 ADDRLP4 12 INDIRP4 ADDRLP4 20 INDIRI4 ADDP4 ASGNP4 ADDRLP4 4 ADDRLP4 12 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 16 ADDRFP4 8 INDIRI4 ASGNI4 ADDRFP4 8 ADDRLP4 16 INDIRI4 ADDRLP4 20 INDIRI4 SUBI4 ASGNI4 ADDRLP4 16 INDIRI4 CNSTI4 0 NEI4 $296 CNSTI4 0 RETI4 ADDRGP4 $292 JUMPV LABELV $296 ADDRLP4 0 INDIRI4 ADDRLP4 4 INDIRI4 EQI4 $298 ADDRLP4 0 INDIRI4 ADDRLP4 4 INDIRI4 GEI4 $301 ADDRLP4 24 CNSTI4 -1 ASGNI4 ADDRGP4 $302 JUMPV LABELV $301 ADDRLP4 24 CNSTI4 1 ASGNI4 LABELV $302 ADDRLP4 24 INDIRI4 RETI4 ADDRGP4 $292 JUMPV LABELV $298 LABELV $294 ADDRLP4 0 INDIRI4 CNSTI4 0 NEI4 $293 CNSTI4 0 RETI4 LABELV $292 endproc Q_strncmp 28 0 export Q_stricmp proc Q_stricmp 12 12 ADDRLP4 4 CNSTU4 0 ASGNU4 ADDRFP4 0 INDIRP4 CVPU4 4 ADDRLP4 4 INDIRU4 EQU4 $305 ADDRFP4 4 INDIRP4 CVPU4 4 ADDRLP4 4 INDIRU4 EQU4 $305 ADDRFP4 0 INDIRP4 ARGP4 ADDRFP4 4 INDIRP4 ARGP4 CNSTI4 99999 ARGI4 ADDRLP4 8 ADDRGP4 Q_stricmpn CALLI4 ASGNI4 ADDRLP4 0 ADDRLP4 8 INDIRI4 ASGNI4 ADDRGP4 $306 JUMPV LABELV $305 ADDRLP4 0 CNSTI4 -1 ASGNI4 LABELV $306 ADDRLP4 0 INDIRI4 RETI4 LABELV $303 endproc Q_stricmp 12 12 export Q_strlwr proc Q_strlwr 12 4 ADDRLP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRGP4 $309 JUMPV LABELV $308 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ARGI4 ADDRLP4 8 ADDRGP4 qk_tolower CALLI4 ASGNI4 ADDRLP4 0 INDIRP4 ADDRLP4 8 INDIRI4 CVII1 4 ASGNI1 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $309 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $308 ADDRFP4 0 INDIRP4 RETP4 LABELV $307 endproc Q_strlwr 12 4 export Q_strupr proc Q_strupr 12 4 ADDRLP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRGP4 $313 JUMPV LABELV $312 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ARGI4 ADDRLP4 8 ADDRGP4 qk_toupper CALLI4 ASGNI4 ADDRLP4 0 INDIRP4 ADDRLP4 8 INDIRI4 CVII1 4 ASGNI1 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $313 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $312 ADDRFP4 0 INDIRP4 RETP4 LABELV $311 endproc Q_strupr 12 4 export Q_strcat proc Q_strcat 12 12 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 4 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRLP4 0 ADDRLP4 4 INDIRU4 CVUI4 4 ASGNI4 ADDRLP4 0 INDIRI4 ADDRFP4 4 INDIRI4 LTI4 $316 CNSTI4 0 ARGI4 ADDRGP4 $318 ARGP4 ADDRGP4 Com_Error CALLV pop LABELV $316 ADDRLP4 0 INDIRI4 ADDRFP4 0 INDIRP4 ADDP4 ARGP4 ADDRFP4 8 INDIRP4 ARGP4 ADDRFP4 4 INDIRI4 ADDRLP4 0 INDIRI4 SUBI4 ARGI4 ADDRGP4 Q_strncpyz CALLV pop LABELV $315 endproc Q_strcat 12 12 export Q_stristr proc Q_stristr 36 12 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 4 ADDRFP4 4 INDIRP4 ASGNP4 ADDRLP4 8 ADDRFP4 4 INDIRP4 ASGNP4 ADDRFP4 4 ADDRLP4 8 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 12 ADDRLP4 8 INDIRP4 INDIRI1 ASGNI1 ADDRLP4 1 ADDRLP4 12 INDIRI1 ASGNI1 ADDRLP4 12 INDIRI1 CVII4 1 CNSTI4 0 EQI4 $320 ADDRLP4 16 ADDRLP4 1 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 16 INDIRI4 CNSTI4 97 LTI4 $322 ADDRLP4 16 INDIRI4 CNSTI4 122 GTI4 $322 ADDRLP4 1 ADDRLP4 1 INDIRI1 CVII4 1 CNSTI4 32 SUBI4 CVII1 4 ASGNI1 LABELV $322 ADDRFP4 4 INDIRP4 ARGP4 ADDRLP4 20 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRLP4 4 ADDRLP4 20 INDIRU4 ASGNU4 LABELV $324 LABELV $327 ADDRLP4 24 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 0 ADDRLP4 24 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 28 ADDRLP4 24 INDIRP4 INDIRI1 ASGNI1 ADDRLP4 0 ADDRLP4 28 INDIRI1 ASGNI1 ADDRLP4 28 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $330 CNSTP4 0 RETP4 ADDRGP4 $319 JUMPV LABELV $330 ADDRLP4 32 ADDRLP4 0 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 32 INDIRI4 CNSTI4 97 LTI4 $332 ADDRLP4 32 INDIRI4 CNSTI4 122 GTI4 $332 ADDRLP4 0 ADDRLP4 0 INDIRI1 CVII4 1 CNSTI4 32 SUBI4 CVII1 4 ASGNI1 LABELV $332 LABELV $328 ADDRLP4 0 INDIRI1 CVII4 1 ADDRLP4 1 INDIRI1 CVII4 1 NEI4 $327 LABELV $325 ADDRFP4 0 INDIRP4 ARGP4 ADDRFP4 4 INDIRP4 ARGP4 ADDRLP4 4 INDIRU4 CVUI4 4 ARGI4 ADDRLP4 24 ADDRGP4 Q_stricmpn CALLI4 ASGNI4 ADDRLP4 24 INDIRI4 CNSTI4 0 NEI4 $324 ADDRFP4 0 ADDRFP4 0 INDIRP4 CNSTI4 -1 ADDP4 ASGNP4 LABELV $320 ADDRFP4 0 INDIRP4 RETP4 LABELV $319 endproc Q_stristr 36 12 export Q_PrintStrlen proc Q_PrintStrlen 28 0 ADDRFP4 0 INDIRP4 CVPU4 4 CNSTU4 0 NEU4 $335 CNSTI4 0 RETI4 ADDRGP4 $334 JUMPV LABELV $335 ADDRLP4 4 CNSTI4 0 ASGNI4 ADDRLP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRGP4 $338 JUMPV LABELV $337 ADDRLP4 0 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $340 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 94 NEI4 $340 ADDRLP4 12 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 12 INDIRI4 CNSTI4 0 EQI4 $340 ADDRLP4 12 INDIRI4 CNSTI4 65 LTI4 $343 ADDRLP4 12 INDIRI4 CNSTI4 90 LEI4 $342 LABELV $343 ADDRLP4 16 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 16 INDIRI4 CNSTI4 97 LTI4 $344 ADDRLP4 16 INDIRI4 CNSTI4 122 LEI4 $342 LABELV $344 ADDRLP4 20 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 20 INDIRI4 CNSTI4 48 LTI4 $340 ADDRLP4 20 INDIRI4 CNSTI4 57 GTI4 $340 LABELV $342 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 2 ADDP4 ASGNP4 ADDRGP4 $338 JUMPV LABELV $340 ADDRLP4 24 CNSTI4 1 ASGNI4 ADDRLP4 0 ADDRLP4 0 INDIRP4 ADDRLP4 24 INDIRI4 ADDP4 ASGNP4 ADDRLP4 4 ADDRLP4 4 INDIRI4 ADDRLP4 24 INDIRI4 ADDI4 ASGNI4 LABELV $338 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $337 ADDRLP4 4 INDIRI4 RETI4 LABELV $334 endproc Q_PrintStrlen 28 0 export Q_CleanStr proc Q_CleanStr 40 0 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRLP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRLP4 8 ADDRFP4 0 INDIRP4 ASGNP4 ADDRGP4 $347 JUMPV LABELV $346 ADDRLP4 0 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $349 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 94 NEI4 $349 ADDRLP4 20 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 20 INDIRI4 CNSTI4 0 EQI4 $349 ADDRLP4 20 INDIRI4 CNSTI4 65 LTI4 $352 ADDRLP4 20 INDIRI4 CNSTI4 90 LEI4 $351 LABELV $352 ADDRLP4 24 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 24 INDIRI4 CNSTI4 97 LTI4 $353 ADDRLP4 24 INDIRI4 CNSTI4 122 LEI4 $351 LABELV $353 ADDRLP4 28 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 28 INDIRI4 CNSTI4 48 LTI4 $349 ADDRLP4 28 INDIRI4 CNSTI4 57 GTI4 $349 LABELV $351 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRGP4 $350 JUMPV LABELV $349 ADDRLP4 4 INDIRI4 CNSTI4 32 LTI4 $354 ADDRLP4 4 INDIRI4 CNSTI4 126 GTI4 $354 ADDRLP4 36 ADDRLP4 8 INDIRP4 ASGNP4 ADDRLP4 8 ADDRLP4 36 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 36 INDIRP4 ADDRLP4 4 INDIRI4 CVII1 4 ASGNI1 LABELV $354 LABELV $350 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $347 ADDRLP4 16 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 4 ADDRLP4 16 INDIRI4 ASGNI4 ADDRLP4 16 INDIRI4 CNSTI4 0 NEI4 $346 ADDRLP4 8 INDIRP4 CNSTI1 0 ASGNI1 ADDRFP4 0 INDIRP4 RETP4 LABELV $345 endproc Q_CleanStr 40 0 export Q_CountChar proc Q_CountChar 4 0 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 4 ADDRFP4 4 INDIRI4 CVII1 4 ASGNI1 ADDRLP4 0 CNSTI4 0 ASGNI4 ADDRGP4 $360 JUMPV LABELV $357 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 ADDRFP4 4 INDIRI1 CVII4 1 NEI4 $361 ADDRLP4 0 ADDRLP4 0 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 LABELV $361 LABELV $358 ADDRFP4 0 ADDRFP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $360 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $357 ADDRLP4 0 INDIRI4 RETI4 LABELV $356 endproc Q_CountChar 4 0 export Com_sprintf proc Com_sprintf 12 16 ADDRLP4 4 ADDRFP4 8+4 ASGNP4 ADDRFP4 0 INDIRP4 ARGP4 ADDRFP4 4 INDIRI4 CVIU4 4 ARGU4 ADDRFP4 8 INDIRP4 ARGP4 ADDRLP4 4 INDIRP4 ARGP4 ADDRLP4 8 ADDRGP4 qk_vsnprintf CALLI4 ASGNI4 ADDRLP4 0 ADDRLP4 8 INDIRI4 ASGNI4 ADDRLP4 4 CNSTP4 0 ASGNP4 ADDRLP4 0 INDIRI4 ADDRFP4 4 INDIRI4 LTI4 $365 ADDRGP4 $367 ARGP4 ADDRFP4 4 INDIRI4 ARGI4 ADDRLP4 0 INDIRI4 CNSTI4 1 ADDI4 ARGI4 ADDRGP4 Com_Printf CALLV pop LABELV $365 ADDRLP4 0 INDIRI4 RETI4 LABELV $363 endproc Com_sprintf 12 16 bss align 1 LABELV $369 skip 64000 data align 4 LABELV $370 byte 4 0 export va code proc va 20 16 ADDRLP4 8 ADDRGP4 $370 ASGNP4 ADDRLP4 12 ADDRLP4 8 INDIRP4 INDIRI4 ASGNI4 ADDRLP4 16 CNSTI4 1 ASGNI4 ADDRLP4 4 CNSTI4 32000 ADDRLP4 12 INDIRI4 ADDRLP4 16 INDIRI4 BANDI4 MULI4 ADDRGP4 $369 ADDP4 ASGNP4 ADDRLP4 8 INDIRP4 ADDRLP4 12 INDIRI4 ADDRLP4 16 INDIRI4 ADDI4 ASGNI4 ADDRLP4 0 ADDRFP4 0+4 ASGNP4 ADDRLP4 4 INDIRP4 ARGP4 CNSTU4 32000 ARGU4 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 0 INDIRP4 ARGP4 ADDRGP4 qk_vsnprintf CALLI4 pop ADDRLP4 0 CNSTP4 0 ASGNP4 ADDRLP4 4 INDIRP4 RETP4 LABELV $368 endproc va 20 16 export Com_TruncateLongString proc Com_TruncateLongString 8 12 ADDRFP4 4 INDIRP4 ARGP4 ADDRLP4 4 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRLP4 0 ADDRLP4 4 INDIRU4 CVUI4 4 ASGNI4 ADDRLP4 0 INDIRI4 CNSTI4 64 GTI4 $373 ADDRFP4 0 INDIRP4 ARGP4 ADDRFP4 4 INDIRP4 ARGP4 CNSTI4 64 ARGI4 ADDRGP4 Q_strncpyz CALLV pop ADDRGP4 $374 JUMPV LABELV $373 ADDRFP4 0 INDIRP4 ARGP4 ADDRFP4 4 INDIRP4 ARGP4 CNSTI4 29 ARGI4 ADDRGP4 Q_strncpyz CALLV pop ADDRFP4 0 INDIRP4 ARGP4 CNSTI4 64 ARGI4 ADDRGP4 $375 ARGP4 ADDRGP4 Q_strcat CALLV pop ADDRFP4 0 INDIRP4 ARGP4 CNSTI4 64 ARGI4 ADDRLP4 0 INDIRI4 ADDRFP4 4 INDIRP4 ADDP4 CNSTI4 -29 ADDP4 ARGP4 ADDRGP4 Q_strcat CALLV pop LABELV $374 LABELV $372 endproc Com_TruncateLongString 8 12 bss align 1 LABELV $377 skip 16384 data align 4 LABELV $378 byte 4 0 export Info_ValueForKey code proc Info_ValueForKey 8220 8 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 4 ADDRFP4 4 INDIRP4 ASGNP4 ADDRLP4 8196 CNSTU4 0 ASGNU4 ADDRFP4 0 INDIRP4 CVPU4 4 ADDRLP4 8196 INDIRU4 EQU4 $381 ADDRFP4 4 INDIRP4 CVPU4 4 ADDRLP4 8196 INDIRU4 NEU4 $379 LABELV $381 ADDRGP4 $38 RETP4 ADDRGP4 $376 JUMPV LABELV $379 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 8200 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRLP4 8200 INDIRU4 CNSTU4 8192 LTU4 $382 CNSTI4 1 ARGI4 ADDRGP4 $384 ARGP4 ADDRGP4 Com_Error CALLV pop LABELV $382 ADDRLP4 8204 ADDRGP4 $378 ASGNP4 ADDRLP4 8204 INDIRP4 ADDRLP4 8204 INDIRP4 INDIRI4 CNSTI4 1 BXORI4 ASGNI4 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 92 NEI4 $388 ADDRFP4 0 ADDRFP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRGP4 $388 JUMPV LABELV $387 ADDRLP4 0 ADDRLP4 4 ASGNP4 ADDRGP4 $391 JUMPV LABELV $390 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $393 ADDRGP4 $38 RETP4 ADDRGP4 $376 JUMPV LABELV $393 ADDRLP4 8208 ADDRLP4 0 INDIRP4 ASGNP4 ADDRLP4 8216 CNSTI4 1 ASGNI4 ADDRLP4 0 ADDRLP4 8208 INDIRP4 ADDRLP4 8216 INDIRI4 ADDP4 ASGNP4 ADDRLP4 8212 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 0 ADDRLP4 8212 INDIRP4 ADDRLP4 8216 INDIRI4 ADDP4 ASGNP4 ADDRLP4 8208 INDIRP4 ADDRLP4 8212 INDIRP4 INDIRI1 ASGNI1 LABELV $391 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 92 NEI4 $390 ADDRLP4 0 INDIRP4 CNSTI1 0 ASGNI1 ADDRFP4 0 ADDRFP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 0 ADDRGP4 $378 INDIRI4 CNSTI4 13 LSHI4 ADDRGP4 $377 ADDP4 ASGNP4 ADDRGP4 $396 JUMPV LABELV $395 ADDRLP4 8208 ADDRLP4 0 INDIRP4 ASGNP4 ADDRLP4 8216 CNSTI4 1 ASGNI4 ADDRLP4 0 ADDRLP4 8208 INDIRP4 ADDRLP4 8216 INDIRI4 ADDP4 ASGNP4 ADDRLP4 8212 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 0 ADDRLP4 8212 INDIRP4 ADDRLP4 8216 INDIRI4 ADDP4 ASGNP4 ADDRLP4 8208 INDIRP4 ADDRLP4 8212 INDIRP4 INDIRI1 ASGNI1 LABELV $396 ADDRLP4 8208 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 8208 INDIRI4 CNSTI4 92 EQI4 $398 ADDRLP4 8208 INDIRI4 CNSTI4 0 NEI4 $395 LABELV $398 ADDRLP4 0 INDIRP4 CNSTI1 0 ASGNI1 ADDRFP4 4 INDIRP4 ARGP4 ADDRLP4 4 ARGP4 ADDRLP4 8212 ADDRGP4 Q_stricmp CALLI4 ASGNI4 ADDRLP4 8212 INDIRI4 CNSTI4 0 NEI4 $399 ADDRGP4 $378 INDIRI4 CNSTI4 13 LSHI4 ADDRGP4 $377 ADDP4 RETP4 ADDRGP4 $376 JUMPV LABELV $399 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $401 ADDRGP4 $389 JUMPV LABELV $401 ADDRFP4 0 ADDRFP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $388 ADDRGP4 $387 JUMPV LABELV $389 ADDRGP4 $38 RETP4 LABELV $376 endproc Info_ValueForKey 8220 8 export Info_NextPair proc Info_NextPair 20 0 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRLP4 0 ADDRFP4 0 INDIRP4 INDIRP4 ASGNP4 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 92 NEI4 $404 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $404 ADDRFP4 4 INDIRP4 CNSTI1 0 ASGNI1 ADDRFP4 8 INDIRP4 CNSTI1 0 ASGNI1 ADDRLP4 4 ADDRFP4 4 INDIRP4 ASGNP4 ADDRGP4 $407 JUMPV LABELV $406 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $409 ADDRLP4 4 INDIRP4 CNSTI1 0 ASGNI1 ADDRFP4 0 INDIRP4 ADDRLP4 0 INDIRP4 ASGNP4 ADDRGP4 $403 JUMPV LABELV $409 ADDRLP4 8 ADDRLP4 4 INDIRP4 ASGNP4 ADDRLP4 16 CNSTI4 1 ASGNI4 ADDRLP4 4 ADDRLP4 8 INDIRP4 ADDRLP4 16 INDIRI4 ADDP4 ASGNP4 ADDRLP4 12 ADDRLP4 0 INDIRP4 ASGNP4 ADDRLP4 0 ADDRLP4 12 INDIRP4 ADDRLP4 16 INDIRI4 ADDP4 ASGNP4 ADDRLP4 8 INDIRP4 ADDRLP4 12 INDIRP4 INDIRI1 ASGNI1 LABELV $407 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 92 NEI4 $406 ADDRLP4 4 INDIRP4 CNSTI1 0 ASGNI1 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 4 ADDRFP4 8 INDIRP4 ASGNP4 ADDRGP4 $412 JUMPV LABELV $411 ADDRLP4 8 ADDRLP4 4 INDIRP4 ASGNP4 ADDRLP4 16 CNSTI4 1 ASGNI4 ADDRLP4 4 ADDRLP4 8 INDIRP4 ADDRLP4 16 INDIRI4 ADDP4 ASGNP4 ADDRLP4 12 ADDRLP4 0 INDIRP4 ASGNP4 ADDRLP4 0 ADDRLP4 12 INDIRP4 ADDRLP4 16 INDIRI4 ADDP4 ASGNP4 ADDRLP4 8 INDIRP4 ADDRLP4 12 INDIRP4 INDIRI1 ASGNI1 LABELV $412 ADDRLP4 8 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 8 INDIRI4 CNSTI4 92 EQI4 $414 ADDRLP4 8 INDIRI4 CNSTI4 0 NEI4 $411 LABELV $414 ADDRLP4 4 INDIRP4 CNSTI1 0 ASGNI1 ADDRFP4 0 INDIRP4 ADDRLP4 0 INDIRP4 ASGNP4 LABELV $403 endproc Info_NextPair 20 0 export Info_RemoveKey proc Info_RemoveKey 2080 12 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 4 ADDRFP4 4 INDIRP4 ASGNP4 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 2056 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRLP4 2056 INDIRU4 CNSTU4 1024 LTU4 $416 CNSTI4 1 ARGI4 ADDRGP4 $418 ARGP4 ADDRGP4 Com_Error CALLV pop LABELV $416 ADDRFP4 4 INDIRP4 ARGP4 CNSTI4 92 ARGI4 ADDRLP4 2060 ADDRGP4 qk_strchr CALLP4 ASGNP4 ADDRLP4 2060 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $422 ADDRGP4 $415 JUMPV LABELV $421 ADDRLP4 1028 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 92 NEI4 $424 ADDRFP4 0 ADDRFP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $424 ADDRLP4 0 ADDRLP4 4 ASGNP4 ADDRGP4 $427 JUMPV LABELV $426 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $429 ADDRGP4 $415 JUMPV LABELV $429 ADDRLP4 2068 ADDRLP4 0 INDIRP4 ASGNP4 ADDRLP4 2076 CNSTI4 1 ASGNI4 ADDRLP4 0 ADDRLP4 2068 INDIRP4 ADDRLP4 2076 INDIRI4 ADDP4 ASGNP4 ADDRLP4 2072 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 0 ADDRLP4 2072 INDIRP4 ADDRLP4 2076 INDIRI4 ADDP4 ASGNP4 ADDRLP4 2068 INDIRP4 ADDRLP4 2072 INDIRP4 INDIRI1 ASGNI1 LABELV $427 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 92 NEI4 $426 ADDRLP4 0 INDIRP4 CNSTI1 0 ASGNI1 ADDRFP4 0 ADDRFP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 0 ADDRLP4 1032 ASGNP4 ADDRGP4 $432 JUMPV LABELV $431 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $434 ADDRGP4 $415 JUMPV LABELV $434 ADDRLP4 2068 ADDRLP4 0 INDIRP4 ASGNP4 ADDRLP4 2076 CNSTI4 1 ASGNI4 ADDRLP4 0 ADDRLP4 2068 INDIRP4 ADDRLP4 2076 INDIRI4 ADDP4 ASGNP4 ADDRLP4 2072 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 0 ADDRLP4 2072 INDIRP4 ADDRLP4 2076 INDIRI4 ADDP4 ASGNP4 ADDRLP4 2068 INDIRP4 ADDRLP4 2072 INDIRP4 INDIRI1 ASGNI1 LABELV $432 ADDRLP4 2068 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 2068 INDIRI4 CNSTI4 92 EQI4 $436 ADDRLP4 2068 INDIRI4 CNSTI4 0 NEI4 $431 LABELV $436 ADDRLP4 0 INDIRP4 CNSTI1 0 ASGNI1 ADDRFP4 4 INDIRP4 ARGP4 ADDRLP4 4 ARGP4 ADDRLP4 2072 ADDRGP4 qk_strcmp CALLI4 ASGNI4 ADDRLP4 2072 INDIRI4 CNSTI4 0 NEI4 $437 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 2076 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRLP4 1028 INDIRP4 ARGP4 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 2076 INDIRU4 CNSTU4 1 ADDU4 ARGU4 ADDRGP4 qk_memmove CALLP4 pop ADDRGP4 $415 JUMPV LABELV $437 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $439 ADDRGP4 $415 JUMPV LABELV $439 LABELV $422 ADDRGP4 $421 JUMPV LABELV $415 endproc Info_RemoveKey 2080 12 export Info_RemoveKey_Big proc Info_RemoveKey_Big 16416 8 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 4 ADDRFP4 4 INDIRP4 ASGNP4 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 16392 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRLP4 16392 INDIRU4 CNSTU4 8192 LTU4 $442 CNSTI4 1 ARGI4 ADDRGP4 $444 ARGP4 ADDRGP4 Com_Error CALLV pop LABELV $442 ADDRFP4 4 INDIRP4 ARGP4 CNSTI4 92 ARGI4 ADDRLP4 16396 ADDRGP4 qk_strchr CALLP4 ASGNP4 ADDRLP4 16396 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $448 ADDRGP4 $441 JUMPV LABELV $447 ADDRLP4 8196 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 92 NEI4 $450 ADDRFP4 0 ADDRFP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $450 ADDRLP4 0 ADDRLP4 4 ASGNP4 ADDRGP4 $453 JUMPV LABELV $452 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $455 ADDRGP4 $441 JUMPV LABELV $455 ADDRLP4 16404 ADDRLP4 0 INDIRP4 ASGNP4 ADDRLP4 16412 CNSTI4 1 ASGNI4 ADDRLP4 0 ADDRLP4 16404 INDIRP4 ADDRLP4 16412 INDIRI4 ADDP4 ASGNP4 ADDRLP4 16408 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 0 ADDRLP4 16408 INDIRP4 ADDRLP4 16412 INDIRI4 ADDP4 ASGNP4 ADDRLP4 16404 INDIRP4 ADDRLP4 16408 INDIRP4 INDIRI1 ASGNI1 LABELV $453 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 92 NEI4 $452 ADDRLP4 0 INDIRP4 CNSTI1 0 ASGNI1 ADDRFP4 0 ADDRFP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 0 ADDRLP4 8200 ASGNP4 ADDRGP4 $458 JUMPV LABELV $457 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $460 ADDRGP4 $441 JUMPV LABELV $460 ADDRLP4 16404 ADDRLP4 0 INDIRP4 ASGNP4 ADDRLP4 16412 CNSTI4 1 ASGNI4 ADDRLP4 0 ADDRLP4 16404 INDIRP4 ADDRLP4 16412 INDIRI4 ADDP4 ASGNP4 ADDRLP4 16408 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 0 ADDRLP4 16408 INDIRP4 ADDRLP4 16412 INDIRI4 ADDP4 ASGNP4 ADDRLP4 16404 INDIRP4 ADDRLP4 16408 INDIRP4 INDIRI1 ASGNI1 LABELV $458 ADDRLP4 16404 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 ASGNI4 ADDRLP4 16404 INDIRI4 CNSTI4 92 EQI4 $462 ADDRLP4 16404 INDIRI4 CNSTI4 0 NEI4 $457 LABELV $462 ADDRLP4 0 INDIRP4 CNSTI1 0 ASGNI1 ADDRFP4 4 INDIRP4 ARGP4 ADDRLP4 4 ARGP4 ADDRLP4 16408 ADDRGP4 qk_strcmp CALLI4 ASGNI4 ADDRLP4 16408 INDIRI4 CNSTI4 0 NEI4 $463 ADDRLP4 8196 INDIRP4 ARGP4 ADDRFP4 0 INDIRP4 ARGP4 ADDRGP4 qk_strcpy CALLP4 pop ADDRGP4 $441 JUMPV LABELV $463 ADDRFP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $465 ADDRGP4 $441 JUMPV LABELV $465 LABELV $448 ADDRGP4 $447 JUMPV LABELV $441 endproc Info_RemoveKey_Big 16416 8 export Info_Validate proc Info_Validate 8 8 ADDRFP4 0 INDIRP4 ARGP4 CNSTI4 34 ARGI4 ADDRLP4 0 ADDRGP4 qk_strchr CALLP4 ASGNP4 ADDRLP4 0 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $468 CNSTI4 0 RETI4 ADDRGP4 $467 JUMPV LABELV $468 ADDRFP4 0 INDIRP4 ARGP4 CNSTI4 59 ARGI4 ADDRLP4 4 ADDRGP4 qk_strchr CALLP4 ASGNP4 ADDRLP4 4 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $470 CNSTI4 0 RETI4 ADDRGP4 $467 JUMPV LABELV $470 CNSTI4 1 RETI4 LABELV $467 endproc Info_Validate 8 8 export Info_SetValueForKey proc Info_SetValueForKey 1048 20 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 4 ADDRFP4 4 INDIRP4 ASGNP4 ADDRFP4 8 ADDRFP4 8 INDIRP4 ASGNP4 ADDRLP4 0 ADDRGP4 $473 ASGNP4 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 1028 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRLP4 1028 INDIRU4 CNSTU4 1024 LTU4 $480 CNSTI4 1 ARGI4 ADDRGP4 $476 ARGP4 ADDRGP4 Com_Error CALLV pop ADDRGP4 $480 JUMPV LABELV $477 ADDRFP4 4 INDIRP4 ARGP4 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ARGI4 ADDRLP4 1032 ADDRGP4 qk_strchr CALLP4 ASGNP4 ADDRLP4 1032 INDIRP4 CVPU4 4 CNSTU4 0 NEU4 $483 ADDRFP4 8 INDIRP4 ARGP4 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ARGI4 ADDRLP4 1036 ADDRGP4 qk_strchr CALLP4 ASGNP4 ADDRLP4 1036 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $481 LABELV $483 ADDRGP4 $484 ARGP4 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ARGI4 ADDRFP4 4 INDIRP4 ARGP4 ADDRFP4 8 INDIRP4 ARGP4 ADDRGP4 Com_Printf CALLV pop ADDRGP4 $472 JUMPV LABELV $481 LABELV $478 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $480 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $477 ADDRFP4 0 INDIRP4 ARGP4 ADDRFP4 4 INDIRP4 ARGP4 ADDRGP4 Info_RemoveKey CALLV pop ADDRFP4 8 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $487 ADDRFP4 8 INDIRP4 ARGP4 ADDRLP4 1036 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRLP4 1036 INDIRU4 CNSTU4 0 NEU4 $485 LABELV $487 ADDRGP4 $472 JUMPV LABELV $485 ADDRLP4 4 ARGP4 CNSTI4 1024 ARGI4 ADDRGP4 $488 ARGP4 ADDRFP4 4 INDIRP4 ARGP4 ADDRFP4 8 INDIRP4 ARGP4 ADDRGP4 Com_sprintf CALLI4 pop ADDRLP4 4 ARGP4 ADDRLP4 1040 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 1044 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRLP4 1040 INDIRU4 ADDRLP4 1044 INDIRU4 ADDU4 CNSTU4 1024 LTU4 $489 ADDRGP4 $491 ARGP4 ADDRGP4 Com_Printf CALLV pop ADDRGP4 $472 JUMPV LABELV $489 ADDRLP4 4 ARGP4 ADDRFP4 0 INDIRP4 ARGP4 ADDRGP4 qk_strcat CALLP4 pop ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 4 ARGP4 ADDRGP4 qk_strcpy CALLP4 pop LABELV $472 endproc Info_SetValueForKey 1048 20 export Info_SetValueForKey_Big proc Info_SetValueForKey_Big 8208 20 ADDRFP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRFP4 4 ADDRFP4 4 INDIRP4 ASGNP4 ADDRFP4 8 ADDRFP4 8 INDIRP4 ASGNP4 ADDRLP4 0 ADDRGP4 $473 ASGNP4 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 8196 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRLP4 8196 INDIRU4 CNSTU4 8192 LTU4 $498 CNSTI4 1 ARGI4 ADDRGP4 $476 ARGP4 ADDRGP4 Com_Error CALLV pop ADDRGP4 $498 JUMPV LABELV $495 ADDRFP4 4 INDIRP4 ARGP4 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ARGI4 ADDRLP4 8200 ADDRGP4 qk_strchr CALLP4 ASGNP4 ADDRLP4 8200 INDIRP4 CVPU4 4 CNSTU4 0 NEU4 $501 ADDRFP4 8 INDIRP4 ARGP4 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ARGI4 ADDRLP4 8204 ADDRGP4 qk_strchr CALLP4 ASGNP4 ADDRLP4 8204 INDIRP4 CVPU4 4 CNSTU4 0 EQU4 $499 LABELV $501 ADDRGP4 $484 ARGP4 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ARGI4 ADDRFP4 4 INDIRP4 ARGP4 ADDRFP4 8 INDIRP4 ARGP4 ADDRGP4 Com_Printf CALLV pop ADDRGP4 $492 JUMPV LABELV $499 LABELV $496 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $498 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $495 ADDRFP4 0 INDIRP4 ARGP4 ADDRFP4 4 INDIRP4 ARGP4 ADDRGP4 Info_RemoveKey_Big CALLV pop ADDRFP4 8 INDIRP4 CVPU4 4 CNSTU4 0 NEU4 $502 ADDRGP4 $492 JUMPV LABELV $502 ADDRLP4 4 ARGP4 CNSTI4 8192 ARGI4 ADDRGP4 $488 ARGP4 ADDRFP4 4 INDIRP4 ARGP4 ADDRFP4 8 INDIRP4 ARGP4 ADDRGP4 Com_sprintf CALLI4 pop ADDRLP4 4 ARGP4 ADDRLP4 8200 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 8204 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRLP4 8200 INDIRU4 ADDRLP4 8204 INDIRU4 ADDU4 CNSTU4 8192 LTU4 $504 ADDRGP4 $506 ARGP4 ADDRGP4 Com_Printf CALLV pop ADDRGP4 $492 JUMPV LABELV $504 ADDRFP4 0 INDIRP4 ARGP4 ADDRLP4 4 ARGP4 ADDRGP4 qk_strcat CALLP4 pop LABELV $492 endproc Info_SetValueForKey_Big 8208 20 proc Com_CharIsOneOfCharset 8 4 ADDRFP4 0 ADDRFP4 0 INDIRI4 CVII1 4 ASGNI1 ADDRFP4 4 ADDRFP4 4 INDIRP4 ASGNP4 ADDRLP4 0 CNSTI4 0 ASGNI4 ADDRGP4 $511 JUMPV LABELV $508 ADDRLP4 0 INDIRI4 ADDRFP4 4 INDIRP4 ADDP4 INDIRI1 CVII4 1 ADDRFP4 0 INDIRI1 CVII4 1 NEI4 $512 CNSTI4 1 RETI4 ADDRGP4 $507 JUMPV LABELV $512 LABELV $509 ADDRLP4 0 ADDRLP4 0 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 LABELV $511 ADDRFP4 4 INDIRP4 ARGP4 ADDRLP4 4 ADDRGP4 qk_strlen CALLU4 ASGNU4 ADDRLP4 0 INDIRI4 CVIU4 4 ADDRLP4 4 INDIRU4 LTU4 $508 CNSTI4 0 RETI4 LABELV $507 endproc Com_CharIsOneOfCharset 8 4 export Com_SkipCharset proc Com_SkipCharset 8 8 ADDRFP4 4 ADDRFP4 4 INDIRP4 ASGNP4 ADDRLP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRGP4 $516 JUMPV LABELV $515 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ARGI4 ADDRFP4 4 INDIRP4 ARGP4 ADDRLP4 4 ADDRGP4 Com_CharIsOneOfCharset CALLI4 ASGNI4 ADDRLP4 4 INDIRI4 CNSTI4 0 EQI4 $517 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $519 LABELV $516 ADDRLP4 0 INDIRP4 CVPU4 4 CNSTU4 0 NEU4 $515 LABELV $517 ADDRLP4 0 INDIRP4 RETP4 LABELV $514 endproc Com_SkipCharset 8 8 export Com_SkipTokens proc Com_SkipTokens 20 8 ADDRFP4 4 ADDRFP4 4 INDIRI4 ASGNI4 ADDRFP4 8 ADDRFP4 8 INDIRP4 ASGNP4 ADDRLP4 4 CNSTI4 0 ASGNI4 ADDRLP4 0 ADDRFP4 0 INDIRP4 ASGNP4 ADDRGP4 $522 JUMPV LABELV $521 ADDRLP4 8 ADDRLP4 0 INDIRP4 ASGNP4 ADDRLP4 0 ADDRLP4 8 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 ADDRLP4 8 INDIRP4 INDIRI1 CVII4 1 ARGI4 ADDRFP4 8 INDIRP4 ARGP4 ADDRLP4 12 ADDRGP4 Com_CharIsOneOfCharset CALLI4 ASGNI4 ADDRLP4 12 INDIRI4 CNSTI4 0 EQI4 $524 ADDRLP4 4 ADDRLP4 4 INDIRI4 CNSTI4 1 ADDI4 ASGNI4 ADDRGP4 $527 JUMPV LABELV $526 ADDRLP4 0 ADDRLP4 0 INDIRP4 CNSTI4 1 ADDP4 ASGNP4 LABELV $527 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 ARGI4 ADDRFP4 8 INDIRP4 ARGP4 ADDRLP4 16 ADDRGP4 Com_CharIsOneOfCharset CALLI4 ASGNI4 ADDRLP4 16 INDIRI4 CNSTI4 0 NEI4 $526 ADDRGP4 $525 JUMPV LABELV $524 ADDRLP4 0 INDIRP4 INDIRI1 CVII4 1 CNSTI4 0 NEI4 $529 ADDRGP4 $523 JUMPV LABELV $529 LABELV $525 LABELV $522 ADDRLP4 4 INDIRI4 ADDRFP4 4 INDIRI4 LTI4 $521 LABELV $523 ADDRLP4 4 INDIRI4 ADDRFP4 4 INDIRI4 NEI4 $531 ADDRLP4 0 INDIRP4 RETP4 ADDRGP4 $520 JUMPV LABELV $531 ADDRFP4 0 INDIRP4 RETP4 LABELV $520 endproc Com_SkipTokens 20 8 bss align 4 LABELV com_tokenline skip 4 align 4 LABELV com_lines skip 4 align 1 LABELV com_parsename skip 1024 align 1 LABELV com_token skip 1024 import Com_Printf import Com_Error import Com_RandomBytes import PerpendicularVector import AngleVectors import MatrixMultiply import MakeNormalVectors import RotateAroundDirection import RotatePointAroundVector import ProjectPointOnPlane import PlaneFromPoints import AngleDelta import AngleNormalize180 import AngleNormalize360 import AnglesSubtract import AngleSubtract import LerpAngle import AngleMod import BoundsIntersectPoint import BoundsIntersectSphere import BoundsIntersect import BoxOnPlaneSide import SetPlaneSignbits import AxisCopy import AxisClear import AnglesToAxis import vectoangles import Q_crandom import Q_random import Q_rand import Q_acos import Q_log2 import VectorRotate import Vector4Scale import VectorNormalize2 import VectorNormalize import CrossProduct import VectorInverse import VectorNormalizeFast import DistanceSquared import Distance import VectorLengthSquared import VectorLength import VectorCompare import AddPointToBounds import ClearBounds import RadiusFromBounds import NormalizeColor import ColorBytes4 import ColorBytes3 import _VectorMA import _VectorScale import _VectorCopy import _VectorAdd import _VectorSubtract import _DotProduct import ByteToDir import DirToByte import ClampShort import ClampChar import Q_rsqrt import Q_fabs import Q_isnan import axisDefault import vec3_origin import g_color_table import colorDkGrey import colorMdGrey import colorLtGrey import colorWhite import colorCyan import colorMagenta import colorYellow import colorBlue import colorGreen import colorRed import colorBlack import bytedirs import Hunk_AllocDebug import qk_acos import qk_fabs import qk_abs import qk_tan import qk_atan2 import qk_cos import qk_sin import qk_sqrt import qk_floor import qk_ceil import qk_memcpy import qk_memset import qk_memmove import qk_sscanf import qk_vsnprintf import qk_strtol import qk_atoi import qk_strtod import qk_atof import qk_toupper import qk_tolower import qk_strncpy import qk_strstr import qk_strrchr import qk_strchr import qk_strcmp import qk_strcpy import qk_strcat import qk_strlen import qk_rand import qk_srand import qk_qsort lit align 1 LABELV $506 byte 1 66 byte 1 73 byte 1 71 byte 1 32 byte 1 73 byte 1 110 byte 1 102 byte 1 111 byte 1 32 byte 1 115 byte 1 116 byte 1 114 byte 1 105 byte 1 110 byte 1 103 byte 1 32 byte 1 108 byte 1 101 byte 1 110 byte 1 103 byte 1 116 byte 1 104 byte 1 32 byte 1 101 byte 1 120 byte 1 99 byte 1 101 byte 1 101 byte 1 100 byte 1 101 byte 1 100 byte 1 10 byte 1 0 align 1 LABELV $491 byte 1 73 byte 1 110 byte 1 102 byte 1 111 byte 1 32 byte 1 115 byte 1 116 byte 1 114 byte 1 105 byte 1 110 byte 1 103 byte 1 32 byte 1 108 byte 1 101 byte 1 110 byte 1 103 byte 1 116 byte 1 104 byte 1 32 byte 1 101 byte 1 120 byte 1 99 byte 1 101 byte 1 101 byte 1 100 byte 1 101 byte 1 100 byte 1 10 byte 1 0 align 1 LABELV $488 byte 1 92 byte 1 37 byte 1 115 byte 1 92 byte 1 37 byte 1 115 byte 1 0 align 1 LABELV $484 byte 1 94 byte 1 51 byte 1 67 byte 1 97 byte 1 110 byte 1 39 byte 1 116 byte 1 32 byte 1 117 byte 1 115 byte 1 101 byte 1 32 byte 1 107 byte 1 101 byte 1 121 byte 1 115 byte 1 32 byte 1 111 byte 1 114 byte 1 32 byte 1 118 byte 1 97 byte 1 108 byte 1 117 byte 1 101 byte 1 115 byte 1 32 byte 1 119 byte 1 105 byte 1 116 byte 1 104 byte 1 32 byte 1 97 byte 1 32 byte 1 39 byte 1 37 byte 1 99 byte 1 39 byte 1 58 byte 1 32 byte 1 37 byte 1 115 byte 1 32 byte 1 61 byte 1 32 byte 1 37 byte 1 115 byte 1 10 byte 1 0 align 1 LABELV $476 byte 1 73 byte 1 110 byte 1 102 byte 1 111 byte 1 95 byte 1 83 byte 1 101 byte 1 116 byte 1 86 byte 1 97 byte 1 108 byte 1 117 byte 1 101 byte 1 70 byte 1 111 byte 1 114 byte 1 75 byte 1 101 byte 1 121 byte 1 58 byte 1 32 byte 1 111 byte 1 118 byte 1 101 byte 1 114 byte 1 115 byte 1 105 byte 1 122 byte 1 101 byte 1 32 byte 1 105 byte 1 110 byte 1 102 byte 1 111 byte 1 115 byte 1 116 byte 1 114 byte 1 105 byte 1 110 byte 1 103 byte 1 0 align 1 LABELV $473 byte 1 92 byte 1 59 byte 1 34 byte 1 0 align 1 LABELV $444 byte 1 73 byte 1 110 byte 1 102 byte 1 111 byte 1 95 byte 1 82 byte 1 101 byte 1 109 byte 1 111 byte 1 118 byte 1 101 byte 1 75 byte 1 101 byte 1 121 byte 1 95 byte 1 66 byte 1 105 byte 1 103 byte 1 58 byte 1 32 byte 1 111 byte 1 118 byte 1 101 byte 1 114 byte 1 115 byte 1 105 byte 1 122 byte 1 101 byte 1 32 byte 1 105 byte 1 110 byte 1 102 byte 1 111 byte 1 115 byte 1 116 byte 1 114 byte 1 105 byte 1 110 byte 1 103 byte 1 0 align 1 LABELV $418 byte 1 73 byte 1 110 byte 1 102 byte 1 111 byte 1 95 byte 1 82 byte 1 101 byte 1 109 byte 1 111 byte 1 118 byte 1 101 byte 1 75 byte 1 101 byte 1 121 byte 1 58 byte 1 32 byte 1 111 byte 1 118 byte 1 101 byte 1 114 byte 1 115 byte 1 105 byte 1 122 byte 1 101 byte 1 32 byte 1 105 byte 1 110 byte 1 102 byte 1 111 byte 1 115 byte 1 116 byte 1 114 byte 1 105 byte 1 110 byte 1 103 byte 1 0 align 1 LABELV $384 byte 1 73 byte 1 110 byte 1 102 byte 1 111 byte 1 95 byte 1 86 byte 1 97 byte 1 108 byte 1 117 byte 1 101 byte 1 70 byte 1 111 byte 1 114 byte 1 75 byte 1 101 byte 1 121 byte 1 58 byte 1 32 byte 1 111 byte 1 118 byte 1 101 byte 1 114 byte 1 115 byte 1 105 byte 1 122 byte 1 101 byte 1 32 byte 1 105 byte 1 110 byte 1 102 byte 1 111 byte 1 115 byte 1 116 byte 1 114 byte 1 105 byte 1 110 byte 1 103 byte 1 0 align 1 LABELV $375 byte 1 32 byte 1 46 byte 1 46 byte 1 46 byte 1 32 byte 1 0 align 1 LABELV $367 byte 1 67 byte 1 111 byte 1 109 byte 1 95 byte 1 115 byte 1 112 byte 1 114 byte 1 105 byte 1 110 byte 1 116 byte 1 102 byte 1 58 byte 1 32 byte 1 79 byte 1 117 byte 1 116 byte 1 112 byte 1 117 byte 1 116 byte 1 32 byte 1 108 byte 1 101 byte 1 110 byte 1 103 byte 1 116 byte 1 104 byte 1 32 byte 1 37 byte 1 100 byte 1 32 byte 1 116 byte 1 111 byte 1 111 byte 1 32 byte 1 115 byte 1 104 byte 1 111 byte 1 114 byte 1 116 byte 1 44 byte 1 32 byte 1 114 byte 1 101 byte 1 113 byte 1 117 byte 1 105 byte 1 114 byte 1 101 byte 1 32 byte 1 37 byte 1 100 byte 1 32 byte 1 98 byte 1 121 byte 1 116 byte 1 101 byte 1 115 byte 1 46 byte 1 10 byte 1 0 align 1 LABELV $318 byte 1 81 byte 1 95 byte 1 115 byte 1 116 byte 1 114 byte 1 99 byte 1 97 byte 1 116 byte 1 58 byte 1 32 byte 1 97 byte 1 108 byte 1 114 byte 1 101 byte 1 97 byte 1 100 byte 1 121 byte 1 32 byte 1 111 byte 1 118 byte 1 101 byte 1 114 byte 1 102 byte 1 108 byte 1 111 byte 1 119 byte 1 101 byte 1 100 byte 1 0 align 1 LABELV $268 byte 1 81 byte 1 95 byte 1 115 byte 1 116 byte 1 114 byte 1 110 byte 1 99 byte 1 112 byte 1 121 byte 1 122 byte 1 58 byte 1 32 byte 1 100 byte 1 101 byte 1 115 byte 1 116 byte 1 115 byte 1 105 byte 1 122 byte 1 101 byte 1 32 byte 1 60 byte 1 32 byte 1 49 byte 1 0 align 1 LABELV $265 byte 1 81 byte 1 95 byte 1 115 byte 1 116 byte 1 114 byte 1 110 byte 1 99 byte 1 112 byte 1 121 byte 1 122 byte 1 58 byte 1 32 byte 1 78 byte 1 85 byte 1 76 byte 1 76 byte 1 32 byte 1 115 byte 1 114 byte 1 99 byte 1 0 align 1 LABELV $262 byte 1 81 byte 1 95 byte 1 115 byte 1 116 byte 1 114 byte 1 110 byte 1 99 byte 1 112 byte 1 121 byte 1 122 byte 1 58 byte 1 32 byte 1 78 byte 1 85 byte 1 76 byte 1 76 byte 1 32 byte 1 100 byte 1 101 byte 1 115 byte 1 116 byte 1 0 align 1 LABELV $210 byte 1 41 byte 1 0 align 1 LABELV $205 byte 1 40 byte 1 0 align 1 LABELV $183 byte 1 77 byte 1 97 byte 1 116 byte 1 99 byte 1 104 byte 1 84 byte 1 111 byte 1 107 byte 1 101 byte 1 110 byte 1 58 byte 1 32 byte 1 37 byte 1 115 byte 1 32 byte 1 33 byte 1 61 byte 1 32 byte 1 37 byte 1 115 byte 1 0 align 1 LABELV $89 byte 1 87 byte 1 65 byte 1 82 byte 1 78 byte 1 73 byte 1 78 byte 1 71 byte 1 58 byte 1 32 byte 1 37 byte 1 115 byte 1 44 byte 1 32 byte 1 108 byte 1 105 byte 1 110 byte 1 101 byte 1 32 byte 1 37 byte 1 100 byte 1 58 byte 1 32 byte 1 37 byte 1 115 byte 1 10 byte 1 0 align 1 LABELV $85 byte 1 69 byte 1 82 byte 1 82 byte 1 79 byte 1 82 byte 1 58 byte 1 32 byte 1 37 byte 1 115 byte 1 44 byte 1 32 byte 1 108 byte 1 105 byte 1 110 byte 1 101 byte 1 32 byte 1 37 byte 1 100 byte 1 58 byte 1 32 byte 1 37 byte 1 115 byte 1 10 byte 1 0 align 1 LABELV $77 byte 1 37 byte 1 115 byte 1 0 align 1 LABELV $38 byte 1 0
// RobotBuilder Version: 3.1 // // This file was generated by RobotBuilder. It contains sections of // code that are automatically generated and assigned by robotbuilder. // These sections will be updated in the future when you export to // C++ from RobotBuilder. Do not put any code or make any change in // the blocks indicating autogenerated code or it will be lost on an // update. Deleting the comments indicating the section will prevent // it from being updated in the future. #include "commands/AutoDrivePath.h" #include "commands/AutoDriveStop.h" #include "frc2135/RobotConfig.h" #include <spdlog/spdlog.h> // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR #include "commands/AutoPathSequence.h" AutoPathSequence::AutoPathSequence(Drivetrain *drivetrain) { // Use AddRequirements() here to declare subsystem dependencies // eg. AddRequirements(m_Subsystem); SetName("AutoPathSequence"); // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTRUCTOR // Add your commands here, e.g. // AddCommands(FooCommand(), BarCommand()); frc2135::RobotConfig *config = frc2135::RobotConfig::GetInstance(); config->GetValueAsString("path1", path1, "driveForward"); config->GetValueAsString("path2", path2, "driveForward"); config->GetValueAsString("path3", path3, "driveForward"); spdlog::info("AutoPathSequence: path1 name: {}", path1); spdlog::info("AutoPathSequence: path2 name: {}", path2); spdlog::info("AutoPathSequence: path3 name: {}", path3); AddCommands( AutoDrivePath(path1.c_str(), drivetrain), AutoDrivePath(path2.c_str(), drivetrain), // AutoDrivePath(path3.c_str(), drivetrain) AutoDriveStop(drivetrain)); } bool AutoPathSequence::RunsWhenDisabled() const { // BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DISABLED return false; // END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DISABLED }
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2013, OpenCV Foundation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the OpenCV Foundation 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 <list> #include <map> #include <string> #include <sstream> #include <iostream> // std::cerr #define CV_OPENCL_ALWAYS_SHOW_BUILD_LOG 0 #include "opencv2/core/bufferpool.hpp" #ifndef LOG_BUFFER_POOL # if 0 # define LOG_BUFFER_POOL printf # else # define LOG_BUFFER_POOL(...) # endif #endif // TODO Move to some common place static size_t getConfigurationParameterForSize(const char* name, size_t defaultValue) { const char* envValue = getenv(name); if (envValue == NULL) { return defaultValue; } cv::String value = envValue; size_t pos = 0; for (; pos < value.size(); pos++) { if (!isdigit(value[pos])) break; } cv::String valueStr = value.substr(0, pos); cv::String suffixStr = value.substr(pos, value.length() - pos); int v = atoi(valueStr.c_str()); if (suffixStr.length() == 0) return v; else if (suffixStr == "MB" || suffixStr == "Mb" || suffixStr == "mb") return v * 1024 * 1024; else if (suffixStr == "KB" || suffixStr == "Kb" || suffixStr == "kb") return v * 1024; CV_ErrorNoReturn(cv::Error::StsBadArg, cv::format("Invalid value for %s parameter: %s", name, value.c_str())); } #include "opencv2/core/opencl/runtime/opencl_clamdblas.hpp" #include "opencv2/core/opencl/runtime/opencl_clamdfft.hpp" #ifdef HAVE_OPENCL #include "opencv2/core/opencl/runtime/opencl_core.hpp" #else // TODO FIXIT: This file can't be build without OPENCL /* Part of the file is an extract from the standard OpenCL headers from Khronos site. Below is the original copyright. */ /******************************************************************************* * Copyright (c) 2008 - 2012 The Khronos Group Inc. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and/or associated documentation files (the * "Materials"), to deal in the Materials without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Materials, and to * permit persons to whom the Materials are furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Materials. * * THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. ******************************************************************************/ #if 0 //defined __APPLE__ #define HAVE_OPENCL 1 #else #undef HAVE_OPENCL #endif #define OPENCV_CL_NOT_IMPLEMENTED -1000 #ifdef HAVE_OPENCL #if defined __APPLE__ #include <OpenCL/opencl.h> #else #include <CL/opencl.h> #endif static const bool g_haveOpenCL = true; #else extern "C" { struct _cl_platform_id { int dummy; }; struct _cl_device_id { int dummy; }; struct _cl_context { int dummy; }; struct _cl_command_queue { int dummy; }; struct _cl_mem { int dummy; }; struct _cl_program { int dummy; }; struct _cl_kernel { int dummy; }; struct _cl_event { int dummy; }; struct _cl_sampler { int dummy; }; typedef struct _cl_platform_id * cl_platform_id; typedef struct _cl_device_id * cl_device_id; typedef struct _cl_context * cl_context; typedef struct _cl_command_queue * cl_command_queue; typedef struct _cl_mem * cl_mem; typedef struct _cl_program * cl_program; typedef struct _cl_kernel * cl_kernel; typedef struct _cl_event * cl_event; typedef struct _cl_sampler * cl_sampler; typedef int cl_int; typedef unsigned cl_uint; #if defined (_WIN32) && defined(_MSC_VER) typedef __int64 cl_long; typedef unsigned __int64 cl_ulong; #else typedef long cl_long; typedef unsigned long cl_ulong; #endif typedef cl_uint cl_bool; /* WARNING! Unlike cl_ types in cl_platform.h, cl_bool is not guaranteed to be the same size as the bool in kernels. */ typedef cl_ulong cl_bitfield; typedef cl_bitfield cl_device_type; typedef cl_uint cl_platform_info; typedef cl_uint cl_device_info; typedef cl_bitfield cl_device_fp_config; typedef cl_uint cl_device_mem_cache_type; typedef cl_uint cl_device_local_mem_type; typedef cl_bitfield cl_device_exec_capabilities; typedef cl_bitfield cl_command_queue_properties; typedef intptr_t cl_device_partition_property; typedef cl_bitfield cl_device_affinity_domain; typedef intptr_t cl_context_properties; typedef cl_uint cl_context_info; typedef cl_uint cl_command_queue_info; typedef cl_uint cl_channel_order; typedef cl_uint cl_channel_type; typedef cl_bitfield cl_mem_flags; typedef cl_uint cl_mem_object_type; typedef cl_uint cl_mem_info; typedef cl_bitfield cl_mem_migration_flags; typedef cl_uint cl_image_info; typedef cl_uint cl_buffer_create_type; typedef cl_uint cl_addressing_mode; typedef cl_uint cl_filter_mode; typedef cl_uint cl_sampler_info; typedef cl_bitfield cl_map_flags; typedef cl_uint cl_program_info; typedef cl_uint cl_program_build_info; typedef cl_uint cl_program_binary_type; typedef cl_int cl_build_status; typedef cl_uint cl_kernel_info; typedef cl_uint cl_kernel_arg_info; typedef cl_uint cl_kernel_arg_address_qualifier; typedef cl_uint cl_kernel_arg_access_qualifier; typedef cl_bitfield cl_kernel_arg_type_qualifier; typedef cl_uint cl_kernel_work_group_info; typedef cl_uint cl_event_info; typedef cl_uint cl_command_type; typedef cl_uint cl_profiling_info; typedef struct _cl_image_format { cl_channel_order image_channel_order; cl_channel_type image_channel_data_type; } cl_image_format; typedef struct _cl_image_desc { cl_mem_object_type image_type; size_t image_width; size_t image_height; size_t image_depth; size_t image_array_size; size_t image_row_pitch; size_t image_slice_pitch; cl_uint num_mip_levels; cl_uint num_samples; cl_mem buffer; } cl_image_desc; typedef struct _cl_buffer_region { size_t origin; size_t size; } cl_buffer_region; ////////////////////////////////////////////////////////// #define CL_SUCCESS 0 #define CL_DEVICE_NOT_FOUND -1 #define CL_DEVICE_NOT_AVAILABLE -2 #define CL_COMPILER_NOT_AVAILABLE -3 #define CL_MEM_OBJECT_ALLOCATION_FAILURE -4 #define CL_OUT_OF_RESOURCES -5 #define CL_OUT_OF_HOST_MEMORY -6 #define CL_PROFILING_INFO_NOT_AVAILABLE -7 #define CL_MEM_COPY_OVERLAP -8 #define CL_IMAGE_FORMAT_MISMATCH -9 #define CL_IMAGE_FORMAT_NOT_SUPPORTED -10 #define CL_BUILD_PROGRAM_FAILURE -11 #define CL_MAP_FAILURE -12 #define CL_MISALIGNED_SUB_BUFFER_OFFSET -13 #define CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST -14 #define CL_COMPILE_PROGRAM_FAILURE -15 #define CL_LINKER_NOT_AVAILABLE -16 #define CL_LINK_PROGRAM_FAILURE -17 #define CL_DEVICE_PARTITION_FAILED -18 #define CL_KERNEL_ARG_INFO_NOT_AVAILABLE -19 #define CL_INVALID_VALUE -30 #define CL_INVALID_DEVICE_TYPE -31 #define CL_INVALID_PLATFORM -32 #define CL_INVALID_DEVICE -33 #define CL_INVALID_CONTEXT -34 #define CL_INVALID_QUEUE_PROPERTIES -35 #define CL_INVALID_COMMAND_QUEUE -36 #define CL_INVALID_HOST_PTR -37 #define CL_INVALID_MEM_OBJECT -38 #define CL_INVALID_IMAGE_FORMAT_DESCRIPTOR -39 #define CL_INVALID_IMAGE_SIZE -40 #define CL_INVALID_SAMPLER -41 #define CL_INVALID_BINARY -42 #define CL_INVALID_BUILD_OPTIONS -43 #define CL_INVALID_PROGRAM -44 #define CL_INVALID_PROGRAM_EXECUTABLE -45 #define CL_INVALID_KERNEL_NAME -46 #define CL_INVALID_KERNEL_DEFINITION -47 #define CL_INVALID_KERNEL -48 #define CL_INVALID_ARG_INDEX -49 #define CL_INVALID_ARG_VALUE -50 #define CL_INVALID_ARG_SIZE -51 #define CL_INVALID_KERNEL_ARGS -52 #define CL_INVALID_WORK_DIMENSION -53 #define CL_INVALID_WORK_GROUP_SIZE -54 #define CL_INVALID_WORK_ITEM_SIZE -55 #define CL_INVALID_GLOBAL_OFFSET -56 #define CL_INVALID_EVENT_WAIT_LIST -57 #define CL_INVALID_EVENT -58 #define CL_INVALID_OPERATION -59 #define CL_INVALID_GL_OBJECT -60 #define CL_INVALID_BUFFER_SIZE -61 #define CL_INVALID_MIP_LEVEL -62 #define CL_INVALID_GLOBAL_WORK_SIZE -63 #define CL_INVALID_PROPERTY -64 #define CL_INVALID_IMAGE_DESCRIPTOR -65 #define CL_INVALID_COMPILER_OPTIONS -66 #define CL_INVALID_LINKER_OPTIONS -67 #define CL_INVALID_DEVICE_PARTITION_COUNT -68 /*#define CL_VERSION_1_0 1 #define CL_VERSION_1_1 1 #define CL_VERSION_1_2 1*/ #define CL_FALSE 0 #define CL_TRUE 1 #define CL_BLOCKING CL_TRUE #define CL_NON_BLOCKING CL_FALSE #define CL_PLATFORM_PROFILE 0x0900 #define CL_PLATFORM_VERSION 0x0901 #define CL_PLATFORM_NAME 0x0902 #define CL_PLATFORM_VENDOR 0x0903 #define CL_PLATFORM_EXTENSIONS 0x0904 #define CL_DEVICE_TYPE_DEFAULT (1 << 0) #define CL_DEVICE_TYPE_CPU (1 << 1) #define CL_DEVICE_TYPE_GPU (1 << 2) #define CL_DEVICE_TYPE_ACCELERATOR (1 << 3) #define CL_DEVICE_TYPE_CUSTOM (1 << 4) #define CL_DEVICE_TYPE_ALL 0xFFFFFFFF #define CL_DEVICE_TYPE 0x1000 #define CL_DEVICE_VENDOR_ID 0x1001 #define CL_DEVICE_MAX_COMPUTE_UNITS 0x1002 #define CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS 0x1003 #define CL_DEVICE_MAX_WORK_GROUP_SIZE 0x1004 #define CL_DEVICE_MAX_WORK_ITEM_SIZES 0x1005 #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR 0x1006 #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT 0x1007 #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT 0x1008 #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG 0x1009 #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT 0x100A #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE 0x100B #define CL_DEVICE_MAX_CLOCK_FREQUENCY 0x100C #define CL_DEVICE_ADDRESS_BITS 0x100D #define CL_DEVICE_MAX_READ_IMAGE_ARGS 0x100E #define CL_DEVICE_MAX_WRITE_IMAGE_ARGS 0x100F #define CL_DEVICE_MAX_MEM_ALLOC_SIZE 0x1010 #define CL_DEVICE_IMAGE2D_MAX_WIDTH 0x1011 #define CL_DEVICE_IMAGE2D_MAX_HEIGHT 0x1012 #define CL_DEVICE_IMAGE3D_MAX_WIDTH 0x1013 #define CL_DEVICE_IMAGE3D_MAX_HEIGHT 0x1014 #define CL_DEVICE_IMAGE3D_MAX_DEPTH 0x1015 #define CL_DEVICE_IMAGE_SUPPORT 0x1016 #define CL_DEVICE_MAX_PARAMETER_SIZE 0x1017 #define CL_DEVICE_MAX_SAMPLERS 0x1018 #define CL_DEVICE_MEM_BASE_ADDR_ALIGN 0x1019 #define CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE 0x101A #define CL_DEVICE_SINGLE_FP_CONFIG 0x101B #define CL_DEVICE_GLOBAL_MEM_CACHE_TYPE 0x101C #define CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE 0x101D #define CL_DEVICE_GLOBAL_MEM_CACHE_SIZE 0x101E #define CL_DEVICE_GLOBAL_MEM_SIZE 0x101F #define CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE 0x1020 #define CL_DEVICE_MAX_CONSTANT_ARGS 0x1021 #define CL_DEVICE_LOCAL_MEM_TYPE 0x1022 #define CL_DEVICE_LOCAL_MEM_SIZE 0x1023 #define CL_DEVICE_ERROR_CORRECTION_SUPPORT 0x1024 #define CL_DEVICE_PROFILING_TIMER_RESOLUTION 0x1025 #define CL_DEVICE_ENDIAN_LITTLE 0x1026 #define CL_DEVICE_AVAILABLE 0x1027 #define CL_DEVICE_COMPILER_AVAILABLE 0x1028 #define CL_DEVICE_EXECUTION_CAPABILITIES 0x1029 #define CL_DEVICE_QUEUE_PROPERTIES 0x102A #define CL_DEVICE_NAME 0x102B #define CL_DEVICE_VENDOR 0x102C #define CL_DRIVER_VERSION 0x102D #define CL_DEVICE_PROFILE 0x102E #define CL_DEVICE_VERSION 0x102F #define CL_DEVICE_EXTENSIONS 0x1030 #define CL_DEVICE_PLATFORM 0x1031 #define CL_DEVICE_DOUBLE_FP_CONFIG 0x1032 #define CL_DEVICE_HALF_FP_CONFIG 0x1033 #define CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF 0x1034 #define CL_DEVICE_HOST_UNIFIED_MEMORY 0x1035 #define CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR 0x1036 #define CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT 0x1037 #define CL_DEVICE_NATIVE_VECTOR_WIDTH_INT 0x1038 #define CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG 0x1039 #define CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT 0x103A #define CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE 0x103B #define CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF 0x103C #define CL_DEVICE_OPENCL_C_VERSION 0x103D #define CL_DEVICE_LINKER_AVAILABLE 0x103E #define CL_DEVICE_BUILT_IN_KERNELS 0x103F #define CL_DEVICE_IMAGE_MAX_BUFFER_SIZE 0x1040 #define CL_DEVICE_IMAGE_MAX_ARRAY_SIZE 0x1041 #define CL_DEVICE_PARENT_DEVICE 0x1042 #define CL_DEVICE_PARTITION_MAX_SUB_DEVICES 0x1043 #define CL_DEVICE_PARTITION_PROPERTIES 0x1044 #define CL_DEVICE_PARTITION_AFFINITY_DOMAIN 0x1045 #define CL_DEVICE_PARTITION_TYPE 0x1046 #define CL_DEVICE_REFERENCE_COUNT 0x1047 #define CL_DEVICE_PREFERRED_INTEROP_USER_SYNC 0x1048 #define CL_DEVICE_PRINTF_BUFFER_SIZE 0x1049 #define CL_DEVICE_IMAGE_PITCH_ALIGNMENT 0x104A #define CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT 0x104B #define CL_FP_DENORM (1 << 0) #define CL_FP_INF_NAN (1 << 1) #define CL_FP_ROUND_TO_NEAREST (1 << 2) #define CL_FP_ROUND_TO_ZERO (1 << 3) #define CL_FP_ROUND_TO_INF (1 << 4) #define CL_FP_FMA (1 << 5) #define CL_FP_SOFT_FLOAT (1 << 6) #define CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT (1 << 7) #define CL_NONE 0x0 #define CL_READ_ONLY_CACHE 0x1 #define CL_READ_WRITE_CACHE 0x2 #define CL_LOCAL 0x1 #define CL_GLOBAL 0x2 #define CL_EXEC_KERNEL (1 << 0) #define CL_EXEC_NATIVE_KERNEL (1 << 1) #define CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE (1 << 0) #define CL_QUEUE_PROFILING_ENABLE (1 << 1) #define CL_CONTEXT_REFERENCE_COUNT 0x1080 #define CL_CONTEXT_DEVICES 0x1081 #define CL_CONTEXT_PROPERTIES 0x1082 #define CL_CONTEXT_NUM_DEVICES 0x1083 #define CL_CONTEXT_PLATFORM 0x1084 #define CL_CONTEXT_INTEROP_USER_SYNC 0x1085 #define CL_DEVICE_PARTITION_EQUALLY 0x1086 #define CL_DEVICE_PARTITION_BY_COUNTS 0x1087 #define CL_DEVICE_PARTITION_BY_COUNTS_LIST_END 0x0 #define CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN 0x1088 #define CL_DEVICE_AFFINITY_DOMAIN_NUMA (1 << 0) #define CL_DEVICE_AFFINITY_DOMAIN_L4_CACHE (1 << 1) #define CL_DEVICE_AFFINITY_DOMAIN_L3_CACHE (1 << 2) #define CL_DEVICE_AFFINITY_DOMAIN_L2_CACHE (1 << 3) #define CL_DEVICE_AFFINITY_DOMAIN_L1_CACHE (1 << 4) #define CL_DEVICE_AFFINITY_DOMAIN_NEXT_PARTITIONABLE (1 << 5) #define CL_QUEUE_CONTEXT 0x1090 #define CL_QUEUE_DEVICE 0x1091 #define CL_QUEUE_REFERENCE_COUNT 0x1092 #define CL_QUEUE_PROPERTIES 0x1093 #define CL_MEM_READ_WRITE (1 << 0) #define CL_MEM_WRITE_ONLY (1 << 1) #define CL_MEM_READ_ONLY (1 << 2) #define CL_MEM_USE_HOST_PTR (1 << 3) #define CL_MEM_ALLOC_HOST_PTR (1 << 4) #define CL_MEM_COPY_HOST_PTR (1 << 5) // reserved (1 << 6) #define CL_MEM_HOST_WRITE_ONLY (1 << 7) #define CL_MEM_HOST_READ_ONLY (1 << 8) #define CL_MEM_HOST_NO_ACCESS (1 << 9) #define CL_MIGRATE_MEM_OBJECT_HOST (1 << 0) #define CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED (1 << 1) #define CL_R 0x10B0 #define CL_A 0x10B1 #define CL_RG 0x10B2 #define CL_RA 0x10B3 #define CL_RGB 0x10B4 #define CL_RGBA 0x10B5 #define CL_BGRA 0x10B6 #define CL_ARGB 0x10B7 #define CL_INTENSITY 0x10B8 #define CL_LUMINANCE 0x10B9 #define CL_Rx 0x10BA #define CL_RGx 0x10BB #define CL_RGBx 0x10BC #define CL_DEPTH 0x10BD #define CL_DEPTH_STENCIL 0x10BE #define CL_SNORM_INT8 0x10D0 #define CL_SNORM_INT16 0x10D1 #define CL_UNORM_INT8 0x10D2 #define CL_UNORM_INT16 0x10D3 #define CL_UNORM_SHORT_565 0x10D4 #define CL_UNORM_SHORT_555 0x10D5 #define CL_UNORM_INT_101010 0x10D6 #define CL_SIGNED_INT8 0x10D7 #define CL_SIGNED_INT16 0x10D8 #define CL_SIGNED_INT32 0x10D9 #define CL_UNSIGNED_INT8 0x10DA #define CL_UNSIGNED_INT16 0x10DB #define CL_UNSIGNED_INT32 0x10DC #define CL_HALF_FLOAT 0x10DD #define CL_FLOAT 0x10DE #define CL_UNORM_INT24 0x10DF #define CL_MEM_OBJECT_BUFFER 0x10F0 #define CL_MEM_OBJECT_IMAGE2D 0x10F1 #define CL_MEM_OBJECT_IMAGE3D 0x10F2 #define CL_MEM_OBJECT_IMAGE2D_ARRAY 0x10F3 #define CL_MEM_OBJECT_IMAGE1D 0x10F4 #define CL_MEM_OBJECT_IMAGE1D_ARRAY 0x10F5 #define CL_MEM_OBJECT_IMAGE1D_BUFFER 0x10F6 #define CL_MEM_TYPE 0x1100 #define CL_MEM_FLAGS 0x1101 #define CL_MEM_SIZE 0x1102 #define CL_MEM_HOST_PTR 0x1103 #define CL_MEM_MAP_COUNT 0x1104 #define CL_MEM_REFERENCE_COUNT 0x1105 #define CL_MEM_CONTEXT 0x1106 #define CL_MEM_ASSOCIATED_MEMOBJECT 0x1107 #define CL_MEM_OFFSET 0x1108 #define CL_IMAGE_FORMAT 0x1110 #define CL_IMAGE_ELEMENT_SIZE 0x1111 #define CL_IMAGE_ROW_PITCH 0x1112 #define CL_IMAGE_SLICE_PITCH 0x1113 #define CL_IMAGE_WIDTH 0x1114 #define CL_IMAGE_HEIGHT 0x1115 #define CL_IMAGE_DEPTH 0x1116 #define CL_IMAGE_ARRAY_SIZE 0x1117 #define CL_IMAGE_BUFFER 0x1118 #define CL_IMAGE_NUM_MIP_LEVELS 0x1119 #define CL_IMAGE_NUM_SAMPLES 0x111A #define CL_ADDRESS_NONE 0x1130 #define CL_ADDRESS_CLAMP_TO_EDGE 0x1131 #define CL_ADDRESS_CLAMP 0x1132 #define CL_ADDRESS_REPEAT 0x1133 #define CL_ADDRESS_MIRRORED_REPEAT 0x1134 #define CL_FILTER_NEAREST 0x1140 #define CL_FILTER_LINEAR 0x1141 #define CL_SAMPLER_REFERENCE_COUNT 0x1150 #define CL_SAMPLER_CONTEXT 0x1151 #define CL_SAMPLER_NORMALIZED_COORDS 0x1152 #define CL_SAMPLER_ADDRESSING_MODE 0x1153 #define CL_SAMPLER_FILTER_MODE 0x1154 #define CL_MAP_READ (1 << 0) #define CL_MAP_WRITE (1 << 1) #define CL_MAP_WRITE_INVALIDATE_REGION (1 << 2) #define CL_PROGRAM_REFERENCE_COUNT 0x1160 #define CL_PROGRAM_CONTEXT 0x1161 #define CL_PROGRAM_NUM_DEVICES 0x1162 #define CL_PROGRAM_DEVICES 0x1163 #define CL_PROGRAM_SOURCE 0x1164 #define CL_PROGRAM_BINARY_SIZES 0x1165 #define CL_PROGRAM_BINARIES 0x1166 #define CL_PROGRAM_NUM_KERNELS 0x1167 #define CL_PROGRAM_KERNEL_NAMES 0x1168 #define CL_PROGRAM_BUILD_STATUS 0x1181 #define CL_PROGRAM_BUILD_OPTIONS 0x1182 #define CL_PROGRAM_BUILD_LOG 0x1183 #define CL_PROGRAM_BINARY_TYPE 0x1184 #define CL_PROGRAM_BINARY_TYPE_NONE 0x0 #define CL_PROGRAM_BINARY_TYPE_COMPILED_OBJECT 0x1 #define CL_PROGRAM_BINARY_TYPE_LIBRARY 0x2 #define CL_PROGRAM_BINARY_TYPE_EXECUTABLE 0x4 #define CL_BUILD_SUCCESS 0 #define CL_BUILD_NONE -1 #define CL_BUILD_ERROR -2 #define CL_BUILD_IN_PROGRESS -3 #define CL_KERNEL_FUNCTION_NAME 0x1190 #define CL_KERNEL_NUM_ARGS 0x1191 #define CL_KERNEL_REFERENCE_COUNT 0x1192 #define CL_KERNEL_CONTEXT 0x1193 #define CL_KERNEL_PROGRAM 0x1194 #define CL_KERNEL_ATTRIBUTES 0x1195 #define CL_KERNEL_ARG_ADDRESS_QUALIFIER 0x1196 #define CL_KERNEL_ARG_ACCESS_QUALIFIER 0x1197 #define CL_KERNEL_ARG_TYPE_NAME 0x1198 #define CL_KERNEL_ARG_TYPE_QUALIFIER 0x1199 #define CL_KERNEL_ARG_NAME 0x119A #define CL_KERNEL_ARG_ADDRESS_GLOBAL 0x119B #define CL_KERNEL_ARG_ADDRESS_LOCAL 0x119C #define CL_KERNEL_ARG_ADDRESS_CONSTANT 0x119D #define CL_KERNEL_ARG_ADDRESS_PRIVATE 0x119E #define CL_KERNEL_ARG_ACCESS_READ_ONLY 0x11A0 #define CL_KERNEL_ARG_ACCESS_WRITE_ONLY 0x11A1 #define CL_KERNEL_ARG_ACCESS_READ_WRITE 0x11A2 #define CL_KERNEL_ARG_ACCESS_NONE 0x11A3 #define CL_KERNEL_ARG_TYPE_NONE 0 #define CL_KERNEL_ARG_TYPE_CONST (1 << 0) #define CL_KERNEL_ARG_TYPE_RESTRICT (1 << 1) #define CL_KERNEL_ARG_TYPE_VOLATILE (1 << 2) #define CL_KERNEL_WORK_GROUP_SIZE 0x11B0 #define CL_KERNEL_COMPILE_WORK_GROUP_SIZE 0x11B1 #define CL_KERNEL_LOCAL_MEM_SIZE 0x11B2 #define CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE 0x11B3 #define CL_KERNEL_PRIVATE_MEM_SIZE 0x11B4 #define CL_KERNEL_GLOBAL_WORK_SIZE 0x11B5 #define CL_EVENT_COMMAND_QUEUE 0x11D0 #define CL_EVENT_COMMAND_TYPE 0x11D1 #define CL_EVENT_REFERENCE_COUNT 0x11D2 #define CL_EVENT_COMMAND_EXECUTION_STATUS 0x11D3 #define CL_EVENT_CONTEXT 0x11D4 #define CL_COMMAND_NDRANGE_KERNEL 0x11F0 #define CL_COMMAND_TASK 0x11F1 #define CL_COMMAND_NATIVE_KERNEL 0x11F2 #define CL_COMMAND_READ_BUFFER 0x11F3 #define CL_COMMAND_WRITE_BUFFER 0x11F4 #define CL_COMMAND_COPY_BUFFER 0x11F5 #define CL_COMMAND_READ_IMAGE 0x11F6 #define CL_COMMAND_WRITE_IMAGE 0x11F7 #define CL_COMMAND_COPY_IMAGE 0x11F8 #define CL_COMMAND_COPY_IMAGE_TO_BUFFER 0x11F9 #define CL_COMMAND_COPY_BUFFER_TO_IMAGE 0x11FA #define CL_COMMAND_MAP_BUFFER 0x11FB #define CL_COMMAND_MAP_IMAGE 0x11FC #define CL_COMMAND_UNMAP_MEM_OBJECT 0x11FD #define CL_COMMAND_MARKER 0x11FE #define CL_COMMAND_ACQUIRE_GL_OBJECTS 0x11FF #define CL_COMMAND_RELEASE_GL_OBJECTS 0x1200 #define CL_COMMAND_READ_BUFFER_RECT 0x1201 #define CL_COMMAND_WRITE_BUFFER_RECT 0x1202 #define CL_COMMAND_COPY_BUFFER_RECT 0x1203 #define CL_COMMAND_USER 0x1204 #define CL_COMMAND_BARRIER 0x1205 #define CL_COMMAND_MIGRATE_MEM_OBJECTS 0x1206 #define CL_COMMAND_FILL_BUFFER 0x1207 #define CL_COMMAND_FILL_IMAGE 0x1208 #define CL_COMPLETE 0x0 #define CL_RUNNING 0x1 #define CL_SUBMITTED 0x2 #define CL_QUEUED 0x3 #define CL_BUFFER_CREATE_TYPE_REGION 0x1220 #define CL_PROFILING_COMMAND_QUEUED 0x1280 #define CL_PROFILING_COMMAND_SUBMIT 0x1281 #define CL_PROFILING_COMMAND_START 0x1282 #define CL_PROFILING_COMMAND_END 0x1283 #define CL_CALLBACK CV_STDCALL static volatile bool g_haveOpenCL = false; static const char* oclFuncToCheck = "clEnqueueReadBufferRect"; #if defined(__APPLE__) #include <dlfcn.h> static void* initOpenCLAndLoad(const char* funcname) { static bool initialized = false; static void* handle = 0; if (!handle) { if(!initialized) { const char* oclpath = getenv("OPENCV_OPENCL_RUNTIME"); oclpath = oclpath && strlen(oclpath) > 0 ? oclpath : "/System/Library/Frameworks/OpenCL.framework/Versions/Current/OpenCL"; handle = dlopen(oclpath, RTLD_LAZY); initialized = true; g_haveOpenCL = handle != 0 && dlsym(handle, oclFuncToCheck) != 0; if( g_haveOpenCL ) fprintf(stderr, "Successfully loaded OpenCL v1.1+ runtime from %s\n", oclpath); else fprintf(stderr, "Failed to load OpenCL runtime\n"); } if(!handle) return 0; } return funcname && handle ? dlsym(handle, funcname) : 0; } #elif defined WIN32 || defined _WIN32 #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 static void* initOpenCLAndLoad(const char* funcname) { static bool initialized = false; static HMODULE handle = 0; if (!handle) { if(!initialized) { handle = LoadLibraryA("OpenCL.dll"); initialized = true; g_haveOpenCL = handle != 0 && GetProcAddress(handle, oclFuncToCheck) != 0; } if(!handle) return 0; } return funcname ? (void*)GetProcAddress(handle, funcname) : 0; } #elif defined(__linux) #include <dlfcn.h> #include <stdio.h> static void* initOpenCLAndLoad(const char* funcname) { static bool initialized = false; static void* handle = 0; if (!handle) { if(!initialized) { handle = dlopen("libOpenCL.so", RTLD_LAZY); if(!handle) handle = dlopen("libCL.so", RTLD_LAZY); initialized = true; g_haveOpenCL = handle != 0 && dlsym(handle, oclFuncToCheck) != 0; } if(!handle) return 0; } return funcname ? (void*)dlsym(handle, funcname) : 0; } #else static void* initOpenCLAndLoad(const char*) { return 0; } #endif #define OCL_FUNC(rettype, funcname, argsdecl, args) \ typedef rettype (CV_STDCALL * funcname##_t) argsdecl; \ static rettype funcname argsdecl \ { \ static funcname##_t funcname##_p = 0; \ if( !funcname##_p ) \ { \ funcname##_p = (funcname##_t)initOpenCLAndLoad(#funcname); \ if( !funcname##_p ) \ return OPENCV_CL_NOT_IMPLEMENTED; \ } \ return funcname##_p args; \ } #define OCL_FUNC_P(rettype, funcname, argsdecl, args) \ typedef rettype (CV_STDCALL * funcname##_t) argsdecl; \ static rettype funcname argsdecl \ { \ static funcname##_t funcname##_p = 0; \ if( !funcname##_p ) \ { \ funcname##_p = (funcname##_t)initOpenCLAndLoad(#funcname); \ if( !funcname##_p ) \ { \ if( errcode_ret ) \ *errcode_ret = OPENCV_CL_NOT_IMPLEMENTED; \ return 0; \ } \ } \ return funcname##_p args; \ } OCL_FUNC(cl_int, clGetPlatformIDs, (cl_uint num_entries, cl_platform_id* platforms, cl_uint* num_platforms), (num_entries, platforms, num_platforms)) OCL_FUNC(cl_int, clGetPlatformInfo, (cl_platform_id platform, cl_platform_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret), (platform, param_name, param_value_size, param_value, param_value_size_ret)) OCL_FUNC(cl_int, clGetDeviceInfo, (cl_device_id device, cl_device_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret), (device, param_name, param_value_size, param_value, param_value_size_ret)) OCL_FUNC(cl_int, clGetDeviceIDs, (cl_platform_id platform, cl_device_type device_type, cl_uint num_entries, cl_device_id * devices, cl_uint * num_devices), (platform, device_type, num_entries, devices, num_devices)) OCL_FUNC_P(cl_context, clCreateContext, (const cl_context_properties * properties, cl_uint num_devices, const cl_device_id * devices, void (CL_CALLBACK * pfn_notify)(const char *, const void *, size_t, void *), void * user_data, cl_int * errcode_ret), (properties, num_devices, devices, pfn_notify, user_data, errcode_ret)) OCL_FUNC(cl_int, clReleaseContext, (cl_context context), (context)) /* OCL_FUNC(cl_int, clRetainContext, (cl_context context), (context)) OCL_FUNC_P(cl_context, clCreateContextFromType, (const cl_context_properties * properties, cl_device_type device_type, void (CL_CALLBACK * pfn_notify)(const char *, const void *, size_t, void *), void * user_data, cl_int * errcode_ret), (properties, device_type, pfn_notify, user_data, errcode_ret)) OCL_FUNC(cl_int, clGetContextInfo, (cl_context context, cl_context_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret), (context, param_name, param_value_size, param_value, param_value_size_ret)) */ OCL_FUNC_P(cl_command_queue, clCreateCommandQueue, (cl_context context, cl_device_id device, cl_command_queue_properties properties, cl_int * errcode_ret), (context, device, properties, errcode_ret)) OCL_FUNC(cl_int, clReleaseCommandQueue, (cl_command_queue command_queue), (command_queue)) OCL_FUNC_P(cl_mem, clCreateBuffer, (cl_context context, cl_mem_flags flags, size_t size, void * host_ptr, cl_int * errcode_ret), (context, flags, size, host_ptr, errcode_ret)) /* OCL_FUNC(cl_int, clRetainCommandQueue, (cl_command_queue command_queue), (command_queue)) OCL_FUNC(cl_int, clGetCommandQueueInfo, (cl_command_queue command_queue, cl_command_queue_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret), (command_queue, param_name, param_value_size, param_value, param_value_size_ret)) OCL_FUNC_P(cl_mem, clCreateSubBuffer, (cl_mem buffer, cl_mem_flags flags, cl_buffer_create_type buffer_create_type, const void * buffer_create_info, cl_int * errcode_ret), (buffer, flags, buffer_create_type, buffer_create_info, errcode_ret)) */ OCL_FUNC_P(cl_mem, clCreateImage, (cl_context context, cl_mem_flags flags, const cl_image_format * image_format, const cl_image_desc * image_desc, void * host_ptr, cl_int * errcode_ret), (context, flags, image_format, image_desc, host_ptr, errcode_ret)) OCL_FUNC_P(cl_mem, clCreateImage2D, (cl_context context, cl_mem_flags flags, const cl_image_format * image_format, size_t image_width, size_t image_height, size_t image_row_pitch, void * host_ptr, cl_int *errcode_ret), (context, flags, image_format, image_width, image_height, image_row_pitch, host_ptr, errcode_ret)) /* OCL_FUNC(cl_int, clGetSupportedImageFormats, (cl_context context, cl_mem_flags flags, cl_mem_object_type image_type, cl_uint num_entries, cl_image_format * image_formats, cl_uint * num_image_formats), (context, flags, image_type, num_entries, image_formats, num_image_formats)) OCL_FUNC(cl_int, clGetMemObjectInfo, (cl_mem memobj, cl_mem_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret), (memobj, param_name, param_value_size, param_value, param_value_size_ret)) OCL_FUNC(cl_int, clGetImageInfo, (cl_mem image, cl_image_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret), (image, param_name, param_value_size, param_value, param_value_size_ret)) OCL_FUNC(cl_int, clCreateKernelsInProgram, (cl_program program, cl_uint num_kernels, cl_kernel * kernels, cl_uint * num_kernels_ret), (program, num_kernels, kernels, num_kernels_ret)) OCL_FUNC(cl_int, clRetainKernel, (cl_kernel kernel), (kernel)) OCL_FUNC(cl_int, clGetKernelArgInfo, (cl_kernel kernel, cl_uint arg_indx, cl_kernel_arg_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret), (kernel, arg_indx, param_name, param_value_size, param_value, param_value_size_ret)) OCL_FUNC(cl_int, clEnqueueReadImage, (cl_command_queue command_queue, cl_mem image, cl_bool blocking_read, const size_t * origin[3], const size_t * region[3], size_t row_pitch, size_t slice_pitch, void * ptr, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event), (command_queue, image, blocking_read, origin, region, row_pitch, slice_pitch, ptr, num_events_in_wait_list, event_wait_list, event)) OCL_FUNC(cl_int, clEnqueueWriteImage, (cl_command_queue command_queue, cl_mem image, cl_bool blocking_write, const size_t * origin[3], const size_t * region[3], size_t input_row_pitch, size_t input_slice_pitch, const void * ptr, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event), (command_queue, image, blocking_write, origin, region, input_row_pitch, input_slice_pitch, ptr, num_events_in_wait_list, event_wait_list, event)) OCL_FUNC(cl_int, clEnqueueFillImage, (cl_command_queue command_queue, cl_mem image, const void * fill_color, const size_t * origin[3], const size_t * region[3], cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event), (command_queue, image, fill_color, origin, region, num_events_in_wait_list, event_wait_list, event)) OCL_FUNC(cl_int, clEnqueueCopyImage, (cl_command_queue command_queue, cl_mem src_image, cl_mem dst_image, const size_t * src_origin[3], const size_t * dst_origin[3], const size_t * region[3], cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event), (command_queue, src_image, dst_image, src_origin, dst_origin, region, num_events_in_wait_list, event_wait_list, event)) OCL_FUNC(cl_int, clEnqueueCopyImageToBuffer, (cl_command_queue command_queue, cl_mem src_image, cl_mem dst_buffer, const size_t * src_origin[3], const size_t * region[3], size_t dst_offset, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event), (command_queue, src_image, dst_buffer, src_origin, region, dst_offset, num_events_in_wait_list, event_wait_list, event)) */ OCL_FUNC(cl_int, clEnqueueCopyBufferToImage, (cl_command_queue command_queue, cl_mem src_buffer, cl_mem dst_image, size_t src_offset, const size_t dst_origin[3], const size_t region[3], cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event), (command_queue, src_buffer, dst_image, src_offset, dst_origin, region, num_events_in_wait_list, event_wait_list, event)) OCL_FUNC(cl_int, clFlush, (cl_command_queue command_queue), (command_queue)) /* OCL_FUNC_P(void*, clEnqueueMapImage, (cl_command_queue command_queue, cl_mem image, cl_bool blocking_map, cl_map_flags map_flags, const size_t * origin[3], const size_t * region[3], size_t * image_row_pitch, size_t * image_slice_pitch, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event, cl_int * errcode_ret), (command_queue, image, blocking_map, map_flags, origin, region, image_row_pitch, image_slice_pitch, num_events_in_wait_list, event_wait_list, event, errcode_ret)) */ /* OCL_FUNC(cl_int, clRetainProgram, (cl_program program), (program)) OCL_FUNC(cl_int, clGetKernelInfo, (cl_kernel kernel, cl_kernel_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret), (kernel, param_name, param_value_size, param_value, param_value_size_ret)) OCL_FUNC(cl_int, clRetainMemObject, (cl_mem memobj), (memobj)) */ OCL_FUNC(cl_int, clReleaseMemObject, (cl_mem memobj), (memobj)) OCL_FUNC_P(cl_program, clCreateProgramWithSource, (cl_context context, cl_uint count, const char ** strings, const size_t * lengths, cl_int * errcode_ret), (context, count, strings, lengths, errcode_ret)) OCL_FUNC_P(cl_program, clCreateProgramWithBinary, (cl_context context, cl_uint num_devices, const cl_device_id * device_list, const size_t * lengths, const unsigned char ** binaries, cl_int * binary_status, cl_int * errcode_ret), (context, num_devices, device_list, lengths, binaries, binary_status, errcode_ret)) OCL_FUNC(cl_int, clReleaseProgram, (cl_program program), (program)) OCL_FUNC(cl_int, clBuildProgram, (cl_program program, cl_uint num_devices, const cl_device_id * device_list, const char * options, void (CL_CALLBACK * pfn_notify)(cl_program, void *), void * user_data), (program, num_devices, device_list, options, pfn_notify, user_data)) OCL_FUNC(cl_int, clGetProgramInfo, (cl_program program, cl_program_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret), (program, param_name, param_value_size, param_value, param_value_size_ret)) OCL_FUNC(cl_int, clGetProgramBuildInfo, (cl_program program, cl_device_id device, cl_program_build_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret), (program, device, param_name, param_value_size, param_value, param_value_size_ret)) OCL_FUNC_P(cl_kernel, clCreateKernel, (cl_program program, const char * kernel_name, cl_int * errcode_ret), (program, kernel_name, errcode_ret)) OCL_FUNC(cl_int, clReleaseKernel, (cl_kernel kernel), (kernel)) OCL_FUNC(cl_int, clSetKernelArg, (cl_kernel kernel, cl_uint arg_index, size_t arg_size, const void * arg_value), (kernel, arg_index, arg_size, arg_value)) OCL_FUNC(cl_int, clGetKernelWorkGroupInfo, (cl_kernel kernel, cl_device_id device, cl_kernel_work_group_info param_name, size_t param_value_size, void * param_value, size_t * param_value_size_ret), (kernel, device, param_name, param_value_size, param_value, param_value_size_ret)) OCL_FUNC(cl_int, clFinish, (cl_command_queue command_queue), (command_queue)) OCL_FUNC(cl_int, clEnqueueReadBuffer, (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_read, size_t offset, size_t size, void * ptr, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event), (command_queue, buffer, blocking_read, offset, size, ptr, num_events_in_wait_list, event_wait_list, event)) OCL_FUNC(cl_int, clEnqueueReadBufferRect, (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_read, const size_t * buffer_offset, const size_t * host_offset, const size_t * region, size_t buffer_row_pitch, size_t buffer_slice_pitch, size_t host_row_pitch, size_t host_slice_pitch, void * ptr, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event), (command_queue, buffer, blocking_read, buffer_offset, host_offset, region, buffer_row_pitch, buffer_slice_pitch, host_row_pitch, host_slice_pitch, ptr, num_events_in_wait_list, event_wait_list, event)) OCL_FUNC(cl_int, clEnqueueWriteBuffer, (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_write, size_t offset, size_t size, const void * ptr, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event), (command_queue, buffer, blocking_write, offset, size, ptr, num_events_in_wait_list, event_wait_list, event)) OCL_FUNC(cl_int, clEnqueueWriteBufferRect, (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_write, const size_t * buffer_offset, const size_t * host_offset, const size_t * region, size_t buffer_row_pitch, size_t buffer_slice_pitch, size_t host_row_pitch, size_t host_slice_pitch, const void * ptr, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event), (command_queue, buffer, blocking_write, buffer_offset, host_offset, region, buffer_row_pitch, buffer_slice_pitch, host_row_pitch, host_slice_pitch, ptr, num_events_in_wait_list, event_wait_list, event)) /*OCL_FUNC(cl_int, clEnqueueFillBuffer, (cl_command_queue command_queue, cl_mem buffer, const void * pattern, size_t pattern_size, size_t offset, size_t size, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event), (command_queue, buffer, pattern, pattern_size, offset, size, num_events_in_wait_list, event_wait_list, event))*/ OCL_FUNC(cl_int, clEnqueueCopyBuffer, (cl_command_queue command_queue, cl_mem src_buffer, cl_mem dst_buffer, size_t src_offset, size_t dst_offset, size_t size, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event), (command_queue, src_buffer, dst_buffer, src_offset, dst_offset, size, num_events_in_wait_list, event_wait_list, event)) OCL_FUNC(cl_int, clEnqueueCopyBufferRect, (cl_command_queue command_queue, cl_mem src_buffer, cl_mem dst_buffer, const size_t * src_origin, const size_t * dst_origin, const size_t * region, size_t src_row_pitch, size_t src_slice_pitch, size_t dst_row_pitch, size_t dst_slice_pitch, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event), (command_queue, src_buffer, dst_buffer, src_origin, dst_origin, region, src_row_pitch, src_slice_pitch, dst_row_pitch, dst_slice_pitch, num_events_in_wait_list, event_wait_list, event)) OCL_FUNC_P(void*, clEnqueueMapBuffer, (cl_command_queue command_queue, cl_mem buffer, cl_bool blocking_map, cl_map_flags map_flags, size_t offset, size_t size, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event, cl_int * errcode_ret), (command_queue, buffer, blocking_map, map_flags, offset, size, num_events_in_wait_list, event_wait_list, event, errcode_ret)) OCL_FUNC(cl_int, clEnqueueUnmapMemObject, (cl_command_queue command_queue, cl_mem memobj, void * mapped_ptr, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event), (command_queue, memobj, mapped_ptr, num_events_in_wait_list, event_wait_list, event)) OCL_FUNC(cl_int, clEnqueueNDRangeKernel, (cl_command_queue command_queue, cl_kernel kernel, cl_uint work_dim, const size_t * global_work_offset, const size_t * global_work_size, const size_t * local_work_size, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event), (command_queue, kernel, work_dim, global_work_offset, global_work_size, local_work_size, num_events_in_wait_list, event_wait_list, event)) OCL_FUNC(cl_int, clEnqueueTask, (cl_command_queue command_queue, cl_kernel kernel, cl_uint num_events_in_wait_list, const cl_event * event_wait_list, cl_event * event), (command_queue, kernel, num_events_in_wait_list, event_wait_list, event)) OCL_FUNC(cl_int, clSetEventCallback, (cl_event event, cl_int command_exec_callback_type , void (CL_CALLBACK *pfn_event_notify) (cl_event event, cl_int event_command_exec_status, void *user_data), void *user_data), (event, command_exec_callback_type, pfn_event_notify, user_data)) OCL_FUNC(cl_int, clReleaseEvent, (cl_event event), (event)) } #endif #ifndef CL_VERSION_1_2 #define CL_VERSION_1_2 #endif #endif #ifdef _DEBUG #define CV_OclDbgAssert CV_DbgAssert #else #define CV_OclDbgAssert(expr) (void)(expr) #endif namespace cv { namespace ocl { struct UMat2D { UMat2D(const UMat& m) { offset = (int)m.offset; step = (int)m.step; rows = m.rows; cols = m.cols; } int offset; int step; int rows; int cols; }; struct UMat3D { UMat3D(const UMat& m) { offset = (int)m.offset; step = (int)m.step.p[1]; slicestep = (int)m.step.p[0]; slices = (int)m.size.p[0]; rows = m.size.p[1]; cols = m.size.p[2]; } int offset; int slicestep; int step; int slices; int rows; int cols; }; // Computes 64-bit "cyclic redundancy check" sum, as specified in ECMA-182 static uint64 crc64( const uchar* data, size_t size, uint64 crc0=0 ) { static uint64 table[256]; static bool initialized = false; if( !initialized ) { for( int i = 0; i < 256; i++ ) { uint64 c = i; for( int j = 0; j < 8; j++ ) c = ((c & 1) ? CV_BIG_UINT(0xc96c5795d7870f42) : 0) ^ (c >> 1); table[i] = c; } initialized = true; } uint64 crc = ~crc0; for( size_t idx = 0; idx < size; idx++ ) crc = table[(uchar)crc ^ data[idx]] ^ (crc >> 8); return ~crc; } struct HashKey { typedef uint64 part; HashKey(part _a, part _b) : a(_a), b(_b) {} part a, b; }; inline bool operator == (const HashKey& h1, const HashKey& h2) { return h1.a == h2.a && h1.b == h2.b; } inline bool operator < (const HashKey& h1, const HashKey& h2) { return h1.a < h2.a || (h1.a == h2.a && h1.b < h2.b); } bool haveOpenCL() { #ifdef HAVE_OPENCL static bool g_isOpenCLInitialized = false; static bool g_isOpenCLAvailable = false; if (!g_isOpenCLInitialized) { try { cl_uint n = 0; g_isOpenCLAvailable = ::clGetPlatformIDs(0, NULL, &n) == CL_SUCCESS; } catch (...) { g_isOpenCLAvailable = false; } g_isOpenCLInitialized = true; } return g_isOpenCLAvailable; #else return false; #endif } bool useOpenCL() { CoreTLSData* data = coreTlsData.get(); if( data->useOpenCL < 0 ) data->useOpenCL = (int)haveOpenCL() && Device::getDefault().ptr() != NULL; return data->useOpenCL > 0; } void setUseOpenCL(bool flag) { if( haveOpenCL() ) { CoreTLSData* data = coreTlsData.get(); data->useOpenCL = (flag && Device::getDefault().ptr() != NULL) ? 1 : 0; } } #ifdef HAVE_CLAMDBLAS class AmdBlasHelper { public: static AmdBlasHelper & getInstance() { static AmdBlasHelper amdBlas; return amdBlas; } bool isAvailable() const { return g_isAmdBlasAvailable; } ~AmdBlasHelper() { try { clAmdBlasTeardown(); } catch (...) { } } protected: AmdBlasHelper() { if (!g_isAmdBlasInitialized) { AutoLock lock(m); if (!g_isAmdBlasInitialized && haveOpenCL()) { try { g_isAmdBlasAvailable = clAmdBlasSetup() == clAmdBlasSuccess; } catch (...) { g_isAmdBlasAvailable = false; } } else g_isAmdBlasAvailable = false; g_isAmdBlasInitialized = true; } } private: static Mutex m; static bool g_isAmdBlasInitialized; static bool g_isAmdBlasAvailable; }; bool AmdBlasHelper::g_isAmdBlasAvailable = false; bool AmdBlasHelper::g_isAmdBlasInitialized = false; Mutex AmdBlasHelper::m; bool haveAmdBlas() { return AmdBlasHelper::getInstance().isAvailable(); } #else bool haveAmdBlas() { return false; } #endif #ifdef HAVE_CLAMDFFT class AmdFftHelper { public: static AmdFftHelper & getInstance() { static AmdFftHelper amdFft; return amdFft; } bool isAvailable() const { return g_isAmdFftAvailable; } ~AmdFftHelper() { try { // clAmdFftTeardown(); } catch (...) { } } protected: AmdFftHelper() { if (!g_isAmdFftInitialized) { AutoLock lock(m); if (!g_isAmdFftInitialized && haveOpenCL()) { try { CV_Assert(clAmdFftInitSetupData(&setupData) == CLFFT_SUCCESS); g_isAmdFftAvailable = true; } catch (const Exception &) { g_isAmdFftAvailable = false; } } else g_isAmdFftAvailable = false; g_isAmdFftInitialized = true; } } private: static clAmdFftSetupData setupData; static Mutex m; static bool g_isAmdFftInitialized; static bool g_isAmdFftAvailable; }; clAmdFftSetupData AmdFftHelper::setupData; bool AmdFftHelper::g_isAmdFftAvailable = false; bool AmdFftHelper::g_isAmdFftInitialized = false; Mutex AmdFftHelper::m; bool haveAmdFft() { return AmdFftHelper::getInstance().isAvailable(); } #else bool haveAmdFft() { return false; } #endif void finish() { Queue::getDefault().finish(); } #define IMPLEMENT_REFCOUNTABLE() \ void addref() { CV_XADD(&refcount, 1); } \ void release() { if( CV_XADD(&refcount, -1) == 1 ) delete this; } \ int refcount /////////////////////////////////////////// Platform ///////////////////////////////////////////// struct Platform::Impl { Impl() { refcount = 1; handle = 0; initialized = false; } ~Impl() {} void init() { if( !initialized ) { //cl_uint num_entries cl_uint n = 0; if( clGetPlatformIDs(1, &handle, &n) != CL_SUCCESS || n == 0 ) handle = 0; if( handle != 0 ) { char buf[1000]; size_t len = 0; CV_OclDbgAssert(clGetPlatformInfo(handle, CL_PLATFORM_VENDOR, sizeof(buf), buf, &len) == CL_SUCCESS); buf[len] = '\0'; vendor = String(buf); } initialized = true; } } IMPLEMENT_REFCOUNTABLE(); cl_platform_id handle; String vendor; bool initialized; }; Platform::Platform() { p = 0; } Platform::~Platform() { if(p) p->release(); } Platform::Platform(const Platform& pl) { p = (Impl*)pl.p; if(p) p->addref(); } Platform& Platform::operator = (const Platform& pl) { Impl* newp = (Impl*)pl.p; if(newp) newp->addref(); if(p) p->release(); p = newp; return *this; } void* Platform::ptr() const { return p ? p->handle : 0; } Platform& Platform::getDefault() { static Platform p; if( !p.p ) { p.p = new Impl; p.p->init(); } return p; } /////////////////////////////////////// Device //////////////////////////////////////////// // deviceVersion has format // OpenCL<space><major_version.minor_version><space><vendor-specific information> // by specification // http://www.khronos.org/registry/cl/sdk/1.1/docs/man/xhtml/clGetDeviceInfo.html // http://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/clGetDeviceInfo.html static void parseDeviceVersion(const String &deviceVersion, int &major, int &minor) { major = minor = 0; if (10 >= deviceVersion.length()) return; const char *pstr = deviceVersion.c_str(); if (0 != strncmp(pstr, "OpenCL ", 7)) return; size_t ppos = deviceVersion.find('.', 7); if (String::npos == ppos) return; String temp = deviceVersion.substr(7, ppos - 7); major = atoi(temp.c_str()); temp = deviceVersion.substr(ppos + 1); minor = atoi(temp.c_str()); } struct Device::Impl { Impl(void* d) { handle = (cl_device_id)d; refcount = 1; name_ = getStrProp(CL_DEVICE_NAME); version_ = getStrProp(CL_DEVICE_VERSION); doubleFPConfig_ = getProp<cl_device_fp_config, int>(CL_DEVICE_DOUBLE_FP_CONFIG); hostUnifiedMemory_ = getBoolProp(CL_DEVICE_HOST_UNIFIED_MEMORY); maxComputeUnits_ = getProp<cl_uint, int>(CL_DEVICE_MAX_COMPUTE_UNITS); maxWorkGroupSize_ = getProp<size_t, size_t>(CL_DEVICE_MAX_WORK_GROUP_SIZE); type_ = getProp<cl_device_type, int>(CL_DEVICE_TYPE); driverVersion_ = getStrProp(CL_DRIVER_VERSION); String deviceVersion_ = getStrProp(CL_DEVICE_VERSION); parseDeviceVersion(deviceVersion_, deviceVersionMajor_, deviceVersionMinor_); vendorName_ = getStrProp(CL_DEVICE_VENDOR); if (vendorName_ == "Advanced Micro Devices, Inc." || vendorName_ == "AMD") vendorID_ = VENDOR_AMD; else if (vendorName_ == "Intel(R) Corporation") vendorID_ = VENDOR_INTEL; else if (vendorName_ == "NVIDIA Corporation") vendorID_ = VENDOR_NVIDIA; else vendorID_ = UNKNOWN_VENDOR; } template<typename _TpCL, typename _TpOut> _TpOut getProp(cl_device_info prop) const { _TpCL temp=_TpCL(); size_t sz = 0; return clGetDeviceInfo(handle, prop, sizeof(temp), &temp, &sz) == CL_SUCCESS && sz == sizeof(temp) ? _TpOut(temp) : _TpOut(); } bool getBoolProp(cl_device_info prop) const { cl_bool temp = CL_FALSE; size_t sz = 0; return clGetDeviceInfo(handle, prop, sizeof(temp), &temp, &sz) == CL_SUCCESS && sz == sizeof(temp) ? temp != 0 : false; } String getStrProp(cl_device_info prop) const { char buf[1024]; size_t sz=0; return clGetDeviceInfo(handle, prop, sizeof(buf)-16, buf, &sz) == CL_SUCCESS && sz < sizeof(buf) ? String(buf) : String(); } IMPLEMENT_REFCOUNTABLE(); cl_device_id handle; String name_; String version_; int doubleFPConfig_; bool hostUnifiedMemory_; int maxComputeUnits_; size_t maxWorkGroupSize_; int type_; int deviceVersionMajor_; int deviceVersionMinor_; String driverVersion_; String vendorName_; int vendorID_; }; Device::Device() { p = 0; } Device::Device(void* d) { p = 0; set(d); } Device::Device(const Device& d) { p = d.p; if(p) p->addref(); } Device& Device::operator = (const Device& d) { Impl* newp = (Impl*)d.p; if(newp) newp->addref(); if(p) p->release(); p = newp; return *this; } Device::~Device() { if(p) p->release(); } void Device::set(void* d) { if(p) p->release(); p = new Impl(d); } void* Device::ptr() const { return p ? p->handle : 0; } String Device::name() const { return p ? p->name_ : String(); } String Device::extensions() const { return p ? p->getStrProp(CL_DEVICE_EXTENSIONS) : String(); } String Device::version() const { return p ? p->version_ : String(); } String Device::vendorName() const { return p ? p->vendorName_ : String(); } int Device::vendorID() const { return p ? p->vendorID_ : 0; } String Device::OpenCL_C_Version() const { return p ? p->getStrProp(CL_DEVICE_OPENCL_C_VERSION) : String(); } String Device::OpenCLVersion() const { return p ? p->getStrProp(CL_DEVICE_EXTENSIONS) : String(); } int Device::deviceVersionMajor() const { return p ? p->deviceVersionMajor_ : 0; } int Device::deviceVersionMinor() const { return p ? p->deviceVersionMinor_ : 0; } String Device::driverVersion() const { return p ? p->driverVersion_ : String(); } int Device::type() const { return p ? p->type_ : 0; } int Device::addressBits() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_ADDRESS_BITS) : 0; } bool Device::available() const { return p ? p->getBoolProp(CL_DEVICE_AVAILABLE) : false; } bool Device::compilerAvailable() const { return p ? p->getBoolProp(CL_DEVICE_COMPILER_AVAILABLE) : false; } bool Device::linkerAvailable() const #ifdef CL_VERSION_1_2 { return p ? p->getBoolProp(CL_DEVICE_LINKER_AVAILABLE) : false; } #else { CV_REQUIRE_OPENCL_1_2_ERROR; } #endif int Device::doubleFPConfig() const { return p ? p->doubleFPConfig_ : 0; } int Device::singleFPConfig() const { return p ? p->getProp<cl_device_fp_config, int>(CL_DEVICE_SINGLE_FP_CONFIG) : 0; } int Device::halfFPConfig() const #ifdef CL_VERSION_1_2 { return p ? p->getProp<cl_device_fp_config, int>(CL_DEVICE_HALF_FP_CONFIG) : 0; } #else { CV_REQUIRE_OPENCL_1_2_ERROR; } #endif bool Device::endianLittle() const { return p ? p->getBoolProp(CL_DEVICE_ENDIAN_LITTLE) : false; } bool Device::errorCorrectionSupport() const { return p ? p->getBoolProp(CL_DEVICE_ERROR_CORRECTION_SUPPORT) : false; } int Device::executionCapabilities() const { return p ? p->getProp<cl_device_exec_capabilities, int>(CL_DEVICE_EXECUTION_CAPABILITIES) : 0; } size_t Device::globalMemCacheSize() const { return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_GLOBAL_MEM_CACHE_SIZE) : 0; } int Device::globalMemCacheType() const { return p ? p->getProp<cl_device_mem_cache_type, int>(CL_DEVICE_GLOBAL_MEM_CACHE_TYPE) : 0; } int Device::globalMemCacheLineSize() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE) : 0; } size_t Device::globalMemSize() const { return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_GLOBAL_MEM_SIZE) : 0; } size_t Device::localMemSize() const { return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_LOCAL_MEM_SIZE) : 0; } int Device::localMemType() const { return p ? p->getProp<cl_device_local_mem_type, int>(CL_DEVICE_LOCAL_MEM_TYPE) : 0; } bool Device::hostUnifiedMemory() const { return p ? p->hostUnifiedMemory_ : false; } bool Device::imageSupport() const { return p ? p->getBoolProp(CL_DEVICE_IMAGE_SUPPORT) : false; } size_t Device::image2DMaxWidth() const { return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE2D_MAX_WIDTH) : 0; } size_t Device::image2DMaxHeight() const { return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE2D_MAX_HEIGHT) : 0; } size_t Device::image3DMaxWidth() const { return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE3D_MAX_WIDTH) : 0; } size_t Device::image3DMaxHeight() const { return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE3D_MAX_HEIGHT) : 0; } size_t Device::image3DMaxDepth() const { return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE3D_MAX_DEPTH) : 0; } size_t Device::imageMaxBufferSize() const #ifdef CL_VERSION_1_2 { return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE_MAX_BUFFER_SIZE) : 0; } #else { CV_REQUIRE_OPENCL_1_2_ERROR; } #endif size_t Device::imageMaxArraySize() const #ifdef CL_VERSION_1_2 { return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE_MAX_ARRAY_SIZE) : 0; } #else { CV_REQUIRE_OPENCL_1_2_ERROR; } #endif int Device::maxClockFrequency() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_CLOCK_FREQUENCY) : 0; } int Device::maxComputeUnits() const { return p ? p->maxComputeUnits_ : 0; } int Device::maxConstantArgs() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_CONSTANT_ARGS) : 0; } size_t Device::maxConstantBufferSize() const { return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE) : 0; } size_t Device::maxMemAllocSize() const { return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_MAX_MEM_ALLOC_SIZE) : 0; } size_t Device::maxParameterSize() const { return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_MAX_PARAMETER_SIZE) : 0; } int Device::maxReadImageArgs() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_READ_IMAGE_ARGS) : 0; } int Device::maxWriteImageArgs() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_WRITE_IMAGE_ARGS) : 0; } int Device::maxSamplers() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_SAMPLERS) : 0; } size_t Device::maxWorkGroupSize() const { return p ? p->maxWorkGroupSize_ : 0; } int Device::maxWorkItemDims() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS) : 0; } void Device::maxWorkItemSizes(size_t* sizes) const { if(p) { const int MAX_DIMS = 32; size_t retsz = 0; CV_OclDbgAssert(clGetDeviceInfo(p->handle, CL_DEVICE_MAX_WORK_ITEM_SIZES, MAX_DIMS*sizeof(sizes[0]), &sizes[0], &retsz) == CL_SUCCESS); } } int Device::memBaseAddrAlign() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_MEM_BASE_ADDR_ALIGN) : 0; } int Device::nativeVectorWidthChar() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR) : 0; } int Device::nativeVectorWidthShort() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT) : 0; } int Device::nativeVectorWidthInt() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_INT) : 0; } int Device::nativeVectorWidthLong() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG) : 0; } int Device::nativeVectorWidthFloat() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT) : 0; } int Device::nativeVectorWidthDouble() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE) : 0; } int Device::nativeVectorWidthHalf() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF) : 0; } int Device::preferredVectorWidthChar() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR) : 0; } int Device::preferredVectorWidthShort() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT) : 0; } int Device::preferredVectorWidthInt() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT) : 0; } int Device::preferredVectorWidthLong() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG) : 0; } int Device::preferredVectorWidthFloat() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT) : 0; } int Device::preferredVectorWidthDouble() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE) : 0; } int Device::preferredVectorWidthHalf() const { return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF) : 0; } size_t Device::printfBufferSize() const #ifdef CL_VERSION_1_2 { return p ? p->getProp<size_t, size_t>(CL_DEVICE_PRINTF_BUFFER_SIZE) : 0; } #else { CV_REQUIRE_OPENCL_1_2_ERROR; } #endif size_t Device::profilingTimerResolution() const { return p ? p->getProp<size_t, size_t>(CL_DEVICE_PROFILING_TIMER_RESOLUTION) : 0; } const Device& Device::getDefault() { const Context& ctx = Context::getDefault(); int idx = coreTlsData.get()->device; return ctx.device(idx); } ////////////////////////////////////// Context /////////////////////////////////////////////////// template <typename Functor, typename ObjectType> inline cl_int getStringInfo(Functor f, ObjectType obj, cl_uint name, std::string& param) { ::size_t required; cl_int err = f(obj, name, 0, NULL, &required); if (err != CL_SUCCESS) return err; param.clear(); if (required > 0) { AutoBuffer<char> buf(required + 1); char* ptr = (char*)buf; // cleanup is not needed err = f(obj, name, required, ptr, NULL); if (err != CL_SUCCESS) return err; param = ptr; } return CL_SUCCESS; } static void split(const std::string &s, char delim, std::vector<std::string> &elems) { elems.clear(); if (s.size() == 0) return; std::istringstream ss(s); std::string item; while (!ss.eof()) { std::getline(ss, item, delim); elems.push_back(item); } } // Layout: <Platform>:<CPU|GPU|ACCELERATOR|nothing=GPU/CPU>:<deviceName> // Sample: AMD:GPU: // Sample: AMD:GPU:Tahiti // Sample: :GPU|CPU: = '' = ':' = '::' static bool parseOpenCLDeviceConfiguration(const std::string& configurationStr, std::string& platform, std::vector<std::string>& deviceTypes, std::string& deviceNameOrID) { std::vector<std::string> parts; split(configurationStr, ':', parts); if (parts.size() > 3) { std::cerr << "ERROR: Invalid configuration string for OpenCL device" << std::endl; return false; } if (parts.size() > 2) deviceNameOrID = parts[2]; if (parts.size() > 1) { split(parts[1], '|', deviceTypes); } if (parts.size() > 0) { platform = parts[0]; } return true; } static cl_device_id selectOpenCLDevice() { std::string platform, deviceName; std::vector<std::string> deviceTypes; const char* configuration = getenv("OPENCV_OPENCL_DEVICE"); if (configuration && !parseOpenCLDeviceConfiguration(std::string(configuration), platform, deviceTypes, deviceName)) return NULL; bool isID = false; int deviceID = -1; if (deviceName.length() == 1) // We limit ID range to 0..9, because we want to write: // - '2500' to mean i5-2500 // - '8350' to mean AMD FX-8350 // - '650' to mean GeForce 650 // To extend ID range change condition to '> 0' { isID = true; for (size_t i = 0; i < deviceName.length(); i++) { if (!isdigit(deviceName[i])) { isID = false; break; } } if (isID) { deviceID = atoi(deviceName.c_str()); if (deviceID < 0) return NULL; } } std::vector<cl_platform_id> platforms; { cl_uint numPlatforms = 0; CV_OclDbgAssert(clGetPlatformIDs(0, NULL, &numPlatforms) == CL_SUCCESS); if (numPlatforms == 0) return NULL; platforms.resize((size_t)numPlatforms); CV_OclDbgAssert(clGetPlatformIDs(numPlatforms, &platforms[0], &numPlatforms) == CL_SUCCESS); platforms.resize(numPlatforms); } int selectedPlatform = -1; if (platform.length() > 0) { for (size_t i = 0; i < platforms.size(); i++) { std::string name; CV_OclDbgAssert(getStringInfo(clGetPlatformInfo, platforms[i], CL_PLATFORM_NAME, name) == CL_SUCCESS); if (name.find(platform) != std::string::npos) { selectedPlatform = (int)i; break; } } if (selectedPlatform == -1) { std::cerr << "ERROR: Can't find OpenCL platform by name: " << platform << std::endl; goto not_found; } } if (deviceTypes.size() == 0) { if (!isID) { deviceTypes.push_back("GPU"); deviceTypes.push_back("CPU"); } else deviceTypes.push_back("ALL"); } for (size_t t = 0; t < deviceTypes.size(); t++) { int deviceType = 0; std::string tempStrDeviceType = deviceTypes[t]; std::transform( tempStrDeviceType.begin(), tempStrDeviceType.end(), tempStrDeviceType.begin(), tolower ); if (tempStrDeviceType == "gpu" || tempStrDeviceType == "dgpu" || tempStrDeviceType == "igpu") deviceType = Device::TYPE_GPU; else if (tempStrDeviceType == "cpu") deviceType = Device::TYPE_CPU; else if (tempStrDeviceType == "accelerator") deviceType = Device::TYPE_ACCELERATOR; else if (tempStrDeviceType == "all") deviceType = Device::TYPE_ALL; else { std::cerr << "ERROR: Unsupported device type for OpenCL device (GPU, CPU, ACCELERATOR): " << deviceTypes[t] << std::endl; goto not_found; } std::vector<cl_device_id> devices; // TODO Use clReleaseDevice to cleanup for (int i = selectedPlatform >= 0 ? selectedPlatform : 0; (selectedPlatform >= 0 ? i == selectedPlatform : true) && (i < (int)platforms.size()); i++) { cl_uint count = 0; cl_int status = clGetDeviceIDs(platforms[i], deviceType, 0, NULL, &count); CV_OclDbgAssert(status == CL_SUCCESS || status == CL_DEVICE_NOT_FOUND); if (count == 0) continue; size_t base = devices.size(); devices.resize(base + count); status = clGetDeviceIDs(platforms[i], deviceType, count, &devices[base], &count); CV_OclDbgAssert(status == CL_SUCCESS || status == CL_DEVICE_NOT_FOUND); } for (size_t i = (isID ? deviceID : 0); (isID ? (i == (size_t)deviceID) : true) && (i < devices.size()); i++) { std::string name; CV_OclDbgAssert(getStringInfo(clGetDeviceInfo, devices[i], CL_DEVICE_NAME, name) == CL_SUCCESS); cl_bool useGPU = true; if(tempStrDeviceType == "dgpu" || tempStrDeviceType == "igpu") { cl_bool isIGPU = CL_FALSE; clGetDeviceInfo(devices[i], CL_DEVICE_HOST_UNIFIED_MEMORY, sizeof(isIGPU), &isIGPU, NULL); useGPU = tempStrDeviceType == "dgpu" ? !isIGPU : isIGPU; } if ( (isID || name.find(deviceName) != std::string::npos) && useGPU) { // TODO check for OpenCL 1.1 return devices[i]; } } } not_found: std::cerr << "ERROR: Required OpenCL device not found, check configuration: " << (configuration == NULL ? "" : configuration) << std::endl << " Platform: " << (platform.length() == 0 ? "any" : platform) << std::endl << " Device types: "; for (size_t t = 0; t < deviceTypes.size(); t++) std::cerr << deviceTypes[t] << " "; std::cerr << std::endl << " Device name: " << (deviceName.length() == 0 ? "any" : deviceName) << std::endl; CV_Error(CL_INVALID_DEVICE, "Requested OpenCL device is not found"); return NULL; } struct Context::Impl { Impl() { refcount = 1; handle = 0; } void setDefault() { CV_Assert(handle == NULL); cl_device_id d = selectOpenCLDevice(); if (d == NULL) return; cl_platform_id pl = NULL; CV_OclDbgAssert(clGetDeviceInfo(d, CL_DEVICE_PLATFORM, sizeof(cl_platform_id), &pl, NULL) == CL_SUCCESS); cl_context_properties prop[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)pl, 0 }; // !!! in the current implementation force the number of devices to 1 !!! cl_uint nd = 1; cl_int status; handle = clCreateContext(prop, nd, &d, 0, 0, &status); bool ok = handle != 0 && status == CL_SUCCESS; if( ok ) { devices.resize(nd); devices[0].set(d); } else handle = NULL; } Impl(int dtype0) { refcount = 1; handle = 0; cl_int retval = 0; cl_platform_id pl = (cl_platform_id)Platform::getDefault().ptr(); cl_context_properties prop[] = { CL_CONTEXT_PLATFORM, (cl_context_properties)pl, 0 }; cl_uint i, nd0 = 0, nd = 0; int dtype = dtype0 & 15; CV_OclDbgAssert(clGetDeviceIDs( pl, dtype, 0, 0, &nd0 ) == CL_SUCCESS); AutoBuffer<void*> dlistbuf(nd0*2+1); cl_device_id* dlist = (cl_device_id*)(void**)dlistbuf; cl_device_id* dlist_new = dlist + nd0; CV_OclDbgAssert(clGetDeviceIDs( pl, dtype, nd0, dlist, &nd0 ) == CL_SUCCESS); String name0; for(i = 0; i < nd0; i++) { Device d(dlist[i]); if( !d.available() || !d.compilerAvailable() ) continue; if( dtype0 == Device::TYPE_DGPU && d.hostUnifiedMemory() ) continue; if( dtype0 == Device::TYPE_IGPU && !d.hostUnifiedMemory() ) continue; String name = d.name(); if( nd != 0 && name != name0 ) continue; name0 = name; dlist_new[nd++] = dlist[i]; } if(nd == 0) return; // !!! in the current implementation force the number of devices to 1 !!! nd = 1; handle = clCreateContext(prop, nd, dlist_new, 0, 0, &retval); bool ok = handle != 0 && retval == CL_SUCCESS; if( ok ) { devices.resize(nd); for( i = 0; i < nd; i++ ) devices[i].set(dlist_new[i]); } } ~Impl() { if(handle) { clReleaseContext(handle); handle = NULL; } devices.clear(); } Program getProg(const ProgramSource& src, const String& buildflags, String& errmsg) { String prefix = Program::getPrefix(buildflags); HashKey k(src.hash(), crc64((const uchar*)prefix.c_str(), prefix.size())); phash_t::iterator it = phash.find(k); if( it != phash.end() ) return it->second; //String filename = format("%08x%08x_%08x%08x.clb2", Program prog(src, buildflags, errmsg); if(prog.ptr()) phash.insert(std::pair<HashKey,Program>(k, prog)); return prog; } IMPLEMENT_REFCOUNTABLE(); cl_context handle; std::vector<Device> devices; typedef ProgramSource::hash_t hash_t; struct HashKey { HashKey(hash_t _a, hash_t _b) : a(_a), b(_b) {} bool operator < (const HashKey& k) const { return a < k.a || (a == k.a && b < k.b); } bool operator == (const HashKey& k) const { return a == k.a && b == k.b; } bool operator != (const HashKey& k) const { return a != k.a || b != k.b; } hash_t a, b; }; typedef std::map<HashKey, Program> phash_t; phash_t phash; }; Context::Context() { p = 0; } Context::Context(int dtype) { p = 0; create(dtype); } bool Context::create() { if( !haveOpenCL() ) return false; if(p) p->release(); p = new Impl(); if(!p->handle) { delete p; p = 0; } return p != 0; } bool Context::create(int dtype0) { if( !haveOpenCL() ) return false; if(p) p->release(); p = new Impl(dtype0); if(!p->handle) { delete p; p = 0; } return p != 0; } Context::~Context() { if (p) { p->release(); p = NULL; } } Context::Context(const Context& c) { p = (Impl*)c.p; if(p) p->addref(); } Context& Context::operator = (const Context& c) { Impl* newp = (Impl*)c.p; if(newp) newp->addref(); if(p) p->release(); p = newp; return *this; } void* Context::ptr() const { return p == NULL ? NULL : p->handle; } size_t Context::ndevices() const { return p ? p->devices.size() : 0; } const Device& Context::device(size_t idx) const { static Device dummy; return !p || idx >= p->devices.size() ? dummy : p->devices[idx]; } Context& Context::getDefault(bool initialize) { static Context* ctx = new Context(); if(!ctx->p && haveOpenCL()) { if (!ctx->p) ctx->p = new Impl(); if (initialize) { // do not create new Context right away. // First, try to retrieve existing context of the same type. // In its turn, Platform::getContext() may call Context::create() // if there is no such context. if (ctx->p->handle == NULL) ctx->p->setDefault(); } } return *ctx; } Program Context::getProg(const ProgramSource& prog, const String& buildopts, String& errmsg) { return p ? p->getProg(prog, buildopts, errmsg) : Program(); } void initializeContextFromHandle(Context& ctx, void* platform, void* _context, void* _device) { cl_context context = (cl_context)_context; cl_device_id device = (cl_device_id)_device; // cleanup old context Context::Impl * impl = ctx.p; if (impl->handle) { CV_OclDbgAssert(clReleaseContext(impl->handle) == CL_SUCCESS); } impl->devices.clear(); impl->handle = context; impl->devices.resize(1); impl->devices[0].set(device); Platform& p = Platform::getDefault(); Platform::Impl* pImpl = p.p; pImpl->handle = (cl_platform_id)platform; } /////////////////////////////////////////// Queue ///////////////////////////////////////////// struct Queue::Impl { Impl(const Context& c, const Device& d) { refcount = 1; const Context* pc = &c; cl_context ch = (cl_context)pc->ptr(); if( !ch ) { pc = &Context::getDefault(); ch = (cl_context)pc->ptr(); } cl_device_id dh = (cl_device_id)d.ptr(); if( !dh ) dh = (cl_device_id)pc->device(0).ptr(); cl_int retval = 0; handle = clCreateCommandQueue(ch, dh, 0, &retval); CV_OclDbgAssert(retval == CL_SUCCESS); } ~Impl() { #ifdef _WIN32 if (!cv::__termination) #endif { if(handle) { clFinish(handle); clReleaseCommandQueue(handle); handle = NULL; } } } IMPLEMENT_REFCOUNTABLE(); cl_command_queue handle; }; Queue::Queue() { p = 0; } Queue::Queue(const Context& c, const Device& d) { p = 0; create(c, d); } Queue::Queue(const Queue& q) { p = q.p; if(p) p->addref(); } Queue& Queue::operator = (const Queue& q) { Impl* newp = (Impl*)q.p; if(newp) newp->addref(); if(p) p->release(); p = newp; return *this; } Queue::~Queue() { if(p) p->release(); } bool Queue::create(const Context& c, const Device& d) { if(p) p->release(); p = new Impl(c, d); return p->handle != 0; } void Queue::finish() { if(p && p->handle) { CV_OclDbgAssert(clFinish(p->handle) == CL_SUCCESS); } } void* Queue::ptr() const { return p ? p->handle : 0; } Queue& Queue::getDefault() { Queue& q = coreTlsData.get()->oclQueue; if( !q.p && haveOpenCL() ) q.create(Context::getDefault()); return q; } static cl_command_queue getQueue(const Queue& q) { cl_command_queue qq = (cl_command_queue)q.ptr(); if(!qq) qq = (cl_command_queue)Queue::getDefault().ptr(); return qq; } /////////////////////////////////////////// KernelArg ///////////////////////////////////////////// KernelArg::KernelArg() : flags(0), m(0), obj(0), sz(0), wscale(1), iwscale(1) { } KernelArg::KernelArg(int _flags, UMat* _m, int _wscale, int _iwscale, const void* _obj, size_t _sz) : flags(_flags), m(_m), obj(_obj), sz(_sz), wscale(_wscale), iwscale(_iwscale) { } KernelArg KernelArg::Constant(const Mat& m) { CV_Assert(m.isContinuous()); return KernelArg(CONSTANT, 0, 0, 0, m.data, m.total()*m.elemSize()); } /////////////////////////////////////////// Kernel ///////////////////////////////////////////// struct Kernel::Impl { Impl(const char* kname, const Program& prog) : refcount(1), e(0), nu(0) { cl_program ph = (cl_program)prog.ptr(); cl_int retval = 0; handle = ph != 0 ? clCreateKernel(ph, kname, &retval) : 0; CV_OclDbgAssert(retval == CL_SUCCESS); for( int i = 0; i < MAX_ARRS; i++ ) u[i] = 0; haveTempDstUMats = false; } void cleanupUMats() { for( int i = 0; i < MAX_ARRS; i++ ) if( u[i] ) { if( CV_XADD(&u[i]->urefcount, -1) == 1 ) u[i]->currAllocator->deallocate(u[i]); u[i] = 0; } nu = 0; haveTempDstUMats = false; } void addUMat(const UMat& m, bool dst) { CV_Assert(nu < MAX_ARRS && m.u && m.u->urefcount > 0); u[nu] = m.u; CV_XADD(&m.u->urefcount, 1); nu++; if(dst && m.u->tempUMat()) haveTempDstUMats = true; } void finit() { cleanupUMats(); if(e) { clReleaseEvent(e); e = 0; } release(); } ~Impl() { if(handle) clReleaseKernel(handle); } IMPLEMENT_REFCOUNTABLE(); cl_kernel handle; cl_event e; enum { MAX_ARRS = 16 }; UMatData* u[MAX_ARRS]; int nu; bool haveTempDstUMats; }; }} extern "C" { static void CL_CALLBACK oclCleanupCallback(cl_event, cl_int, void *p) { ((cv::ocl::Kernel::Impl*)p)->finit(); } } namespace cv { namespace ocl { Kernel::Kernel() { p = 0; } Kernel::Kernel(const char* kname, const Program& prog) { p = 0; create(kname, prog); } Kernel::Kernel(const char* kname, const ProgramSource& src, const String& buildopts, String* errmsg) { p = 0; create(kname, src, buildopts, errmsg); } Kernel::Kernel(const Kernel& k) { p = k.p; if(p) p->addref(); } Kernel& Kernel::operator = (const Kernel& k) { Impl* newp = (Impl*)k.p; if(newp) newp->addref(); if(p) p->release(); p = newp; return *this; } Kernel::~Kernel() { if(p) p->release(); } bool Kernel::create(const char* kname, const Program& prog) { if(p) p->release(); p = new Impl(kname, prog); if(p->handle == 0) { p->release(); p = 0; } return p != 0; } bool Kernel::create(const char* kname, const ProgramSource& src, const String& buildopts, String* errmsg) { if(p) { p->release(); p = 0; } String tempmsg; if( !errmsg ) errmsg = &tempmsg; const Program& prog = Context::getDefault().getProg(src, buildopts, *errmsg); return create(kname, prog); } void* Kernel::ptr() const { return p ? p->handle : 0; } bool Kernel::empty() const { return ptr() == 0; } int Kernel::set(int i, const void* value, size_t sz) { if (!p || !p->handle) return -1; if (i < 0) return i; if( i == 0 ) p->cleanupUMats(); cl_int retval = clSetKernelArg(p->handle, (cl_uint)i, sz, value); CV_OclDbgAssert(retval == CL_SUCCESS); if (retval != CL_SUCCESS) return -1; return i+1; } int Kernel::set(int i, const Image2D& image2D) { cl_mem h = (cl_mem)image2D.ptr(); return set(i, &h, sizeof(h)); } int Kernel::set(int i, const UMat& m) { return set(i, KernelArg(KernelArg::READ_WRITE, (UMat*)&m, 0, 0)); } int Kernel::set(int i, const KernelArg& arg) { if( !p || !p->handle ) return -1; if (i < 0) return i; if( i == 0 ) p->cleanupUMats(); if( arg.m ) { int accessFlags = ((arg.flags & KernelArg::READ_ONLY) ? ACCESS_READ : 0) + ((arg.flags & KernelArg::WRITE_ONLY) ? ACCESS_WRITE : 0); bool ptronly = (arg.flags & KernelArg::PTR_ONLY) != 0; cl_mem h = (cl_mem)arg.m->handle(accessFlags); if (!h) { p->release(); p = 0; return -1; } if (ptronly) CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)i++, sizeof(h), &h) == CL_SUCCESS); else if( arg.m->dims <= 2 ) { UMat2D u2d(*arg.m); CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)i, sizeof(h), &h) == CL_SUCCESS); CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)(i+1), sizeof(u2d.step), &u2d.step) == CL_SUCCESS); CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)(i+2), sizeof(u2d.offset), &u2d.offset) == CL_SUCCESS); i += 3; if( !(arg.flags & KernelArg::NO_SIZE) ) { int cols = u2d.cols*arg.wscale/arg.iwscale; CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)i, sizeof(u2d.rows), &u2d.rows) == CL_SUCCESS); CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)(i+1), sizeof(cols), &cols) == CL_SUCCESS); i += 2; } } else { UMat3D u3d(*arg.m); CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)i, sizeof(h), &h) == CL_SUCCESS); CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)(i+1), sizeof(u3d.slicestep), &u3d.slicestep) == CL_SUCCESS); CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)(i+2), sizeof(u3d.step), &u3d.step) == CL_SUCCESS); CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)(i+3), sizeof(u3d.offset), &u3d.offset) == CL_SUCCESS); i += 4; if( !(arg.flags & KernelArg::NO_SIZE) ) { int cols = u3d.cols*arg.wscale/arg.iwscale; CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)i, sizeof(u3d.slices), &u3d.rows) == CL_SUCCESS); CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)(i+1), sizeof(u3d.rows), &u3d.rows) == CL_SUCCESS); CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)(i+2), sizeof(u3d.cols), &cols) == CL_SUCCESS); i += 3; } } p->addUMat(*arg.m, (accessFlags & ACCESS_WRITE) != 0); return i; } CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)i, arg.sz, arg.obj) == CL_SUCCESS); return i+1; } bool Kernel::run(int dims, size_t _globalsize[], size_t _localsize[], bool sync, const Queue& q) { if(!p || !p->handle || p->e != 0) return false; cl_command_queue qq = getQueue(q); size_t offset[CV_MAX_DIM] = {0}, globalsize[CV_MAX_DIM] = {1,1,1}; size_t total = 1; CV_Assert(_globalsize != 0); for (int i = 0; i < dims; i++) { size_t val = _localsize ? _localsize[i] : dims == 1 ? 64 : dims == 2 ? (i == 0 ? 256 : 8) : dims == 3 ? (8>>(int)(i>0)) : 1; CV_Assert( val > 0 ); total *= _globalsize[i]; globalsize[i] = ((_globalsize[i] + val - 1)/val)*val; } if( total == 0 ) return true; if( p->haveTempDstUMats ) sync = true; cl_int retval = clEnqueueNDRangeKernel(qq, p->handle, (cl_uint)dims, offset, globalsize, _localsize, 0, 0, sync ? 0 : &p->e); if( sync || retval != CL_SUCCESS ) { CV_OclDbgAssert(clFinish(qq) == CL_SUCCESS); p->cleanupUMats(); } else { p->addref(); CV_OclDbgAssert(clSetEventCallback(p->e, CL_COMPLETE, oclCleanupCallback, p) == CL_SUCCESS); } return retval == CL_SUCCESS; } bool Kernel::runTask(bool sync, const Queue& q) { if(!p || !p->handle || p->e != 0) return false; cl_command_queue qq = getQueue(q); cl_int retval = clEnqueueTask(qq, p->handle, 0, 0, sync ? 0 : &p->e); if( sync || retval != CL_SUCCESS ) { CV_OclDbgAssert(clFinish(qq) == CL_SUCCESS); p->cleanupUMats(); } else { p->addref(); CV_OclDbgAssert(clSetEventCallback(p->e, CL_COMPLETE, oclCleanupCallback, p) == CL_SUCCESS); } return retval == CL_SUCCESS; } size_t Kernel::workGroupSize() const { if(!p || !p->handle) return 0; size_t val = 0, retsz = 0; cl_device_id dev = (cl_device_id)Device::getDefault().ptr(); return clGetKernelWorkGroupInfo(p->handle, dev, CL_KERNEL_WORK_GROUP_SIZE, sizeof(val), &val, &retsz) == CL_SUCCESS ? val : 0; } size_t Kernel::preferedWorkGroupSizeMultiple() const { if(!p || !p->handle) return 0; size_t val = 0, retsz = 0; cl_device_id dev = (cl_device_id)Device::getDefault().ptr(); return clGetKernelWorkGroupInfo(p->handle, dev, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, sizeof(val), &val, &retsz) == CL_SUCCESS ? val : 0; } bool Kernel::compileWorkGroupSize(size_t wsz[]) const { if(!p || !p->handle || !wsz) return 0; size_t retsz = 0; cl_device_id dev = (cl_device_id)Device::getDefault().ptr(); return clGetKernelWorkGroupInfo(p->handle, dev, CL_KERNEL_COMPILE_WORK_GROUP_SIZE, sizeof(wsz[0]*3), wsz, &retsz) == CL_SUCCESS; } size_t Kernel::localMemSize() const { if(!p || !p->handle) return 0; size_t retsz = 0; cl_ulong val = 0; cl_device_id dev = (cl_device_id)Device::getDefault().ptr(); return clGetKernelWorkGroupInfo(p->handle, dev, CL_KERNEL_LOCAL_MEM_SIZE, sizeof(val), &val, &retsz) == CL_SUCCESS ? (size_t)val : 0; } /////////////////////////////////////////// Program ///////////////////////////////////////////// struct Program::Impl { Impl(const ProgramSource& _src, const String& _buildflags, String& errmsg) { refcount = 1; const Context& ctx = Context::getDefault(); src = _src; buildflags = _buildflags; const String& srcstr = src.source(); const char* srcptr = srcstr.c_str(); size_t srclen = srcstr.size(); cl_int retval = 0; handle = clCreateProgramWithSource((cl_context)ctx.ptr(), 1, &srcptr, &srclen, &retval); if( handle && retval == CL_SUCCESS ) { int i, n = (int)ctx.ndevices(); AutoBuffer<void*> deviceListBuf(n+1); void** deviceList = deviceListBuf; for( i = 0; i < n; i++ ) deviceList[i] = ctx.device(i).ptr(); Device device = Device::getDefault(); if (device.isAMD()) buildflags += " -D AMD_DEVICE"; else if (device.isIntel()) buildflags += " -D INTEL_DEVICE"; retval = clBuildProgram(handle, n, (const cl_device_id*)deviceList, buildflags.c_str(), 0, 0); #if !CV_OPENCL_ALWAYS_SHOW_BUILD_LOG if( retval != CL_SUCCESS ) #endif { size_t retsz = 0; cl_int buildInfo_retval = clGetProgramBuildInfo(handle, (cl_device_id)deviceList[0], CL_PROGRAM_BUILD_LOG, 0, 0, &retsz); if (buildInfo_retval == CL_SUCCESS && retsz > 1) { AutoBuffer<char> bufbuf(retsz + 16); char* buf = bufbuf; buildInfo_retval = clGetProgramBuildInfo(handle, (cl_device_id)deviceList[0], CL_PROGRAM_BUILD_LOG, retsz+1, buf, &retsz); if (buildInfo_retval == CL_SUCCESS) { // TODO It is useful to see kernel name & program file name also errmsg = String(buf); printf("OpenCL program build log: %s\n%s\n", buildflags.c_str(), errmsg.c_str()); fflush(stdout); } } if (retval != CL_SUCCESS && handle) { clReleaseProgram(handle); handle = NULL; } } } } Impl(const String& _buf, const String& _buildflags) { refcount = 1; handle = 0; buildflags = _buildflags; if(_buf.empty()) return; String prefix0 = Program::getPrefix(buildflags); const Context& ctx = Context::getDefault(); const Device& dev = Device::getDefault(); const char* pos0 = _buf.c_str(); const char* pos1 = strchr(pos0, '\n'); if(!pos1) return; const char* pos2 = strchr(pos1+1, '\n'); if(!pos2) return; const char* pos3 = strchr(pos2+1, '\n'); if(!pos3) return; size_t prefixlen = (pos3 - pos0)+1; String prefix(pos0, prefixlen); if( prefix != prefix0 ) return; const uchar* bin = (uchar*)(pos3+1); void* devid = dev.ptr(); size_t codelen = _buf.length() - prefixlen; cl_int binstatus = 0, retval = 0; handle = clCreateProgramWithBinary((cl_context)ctx.ptr(), 1, (cl_device_id*)&devid, &codelen, &bin, &binstatus, &retval); CV_OclDbgAssert(retval == CL_SUCCESS); } String store() { if(!handle) return String(); size_t progsz = 0, retsz = 0; String prefix = Program::getPrefix(buildflags); size_t prefixlen = prefix.length(); if(clGetProgramInfo(handle, CL_PROGRAM_BINARY_SIZES, sizeof(progsz), &progsz, &retsz) != CL_SUCCESS) return String(); AutoBuffer<uchar> bufbuf(prefixlen + progsz + 16); uchar* buf = bufbuf; memcpy(buf, prefix.c_str(), prefixlen); buf += prefixlen; if(clGetProgramInfo(handle, CL_PROGRAM_BINARIES, sizeof(buf), &buf, &retsz) != CL_SUCCESS) return String(); buf[progsz] = (uchar)'\0'; return String((const char*)(uchar*)bufbuf, prefixlen + progsz); } ~Impl() { if( handle ) { #ifdef _WIN32 if (!cv::__termination) #endif { clReleaseProgram(handle); } handle = NULL; } } IMPLEMENT_REFCOUNTABLE(); ProgramSource src; String buildflags; cl_program handle; }; Program::Program() { p = 0; } Program::Program(const ProgramSource& src, const String& buildflags, String& errmsg) { p = 0; create(src, buildflags, errmsg); } Program::Program(const Program& prog) { p = prog.p; if(p) p->addref(); } Program& Program::operator = (const Program& prog) { Impl* newp = (Impl*)prog.p; if(newp) newp->addref(); if(p) p->release(); p = newp; return *this; } Program::~Program() { if(p) p->release(); } bool Program::create(const ProgramSource& src, const String& buildflags, String& errmsg) { if(p) p->release(); p = new Impl(src, buildflags, errmsg); if(!p->handle) { p->release(); p = 0; } return p != 0; } const ProgramSource& Program::source() const { static ProgramSource dummy; return p ? p->src : dummy; } void* Program::ptr() const { return p ? p->handle : 0; } bool Program::read(const String& bin, const String& buildflags) { if(p) p->release(); p = new Impl(bin, buildflags); return p->handle != 0; } bool Program::write(String& bin) const { if(!p) return false; bin = p->store(); return !bin.empty(); } String Program::getPrefix() const { if(!p) return String(); return getPrefix(p->buildflags); } String Program::getPrefix(const String& buildflags) { const Context& ctx = Context::getDefault(); const Device& dev = ctx.device(0); return format("name=%s\ndriver=%s\nbuildflags=%s\n", dev.name().c_str(), dev.driverVersion().c_str(), buildflags.c_str()); } ///////////////////////////////////////// ProgramSource /////////////////////////////////////////////// struct ProgramSource::Impl { Impl(const char* _src) { init(String(_src)); } Impl(const String& _src) { init(_src); } void init(const String& _src) { refcount = 1; src = _src; h = crc64((uchar*)src.c_str(), src.size()); } IMPLEMENT_REFCOUNTABLE(); String src; ProgramSource::hash_t h; }; ProgramSource::ProgramSource() { p = 0; } ProgramSource::ProgramSource(const char* prog) { p = new Impl(prog); } ProgramSource::ProgramSource(const String& prog) { p = new Impl(prog); } ProgramSource::~ProgramSource() { if(p) p->release(); } ProgramSource::ProgramSource(const ProgramSource& prog) { p = prog.p; if(p) p->addref(); } ProgramSource& ProgramSource::operator = (const ProgramSource& prog) { Impl* newp = (Impl*)prog.p; if(newp) newp->addref(); if(p) p->release(); p = newp; return *this; } const String& ProgramSource::source() const { static String dummy; return p ? p->src : dummy; } ProgramSource::hash_t ProgramSource::hash() const { return p ? p->h : 0; } //////////////////////////////////////////// OpenCLAllocator ////////////////////////////////////////////////// class OpenCLBufferPool { protected: ~OpenCLBufferPool() { } public: virtual cl_mem allocate(size_t size, CV_OUT size_t& capacity) = 0; virtual void release(cl_mem handle, size_t capacity) = 0; }; class OpenCLBufferPoolImpl : public BufferPoolController, public OpenCLBufferPool { public: struct BufferEntry { cl_mem clBuffer_; size_t capacity_; }; protected: Mutex mutex_; size_t currentReservedSize; size_t maxReservedSize; std::list<BufferEntry> reservedEntries_; // LRU order // synchronized bool _findAndRemoveEntryFromReservedList(CV_OUT BufferEntry& entry, const size_t size) { if (reservedEntries_.empty()) return false; std::list<BufferEntry>::iterator i = reservedEntries_.begin(); std::list<BufferEntry>::iterator result_pos = reservedEntries_.end(); BufferEntry result = {NULL, 0}; size_t minDiff = (size_t)(-1); for (; i != reservedEntries_.end(); ++i) { BufferEntry& e = *i; if (e.capacity_ >= size) { size_t diff = e.capacity_ - size; if (diff < size / 8 && (result_pos == reservedEntries_.end() || diff < minDiff)) { minDiff = diff; result_pos = i; result = e; if (diff == 0) break; } } } if (result_pos != reservedEntries_.end()) { //CV_DbgAssert(result == *result_pos); reservedEntries_.erase(result_pos); entry = result; currentReservedSize -= entry.capacity_; return true; } return false; } // synchronized void _checkSizeOfReservedEntries() { while (currentReservedSize > maxReservedSize) { CV_DbgAssert(!reservedEntries_.empty()); const BufferEntry& entry = reservedEntries_.back(); CV_DbgAssert(currentReservedSize >= entry.capacity_); currentReservedSize -= entry.capacity_; _releaseBufferEntry(entry); reservedEntries_.pop_back(); } } inline size_t _allocationGranularity(size_t size) { // heuristic values if (size < 1024) return 16; else if (size < 64*1024) return 64; else if (size < 1024*1024) return 4096; else if (size < 16*1024*1024) return 64*1024; else return 1024*1024; } void _allocateBufferEntry(BufferEntry& entry, size_t size) { CV_DbgAssert(entry.clBuffer_ == NULL); entry.capacity_ = alignSize(size, (int)_allocationGranularity(size)); Context& ctx = Context::getDefault(); cl_int retval = CL_SUCCESS; entry.clBuffer_ = clCreateBuffer((cl_context)ctx.ptr(), CL_MEM_READ_WRITE, entry.capacity_, 0, &retval); CV_Assert(retval == CL_SUCCESS); CV_Assert(entry.clBuffer_ != NULL); LOG_BUFFER_POOL("OpenCL allocate %lld (0x%llx) bytes: %p\n", (long long)entry.capacity_, (long long)entry.capacity_, entry.clBuffer_); } void _releaseBufferEntry(const BufferEntry& entry) { CV_Assert(entry.capacity_ != 0); CV_Assert(entry.clBuffer_ != NULL); LOG_BUFFER_POOL("OpenCL release buffer: %p, %lld (0x%llx) bytes\n", entry.clBuffer_, (long long)entry.capacity_, (long long)entry.capacity_); clReleaseMemObject(entry.clBuffer_); } public: OpenCLBufferPoolImpl() : currentReservedSize(0), maxReservedSize(0) { // Note: Buffer pool is disabled by default, // because we didn't receive significant performance improvement maxReservedSize = getConfigurationParameterForSize("OPENCV_OPENCL_BUFFERPOOL_LIMIT", 0); } virtual ~OpenCLBufferPoolImpl() { freeAllReservedBuffers(); CV_Assert(reservedEntries_.empty()); } public: virtual cl_mem allocate(size_t size, CV_OUT size_t& capacity) { BufferEntry entry = {NULL, 0}; if (maxReservedSize > 0) { AutoLock locker(mutex_); if (_findAndRemoveEntryFromReservedList(entry, size)) { CV_DbgAssert(size <= entry.capacity_); LOG_BUFFER_POOL("Reuse reserved buffer: %p\n", entry.clBuffer_); capacity = entry.capacity_; return entry.clBuffer_; } } _allocateBufferEntry(entry, size); capacity = entry.capacity_; return entry.clBuffer_; } virtual void release(cl_mem handle, size_t capacity) { BufferEntry entry = {handle, capacity}; if (maxReservedSize == 0 || entry.capacity_ > maxReservedSize / 8) { _releaseBufferEntry(entry); } else { AutoLock locker(mutex_); reservedEntries_.push_front(entry); currentReservedSize += entry.capacity_; _checkSizeOfReservedEntries(); } } virtual size_t getReservedSize() const { return currentReservedSize; } virtual size_t getMaxReservedSize() const { return maxReservedSize; } virtual void setMaxReservedSize(size_t size) { AutoLock locker(mutex_); size_t oldMaxReservedSize = maxReservedSize; maxReservedSize = size; if (maxReservedSize < oldMaxReservedSize) { std::list<BufferEntry>::iterator i = reservedEntries_.begin(); for (; i != reservedEntries_.end();) { const BufferEntry& entry = *i; if (entry.capacity_ > maxReservedSize / 8) { CV_DbgAssert(currentReservedSize >= entry.capacity_); currentReservedSize -= entry.capacity_; _releaseBufferEntry(entry); i = reservedEntries_.erase(i); continue; } ++i; } _checkSizeOfReservedEntries(); } } virtual void freeAllReservedBuffers() { AutoLock locker(mutex_); std::list<BufferEntry>::const_iterator i = reservedEntries_.begin(); for (; i != reservedEntries_.end(); ++i) { const BufferEntry& entry = *i; _releaseBufferEntry(entry); } reservedEntries_.clear(); } }; #if defined _MSC_VER #pragma warning(disable:4127) // conditional expression is constant #endif template <bool readAccess, bool writeAccess> class AlignedDataPtr { protected: const size_t size_; uchar* const originPtr_; const size_t alignment_; uchar* ptr_; uchar* allocatedPtr_; public: AlignedDataPtr(uchar* ptr, size_t size, size_t alignment) : size_(size), originPtr_(ptr), alignment_(alignment), ptr_(ptr), allocatedPtr_(NULL) { CV_DbgAssert((alignment & (alignment - 1)) == 0); // check for 2^n if (((size_t)ptr_ & (alignment - 1)) != 0) { allocatedPtr_ = new uchar[size_ + alignment - 1]; ptr_ = (uchar*)(((uintptr_t)allocatedPtr_ + (alignment - 1)) & ~(alignment - 1)); if (readAccess) { memcpy(ptr_, originPtr_, size_); } } } uchar* getAlignedPtr() const { CV_DbgAssert(((size_t)ptr_ & (alignment_ - 1)) == 0); return ptr_; } ~AlignedDataPtr() { if (allocatedPtr_) { if (writeAccess) { memcpy(originPtr_, ptr_, size_); } delete[] allocatedPtr_; allocatedPtr_ = NULL; } ptr_ = NULL; } private: AlignedDataPtr(const AlignedDataPtr&); // disabled AlignedDataPtr& operator=(const AlignedDataPtr&); // disabled }; #if defined _MSC_VER #pragma warning(default:4127) // conditional expression is constant #endif #ifndef CV_OPENCL_DATA_PTR_ALIGNMENT #define CV_OPENCL_DATA_PTR_ALIGNMENT 16 #endif class OpenCLAllocator : public MatAllocator { mutable OpenCLBufferPoolImpl bufferPool; enum AllocatorFlags { ALLOCATOR_FLAGS_BUFFER_POOL_USED = 1 << 0 }; public: OpenCLAllocator() { matStdAllocator = Mat::getStdAllocator(); } UMatData* defaultAllocate(int dims, const int* sizes, int type, void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const { UMatData* u = matStdAllocator->allocate(dims, sizes, type, data, step, flags, usageFlags); return u; } void getBestFlags(const Context& ctx, int /*flags*/, UMatUsageFlags usageFlags, int& createFlags, int& flags0) const { const Device& dev = ctx.device(0); createFlags = 0; if ((usageFlags & USAGE_ALLOCATE_HOST_MEMORY) != 0) createFlags |= CL_MEM_ALLOC_HOST_PTR; if( dev.hostUnifiedMemory() ) flags0 = 0; else flags0 = UMatData::COPY_ON_MAP; } UMatData* allocate(int dims, const int* sizes, int type, void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const { if(!useOpenCL()) return defaultAllocate(dims, sizes, type, data, step, flags, usageFlags); CV_Assert(data == 0); size_t total = CV_ELEM_SIZE(type); for( int i = dims-1; i >= 0; i-- ) { if( step ) step[i] = total; total *= sizes[i]; } Context& ctx = Context::getDefault(); int createFlags = 0, flags0 = 0; getBestFlags(ctx, flags, usageFlags, createFlags, flags0); size_t capacity = 0; void* handle = NULL; int allocatorFlags = 0; if (createFlags == 0) { handle = bufferPool.allocate(total, capacity); if (!handle) return defaultAllocate(dims, sizes, type, data, step, flags, usageFlags); allocatorFlags = ALLOCATOR_FLAGS_BUFFER_POOL_USED; } else { capacity = total; cl_int retval = 0; handle = clCreateBuffer((cl_context)ctx.ptr(), CL_MEM_READ_WRITE|createFlags, total, 0, &retval); if( !handle || retval != CL_SUCCESS ) return defaultAllocate(dims, sizes, type, data, step, flags, usageFlags); } UMatData* u = new UMatData(this); u->data = 0; u->size = total; u->capacity = capacity; u->handle = handle; u->flags = flags0; u->allocatorFlags_ = allocatorFlags; CV_DbgAssert(!u->tempUMat()); // for bufferPool.release() consistency in deallocate() return u; } bool allocate(UMatData* u, int accessFlags, UMatUsageFlags usageFlags) const { if(!u) return false; UMatDataAutoLock lock(u); if(u->handle == 0) { CV_Assert(u->origdata != 0); Context& ctx = Context::getDefault(); int createFlags = 0, flags0 = 0; getBestFlags(ctx, accessFlags, usageFlags, createFlags, flags0); cl_context ctx_handle = (cl_context)ctx.ptr(); cl_int retval = 0; int tempUMatFlags = UMatData::TEMP_UMAT; u->handle = clCreateBuffer(ctx_handle, CL_MEM_USE_HOST_PTR|CL_MEM_READ_WRITE, u->size, u->origdata, &retval); if((!u->handle || retval != CL_SUCCESS) && !(accessFlags & ACCESS_FAST)) { u->handle = clCreateBuffer(ctx_handle, CL_MEM_COPY_HOST_PTR|CL_MEM_READ_WRITE|createFlags, u->size, u->origdata, &retval); tempUMatFlags = UMatData::TEMP_COPIED_UMAT; } if(!u->handle || retval != CL_SUCCESS) return false; u->prevAllocator = u->currAllocator; u->currAllocator = this; u->flags |= tempUMatFlags; } if(accessFlags & ACCESS_WRITE) u->markHostCopyObsolete(true); return true; } /*void sync(UMatData* u) const { cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr(); UMatDataAutoLock lock(u); if( u->hostCopyObsolete() && u->handle && u->refcount > 0 && u->origdata) { if( u->tempCopiedUMat() ) { clEnqueueReadBuffer(q, (cl_mem)u->handle, CL_TRUE, 0, u->size, u->origdata, 0, 0, 0); } else { cl_int retval = 0; void* data = clEnqueueMapBuffer(q, (cl_mem)u->handle, CL_TRUE, (CL_MAP_READ | CL_MAP_WRITE), 0, u->size, 0, 0, 0, &retval); clEnqueueUnmapMemObject(q, (cl_mem)u->handle, data, 0, 0, 0); clFinish(q); } u->markHostCopyObsolete(false); } else if( u->copyOnMap() && u->deviceCopyObsolete() && u->data ) { clEnqueueWriteBuffer(q, (cl_mem)u->handle, CL_TRUE, 0, u->size, u->data, 0, 0, 0); } }*/ void deallocate(UMatData* u) const { if(!u) return; CV_Assert(u->urefcount >= 0); CV_Assert(u->refcount >= 0); // TODO: !!! when we add Shared Virtual Memory Support, // this function (as well as the others) should be corrected CV_Assert(u->handle != 0 && u->urefcount == 0); if(u->tempUMat()) { // UMatDataAutoLock lock(u); if( u->hostCopyObsolete() && u->refcount > 0 ) { cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr(); if( u->tempCopiedUMat() ) { AlignedDataPtr<false, true> alignedPtr(u->origdata, u->size, CV_OPENCL_DATA_PTR_ALIGNMENT); CV_OclDbgAssert(clEnqueueReadBuffer(q, (cl_mem)u->handle, CL_TRUE, 0, u->size, alignedPtr.getAlignedPtr(), 0, 0, 0) == CL_SUCCESS); } else { cl_int retval = 0; void* data = clEnqueueMapBuffer(q, (cl_mem)u->handle, CL_TRUE, (CL_MAP_READ | CL_MAP_WRITE), 0, u->size, 0, 0, 0, &retval); CV_OclDbgAssert(retval == CL_SUCCESS); CV_OclDbgAssert(clEnqueueUnmapMemObject(q, (cl_mem)u->handle, data, 0, 0, 0) == CL_SUCCESS); CV_OclDbgAssert(clFinish(q) == CL_SUCCESS); } } u->markHostCopyObsolete(false); clReleaseMemObject((cl_mem)u->handle); u->handle = 0; u->currAllocator = u->prevAllocator; if(u->data && u->copyOnMap() && !(u->flags & UMatData::USER_ALLOCATED)) fastFree(u->data); u->data = u->origdata; if(u->refcount == 0) u->currAllocator->deallocate(u); } else { CV_Assert(u->refcount == 0); if(u->data && u->copyOnMap() && !(u->flags & UMatData::USER_ALLOCATED)) { fastFree(u->data); u->data = 0; } if (u->allocatorFlags_ & ALLOCATOR_FLAGS_BUFFER_POOL_USED) { bufferPool.release((cl_mem)u->handle, u->capacity); } else { clReleaseMemObject((cl_mem)u->handle); } u->handle = 0; u->capacity = 0; delete u; } } void map(UMatData* u, int accessFlags) const { if(!u) return; CV_Assert( u->handle != 0 ); UMatDataAutoLock autolock(u); if(accessFlags & ACCESS_WRITE) u->markDeviceCopyObsolete(true); cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr(); if( u->refcount == 0 ) { if( !u->copyOnMap() ) { CV_Assert(u->data == 0); // because there can be other map requests for the same UMat with different access flags, // we use the universal (read-write) access mode. cl_int retval = 0; u->data = (uchar*)clEnqueueMapBuffer(q, (cl_mem)u->handle, CL_TRUE, (CL_MAP_READ | CL_MAP_WRITE), 0, u->size, 0, 0, 0, &retval); if(u->data && retval == CL_SUCCESS) { u->markHostCopyObsolete(false); return; } // if map failed, switch to copy-on-map mode for the particular buffer u->flags |= UMatData::COPY_ON_MAP; } if(!u->data) { u->data = (uchar*)fastMalloc(u->size); u->markHostCopyObsolete(true); } } if( (accessFlags & ACCESS_READ) != 0 && u->hostCopyObsolete() ) { AlignedDataPtr<false, true> alignedPtr(u->data, u->size, CV_OPENCL_DATA_PTR_ALIGNMENT); CV_Assert( clEnqueueReadBuffer(q, (cl_mem)u->handle, CL_TRUE, 0, u->size, alignedPtr.getAlignedPtr(), 0, 0, 0) == CL_SUCCESS ); u->markHostCopyObsolete(false); } } void unmap(UMatData* u) const { if(!u) return; CV_Assert(u->handle != 0); UMatDataAutoLock autolock(u); cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr(); cl_int retval = 0; if( !u->copyOnMap() && u->data ) { CV_Assert( (retval = clEnqueueUnmapMemObject(q, (cl_mem)u->handle, u->data, 0, 0, 0)) == CL_SUCCESS ); CV_OclDbgAssert(clFinish(q) == CL_SUCCESS); u->data = 0; } else if( u->copyOnMap() && u->deviceCopyObsolete() ) { AlignedDataPtr<true, false> alignedPtr(u->data, u->size, CV_OPENCL_DATA_PTR_ALIGNMENT); CV_Assert( (retval = clEnqueueWriteBuffer(q, (cl_mem)u->handle, CL_TRUE, 0, u->size, alignedPtr.getAlignedPtr(), 0, 0, 0)) == CL_SUCCESS ); } u->markDeviceCopyObsolete(false); u->markHostCopyObsolete(false); } bool checkContinuous(int dims, const size_t sz[], const size_t srcofs[], const size_t srcstep[], const size_t dstofs[], const size_t dststep[], size_t& total, size_t new_sz[], size_t& srcrawofs, size_t new_srcofs[], size_t new_srcstep[], size_t& dstrawofs, size_t new_dstofs[], size_t new_dststep[]) const { bool iscontinuous = true; srcrawofs = srcofs ? srcofs[dims-1] : 0; dstrawofs = dstofs ? dstofs[dims-1] : 0; total = sz[dims-1]; for( int i = dims-2; i >= 0; i-- ) { if( i >= 0 && (total != srcstep[i] || total != dststep[i]) ) iscontinuous = false; total *= sz[i]; if( srcofs ) srcrawofs += srcofs[i]*srcstep[i]; if( dstofs ) dstrawofs += dstofs[i]*dststep[i]; } if( !iscontinuous ) { // OpenCL uses {x, y, z} order while OpenCV uses {z, y, x} order. if( dims == 2 ) { new_sz[0] = sz[1]; new_sz[1] = sz[0]; new_sz[2] = 1; // we assume that new_... arrays are initialized by caller // with 0's, so there is no else branch if( srcofs ) { new_srcofs[0] = srcofs[1]; new_srcofs[1] = srcofs[0]; new_srcofs[2] = 0; } if( dstofs ) { new_dstofs[0] = dstofs[1]; new_dstofs[1] = dstofs[0]; new_dstofs[2] = 0; } new_srcstep[0] = srcstep[0]; new_srcstep[1] = 0; new_dststep[0] = dststep[0]; new_dststep[1] = 0; } else { // we could check for dims == 3 here, // but from user perspective this one is more informative CV_Assert(dims <= 3); new_sz[0] = sz[2]; new_sz[1] = sz[1]; new_sz[2] = sz[0]; if( srcofs ) { new_srcofs[0] = srcofs[2]; new_srcofs[1] = srcofs[1]; new_srcofs[2] = srcofs[0]; } if( dstofs ) { new_dstofs[0] = dstofs[2]; new_dstofs[1] = dstofs[1]; new_dstofs[2] = dstofs[0]; } new_srcstep[0] = srcstep[1]; new_srcstep[1] = srcstep[0]; new_dststep[0] = dststep[1]; new_dststep[1] = dststep[0]; } } return iscontinuous; } void download(UMatData* u, void* dstptr, int dims, const size_t sz[], const size_t srcofs[], const size_t srcstep[], const size_t dststep[]) const { if(!u) return; UMatDataAutoLock autolock(u); if( u->data && !u->hostCopyObsolete() ) { Mat::getStdAllocator()->download(u, dstptr, dims, sz, srcofs, srcstep, dststep); return; } CV_Assert( u->handle != 0 ); cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr(); size_t total = 0, new_sz[] = {0, 0, 0}; size_t srcrawofs = 0, new_srcofs[] = {0, 0, 0}, new_srcstep[] = {0, 0, 0}; size_t dstrawofs = 0, new_dstofs[] = {0, 0, 0}, new_dststep[] = {0, 0, 0}; bool iscontinuous = checkContinuous(dims, sz, srcofs, srcstep, 0, dststep, total, new_sz, srcrawofs, new_srcofs, new_srcstep, dstrawofs, new_dstofs, new_dststep); AlignedDataPtr<false, true> alignedPtr((uchar*)dstptr, sz[0] * dststep[0], CV_OPENCL_DATA_PTR_ALIGNMENT); if( iscontinuous ) { CV_Assert( clEnqueueReadBuffer(q, (cl_mem)u->handle, CL_TRUE, srcrawofs, total, alignedPtr.getAlignedPtr(), 0, 0, 0) == CL_SUCCESS ); } else { CV_Assert( clEnqueueReadBufferRect(q, (cl_mem)u->handle, CL_TRUE, new_srcofs, new_dstofs, new_sz, new_srcstep[0], new_srcstep[1], new_dststep[0], new_dststep[1], alignedPtr.getAlignedPtr(), 0, 0, 0) == CL_SUCCESS ); } } void upload(UMatData* u, const void* srcptr, int dims, const size_t sz[], const size_t dstofs[], const size_t dststep[], const size_t srcstep[]) const { if(!u) return; // there should be no user-visible CPU copies of the UMat which we are going to copy to CV_Assert(u->refcount == 0 || u->tempUMat()); size_t total = 0, new_sz[] = {0, 0, 0}; size_t srcrawofs = 0, new_srcofs[] = {0, 0, 0}, new_srcstep[] = {0, 0, 0}; size_t dstrawofs = 0, new_dstofs[] = {0, 0, 0}, new_dststep[] = {0, 0, 0}; bool iscontinuous = checkContinuous(dims, sz, 0, srcstep, dstofs, dststep, total, new_sz, srcrawofs, new_srcofs, new_srcstep, dstrawofs, new_dstofs, new_dststep); UMatDataAutoLock autolock(u); // if there is cached CPU copy of the GPU matrix, // we could use it as a destination. // we can do it in 2 cases: // 1. we overwrite the whole content // 2. we overwrite part of the matrix, but the GPU copy is out-of-date if( u->data && (u->hostCopyObsolete() < u->deviceCopyObsolete() || total == u->size)) { Mat::getStdAllocator()->upload(u, srcptr, dims, sz, dstofs, dststep, srcstep); u->markHostCopyObsolete(false); u->markDeviceCopyObsolete(true); return; } CV_Assert( u->handle != 0 ); cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr(); AlignedDataPtr<true, false> alignedPtr((uchar*)srcptr, sz[0] * srcstep[0], CV_OPENCL_DATA_PTR_ALIGNMENT); if( iscontinuous ) { CV_Assert( clEnqueueWriteBuffer(q, (cl_mem)u->handle, CL_TRUE, dstrawofs, total, srcptr, 0, 0, 0) == CL_SUCCESS ); } else { CV_Assert( clEnqueueWriteBufferRect(q, (cl_mem)u->handle, CL_TRUE, new_dstofs, new_srcofs, new_sz, new_dststep[0], new_dststep[1], new_srcstep[0], new_srcstep[1], srcptr, 0, 0, 0) == CL_SUCCESS ); } u->markHostCopyObsolete(true); u->markDeviceCopyObsolete(false); } void copy(UMatData* src, UMatData* dst, int dims, const size_t sz[], const size_t srcofs[], const size_t srcstep[], const size_t dstofs[], const size_t dststep[], bool _sync) const { if(!src || !dst) return; size_t total = 0, new_sz[] = {0, 0, 0}; size_t srcrawofs = 0, new_srcofs[] = {0, 0, 0}, new_srcstep[] = {0, 0, 0}; size_t dstrawofs = 0, new_dstofs[] = {0, 0, 0}, new_dststep[] = {0, 0, 0}; bool iscontinuous = checkContinuous(dims, sz, srcofs, srcstep, dstofs, dststep, total, new_sz, srcrawofs, new_srcofs, new_srcstep, dstrawofs, new_dstofs, new_dststep); UMatDataAutoLock src_autolock(src); UMatDataAutoLock dst_autolock(dst); if( !src->handle || (src->data && src->hostCopyObsolete() < src->deviceCopyObsolete()) ) { upload(dst, src->data + srcrawofs, dims, sz, dstofs, dststep, srcstep); return; } if( !dst->handle || (dst->data && dst->hostCopyObsolete() < dst->deviceCopyObsolete()) ) { download(src, dst->data + dstrawofs, dims, sz, srcofs, srcstep, dststep); dst->markHostCopyObsolete(false); dst->markDeviceCopyObsolete(true); return; } // there should be no user-visible CPU copies of the UMat which we are going to copy to CV_Assert(dst->refcount == 0); cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr(); if( iscontinuous ) { CV_Assert( clEnqueueCopyBuffer(q, (cl_mem)src->handle, (cl_mem)dst->handle, srcrawofs, dstrawofs, total, 0, 0, 0) == CL_SUCCESS ); } else { cl_int retval; CV_Assert( (retval = clEnqueueCopyBufferRect(q, (cl_mem)src->handle, (cl_mem)dst->handle, new_srcofs, new_dstofs, new_sz, new_srcstep[0], new_srcstep[1], new_dststep[0], new_dststep[1], 0, 0, 0)) == CL_SUCCESS ); } dst->markHostCopyObsolete(true); dst->markDeviceCopyObsolete(false); if( _sync ) { CV_OclDbgAssert(clFinish(q) == CL_SUCCESS); } } BufferPoolController* getBufferPoolController() const { return &bufferPool; } MatAllocator* matStdAllocator; }; MatAllocator* getOpenCLAllocator() { static MatAllocator * allocator = new OpenCLAllocator(); return allocator; } ///////////////////////////////////////////// Utility functions ///////////////////////////////////////////////// static void getDevices(std::vector<cl_device_id>& devices, cl_platform_id platform) { cl_uint numDevices = 0; CV_OclDbgAssert(clGetDeviceIDs(platform, (cl_device_type)Device::TYPE_ALL, 0, NULL, &numDevices) == CL_SUCCESS); if (numDevices == 0) { devices.clear(); return; } devices.resize((size_t)numDevices); CV_OclDbgAssert(clGetDeviceIDs(platform, (cl_device_type)Device::TYPE_ALL, numDevices, &devices[0], &numDevices) == CL_SUCCESS); } struct PlatformInfo::Impl { Impl(void* id) { refcount = 1; handle = *(cl_platform_id*)id; getDevices(devices, handle); } String getStrProp(cl_device_info prop) const { char buf[1024]; size_t sz=0; return clGetPlatformInfo(handle, prop, sizeof(buf)-16, buf, &sz) == CL_SUCCESS && sz < sizeof(buf) ? String(buf) : String(); } IMPLEMENT_REFCOUNTABLE(); std::vector<cl_device_id> devices; cl_platform_id handle; }; PlatformInfo::PlatformInfo() { p = 0; } PlatformInfo::PlatformInfo(void* platform_id) { p = new Impl(platform_id); } PlatformInfo::~PlatformInfo() { if(p) p->release(); } PlatformInfo::PlatformInfo(const PlatformInfo& i) { if (i.p) i.p->addref(); p = i.p; } PlatformInfo& PlatformInfo::operator =(const PlatformInfo& i) { if (i.p != p) { if (i.p) i.p->addref(); if (p) p->release(); p = i.p; } return *this; } int PlatformInfo::deviceNumber() const { return p ? (int)p->devices.size() : 0; } void PlatformInfo::getDevice(Device& device, int d) const { CV_Assert(p && d < (int)p->devices.size() ); if(p) device.set(p->devices[d]); } String PlatformInfo::name() const { return p ? p->getStrProp(CL_PLATFORM_NAME) : String(); } String PlatformInfo::vendor() const { return p ? p->getStrProp(CL_PLATFORM_VENDOR) : String(); } String PlatformInfo::version() const { return p ? p->getStrProp(CL_PLATFORM_VERSION) : String(); } static void getPlatforms(std::vector<cl_platform_id>& platforms) { cl_uint numPlatforms = 0; CV_OclDbgAssert(clGetPlatformIDs(0, NULL, &numPlatforms) == CL_SUCCESS); if (numPlatforms == 0) { platforms.clear(); return; } platforms.resize((size_t)numPlatforms); CV_OclDbgAssert(clGetPlatformIDs(numPlatforms, &platforms[0], &numPlatforms) == CL_SUCCESS); } void getPlatfomsInfo(std::vector<PlatformInfo>& platformsInfo) { std::vector<cl_platform_id> platforms; getPlatforms(platforms); for (size_t i = 0; i < platforms.size(); i++) platformsInfo.push_back( PlatformInfo((void*)&platforms[i]) ); } const char* typeToStr(int type) { static const char* tab[]= { "uchar", "uchar2", "uchar3", "uchar4", 0, 0, 0, "uchar8", 0, 0, 0, 0, 0, 0, 0, "uchar16", "char", "char2", "char3", "char4", 0, 0, 0, "char8", 0, 0, 0, 0, 0, 0, 0, "char16", "ushort", "ushort2", "ushort3", "ushort4",0, 0, 0, "ushort8", 0, 0, 0, 0, 0, 0, 0, "ushort16", "short", "short2", "short3", "short4", 0, 0, 0, "short8", 0, 0, 0, 0, 0, 0, 0, "short16", "int", "int2", "int3", "int4", 0, 0, 0, "int8", 0, 0, 0, 0, 0, 0, 0, "int16", "float", "float2", "float3", "float4", 0, 0, 0, "float8", 0, 0, 0, 0, 0, 0, 0, "float16", "double", "double2", "double3", "double4", 0, 0, 0, "double8", 0, 0, 0, 0, 0, 0, 0, "double16", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?" }; int cn = CV_MAT_CN(type), depth = CV_MAT_DEPTH(type); return cn > 16 ? "?" : tab[depth*16 + cn-1]; } const char* memopTypeToStr(int type) { static const char* tab[] = { "uchar", "uchar2", "uchar3", "uchar4", 0, 0, 0, "uchar8", 0, 0, 0, 0, 0, 0, 0, "uchar16", "char", "char2", "char3", "char4", 0, 0, 0, "char8", 0, 0, 0, 0, 0, 0, 0, "char16", "ushort", "ushort2", "ushort3", "ushort4",0, 0, 0, "ushort8", 0, 0, 0, 0, 0, 0, 0, "ushort16", "short", "short2", "short3", "short4", 0, 0, 0, "short8", 0, 0, 0, 0, 0, 0, 0, "short16", "int", "int2", "int3", "int4", 0, 0, 0, "int8", 0, 0, 0, 0, 0, 0, 0, "int16", "int", "int2", "int3", "int4", 0, 0, 0, "int8", 0, 0, 0, 0, 0, 0, 0, "int16", "ulong", "ulong2", "ulong3", "ulong4", 0, 0, 0, "ulong8", 0, 0, 0, 0, 0, 0, 0, "ulong16", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?" }; int cn = CV_MAT_CN(type), depth = CV_MAT_DEPTH(type); return cn > 16 ? "?" : tab[depth*16 + cn-1]; } const char* convertTypeStr(int sdepth, int ddepth, int cn, char* buf) { if( sdepth == ddepth ) return "noconvert"; const char *typestr = typeToStr(CV_MAKETYPE(ddepth, cn)); if( ddepth >= CV_32F || (ddepth == CV_32S && sdepth < CV_32S) || (ddepth == CV_16S && sdepth <= CV_8S) || (ddepth == CV_16U && sdepth == CV_8U)) { sprintf(buf, "convert_%s", typestr); } else if( sdepth >= CV_32F ) sprintf(buf, "convert_%s%s_rte", typestr, (ddepth < CV_32S ? "_sat" : "")); else sprintf(buf, "convert_%s_sat", typestr); return buf; } template <typename T> static std::string kerToStr(const Mat & k) { int width = k.cols - 1, depth = k.depth(); const T * const data = reinterpret_cast<const T *>(k.data); std::ostringstream stream; stream.precision(10); if (depth <= CV_8S) { for (int i = 0; i < width; ++i) stream << "DIG(" << (int)data[i] << ")"; stream << "DIG(" << (int)data[width] << ")"; } else if (depth == CV_32F) { stream.setf(std::ios_base::showpoint); for (int i = 0; i < width; ++i) stream << "DIG(" << data[i] << "f)"; stream << "DIG(" << data[width] << "f)"; } else { for (int i = 0; i < width; ++i) stream << "DIG(" << data[i] << ")"; stream << "DIG(" << data[width] << ")"; } return stream.str(); } String kernelToStr(InputArray _kernel, int ddepth, const char * name) { Mat kernel = _kernel.getMat().reshape(1, 1); int depth = kernel.depth(); if (ddepth < 0) ddepth = depth; if (ddepth != depth) kernel.convertTo(kernel, ddepth); typedef std::string (* func_t)(const Mat &); static const func_t funcs[] = { kerToStr<uchar>, kerToStr<char>, kerToStr<ushort>, kerToStr<short>, kerToStr<int>, kerToStr<float>, kerToStr<double>, 0 }; const func_t func = funcs[depth]; CV_Assert(func != 0); return cv::format(" -D %s=%s", name ? name : "COEFF", func(kernel).c_str()); } #define PROCESS_SRC(src) \ do \ { \ if (!src.empty()) \ { \ CV_Assert(src.isMat() || src.isUMat()); \ int ctype = src.type(), ccn = CV_MAT_CN(ctype); \ Size csize = src.size(); \ cols.push_back(ccn * src.size().width); \ if (ctype != type || csize != ssize) \ return 1; \ offsets.push_back(src.offset()); \ steps.push_back(src.step()); \ } \ } \ while ((void)0, 0) int predictOptimalVectorWidth(InputArray src1, InputArray src2, InputArray src3, InputArray src4, InputArray src5, InputArray src6, InputArray src7, InputArray src8, InputArray src9) { int type = src1.type(), depth = CV_MAT_DEPTH(type), cn = CV_MAT_CN(type), esz = CV_ELEM_SIZE(depth); Size ssize = src1.size(); const ocl::Device & d = ocl::Device::getDefault(); int vectorWidths[] = { d.preferredVectorWidthChar(), d.preferredVectorWidthChar(), d.preferredVectorWidthShort(), d.preferredVectorWidthShort(), d.preferredVectorWidthInt(), d.preferredVectorWidthFloat(), d.preferredVectorWidthDouble(), -1 }, width = vectorWidths[depth]; if (ssize.width * cn < width || width <= 0) return 1; std::vector<size_t> offsets, steps, cols; PROCESS_SRC(src1); PROCESS_SRC(src2); PROCESS_SRC(src3); PROCESS_SRC(src4); PROCESS_SRC(src5); PROCESS_SRC(src6); PROCESS_SRC(src7); PROCESS_SRC(src8); PROCESS_SRC(src9); size_t size = offsets.size(); int wsz = width * esz; std::vector<int> dividers(size, wsz); for (size_t i = 0; i < size; ++i) while (offsets[i] % dividers[i] != 0 || steps[i] % dividers[i] != 0 || cols[i] % dividers[i] != 0) dividers[i] >>= 1; // default strategy for (size_t i = 0; i < size; ++i) if (dividers[i] != wsz) { width = 1; break; } // another strategy // width = *std::min_element(dividers.begin(), dividers.end()); return width; } #undef PROCESS_SRC /////////////////////////////////////////// Image2D //////////////////////////////////////////////////// struct Image2D::Impl { Impl(const UMat &src) { handle = 0; refcount = 1; init(src); } ~Impl() { if (handle) clReleaseMemObject(handle); } void init(const UMat &src) { CV_Assert(ocl::Device::getDefault().imageSupport()); cl_image_format format; int err, depth = src.depth(), cn = src.channels(); CV_Assert(cn <= 4); static const int channelTypes[] = { CL_UNSIGNED_INT8, CL_SIGNED_INT8, CL_UNSIGNED_INT16, CL_SIGNED_INT16, CL_SIGNED_INT32, CL_FLOAT, -1, -1 }; static const int channelOrders[] = { -1, CL_R, CL_RG, -1, CL_RGBA }; int channelType = channelTypes[depth], channelOrder = channelOrders[cn]; if (channelType < 0 || channelOrder < 0) CV_Error(Error::OpenCLApiCallError, "Image format is not supported"); format.image_channel_data_type = (cl_channel_type)channelType; format.image_channel_order = (cl_channel_order)channelOrder; cl_context context = (cl_context)Context::getDefault().ptr(); cl_command_queue queue = (cl_command_queue)Queue::getDefault().ptr(); #ifdef CL_VERSION_1_2 // this enables backwards portability to // run on OpenCL 1.1 platform if library binaries are compiled with OpenCL 1.2 support const Device & d = ocl::Device::getDefault(); int minor = d.deviceVersionMinor(), major = d.deviceVersionMajor(); if (1 < major || (1 == major && 2 <= minor)) { cl_image_desc desc; desc.image_type = CL_MEM_OBJECT_IMAGE2D; desc.image_width = src.cols; desc.image_height = src.rows; desc.image_depth = 0; desc.image_array_size = 1; desc.image_row_pitch = 0; desc.image_slice_pitch = 0; desc.buffer = NULL; desc.num_mip_levels = 0; desc.num_samples = 0; handle = clCreateImage(context, CL_MEM_READ_WRITE, &format, &desc, NULL, &err); } else #endif { handle = clCreateImage2D(context, CL_MEM_READ_WRITE, &format, src.cols, src.rows, 0, NULL, &err); } CV_OclDbgAssert(err == CL_SUCCESS); size_t origin[] = { 0, 0, 0 }; size_t region[] = { src.cols, src.rows, 1 }; cl_mem devData; if (!src.isContinuous()) { devData = clCreateBuffer(context, CL_MEM_READ_ONLY, src.cols * src.rows * src.elemSize(), NULL, &err); CV_OclDbgAssert(err == CL_SUCCESS); const size_t roi[3] = {src.cols * src.elemSize(), src.rows, 1}; CV_Assert(clEnqueueCopyBufferRect(queue, (cl_mem)src.handle(ACCESS_READ), devData, origin, origin, roi, src.step, 0, src.cols * src.elemSize(), 0, 0, NULL, NULL) == CL_SUCCESS); CV_OclDbgAssert(clFlush(queue) == CL_SUCCESS); } else devData = (cl_mem)src.handle(ACCESS_READ); CV_Assert(devData != NULL); CV_OclDbgAssert(clEnqueueCopyBufferToImage(queue, devData, handle, 0, origin, region, 0, NULL, 0) == CL_SUCCESS); if (!src.isContinuous()) { CV_OclDbgAssert(clFlush(queue) == CL_SUCCESS); CV_OclDbgAssert(clReleaseMemObject(devData) == CL_SUCCESS); } } IMPLEMENT_REFCOUNTABLE(); cl_mem handle; }; Image2D::Image2D() { p = NULL; } Image2D::Image2D(const UMat &src) { p = new Impl(src); } Image2D::Image2D(const Image2D & i) { p = i.p; if (p) p->addref(); } Image2D & Image2D::operator = (const Image2D & i) { if (i.p != p) { if (i.p) i.p->addref(); if (p) p->release(); p = i.p; } return *this; } Image2D::~Image2D() { if (p) p->release(); } void* Image2D::ptr() const { return p ? p->handle : 0; } }}
// Original test: ./kranz/hw4/problem6/sco_1.asm // Author: kranz // Test source code follows // Original test: ./kranz/hw4/problem6/slu_1.asm // Author: kranz //This checks to make sure there is no carry-out generated lbi r1, 0x10 //expected value in r1 = 16 lbi r2, 1 //expected value in r2 = 1 sco r3, r1, r2 //expected value in r3 = 0 halt
; Example of using the CMP and JGE instructions ; Assemble as: nasm -f elf -g cmptst.asm ; Link as: ld -m elf_i386 -o cmptst cmptst.o section .data num1 dd '10' num2 dd '30' msg1 db "ebx > eax", 0xa msg2 db "ebx < eax", 0xa MsgLen equ $-msg2 ;The length of the message section .text global _start _start: nop mov eax, [num1] mov ebx, [num2] cmp ebx, eax ; test to see if ebx > eax jge greater ; jump to "greater" if true mov edx, MsgLen ; msg length mov ecx, msg2 mov ebx, 1 ; stdout mov eax, 4 ; write int 0x80 mov eax, 1 ;exit int 0x80 greater: mov edx, MsgLen mov ecx, msg1 mov ebx, 1 ; stdout mov eax, 4 ; write int 0x80 mov eax, 1 ;exit int 0x80
adc a,ixh ; Error adc a,ixl ; Error adc a,iyh ; Error adc a,iyl ; Error adc ixh ; Error adc ixl ; Error adc iyh ; Error adc iyl ; Error add a,ixh ; Error add a,ixl ; Error add a,iyh ; Error add a,iyl ; Error add ixh ; Error add ixl ; Error add iyh ; Error add iyl ; Error altd res -1,a ; Error altd res -1,b ; Error altd res -1,c ; Error altd res -1,d ; Error altd res -1,e ; Error altd res -1,h ; Error altd res -1,l ; Error altd res 8,a ; Error altd res 8,b ; Error altd res 8,c ; Error altd res 8,d ; Error altd res 8,e ; Error altd res 8,h ; Error altd res 8,l ; Error altd set -1,a ; Error altd set -1,b ; Error altd set -1,c ; Error altd set -1,d ; Error altd set -1,e ; Error altd set -1,h ; Error altd set -1,l ; Error altd set 8,a ; Error altd set 8,b ; Error altd set 8,c ; Error altd set 8,d ; Error altd set 8,e ; Error altd set 8,h ; Error altd set 8,l ; Error and a,ixh ; Error and a,ixl ; Error and a,iyh ; Error and a,iyl ; Error and ixh ; Error and ixl ; Error and iyh ; Error and iyl ; Error bit -1,(hl) ; Error bit -1,(ix) ; Error bit -1,(ix+DIS) ; Error bit -1,(iy) ; Error bit -1,(iy+DIS) ; Error bit -1,a ; Error bit -1,b ; Error bit -1,c ; Error bit -1,d ; Error bit -1,e ; Error bit -1,h ; Error bit -1,l ; Error bit 8,(hl) ; Error bit 8,(ix) ; Error bit 8,(ix+DIS) ; Error bit 8,(iy) ; Error bit 8,(iy+DIS) ; Error bit 8,a ; Error bit 8,b ; Error bit 8,c ; Error bit 8,d ; Error bit 8,e ; Error bit 8,h ; Error bit 8,l ; Error cp a,ixh ; Error cp a,ixl ; Error cp a,iyh ; Error cp a,iyl ; Error cp ixh ; Error cp ixl ; Error cp iyh ; Error cp iyl ; Error dec ixh ; Error dec ixl ; Error dec iyh ; Error dec iyl ; Error di ; Error ei ; Error halt ; Error im -1 ; Error im 0 ; Error im 1 ; Error im 2 ; Error im 3 ; Error in a,(N) ; Error in a,(c) ; Error in b,(c) ; Error in c,(c) ; Error in d,(c) ; Error in e,(c) ; Error in f,(c) ; Error in h,(c) ; Error in l,(c) ; Error in0 a,(N) ; Error in0 b,(N) ; Error in0 c,(N) ; Error in0 d,(N) ; Error in0 e,(N) ; Error in0 f,(N) ; Error in0 h,(N) ; Error in0 l,(N) ; Error inc ixh ; Error inc ixl ; Error inc iyh ; Error inc iyl ; Error ind ; Error indr ; Error ini ; Error inir ; Error ipset -1 ; Error ipset 4 ; Error ld a,i ; Error ld a,ixh ; Error ld a,ixl ; Error ld a,iyh ; Error ld a,iyl ; Error ld a,r ; Error ld b,ixh ; Error ld b,ixl ; Error ld b,iyh ; Error ld b,iyl ; Error ld c,ixh ; Error ld c,ixl ; Error ld c,iyh ; Error ld c,iyl ; Error ld d,ixh ; Error ld d,ixl ; Error ld d,iyh ; Error ld d,iyl ; Error ld e,ixh ; Error ld e,ixl ; Error ld e,iyh ; Error ld e,iyl ; Error ld i,a ; Error ld ixh,N ; Error ld ixh,a ; Error ld ixh,b ; Error ld ixh,c ; Error ld ixh,d ; Error ld ixh,e ; Error ld ixh,ixh ; Error ld ixh,ixl ; Error ld ixl,N ; Error ld ixl,a ; Error ld ixl,b ; Error ld ixl,c ; Error ld ixl,d ; Error ld ixl,e ; Error ld ixl,ixh ; Error ld ixl,ixl ; Error ld iyh,N ; Error ld iyh,a ; Error ld iyh,b ; Error ld iyh,c ; Error ld iyh,d ; Error ld iyh,e ; Error ld iyh,iyh ; Error ld iyh,iyl ; Error ld iyl,N ; Error ld iyl,a ; Error ld iyl,b ; Error ld iyl,c ; Error ld iyl,d ; Error ld iyl,e ; Error ld iyl,iyh ; Error ld iyl,iyl ; Error ld r,a ; Error mlt sp ; Error or a,ixh ; Error or a,ixl ; Error or a,iyh ; Error or a,iyl ; Error or ixh ; Error or ixl ; Error or iyh ; Error or iyl ; Error otdm ; Error otdmr ; Error otdr ; Error otim ; Error otimr ; Error otir ; Error out (N),a ; Error out (c),-1 ; Error out (c),0 ; Error out (c),1 ; Error out (c),a ; Error out (c),b ; Error out (c),c ; Error out (c),d ; Error out (c),e ; Error out (c),h ; Error out (c),l ; Error out0 (N),a ; Error out0 (N),b ; Error out0 (N),c ; Error out0 (N),d ; Error out0 (N),e ; Error out0 (N),h ; Error out0 (N),l ; Error outd ; Error outi ; Error res -1,(hl) ; Error res -1,(ix) ; Error res -1,(ix+DIS) ; Error res -1,(iy) ; Error res -1,(iy+DIS) ; Error res -1,a ; Error res -1,a' ; Error res -1,b ; Error res -1,b' ; Error res -1,c ; Error res -1,c' ; Error res -1,d ; Error res -1,d' ; Error res -1,e ; Error res -1,e' ; Error res -1,h ; Error res -1,h' ; Error res -1,l ; Error res -1,l' ; Error res 8,(hl) ; Error res 8,(ix) ; Error res 8,(ix+DIS) ; Error res 8,(iy) ; Error res 8,(iy+DIS) ; Error res 8,a ; Error res 8,a' ; Error res 8,b ; Error res 8,b' ; Error res 8,c ; Error res 8,c' ; Error res 8,d ; Error res 8,d' ; Error res 8,e ; Error res 8,e' ; Error res 8,h ; Error res 8,h' ; Error res 8,l ; Error res 8,l' ; Error retn ; Error rl (ix),a ; Error rl (ix),b ; Error rl (ix),c ; Error rl (ix),d ; Error rl (ix),e ; Error rl (ix),h ; Error rl (ix),l ; Error rl (ix+DIS),a ; Error rl (ix+DIS),b ; Error rl (ix+DIS),c ; Error rl (ix+DIS),d ; Error rl (ix+DIS),e ; Error rl (ix+DIS),h ; Error rl (ix+DIS),l ; Error rl (iy),a ; Error rl (iy),b ; Error rl (iy),c ; Error rl (iy),d ; Error rl (iy),e ; Error rl (iy),h ; Error rl (iy),l ; Error rl (iy+DIS),a ; Error rl (iy+DIS),b ; Error rl (iy+DIS),c ; Error rl (iy+DIS),d ; Error rl (iy+DIS),e ; Error rl (iy+DIS),h ; Error rl (iy+DIS),l ; Error rlc (ix),a ; Error rlc (ix),b ; Error rlc (ix),c ; Error rlc (ix),d ; Error rlc (ix),e ; Error rlc (ix),h ; Error rlc (ix),l ; Error rlc (ix+DIS),a ; Error rlc (ix+DIS),b ; Error rlc (ix+DIS),c ; Error rlc (ix+DIS),d ; Error rlc (ix+DIS),e ; Error rlc (ix+DIS),h ; Error rlc (ix+DIS),l ; Error rlc (iy),a ; Error rlc (iy),b ; Error rlc (iy),c ; Error rlc (iy),d ; Error rlc (iy),e ; Error rlc (iy),h ; Error rlc (iy),l ; Error rlc (iy+DIS),a ; Error rlc (iy+DIS),b ; Error rlc (iy+DIS),c ; Error rlc (iy+DIS),d ; Error rlc (iy+DIS),e ; Error rlc (iy+DIS),h ; Error rlc (iy+DIS),l ; Error rr (ix),a ; Error rr (ix),b ; Error rr (ix),c ; Error rr (ix),d ; Error rr (ix),e ; Error rr (ix),h ; Error rr (ix),l ; Error rr (ix+DIS),a ; Error rr (ix+DIS),b ; Error rr (ix+DIS),c ; Error rr (ix+DIS),d ; Error rr (ix+DIS),e ; Error rr (ix+DIS),h ; Error rr (ix+DIS),l ; Error rr (iy),a ; Error rr (iy),b ; Error rr (iy),c ; Error rr (iy),d ; Error rr (iy),e ; Error rr (iy),h ; Error rr (iy),l ; Error rr (iy+DIS),a ; Error rr (iy+DIS),b ; Error rr (iy+DIS),c ; Error rr (iy+DIS),d ; Error rr (iy+DIS),e ; Error rr (iy+DIS),h ; Error rr (iy+DIS),l ; Error rrc (ix),a ; Error rrc (ix),b ; Error rrc (ix),c ; Error rrc (ix),d ; Error rrc (ix),e ; Error rrc (ix),h ; Error rrc (ix),l ; Error rrc (ix+DIS),a ; Error rrc (ix+DIS),b ; Error rrc (ix+DIS),c ; Error rrc (ix+DIS),d ; Error rrc (ix+DIS),e ; Error rrc (ix+DIS),h ; Error rrc (ix+DIS),l ; Error rrc (iy),a ; Error rrc (iy),b ; Error rrc (iy),c ; Error rrc (iy),d ; Error rrc (iy),e ; Error rrc (iy),h ; Error rrc (iy),l ; Error rrc (iy+DIS),a ; Error rrc (iy+DIS),b ; Error rrc (iy+DIS),c ; Error rrc (iy+DIS),d ; Error rrc (iy+DIS),e ; Error rrc (iy+DIS),h ; Error rrc (iy+DIS),l ; Error rst -1 ; Error rst 49 ; Error rst 57 ; Error sbc a,ixh ; Error sbc a,ixl ; Error sbc a,iyh ; Error sbc a,iyl ; Error sbc ixh ; Error sbc ixl ; Error sbc iyh ; Error sbc iyl ; Error set -1,(hl) ; Error set -1,(ix) ; Error set -1,(ix+DIS) ; Error set -1,(iy) ; Error set -1,(iy+DIS) ; Error set -1,a ; Error set -1,a' ; Error set -1,b ; Error set -1,b' ; Error set -1,c ; Error set -1,c' ; Error set -1,d ; Error set -1,d' ; Error set -1,e ; Error set -1,e' ; Error set -1,h ; Error set -1,h' ; Error set -1,l ; Error set -1,l' ; Error set 8,(hl) ; Error set 8,(ix) ; Error set 8,(ix+DIS) ; Error set 8,(iy) ; Error set 8,(iy+DIS) ; Error set 8,a ; Error set 8,a' ; Error set 8,b ; Error set 8,b' ; Error set 8,c ; Error set 8,c' ; Error set 8,d ; Error set 8,d' ; Error set 8,e ; Error set 8,e' ; Error set 8,h ; Error set 8,h' ; Error set 8,l ; Error set 8,l' ; Error sla (ix),a ; Error sla (ix),b ; Error sla (ix),c ; Error sla (ix),d ; Error sla (ix),e ; Error sla (ix),h ; Error sla (ix),l ; Error sla (ix+DIS),a ; Error sla (ix+DIS),b ; Error sla (ix+DIS),c ; Error sla (ix+DIS),d ; Error sla (ix+DIS),e ; Error sla (ix+DIS),h ; Error sla (ix+DIS),l ; Error sla (iy),a ; Error sla (iy),b ; Error sla (iy),c ; Error sla (iy),d ; Error sla (iy),e ; Error sla (iy),h ; Error sla (iy),l ; Error sla (iy+DIS),a ; Error sla (iy+DIS),b ; Error sla (iy+DIS),c ; Error sla (iy+DIS),d ; Error sla (iy+DIS),e ; Error sla (iy+DIS),h ; Error sla (iy+DIS),l ; Error sli (hl) ; Error sli (ix) ; Error sli (ix),a ; Error sli (ix),b ; Error sli (ix),c ; Error sli (ix),d ; Error sli (ix),e ; Error sli (ix),h ; Error sli (ix),l ; Error sli (ix+DIS) ; Error sli (ix+DIS),a ; Error sli (ix+DIS),b ; Error sli (ix+DIS),c ; Error sli (ix+DIS),d ; Error sli (ix+DIS),e ; Error sli (ix+DIS),h ; Error sli (ix+DIS),l ; Error sli (iy) ; Error sli (iy),a ; Error sli (iy),b ; Error sli (iy),c ; Error sli (iy),d ; Error sli (iy),e ; Error sli (iy),h ; Error sli (iy),l ; Error sli (iy+DIS) ; Error sli (iy+DIS),a ; Error sli (iy+DIS),b ; Error sli (iy+DIS),c ; Error sli (iy+DIS),d ; Error sli (iy+DIS),e ; Error sli (iy+DIS),h ; Error sli (iy+DIS),l ; Error sli a ; Error sli b ; Error sli c ; Error sli d ; Error sli e ; Error sli h ; Error sli l ; Error sll (hl) ; Error sll (ix) ; Error sll (ix),a ; Error sll (ix),b ; Error sll (ix),c ; Error sll (ix),d ; Error sll (ix),e ; Error sll (ix),h ; Error sll (ix),l ; Error sll (ix+DIS) ; Error sll (ix+DIS),a ; Error sll (ix+DIS),b ; Error sll (ix+DIS),c ; Error sll (ix+DIS),d ; Error sll (ix+DIS),e ; Error sll (ix+DIS),h ; Error sll (ix+DIS),l ; Error sll (iy) ; Error sll (iy),a ; Error sll (iy),b ; Error sll (iy),c ; Error sll (iy),d ; Error sll (iy),e ; Error sll (iy),h ; Error sll (iy),l ; Error sll (iy+DIS) ; Error sll (iy+DIS),a ; Error sll (iy+DIS),b ; Error sll (iy+DIS),c ; Error sll (iy+DIS),d ; Error sll (iy+DIS),e ; Error sll (iy+DIS),h ; Error sll (iy+DIS),l ; Error sll a ; Error sll b ; Error sll c ; Error sll d ; Error sll e ; Error sll h ; Error sll l ; Error slp ; Error sra (ix),a ; Error sra (ix),b ; Error sra (ix),c ; Error sra (ix),d ; Error sra (ix),e ; Error sra (ix),h ; Error sra (ix),l ; Error sra (ix+DIS),a ; Error sra (ix+DIS),b ; Error sra (ix+DIS),c ; Error sra (ix+DIS),d ; Error sra (ix+DIS),e ; Error sra (ix+DIS),h ; Error sra (ix+DIS),l ; Error sra (iy),a ; Error sra (iy),b ; Error sra (iy),c ; Error sra (iy),d ; Error sra (iy),e ; Error sra (iy),h ; Error sra (iy),l ; Error sra (iy+DIS),a ; Error sra (iy+DIS),b ; Error sra (iy+DIS),c ; Error sra (iy+DIS),d ; Error sra (iy+DIS),e ; Error sra (iy+DIS),h ; Error sra (iy+DIS),l ; Error srl (ix),a ; Error srl (ix),b ; Error srl (ix),c ; Error srl (ix),d ; Error srl (ix),e ; Error srl (ix),h ; Error srl (ix),l ; Error srl (ix+DIS),a ; Error srl (ix+DIS),b ; Error srl (ix+DIS),c ; Error srl (ix+DIS),d ; Error srl (ix+DIS),e ; Error srl (ix+DIS),h ; Error srl (ix+DIS),l ; Error srl (iy),a ; Error srl (iy),b ; Error srl (iy),c ; Error srl (iy),d ; Error srl (iy),e ; Error srl (iy),h ; Error srl (iy),l ; Error srl (iy+DIS),a ; Error srl (iy+DIS),b ; Error srl (iy+DIS),c ; Error srl (iy+DIS),d ; Error srl (iy+DIS),e ; Error srl (iy+DIS),h ; Error srl (iy+DIS),l ; Error sub a,ixh ; Error sub a,ixl ; Error sub a,iyh ; Error sub a,iyl ; Error sub ixh ; Error sub ixl ; Error sub iyh ; Error sub iyl ; Error tst (hl) ; Error tst N ; Error tst a ; Error tst a,(hl) ; Error tst a,N ; Error tst a,a ; Error tst a,b ; Error tst a,c ; Error tst a,d ; Error tst a,e ; Error tst a,h ; Error tst a,l ; Error tst b ; Error tst c ; Error tst d ; Error tst e ; Error tst h ; Error tst l ; Error tstio N ; Error xor a,ixh ; Error xor a,ixl ; Error xor a,iyh ; Error xor a,iyl ; Error xor ixh ; Error xor ixl ; Error xor iyh ; Error xor iyl ; Error
// Copyright 2017 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 "components/sync/model/model_error.h" #include "components/sync/model/sync_error.h" namespace syncer { ModelError::ModelError(const base::Location& location, const std::string& message) : location_(location), message_(message) {} ModelError::~ModelError() = default; const base::Location& ModelError::location() const { return location_; } const std::string& ModelError::message() const { return message_; } std::string ModelError::ToString() const { return location_.ToString() + std::string(": ") + message_; } // TODO(https://crbug.com/1057577): Remove this once ProcessSyncChanges in // SyncableService has been refactored. base::Optional<ModelError> ConvertToModelError(const SyncError& sync_error) { if (sync_error.IsSet()) { return ModelError(sync_error.location(), sync_error.message()); } return base::nullopt; } } // namespace syncer
; =============================================================== ; Stefano Bodrato ; =============================================================== ; ; void asm_pop_ei(void) ; ; Pop the ei_di_status from the stack and restore the di/ei ; state to what it was previously when a push was called. ; ; The "ei" in the function name has no bearing on what the ; function does; the name is meant to balance "z80_push_di". ; ; =============================================================== INCLUDE "config_private.inc" SECTION smc_clib PUBLIC asm_pop_ei_jp .asm_pop_ei_jp ; enter : stack = ret, ei_di_status ; ; uses : af pop af ; af = ei_di_status jp po, di_state .ei_state ei ret .di_state di ret
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 <map> #include <string> #include <geode/Cache.hpp> #include <geode/CacheFactory.hpp> #include <geode/PoolManager.hpp> #include <geode/RegionFactory.hpp> #include <geode/RegionShortcut.hpp> #include <geode/SystemProperties.hpp> #include "CacheImpl.hpp" #include "CacheRegionHelper.hpp" #include "CppCacheLibrary.hpp" namespace apache { namespace geode { namespace client { RegionFactory::RegionFactory(RegionShortcut preDefinedRegion, CacheImpl* cacheImpl) : m_preDefinedRegion(preDefinedRegion), m_regionAttributesFactory(std::make_shared<RegionAttributesFactory>()), m_cacheImpl(cacheImpl) { setRegionShortcut(); } std::shared_ptr<Region> RegionFactory::create(std::string name) { std::shared_ptr<Region> retRegionPtr = nullptr; auto regionAttributes = m_regionAttributesFactory->create(); if (m_preDefinedRegion != RegionShortcut::LOCAL && regionAttributes.getPoolName().empty()) { auto pool = m_cacheImpl->getPoolManager().getDefaultPool(); if (!pool) { throw IllegalStateException("No pool for non-local region."); } m_regionAttributesFactory->setPoolName(pool->getName()); regionAttributes = m_regionAttributesFactory->create(); } m_cacheImpl->createRegion(name, regionAttributes, retRegionPtr); return retRegionPtr; } void RegionFactory::setRegionShortcut() { switch (m_preDefinedRegion) { case RegionShortcut::PROXY: { m_regionAttributesFactory->setCachingEnabled(false); } break; case RegionShortcut::CACHING_PROXY: { m_regionAttributesFactory->setCachingEnabled(true); } break; case RegionShortcut::CACHING_PROXY_ENTRY_LRU: { m_regionAttributesFactory->setCachingEnabled(true); m_regionAttributesFactory->setLruEntriesLimit( DEFAULT_LRU_MAXIMUM_ENTRIES); } break; case RegionShortcut::LOCAL: { } break; case RegionShortcut::LOCAL_ENTRY_LRU: { m_regionAttributesFactory->setLruEntriesLimit( DEFAULT_LRU_MAXIMUM_ENTRIES); } break; } } RegionFactory& RegionFactory::setCacheLoader( const std::shared_ptr<CacheLoader>& cacheLoader) { m_regionAttributesFactory->setCacheLoader(cacheLoader); return *this; } RegionFactory& RegionFactory::setCacheWriter( const std::shared_ptr<CacheWriter>& cacheWriter) { m_regionAttributesFactory->setCacheWriter(cacheWriter); return *this; } RegionFactory& RegionFactory::setCacheListener( const std::shared_ptr<CacheListener>& aListener) { m_regionAttributesFactory->setCacheListener(aListener); return *this; } RegionFactory& RegionFactory::setPartitionResolver( const std::shared_ptr<PartitionResolver>& aResolver) { m_regionAttributesFactory->setPartitionResolver(aResolver); return *this; } RegionFactory& RegionFactory::setCacheLoader(const std::string& lib, const std::string& func) { m_regionAttributesFactory->setCacheLoader(lib, func); return *this; } RegionFactory& RegionFactory::setCacheWriter(const std::string& lib, const std::string& func) { m_regionAttributesFactory->setCacheWriter(lib, func); return *this; } RegionFactory& RegionFactory::setCacheListener(const std::string& lib, const std::string& func) { m_regionAttributesFactory->setCacheListener(lib, func); return *this; } RegionFactory& RegionFactory::setPartitionResolver(const std::string& lib, const std::string& func) { m_regionAttributesFactory->setPartitionResolver(lib, func); return *this; } RegionFactory& RegionFactory::setEntryIdleTimeout( ExpirationAction action, std::chrono::seconds idleTimeout) { m_regionAttributesFactory->setEntryIdleTimeout(action, idleTimeout); return *this; } RegionFactory& RegionFactory::setEntryTimeToLive( ExpirationAction action, std::chrono::seconds timeToLive) { m_regionAttributesFactory->setEntryTimeToLive(action, timeToLive); return *this; } RegionFactory& RegionFactory::setRegionIdleTimeout( ExpirationAction action, std::chrono::seconds idleTimeout) { m_regionAttributesFactory->setRegionIdleTimeout(action, idleTimeout); return *this; } RegionFactory& RegionFactory::setRegionTimeToLive( ExpirationAction action, std::chrono::seconds timeToLive) { m_regionAttributesFactory->setRegionTimeToLive(action, timeToLive); return *this; } RegionFactory& RegionFactory::setInitialCapacity(int initialCapacity) { char excpStr[256] = {0}; if (initialCapacity < 0) { std::snprintf(excpStr, 256, "initialCapacity must be >= 0 "); throw IllegalArgumentException(excpStr); } m_regionAttributesFactory->setInitialCapacity(initialCapacity); return *this; } RegionFactory& RegionFactory::setLoadFactor(float loadFactor) { m_regionAttributesFactory->setLoadFactor(loadFactor); return *this; } RegionFactory& RegionFactory::setConcurrencyLevel(uint8_t concurrencyLevel) { m_regionAttributesFactory->setConcurrencyLevel(concurrencyLevel); return *this; } RegionFactory& RegionFactory::setConcurrencyChecksEnabled(bool enable) { m_regionAttributesFactory->setConcurrencyChecksEnabled(enable); return *this; } RegionFactory& RegionFactory::setLruEntriesLimit(const uint32_t entriesLimit) { m_regionAttributesFactory->setLruEntriesLimit(entriesLimit); return *this; } RegionFactory& RegionFactory::setDiskPolicy(const DiskPolicyType diskPolicy) { m_regionAttributesFactory->setDiskPolicy(diskPolicy); return *this; } RegionFactory& RegionFactory::setCachingEnabled(bool cachingEnabled) { m_regionAttributesFactory->setCachingEnabled(cachingEnabled); return *this; } RegionFactory& RegionFactory::setPersistenceManager( const std::shared_ptr<PersistenceManager>& persistenceManager, const std::shared_ptr<Properties>& config) { m_regionAttributesFactory->setPersistenceManager(persistenceManager, config); return *this; } RegionFactory& RegionFactory::setPersistenceManager( const std::string& lib, const std::string& func, const std::shared_ptr<Properties>& config) { m_regionAttributesFactory->setPersistenceManager(lib, func, config); return *this; } RegionFactory& RegionFactory::setPoolName(const std::string& name) { m_regionAttributesFactory->setPoolName(name); return *this; } RegionFactory& RegionFactory::setCloningEnabled(bool isClonable) { m_regionAttributesFactory->setCloningEnabled(isClonable); return *this; } } // namespace client } // namespace geode } // namespace apache
#include <qt/test/wallettests.h> #include <qt/test/util.h> #include <interfaces/node.h> #include <qt/bitcoinamountfield.h> #include <qt/callback.h> #include <qt/optionsmodel.h> #include <qt/platformstyle.h> #include <qt/qvalidatedlineedit.h> #include <qt/sendcoinsdialog.h> #include <qt/sendcoinsentry.h> #include <qt/transactiontablemodel.h> #include <qt/transactionview.h> #include <qt/walletmodel.h> #include <key_io.h> #include <test/test_bitcoin.h> #include <validation.h> #include <wallet/wallet.h> #include <qt/overviewpage.h> #include <qt/receivecoinsdialog.h> #include <qt/recentrequeststablemodel.h> #include <qt/receiverequestdialog.h> #include <memory> #include <QAbstractButton> #include <QAction> #include <QApplication> #include <QCheckBox> #include <QPushButton> #include <QTimer> #include <QVBoxLayout> #include <QTextEdit> #include <QListView> #include <QDialogButtonBox> namespace { //! Press "Yes" or "Cancel" buttons in modal send confirmation dialog. void ConfirmSend(QString* text = nullptr, bool cancel = false) { QTimer::singleShot(0, makeCallback([text, cancel](Callback* callback) { for (QWidget* widget : QApplication::topLevelWidgets()) { if (widget->inherits("SendConfirmationDialog")) { SendConfirmationDialog* dialog = qobject_cast<SendConfirmationDialog*>(widget); if (text) *text = dialog->text(); QAbstractButton* button = dialog->button(cancel ? QMessageBox::Cancel : QMessageBox::Yes); button->setEnabled(true); button->click(); } } delete callback; }), SLOT(call())); } //! Send coins to address and return txid. uint256 SendCoins(CWallet& wallet, SendCoinsDialog& sendCoinsDialog, const CTxDestination& address, CAmount amount, bool rbf) { QVBoxLayout* entries = sendCoinsDialog.findChild<QVBoxLayout*>("entries"); SendCoinsEntry* entry = qobject_cast<SendCoinsEntry*>(entries->itemAt(0)->widget()); entry->findChild<QValidatedLineEdit*>("payTo")->setText(QString::fromStdString(EncodeDestination(address))); entry->findChild<BitcoinAmountField*>("payAmount")->setValue(amount); /* Litecon: Disabled RBF UI sendCoinsDialog.findChild<QFrame*>("frameFee") ->findChild<QFrame*>("frameFeeSelection") ->findChild<QCheckBox*>("optInRBF") ->setCheckState(rbf ? Qt::Checked : Qt::Unchecked); */ uint256 txid; boost::signals2::scoped_connection c(wallet.NotifyTransactionChanged.connect([&txid](CWallet*, const uint256& hash, ChangeType status) { if (status == CT_NEW) txid = hash; })); ConfirmSend(); QMetaObject::invokeMethod(&sendCoinsDialog, "on_sendButton_clicked"); return txid; } //! Find index of txid in transaction list. QModelIndex FindTx(const QAbstractItemModel& model, const uint256& txid) { QString hash = QString::fromStdString(txid.ToString()); int rows = model.rowCount({}); for (int row = 0; row < rows; ++row) { QModelIndex index = model.index(row, 0, {}); if (model.data(index, TransactionTableModel::TxHashRole) == hash) { return index; } } return {}; } //! Invoke bumpfee on txid and check results. /* Hardcoin: Disable RBF void BumpFee(TransactionView& view, const uint256& txid, bool expectDisabled, std::string expectError, bool cancel) { QTableView* table = view.findChild<QTableView*>("transactionView"); QModelIndex index = FindTx(*table->selectionModel()->model(), txid); QVERIFY2(index.isValid(), "Could not find BumpFee txid"); // Select row in table, invoke context menu, and make sure bumpfee action is // enabled or disabled as expected. QAction* action = view.findChild<QAction*>("bumpFeeAction"); table->selectionModel()->select(index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); action->setEnabled(expectDisabled); table->customContextMenuRequested({}); QCOMPARE(action->isEnabled(), !expectDisabled); action->setEnabled(true); QString text; if (expectError.empty()) { ConfirmSend(&text, cancel); } else { ConfirmMessage(&text); } action->trigger(); QVERIFY(text.indexOf(QString::fromStdString(expectError)) != -1); } */ //! Simple qt wallet tests. // // Test widgets can be debugged interactively calling show() on them and // manually running the event loop, e.g.: // // sendCoinsDialog.show(); // QEventLoop().exec(); // // This also requires overriding the default minimal Qt platform: // // src/qt/test/test_bitcoin-qt -platform xcb # Linux // src/qt/test/test_bitcoin-qt -platform windows # Windows // src/qt/test/test_bitcoin-qt -platform cocoa # macOS void TestGUI() { // Set up wallet and chain with 105 blocks (5 mature blocks for spending). TestChain100Setup test; for (int i = 0; i < 5; ++i) { test.CreateAndProcessBlock({}, GetScriptForRawPubKey(test.coinbaseKey.GetPubKey())); } std::shared_ptr<CWallet> wallet = std::make_shared<CWallet>("mock", WalletDatabase::CreateMock()); bool firstRun; wallet->LoadWallet(firstRun); { LOCK(wallet->cs_wallet); wallet->SetAddressBook(GetDestinationForKey(test.coinbaseKey.GetPubKey(), wallet->m_default_address_type), "", "receive"); wallet->AddKeyPubKey(test.coinbaseKey, test.coinbaseKey.GetPubKey()); } { LOCK(cs_main); WalletRescanReserver reserver(wallet.get()); reserver.reserve(); wallet->ScanForWalletTransactions(chainActive.Genesis(), nullptr, reserver, true); } wallet->SetBroadcastTransactions(true); // Create widgets for sending coins and listing transactions. std::unique_ptr<const PlatformStyle> platformStyle(PlatformStyle::instantiate("other")); SendCoinsDialog sendCoinsDialog(platformStyle.get()); TransactionView transactionView(platformStyle.get()); auto node = interfaces::MakeNode(); OptionsModel optionsModel(*node); AddWallet(wallet); WalletModel walletModel(std::move(node->getWallets().back()), *node, platformStyle.get(), &optionsModel); RemoveWallet(wallet); sendCoinsDialog.setModel(&walletModel); transactionView.setModel(&walletModel); // Send two transactions, and verify they are added to transaction list. TransactionTableModel* transactionTableModel = walletModel.getTransactionTableModel(); QCOMPARE(transactionTableModel->rowCount({}), 105); uint256 txid1 = SendCoins(*wallet.get(), sendCoinsDialog, CKeyID(), 5 * COIN, false /* rbf */); uint256 txid2 = SendCoins(*wallet.get(), sendCoinsDialog, CKeyID(), 10 * COIN, true /* rbf */); QCOMPARE(transactionTableModel->rowCount({}), 107); QVERIFY(FindTx(*transactionTableModel, txid1).isValid()); QVERIFY(FindTx(*transactionTableModel, txid2).isValid()); // Call bumpfee. Test disabled, canceled, enabled, then failing cases. // Hardcoin: Disable BumpFee tests // BumpFee(transactionView, txid1, true /* expect disabled */, "not BIP 125 replaceable" /* expected error */, false /* cancel */); // BumpFee(transactionView, txid2, false /* expect disabled */, {} /* expected error */, true /* cancel */); // BumpFee(transactionView, txid2, false /* expect disabled */, {} /* expected error */, false /* cancel */); // BumpFee(transactionView, txid2, true /* expect disabled */, "already bumped" /* expected error */, false /* cancel */); // Check current balance on OverviewPage OverviewPage overviewPage(platformStyle.get()); overviewPage.setWalletModel(&walletModel); QLabel* balanceLabel = overviewPage.findChild<QLabel*>("labelBalance"); QString balanceText = balanceLabel->text(); int unit = walletModel.getOptionsModel()->getDisplayUnit(); CAmount balance = walletModel.wallet().getBalance(); QString balanceComparison = BitcoinUnits::formatWithUnit(unit, balance, false, BitcoinUnits::separatorAlways); QCOMPARE(balanceText, balanceComparison); // Check Request Payment button ReceiveCoinsDialog receiveCoinsDialog(platformStyle.get()); receiveCoinsDialog.setModel(&walletModel); RecentRequestsTableModel* requestTableModel = walletModel.getRecentRequestsTableModel(); // Label input QLineEdit* labelInput = receiveCoinsDialog.findChild<QLineEdit*>("reqLabel"); labelInput->setText("TEST_LABEL_1"); // Amount input BitcoinAmountField* amountInput = receiveCoinsDialog.findChild<BitcoinAmountField*>("reqAmount"); amountInput->setValue(1); // Message input QLineEdit* messageInput = receiveCoinsDialog.findChild<QLineEdit*>("reqMessage"); messageInput->setText("TEST_MESSAGE_1"); int initialRowCount = requestTableModel->rowCount({}); QPushButton* requestPaymentButton = receiveCoinsDialog.findChild<QPushButton*>("receiveButton"); requestPaymentButton->click(); for (QWidget* widget : QApplication::topLevelWidgets()) { if (widget->inherits("ReceiveRequestDialog")) { ReceiveRequestDialog* receiveRequestDialog = qobject_cast<ReceiveRequestDialog*>(widget); QTextEdit* rlist = receiveRequestDialog->QObject::findChild<QTextEdit*>("outUri"); QString paymentText = rlist->toPlainText(); QStringList paymentTextList = paymentText.split('\n'); QCOMPARE(paymentTextList.at(0), QString("Payment information")); QVERIFY(paymentTextList.at(1).indexOf(QString("URI: hardcoin:")) != -1); QVERIFY(paymentTextList.at(2).indexOf(QString("Address:")) != -1); QCOMPARE(paymentTextList.at(3), QString("Amount: 0.00000001 ") + QString::fromStdString(CURRENCY_UNIT)); QCOMPARE(paymentTextList.at(4), QString("Label: TEST_LABEL_1")); QCOMPARE(paymentTextList.at(5), QString("Message: TEST_MESSAGE_1")); } } // Clear button QPushButton* clearButton = receiveCoinsDialog.findChild<QPushButton*>("clearButton"); clearButton->click(); QCOMPARE(labelInput->text(), QString("")); QCOMPARE(amountInput->value(), CAmount(0)); QCOMPARE(messageInput->text(), QString("")); // Check addition to history int currentRowCount = requestTableModel->rowCount({}); QCOMPARE(currentRowCount, initialRowCount+1); // Check Remove button QTableView* table = receiveCoinsDialog.findChild<QTableView*>("recentRequestsView"); table->selectRow(currentRowCount-1); QPushButton* removeRequestButton = receiveCoinsDialog.findChild<QPushButton*>("removeRequestButton"); removeRequestButton->click(); QCOMPARE(requestTableModel->rowCount({}), currentRowCount-1); } } // namespace void WalletTests::walletTests() { #ifdef Q_OS_MAC if (QApplication::platformName() == "minimal") { // Disable for mac on "minimal" platform to avoid crashes inside the Qt // framework when it tries to look up unimplemented cocoa functions, // and fails to handle returned nulls // (https://bugreports.qt.io/browse/QTBUG-49686). QWARN("Skipping WalletTests on mac build with 'minimal' platform set due to Qt bugs. To run AppTests, invoke " "with 'test_bitcoin-qt -platform cocoa' on mac, or else use a linux or windows build."); return; } #endif TestGUI(); }
; A025840: Expansion of 1/((1-x^3)*(1-x^5)*(1-x^12)). ; 1,0,0,1,0,1,1,0,1,1,1,1,2,1,1,3,1,2,3,1,3,3,2,3,4,3,3,5,3,4,6,3,5,6,4,6,7,5,6,8,6,7,9,6,8,10,7,9,11,8,10,12,9,11,13,10,12,14,11,13,16,12,14,17,13,16,18,14,17,19,16,18,21,17,19,23,18,21,24,19,23,25,21,24,27,23,25,29,24,27,31,25,29,32,27,31,34,29,32,36 mov $3,2 mov $5,$0 lpb $3 sub $3,1 add $0,$3 sub $0,1 mov $2,$3 mov $4,$0 max $4,0 seq $4,29044 ; Expansion of 1/((1-x)(1-x^3)(1-x^5)(1-x^12)). mul $2,$4 add $1,$2 lpe min $5,1 mul $5,$4 sub $1,$5 mov $0,$1
<% from pwnlib.shellcraft.powerpc.linux import syscall %> <%page args="mqdes, msg_ptr, msg_len, msg_prio, abs_timeout"/> <%docstring> Invokes the syscall mq_timedsend. See 'man 2 mq_timedsend' for more information. Arguments: mqdes(mqd_t): mqdes msg_ptr(char): msg_ptr msg_len(size_t): msg_len msg_prio(unsigned): msg_prio abs_timeout(timespec): abs_timeout </%docstring> ${syscall('SYS_mq_timedsend', mqdes, msg_ptr, msg_len, msg_prio, abs_timeout)}
; Compilation: nasm -f elf64 quickXOR.asm -o quickxor; ld -o quickxor quickxor.o ; quickXOR(string, key, len_string, len_key) ; len_key <= 16 ; RDI = ptr(string) ; RSI = ptr(key) ; RDX = len_string ; RCX = len_key ; r8 = ptr_for_result section .text GLOBAL quickxor quickxor: ; stack frame and buffer push rbp mov rbp,rsp push r10 push r11 push r12 push r13 push r14 push r15 push rbx handle_params: mov rdi, [rdi] mov rsi, [rsi] mov r11d, edx ; ptr to len of string/file mov r10d, ecx; ptr to len of key ; ==================================================================== ; First of all, we are going to set up all the thing for the key. ; ; The key could be any length, therefore have to be careful in the way ; we read it. That's why we should perform a read byte by byte. ; ; ; Once we load the byte from memory, we should put the value in the correct ; place of the register. Therefore, we should perform shifts depending on which ; byte we are talking about. ; ; For example, if the key is: 0xABCDEF, the progression should be: ; xmm10 = [00|..|00|0xAB] ; xmm10 = [00|..|00|0xCD|0xAB] ; xmm10 = [00|..|00|0xEF|0xCD|0xAB] ; ; Then, afterwards we are going to put the key inside the a 16 byte ; register as much times as possible. As an example, if the key is 4 ; bytes length, then it will fit 4 times inside the register. If it's ; 5 bytes long, it will fit only 3 times. ; ; ==================================================================== calculate_sizes_for_key: xor edx, edx mov eax, 0x10 ; Reference for division: https://www.aldeid.com/wiki/X86-assembly/Instructions/div div r10d ; edx = 16 % len_key (amount_of_leftover_bytes_in_xmm) ; eax = 16 / len_key (times_key_fits_in_xmm) mov r12d, edx; r12 = amount_of_leftover_bytes_in_xmm mov r13d, eax; r13 = times_key_fits_in_xmm pxor xmm10,xmm10; cleaning xmm10 (this will hold always the key) pxor xmm9,xmm9; cleaning xmm9 (this will the partial bytes read) pxor xmm1, xmm1; cleaning xmm1 (this will be the acumulator, where we are going to put the key multiple times) xor rcx,rcx ; Create counter for reading bytes of key. mov r15, rsi read_key_from_mem_byte_by_byte: cmp ecx, r10d ; Counter to now when we read all the bytes of the key. je fill_xmm_with_key xor ebx, ebx; mov bl, [r15];Read byte movd xmm9, ebx ; Store byte in xmm9 mov eax, ecx; Create a new counter. This time to know how many shifts we should make for each byte do_shifts_for_key: cmp eax, 0; Compare the counter to know if we finished je write_byte_in_xmm pslldq xmm9, 1; Perform shift dec eax jmp do_shifts_for_key write_byte_in_xmm: por xmm10, xmm9 ; Once we have the byte in the correct place, we can acummulate the result inside xmm10 inc ecx inc r15 jmp read_key_from_mem_byte_by_byte fill_xmm_with_key: ;Now we already have the key stored in xmm10. We should replicate it as much as possible inside xmm10 . mov ecx, r13d; Counter for "filling key" cycle. In other words, the amount of times that the key will fill inside the xmm register. fill_xmm_with_key_cycle: cmp ecx, 1; If we have only one round left, go to the last one. je finish_filling_xmm_with_key filling_xmm_round: por xmm1, xmm10; fill xmm1 with the key. mov r14d, r10d; r14d = counter of shifts (initially, is the length of the key) shifting_xmm: ; we cannot shift based on the value of a register. So we need to do it like a cycle. cmp r14d, 0 ; compare the counter against 0 je continue_filling_xxm_round ; if it is 0, we finished, otherwwhise, we shift one byte. pslldq xmm1, 1 ; shift by 1 byte dec r14d ; decrement the counter jmp shifting_xmm ; continue cycle. continue_filling_xxm_round: ; once the register is already shifted, we can go to the next round of filling xmm with key multitple times. dec ecx jmp fill_xmm_with_key_cycle finish_filling_xmm_with_key: por xmm1, xmm10 ; last round (without shift). ; ============================================================================= ; At this point xmm1 has multiple times the key inside (as much as possible). ; To ease the languange, I'll call this xmm1, the super key. ; xmm1 = [KEY|...|KEY|LT] where LT is the leftover. len(LT) = r12d ; ============================================================================= ; ============================================================================= ; Let's continue setting up the things regarding the string ; ============================================================================= calculate_sizes_for_string: mov r14d, 0x10 ; r14d= 16 sub r14d, r12d ; r14d = amount_of_bytes_to_xor_by_round (16 - amount_of_leftover_bytes_in_xmm) xor edx, edx mov eax, r11d; eax = len_string div r14d ; eax = len_string / amount_of_bytes_to_xor_by_round (amount_of_rounds) mov r9d, edx; r9d = amount_of_bytes_to_xor_in_last_round inc eax ; amount_of_rounds + 1 (always we have at least one more unless len_string % amount_of_bytes_to_xor_by_round = 0) ; ============================================================================= ; CHECKPOINT. At this point we should remember: ; * r10d: Holds the length of the key to xor. ; * r11d: Holds the length of the string to xor. ; * r12d: Holds the amount of bytes that are not going to be able to be xored in a round (leftovers). ; * r14d: Holds the amount of bytes that are going to be xored in each round. ; * r13d: Holds the amount of times that the key fills into an xmm. ; * xmm1: Holds the super key (key repeated ${r13d} times). ; * r9d: Holds the amount of bytes to be xored in the last round. ; * eax: Holds the amount of rounds that will be needed to xor the whole string. ; ============================================================================= ; ============================================================================= ; START PERFORMING THE XOR ; ============================================================================= begin_xor: mov ecx, eax; create counter with the amount of rounds to perform mov r15, rdi; store the ptr to the string. set_the_final_cut: ; I have discovered that we when the amount of bytes that are goning to be xored en each round + the amount of bytes that are going to be xored in the last ; is less that 16, we were doing invalid reads and writes. Because in the inmedetiately before last round, we're reading the content from [r15] with an xmm, ; therefore reading 16 bytes. But, the amount of bytes that were going to be xored + bytes of the last round is less than 16, we were reading out of bounds. ; This part is to avoid doing this! If that condition is met, then, we are going to stop in the previous to the last round mov ebx, r9d ; Amount of bytes to be xored in the last round add ebx, r14d; Amount of bytes that are going to be xored in each round cmp ebx, 16 jl problematic_case nice_case: mov ebx, 1 jmp xor_round problematic_case: mov r9d, ebx; So, we have to define the new lefovers. mov ebx, 2 xor_round: cmp ecx, ebx; if only one round lefts, xor the last round. Otherwise, just perform a simple xor. je do_last_2_xor_rounds movdqu xmm2, [r15]; Get 16 bytes from the string to xor (We are going to have always 16 bytes to grab here because it is not the last round ) pxor xmm2, xmm1 ; Perform the xor between 16 bytes of the string and the super key and store the result in xmm2 movdqu [r8], xmm2; Write down the result in our return buffer. add r8, r14 ; Move the pointer to the return buffer the amount of bytes that were REALLY xored (depends on r14d) add r15, r14; Move the pointer to the string the same amount as above. dec ecx; decrease the counter of rounds. jmp xor_round ; ============================================================================= ; The last round is the interesting part as we need to be careful with ; the leftovers from the string. In the way we xored it, the way we write ; it down, etc. ; ; It's really close to what we did in the first part reading byte by byte the key. ; ; This part is a little bit tricky as we neeed to read byte by byte all the ; leftovers ones (the ones that are going to be xored in the last round). ; ; As we are going to move data from memory to the reg byte by byte, the byte will ; be placed in the least significant part of the reg. Therefore, we should afterwards ; shift the register to the left to put it in the most significant part of the reg. ; ; Finally, we should do the same thing for writing it down as we should write ; byte by byte. ; ; ============================================================================= do_last_2_xor_rounds: xor r12, r12; Will hold the last key. movq rax, xmm1; We get the first 8 bytes of the key cmp ebx, 1 je prepare_last_key do_prev_to_last_xor_round: ; I achieved the decision that if we re in this case, the number of bytes of the string that are not yet xored are at least 10. ; Therefore, we can use a R register for this part, and then continue with rest. ; The only problem is that if we use here 8 bytes of the key, then we should accomodate the offset for the key again! mov rcx, [r15]; Get 8 bytes from the file xor rcx, rax; Perform xor mov [r8], qword rcx; Write 8 bytes a add r15, 8 add r8, 8 sub r9d, 8; We have 8 less leftovers as we write 8 accomodate_key: ; Due to we have used arbitrary 8 bytes from the key, we should re think again the offset of it (just rotate it :) ) ;Also we have to update the lefovers..! ; we have the amount of lefovers in r9d psrldq xmm1, 8 ; Shift the used key! movq r12, xmm1 ; Get the 8 bytes that left from the key. (this has a combination of parts of the key, plus 0's) [kx|k(len(key-1))|0|0..] lea r13, [r14d-8] ; Get the amount of bytes that left from the xmm1 that are actual parts of the key. ; Now, we should grab the first 8 bytes from the original super key, shift it to the rigth: 8 - the amount of bytes that are actually part of the key and then or it. ; So we will have contigously something like: [kx|k(len(key-1))|k0|k1|k2..] shift_key: ; rax stills has the first 8 bytes of the key. cmp r13,0; je prepare_last_key shl rax, 8;bits! dec r13 jmp shift_key ; psrldq xmm1, 8 prepare_last_key: or r12, rax do_last_xor_round: cmp r9d, 8 jg last_round_with_xmm ;==================================================================================== ;========================= Operate last round with R ============================= ;==================================================================================== ; we need to read byte by byte in order not to perform an out of bounds read. ; we know this part is for sure less than 8 bytes! so we can use an R register. xor rcx, rcx; Counter for leftover bytes written xor rax, rax; Counter for shifts performed xor r13, r13; Auxiliary register to do shits xor rbx, rbx; Auxiliary register to get byte xor r11, r11; Acummulator ;pxor xmm9, xmm9; prepare xmm9, auxilary register ;pxor xmm10, xmm10; prepare xmm10 accumulator read_leftover_bytes_byte_by_byte: cmp ecx, r9d; Check if we already read all the leftover bytes. je do_last_xor xor ebx, ebx; Clean auxiliar register mov bl, [r15]; Read byte from string mov r13, rbx; mov eax, ecx; Creates new counter to know how many shifts should be performed for this byte. do_shift_for_lefover_byte: cmp eax, 0; Did we finish? je add_leftover_byte_to_acumulator ; pslldq xmm9, 1 ; shift once shl r13, 8; in bits dec eax; derement the counter of shifts. jmp do_shift_for_lefover_byte add_leftover_byte_to_acumulator: ;por xmm10, xmm9; Add byte to acumulator or r11, r13; Add byte to acumulator in correct position inc r15 ; increment the ptr to the string inc ecx; increment the counter of leftover read. jmp read_leftover_bytes_byte_by_byte ; ============================================================================= ; At this point we have xmm10 with the following structure ; ; xmm10 = [leftoverbytes|00|..|00] ; ; ============================================================================= do_last_xor: xor r11, r12 ; ; ============================================================================= ; Now we should do the same thing by to write down the result in memory ; ; xmm10 = [leftoverbytesXORED|00|..|00] ; ; In order to write down the result, we are going to store the qudwords inside R ; registers and then go slowly storing it in memory. ; ; Depending on the amount of leftovers, we are going to download the two qwords ; or just one. ; ; Once we have the qword inside the R register, we are going to write byte by byte. ; ; ; ============================================================================= write_last_round: ;movq rbx, xmm10; Download the first qword mov rbx, r11 xor rcx, rcx; Create counter for amount of written bytes write_leftover_bytes: cmp ecx, r9d; If we finished writing all leftovers bytes, finish. je this_is_the_end ;cmp ecx, 8 ; je download_second_qword write_one_lefotver_byte: mov [r8], bl; Write byte in result buffer shr rbx, 8 ; in bits! inc r8 ; Increment the pointer to the result buffer inc ecx; Increment the amount of leftover bytes written jmp write_leftover_bytes ;==================================================================================== ;========================= Operate last round with xmm ============================= ;==================================================================================== last_round_with_xmm: ; we need to read byte by byte in order not to perform an out of bounds read. ; TODO: This may be improved.. if the amount of bytes is 9, we may first read 8 bytes with an R memory for example. xor rcx, rcx; Counter for leftover bytes written xor rax, rax; Counter for shifts performed pxor xmm9, xmm9; prepare xmm9, auxilary register pxor xmm10, xmm10; prepare xmm10 accumulator read_leftover_bytes_byte_by_byte_xmm: cmp ecx, r9d; Check if we already read all the leftover bytes. je do_last_xor_xmm xor ebx, ebx; Clean auxiliar register mov bl, [r15]; Read byte from string movd xmm9, ebx; Read byte from string mov eax, ecx; Creates new counter to know how many shifts should be performed for this byte. do_shift_for_lefover_byte_xmm: cmp eax, 0; Did we finish? je add_leftover_byte_to_acumulator_xmm pslldq xmm9, 1 ; shift once dec eax; derement the counter of shifts. jmp do_shift_for_lefover_byte_xmm add_leftover_byte_to_acumulator_xmm: por xmm10, xmm9; Add byte to acumulator inc r15 ; increment the ptr to the string inc ecx; increment the counter of leftover read. jmp read_leftover_bytes_byte_by_byte_xmm ; ============================================================================= ; At this point we have xmm10 with the following structure ; ; xmm10 = [leftoverbytes|00|..|00] ; ; ============================================================================= do_last_xor_xmm: pxor xmm10, xmm1; perform xor ; ============================================================================= ; Now we should do the same thing by to write down the result in memory ; ; xmm10 = [leftoverbytesXORED|00|..|00] ; ; In order to write down the result, we are going to store the qudwords inside R ; registers and then go slowly storing it in memory. ; ; Depending on the amount of leftovers, we are going to download the two qwords ; or just one. ; ; Once we have the qword inside the R register, we are going to write byte by byte. ; ; ; ============================================================================= write_last_round_xmm: movq rbx, xmm10; Download the first qword xor rcx, rcx; Create counter for amount of written bytes write_leftover_bytes_xmm: cmp ecx, r9d; If we finished writing all leftovers bytes, finish. je this_is_the_end cmp ecx, 8 je download_second_qword_xmm write_one_lefotver_byte_xmm: mov [r8], bl; Write byte in result buffer shr rbx, 8 inc r8 ; Increment the pointer to the result buffer inc ecx; Increment the amount of leftover bytes written jmp write_leftover_bytes_xmm download_second_qword_xmm: psrldq xmm10, 8 movq rbx, xmm10; Download the second qword jmp write_one_lefotver_byte_xmm ; ============================================================================= ; ============================================================================= ; ============================= END ===================================== ; ============================================================================= ; ============================================================================= this_is_the_end: pop rbx pop r15 pop r14 pop r13 pop r12 pop r11 pop r10 pop rbp ret
; void waves_c ( ; unsigned char *src, ; unsigned char *dst, ; int m, ; int n, ; int row_size, ; float x_scale, ; float y_scale, ; float g_scale ; ); ; Parámetros: ; rdi = src ; rsi = dst ; rdx = m ; rcx = n ; r8 = row_size ; xmm0 = x_scale ; xmm1 = y_scale ; xmm2 = g_scale %define Tiene_Ultimo_Tramo 1 %define No_Tiene_ultimo_tramo 0 extern waves_c global waves_asm section .rodata pi: DD 3.14159265359, 3.14159265359, 3.14159265359, 3.14159265359 dos: DD 2.0, 2.0, 2.0, 2.0 jotas1: DD 0.0, 1.0, 2.0, 3.0 jotas2: DD 4.0, 5.0, 6.0, 7.0 seis: DD 6.0, 6.0, 6.0, 6.0 cientoVeinte: DD 120.0, 120.0, 120.0, 120.0 cincoMilCuarenta: DD 5040.0, 5040.0, 5040.0, 5040.0 section .text waves_asm: PUSH rbp ; Alineado MOV rbp,rsp PUSH rbx ; Desalineado PUSH r12 ; Alineado PUSH r13 ; Desalineado PUSH r14 ; Alineado PUSH r15 ; Desalineado ; //////////////////////////////////////////////////////////////////////////////// ; //////////////////////// SETEO DATOS DE USO GENERAL //////////////////////////// ; //////////////////////////////////////////////////////////////////////////////// XOR r12,r12 ; r12 <- i0 XOR r13,r13 ; r13 <- j0 MOVDQU xmm3,[pi] ; xmm0 <- pi,pi,pi,pi MOVDQU xmm4,[dos] ; xmm1 <- 2.0,2.0,2.0,2.0 MOVDQU xmm5,[jotas1] ; xmm5 <- 3,2,1,0 MOVDQU xmm6,[jotas2] ; xmm6 <- 7,6,5,4 MOVDQU xmm7,[seis] ; xmm7 <- 6.0,6.0,6.0,6.0 MOVDQU xmm8,[cientoVeinte] ; xmm8 <- 120.0,120.0,120.0,120.0 MOVDQU xmm9,[cincoMilCuarenta] ; xmm9 <- 5040.0,5040.0,5040.0,5040.0 ; ##################### REPITO LOS _SCALE EN LOSREGISTROS ###################### SHUFPS xmm0,xmm0,0 ; xmm0 <- x_scale,x_scale,x_scale,x_scale SHUFPS xmm1,xmm1,0 ; xmm1 <- y_scale,y_scale,y_scale,y_scale SHUFPS xmm2,xmm2,0 ; xmm2 <- g_scale,g_scale,g_scale,g_scale ; //////////////////// STEO LOS CONTADORES DEL LOOP ///////////////////////////// ; ############ salvo valores hasta terminar de setear los datos ################# MOV r9,rcx ; r9 <- n ; ############ seteo rcx para indicarle cuantas vueltas iterar ################## MOV rcx,rdx ; rcx <- m ; obtengo la cantidad de iteraciones de 8 byte que puedo hacer en una misma fila ; sin pasarme MOV r14,8 XOR rdx,rdx XOR rax,rax MOV rax,r9 ; rax <- n IDIV r14 ; divido n/8 MOV r14,rax ; r14 <- [n/8] MOV r10,r14 ; r10 <- [n/8], ---- en esta variable voy a ir iterando ---- ; cargo el paddin en r8 SUB r8,r9 ; r8 <- row_size - n ; me fijo si queda un tramo mas por recorrer luego de las iteraciones de 16 bytes MOV rbx,No_Tiene_ultimo_tramo MOV r15,0 ; por las dudas si no tiene ultimo tramo le pongo 0 CMP rdx,0 JE .ciclo ; ########## si no salto es porque queda un tramo aparte para recorrer ########## MOV r15,rdx ; r15d <- resto de [n/8] MOV rbx,Tiene_Ultimo_Tramo ; seteo el flag rbx indicando que hay un ultimo tramo ; ############################ EMPIEZA EL CICLO ################################# ; lo primero que miro es si hay algo que recorrer, si es la imagen vacia no tiene ; sentido recorrerla, se que si tiene una fila minimo tiene 16 bytes. ENUNCIADO TP2 CMP rcx,0 JE .fin ; ########################## ESTADO DE LOS REGISTROS ############################# ; ############# REGISTROS PARA EL LOOP ########################################### ; rcx <- m ; r10 <- [n/8] ; r14 <- [n/8] ; rbx <- queda_ultimo_tramo o no ; r15 <- resto de [n/8] ; r8 <- row_size - n ; ############ REGISTROS DE LA IMAGEN ############################################ ; rdi <- src ; rsi <- dst ; r8 <- row_size ; r12 <- i0 ; r13 <- j0 ; xmm0 <- x_scale,x_scale,x_scale,x_scale ; xmm1 <- y_scale,y_scale,y_scale,y_scale ; xmm2 <- g_scale,g_scale,g_scale,g_scale ; xmm3 <- pi,pi,pi,pi ; xmm4 <- 2.0,2.0,2.0,2.0 ; xmm5 <- 3.0,2.0,1.0,0.0 ; xmm6 <- 7.0,6.0,5.0,4.0 ; xmm7 <- 6.0,6.0,6.0,6.0 ; xmm8 <- 120.0,120.0,120.0,120.0 ; xmm9 <- 5040.0,5040.0,5040.0,5040.0 ; ############################ FIN ESTADO DE LOS REGISTROS ####################### .ciclo: ; //////////////////////////////////////////////////////////////////////////////// ; ///////////////// EMPAQUETO TODOS LOS j/80 DE CADA PIXEL /////////////////////// ; //////////////////////////////////////////////////////////////////////////////// ; obtengo los j MOVQ xmm10,r13 ; xmm10 <- basura,basura,basura,j SHUFPS xmm10,xmm10,0 ; xmm10 <- j,j,j,j CVTDQ2PS xmm10,xmm10 ; convierto los J's a punto flotante de simple presicion MOVDQU xmm11,xmm10 ; xmm11 <- j.0,j.0,j.0,j.0 ; a registros de j les sumo 0, ... ,7 ADDPS xmm10,xmm5 ; xmm10 <- (j+3).0, ... ,j.0 ADDPS xmm11,xmm6 ; xmm11 <- (j+7).0, ... ,(j+4).0 ; ######################### DIVIDO POR 2 HASTA DIVIDIR POR 8 ####################### DIVPS xmm10,xmm4 DIVPS xmm10,xmm4 DIVPS xmm10,xmm4 ; xmm10 <- (j+4).0/8.0, ... , j.0/8.0 DIVPS xmm11,xmm4 DIVPS xmm11,xmm4 DIVPS xmm11,xmm4 ; xmm1 <- (j+7).0/8.0, ... , (j+4).0/8.0 ; ########################## ESTADO DE LOS REGISTROS ############################# ; xmm10 <- ; xmm10 <- (j+4).0/8.0, ... , j.0/8.0 ; xmm11 <- ; xmm1 <- (j+7).0/8.0, ... , (j+4).0/8.0 ; ############################ FIN ESTADO DE LOS REGISTROS ####################### ; //////////////////////////////////////////////////////////////////////////////// ; ////////////////////// FUNCION DE TAYLOR PARA LOS j/80 ///////////////////////// ; //////////////////////////////////////////////////////////////////////////////// ; ############################### K = [x/(2*pi)] ################################# MOVDQU xmm12,xmm10 MOVDQU xmm13,xmm11 DIVPS xmm12,xmm4 ; xmm12 <- x.0/2.0 DIVPS xmm13,xmm4 ; xmm13 <- x.0/2.0 DIVPS xmm12,xmm3 ; xmm12 <- x.0/2.0*pi DIVPS xmm13,xmm3 ; xmm13 <- x.0/2.0*pi ; haciendolo por separado x/2*pi = (x/2)/pi no modifico las mascaras evitando ; aumentar errores en futuros pixeles ; ######################## obtengo la parte entera ############################### ; VER COMO FUNCIONA LA INSTRUCCION "ROUNDPS" CVTTPS2DQ xmm12,xmm12 CVTTPS2DQ xmm13,xmm13 CVTDQ2PS xmm12,xmm12 CVTDQ2PS xmm13,xmm13 ; ######################### R = x - K*2*pi ###################################### MULPS xmm12,xmm3 ; xmm12 <- k*pi MULPS xmm13,xmm3 ; xmm13 <- k*pi MULPS xmm12,xmm4 ; xmm12 <- k*2*pi MULPS xmm13,xmm4 ; xmm13 <- k*2*pi SUBPS xmm10,xmm12 ; xmm10 <- x - k*2*pi SUBPS xmm11,xmm13 ; xmm11 <- x - k*2*pi ; ############################### X = R - pi ################################## SUBPS xmm10,xmm3 ; x <- r - pi SUBPS xmm11,xmm3 ; x <- r - pi ; #################### Y = X - X³/6 + X⁵/120 - X⁵/5040 #################### ; ############################### Y = X ################################## MOVDQU xmm12,xmm10 MOVDQU xmm13,xmm11 ; ############################### x³/6 ##################################### MOVDQU xmm14,xmm10 MOVDQU xmm15,xmm11 ; x*x = x² MULPS xmm14,xmm10 MULPS xmm15,xmm11 ; x²*x = x³ MULPS xmm14,xmm10 MULPS xmm15,xmm11 ; x³/6 DIVPS xmm14,xmm7 DIVPS xmm15,xmm7 ; ############################ Y = x - x³/6 ################################ SUBPS xmm12,xmm14 SUBPS xmm13,xmm15 ; ############################### x⁵/120 ##################################### MOVDQU xmm14,xmm10 MOVDQU xmm15,xmm11 ; x*x = x² MULPS xmm14,xmm10 MULPS xmm15,xmm11 ; x²*x² = x^4 MULPS xmm14,xmm14 MULPS xmm15,xmm15 ; x^4*x = x⁵ MULPS xmm14,xmm10 MULPS xmm15,xmm11 ; x⁵/120 DIVPS xmm14,xmm8 DIVPS xmm15,xmm8 ; ########################## Y = x -x³/6 + x⁵/120 ############################ ADDPS xmm12,xmm14 ADDPS xmm13,xmm15 ; ############################### x⁷/5040 ##################################### MOVDQU xmm14,xmm10 MOVDQU xmm15,xmm11 ; x*x = x² MULPS xmm14,xmm10 MULPS xmm15,xmm11 ; x²*x² = x^4 MULPS xmm14,xmm14 MULPS xmm15,xmm15 ; x^4*x = x⁵ MULPS xmm14,xmm10 MULPS xmm15,xmm11 ; x^5*x = x6 MULPS xmm14,xmm10 MULPS xmm15,xmm11 ; x^6*x = x⁷ MULPS xmm14,xmm10 MULPS xmm15,xmm11 ; x⁷/5040 DIVPS xmm14,xmm9 DIVPS xmm15,xmm9 ; ########################## Y = x -x³/6 + x⁵/120 - x⁷/5040 ############################ SUBPS xmm12,xmm14 SUBPS xmm13,xmm15 ; ############################# ESTADO DE LOS REGISTROS ############################## ; xmm12 <- sin_taylor((j+3).0/8.0), sin_taylor((j+2).0/8.0), sin_taylor((j+1).0/8.0), sin_taylor((j).0/8.0), ; xmm13 <- sin_taylor((j+7).0/8.0), sin_taylor((j+6).0/8.0), sin_taylor((j+5).0/8.0), sin_taylor((j+4).0/8.0), ; //////////////////////////////////////////////////////////////////////////////// ; ////////////////////// FUNCION DE TAYLOR PARA LOS i/80 ///////////////////////// ; //////////////////////////////////////////////////////////////////////////////// MOVQ xmm10,r12 ; xmm10 <- basura,basura,basura,i SHUFPS xmm10,xmm10,0 ; xmm10 <- i,i,i,i CVTDQ2PS xmm10,xmm10 ; xmm10 <- i.0,i.0,i.0,i.0 DIVPS xmm10,xmm4 ; xmm10 <- i.0/2.0,i.0/2.0,i.0/2.0,i.0/2.0 DIVPS xmm10,xmm4 ; xmm10 <- i.0/4.0,i.0/4.0,i.0/4.0,i.0/4.0 DIVPS xmm10,xmm4 ; xmm10 <- i.0/8.0,i.0/8.0,i.0/8.0,i.0/8.0 ; ############################### K = [x/(2*pi)] ################################# MOVDQU xmm11,xmm10 DIVPS xmm11,xmm3 ; xmm11 <- x/pi DIVPS xmm11,xmm4 ; xmm11 <- x/2*pi ; ######################## obtengo la parte entera ############################### ; VER SI UTILIZO LA FUNCION ROUNDPS CVTTPS2DQ xmm11,xmm11 CVTDQ2PS xmm11,xmm11 ; ######################### R = x - K*2*pi ###################################### MULPS xmm11,xmm4 ; xmm11 <- k*2 MULPS xmm11,xmm3 ; xmm11 <- k*2*pi SUBPS xmm10,xmm11 ; xmm10 <- x - k*2*pi ; ############################### X = R - pi ################################## SUBPS xmm10,xmm3 ; x <- r - pi ; #################### Y = X - X³/6 + X⁵/120 - X⁷/5040 #################### ; ############################### Y = X ################################## MOVDQU xmm11,xmm10 ; ############################### x³/6 ##################################### MOVDQU xmm14,xmm10 MULPS xmm14,xmm10 MULPS xmm14,xmm10 DIVPS xmm14,xmm7 ; ############################ Y = x - x³/6 ################################ SUBPS xmm11,xmm14 ; ############################### x⁵/120 ##################################### MOVDQU xmm14,xmm10 MULPS xmm14,xmm10 MULPS xmm14,xmm14 MULPS xmm14,xmm10 DIVPS xmm14,xmm8 ; ############################ Y = x + x⁵/6 ################################ ADDPS xmm11,xmm14 ; ############################### x⁷/5040 ################################## MOVDQU xmm14,xmm10 MULPS xmm14,xmm10 MULPS xmm14,xmm14 MULPS xmm14,xmm10 MULPS xmm14,xmm10 MULPS xmm14,xmm10 DIVPS xmm14,xmm9 ; ############################ Y = x + x⁵/6 - x⁷/5040 ######################### SUBPS xmm11,xmm14 ; ######################## ESTADO DE LOS REGISTROS ############################# ; xmm11 <- sin_taylor(i.0/8.0), sin_taylor(i.0/8.0), sin_taylor(i.0/8.0), sin_taylor(i.0/8.0) ; xmm12 <- sin_taylor((j+3).0/8.0), sin_taylor((j+2).0/8.0), sin_taylor((j+1).0/8.0), sin_taylor((j).0/8.0) ; xmm13 <- sin_taylor((j+7).0/8.0), sin_taylor((j+6).0/8.0), sin_taylor((j+5).0/8.0), sin_taylor((j+4).0/8.0) ; //////////////////////////////////////////////////////////////////////////////// ; ////////////////////////////// PROF DE I,J ///////////////////////////////////// ; //////////////////////////////////////////////////////////////////////////////// MULPS xmm11,xmm0 ; xmm11 <- x_sacale*sin_taylor(i.0/8.0), x_sacale*sin_taylor(i.0/8.0), x_sacale*sin_taylor(i.0/8.0), x_sacale*sin_taylor(i.0/8.0) MULPS xmm12,xmm1 ; xmm12 <- y_scale*sin_taylor((j+3).0/8.0), y_scale*sin_taylor((j+2).0/8.0), y_scale*sin_taylor((j+1).0/8.0), y_scale*sin_taylor((j).0/8.0) MULPS xmm13,xmm1 ; xmm13 <- y_scale*sin_taylor((j+7).0/8.0), y_scale*sin_taylor((j+6).0/8.0), y_scale*sin_taylor((j+5).0/8.0), y_scale*sin_taylor((j+4).0/8.0) ADDPS xmm12,xmm11 ; xmm12 <- x_sacale*sin_taylor(i.0/8.0) + y_scale*sin_taylor((j+3).0/8.0), ... ,x_sacale*sin_taylor(i.0/8.0) + y_scale*sin_taylor((j).0/8.0) ADDPS xmm13,xmm11 ; xmm13 <- x_sacale*sin_taylor(i.0/8.0) + y_scale*sin_taylor((j+7).0/8.0), ... ,x_sacale*sin_taylor(i.0/8.0) + y_scale*sin_taylor((j+4).0/8.0) DIVPS xmm12,xmm4 ; xmm12 <- Prof(i,j+3), ... ,Prof(i,j) DIVPS xmm13,xmm4 ; xmm13 <- Prof(i,j+7), ... ,Prof(i,j+4) ; //////////////////////////////////////////////////////////////////////////////// ; ////////////////////////////// I_dest(i,j) ///////////////////////////////////// ; //////////////////////////////////////////////////////////////////////////////// MULPS xmm12,xmm2 ; xmm12 <- Prof(i,j+3)*g_scale, ... ,Prof(i,j)*g_scale MULPS xmm13,xmm2 ; xmm13 <- Prof(i,j+7)*g_scale, ... ,Prof(i,j+4)*g_scale ; ################## RECUPERO Y DESEMPAQUETO LOS DATOS DE LAIMAGEN ############## ; traigo los datos de la memoria MOVQ xmm14,[rdi] ; xmm10 <- [basura, ... ,basura,rdi+7, ... ,rdi+0] ; desempaqueto de Byte a Word PXOR xmm11,xmm11 ; lo seteo en 0 para utilizarlo en el desempaquetamiento PUNPCKLBW xmm14,xmm11 ; xmm14 <- [00rdi+7, ... ,00rdi] ; desempaqueto de Word a Doubleword MOVDQU xmm15,xmm14 PUNPCKLWD xmm14,xmm11 ; xmm14 <- [0000rdi+3, ... ,0000rdi] PUNPCKHWD xmm15,xmm11 ; xmm15 <- [0000rdi+7, ... ,0000rdi+4] ; convierto a punto flotantes. ; las imagenes estan en unsigned, pero como le agrego 0 tambien sirve como signed CVTDQ2PS xmm14,xmm14 ; xmm14 <- [(rdi+3).0, ... ,(rdi).0] CVTDQ2PS xmm15,xmm15 ; xmm15 <- [(rdi+7).0, ... ,(rdi+4).0] ADDPS xmm14,xmm12 ; xmm14 <- Prof(i,j+3)*g_scale + (rdi+3).0, ... ,Prof(i,j)*g_scale + (rdi).0 ADDPS xmm15,xmm13 ; xmm15 <- Prof(i,j+7)*g_scale + (rdi+7).0, ... ,Prof(i,j+4)*g_scale + (rdi+4).0 ; ########################## CONVIERTO A ENTEROS ################################## CVTTPS2DQ xmm14,xmm14 ; xmm14 <- [Prof(i,j+3)*g_scale + (rdi+3).0], ... ,[Prof(i,j)*g_scale + (rdi).0] CVTTPS2DQ xmm15,xmm15 ; xmm15 <- [Prof(i,j+7)*g_scale + (rdi+7).0], ... ,[Prof(i,j+4)*g_scale + (rdi+4).0] ; ########################## EMPAQUETO SATURANDO ################################## ; empaqueto de doubleWord a word PACKUSDW xmm14,xmm15 ; empaqueto de word a bytes PACKUSWB xmm14,xmm14 ; guardo los datos en el destino MOVQ [rsi],xmm14 .configurarIteracion: ; //////////////////////////////////////////////////////////////////////////////// ; ///////////////// configuro la iteración del ciclo ///////////////////////////// ; //////////////////////////////////////////////////////////////////////////////// ; ############# REGISTROS PARA EL LOOP ########################################### ; rcx <- m - filas iteradas ; rbx <- queda_ultimo_tramo o no ; r10 <- [n/8] - ciclos iterados ; r14 <- [n/8] ; r15 <- resto [n/8] ; r8 <- row_size - n ; ############################################################################### DEC r10 ; decremento la cantidad de iteraciones que me faltan para terminar la fila actual ; me fijo si ya llegue al final de la fila CMP r10,0 JE .termine_iteraciones ; en el caso en que halla llegado al final debo ver si tengo que ; recorrer el proximo tramito o no ; me fijo si mire el ultimo tramo CMP r10,-1 JE .saltear_proxima_linea ; si no termine las iteraciones entonces solo sumo 8 para pasar al proximo ciclo menos en la ultima vuelta donde no sumo nada .siguienteCiclo: ADD r13,8 ; r13 <- j = j+8 paso a los siguientes ADD rsi,8 ADD rdi,8 JMP .finCiclo ; si termine las iteraciones entonces me fijo si tengo que saltar directamente a la proxima fila o si queda un tramo menor a 16 por recorrer .termine_iteraciones: CMP rbx,No_Tiene_ultimo_tramo JE .saltear_proxima_linea ; si no hay ultimo tramo salto directamente a la proxima fila a procesar ; si no salto es porque hay un ultimo tramo a recorrer ADD rdi,r15 ADD rsi,r15 ADD r13,r15 JMP .finCiclo .saltear_proxima_linea: ; pongo la memoria en la primera posición de la próxima linea ADD rdi,8 ADD rsi,8 ADD rdi,r8 ; salteo el padding ADD rsi,r8 ; salteo el padding ; reseteo los datos de los contadores para una fila. MOV r10,r14 ; le vuelvo a cargar la cantidad de iteraciones a realizar en una lina MOV r13,0 ; r13 <-j = 0 ; aumento el numero de la fila donde estamos INC r12 ; r12 <- i++ ; decremento la cantidad de filas que me faltan procesar DEC rcx ; m - lineas procesadas .finCiclo: CMP rcx,0 JNE .ciclo .fin: POP r15 POP r14 POP r13 POP r12 POP rbx POP rbp RET
; --------------------------------------------------------------------------- ; Sprite mappings - doors (SBZ) ; --------------------------------------------------------------------------- dc.w byte_89FE-Map_obj2A, byte_8A09-Map_obj2A dc.w byte_8A14-Map_obj2A, byte_8A1F-Map_obj2A dc.w byte_8A2A-Map_obj2A, byte_8A35-Map_obj2A dc.w byte_8A40-Map_obj2A, byte_8A4B-Map_obj2A dc.w byte_8A56-Map_obj2A byte_89FE: dc.b 2 dc.b $E0, 7, 8, 0, $F8 ; door closed dc.b 0, 7, 8, 0, $F8 byte_8A09: dc.b 2 dc.b $DC, 7, 8, 0, $F8 dc.b 4, 7, 8, 0, $F8 byte_8A14: dc.b 2 dc.b $D8, 7, 8, 0, $F8 dc.b 8, 7, 8, 0, $F8 byte_8A1F: dc.b 2 dc.b $D4, 7, 8, 0, $F8 dc.b $C, 7, 8, 0, $F8 byte_8A2A: dc.b 2 dc.b $D0, 7, 8, 0, $F8 dc.b $10, 7, 8, 0, $F8 byte_8A35: dc.b 2 dc.b $CC, 7, 8, 0, $F8 dc.b $14, 7, 8, 0, $F8 byte_8A40: dc.b 2 dc.b $C8, 7, 8, 0, $F8 dc.b $18, 7, 8, 0, $F8 byte_8A4B: dc.b 2 dc.b $C4, 7, 8, 0, $F8 dc.b $1C, 7, 8, 0, $F8 byte_8A56: dc.b 2 dc.b $C0, 7, 8, 0, $F8 ; door fully open dc.b $20, 7, 8, 0, $F8 even
; A157474: a(n) = 16n^2 + n. ; 17,66,147,260,405,582,791,1032,1305,1610,1947,2316,2717,3150,3615,4112,4641,5202,5795,6420,7077,7766,8487,9240,10025,10842,11691,12572,13485,14430,15407,16416,17457,18530,19635,20772,21941,23142,24375,25640,26937,28266,29627,31020,32445,33902,35391,36912,38465,40050,41667,43316,44997,46710,48455,50232,52041,53882,55755,57660,59597,61566,63567,65600,67665,69762,71891,74052,76245,78470,80727,83016,85337,87690,90075,92492,94941,97422,99935,102480,105057,107666,110307,112980,115685,118422,121191,123992,126825,129690,132587,135516,138477,141470,144495,147552,150641,153762,156915,160100 mov $1,16 mul $1,$0 add $1,33 mul $1,$0 add $1,17 mov $0,$1
; ; CPC Maths Routines ; ; August 2003 **_|warp6|_** <kbaccam /at/ free.fr> ; ; $Id: float.asm,v 1.4 2016-06-22 19:50:49 dom Exp $ ; SECTION code_fp INCLUDE "target/cpc/def/cpcfp.def" INCLUDE "target/cpc/def/cpcfirm.def" PUBLIC float EXTERN int_inv_sgn PUBLIC floatc EXTERN fa .float ld a,h push af bit 7,h call nz,int_inv_sgn ; hl=-hl si nz pop af ld de,fa+1 call firmware .floatc defw CPCFP_INT_2_FLO ; (fa+1)<-hl et signe=bit 7,a ret
#include <qt/token.h> #include <qt/execrpccommand.h> #include <qt/contractutil.h> #include <validation.h> #include <util/moneystr.h> #include <key_io.h> #include <util/strencodings.h> #include <util/convert.h> #include <qt/eventlog.h> #include <libethcore/ABI.h> #include <qt/walletmodel.h> namespace Token_NS { const char *PRC_CALL = "callcontract"; const char *PRC_SENDTO = "sendtocontract"; } struct TokenData { ExecRPCCommand* call; ExecRPCCommand* send; EventLog* eventLog; WalletModel* model; QString errorMessage; TokenData(): call(0), send(0), eventLog(0), model(0) {} }; Token::Token() { d = new TokenData(); // Create new call command line interface QStringList lstMandatory; lstMandatory.append(CrowntiumToken::paramAddress()); lstMandatory.append(CrowntiumToken::paramDatahex()); QStringList lstOptional; lstOptional.append(CrowntiumToken::paramSender()); d->call = new ExecRPCCommand(Token_NS::PRC_CALL, lstMandatory, lstOptional, QMap<QString, QString>()); // Create new send command line interface lstMandatory.clear(); lstMandatory.append(CrowntiumToken::paramAddress()); lstMandatory.append(CrowntiumToken::paramDatahex()); lstOptional.clear(); lstOptional.append(CrowntiumToken::paramAmount()); lstOptional.append(CrowntiumToken::paramGasLimit()); lstOptional.append(CrowntiumToken::paramGasPrice()); lstOptional.append(CrowntiumToken::paramSender()); lstOptional.append(CrowntiumToken::paramBroadcast()); lstOptional.append(CrowntiumToken::paramChangeToSender()); lstOptional.append(CrowntiumToken::paramPsbt()); d->send = new ExecRPCCommand(Token_NS::PRC_SENDTO, lstMandatory, lstOptional, QMap<QString, QString>()); // Create new event log interface d->eventLog = new EventLog(); setCrowntiumTokenExec(this); } Token::~Token() { if(d->call) delete d->call; d->call = 0; if(d->send) delete d->send; d->send = 0; if(d->eventLog) delete d->eventLog; d->eventLog = 0; if(d) delete d; d = 0; } void Token::setModel(WalletModel *model) { d->model = model; } bool Token::execValid(const int &func, const bool &sendTo) { ExecRPCCommand* cmd = sendTo ? d->send : d->call; if(func == -1 || d->model == 0 || cmd == 0) return false; return true; } bool Token::execEventsValid(const int &func, const int64_t &fromBlock) { if(func == -1 || fromBlock < 0 || d->model == 0) return false; return true; } bool Token::exec(const bool &sendTo, const std::map<std::string, std::string> &lstParams, std::string &result, std::string &message) { ExecRPCCommand* cmd = sendTo ? d->send : d->call; QVariant resultVar; QString resultJson; QString errorMessage; if(!cmd->exec(d->model->node(), d->model, ContractUtil::fromStdMap(lstParams), resultVar, resultJson, errorMessage)) { message = errorMessage.toStdString(); return false; } if(!sendTo) { QVariantMap variantMap = resultVar.toMap(); QVariantMap executionResultMap = variantMap.value("executionResult").toMap(); result = executionResultMap.value("output").toString().toStdString(); } else { QVariantMap variantMap = resultVar.toMap(); if(d->model->wallet().privateKeysDisabled()) { result = variantMap.value("psbt").toString().toStdString(); } else { result = variantMap.value("txid").toString().toStdString(); } } return true; } bool Token::execEvents(const int64_t &fromBlock, const int64_t &toBlock, const int64_t &minconf, const std::string &eventName, const std::string &contractAddress, const std::string &senderAddress, const int &numTopics, std::vector<TokenEvent> &result) { QVariant resultVar; if(!(d->eventLog->searchTokenTx(d->model->node(), d->model, fromBlock, toBlock, minconf, eventName, contractAddress, senderAddress, numTopics, resultVar))) return false; QList<QVariant> list = resultVar.toList(); for(int i = 0; i < list.size(); i++) { // Search the log for events QVariantMap variantMap = list[i].toMap(); QList<QVariant> listLog = variantMap.value("log").toList(); for(int i = 0; i < listLog.size(); i++) { // Skip the not needed events QVariantMap variantLog = listLog[i].toMap(); QList<QVariant> topicsList = variantLog.value("topics").toList(); if(topicsList.count() < numTopics) continue; if(topicsList[0].toString().toStdString() != eventName) continue; // Create new event TokenEvent tokenEvent; tokenEvent.address = variantMap.value("contractAddress").toString().toStdString(); if(numTopics > 1) { tokenEvent.sender = topicsList[1].toString().toStdString().substr(24); Token::ToCrowntiumAddress(tokenEvent.sender, tokenEvent.sender); } if(numTopics > 2) { tokenEvent.receiver = topicsList[2].toString().toStdString().substr(24); Token::ToCrowntiumAddress(tokenEvent.receiver, tokenEvent.receiver); } tokenEvent.blockHash = uint256S(variantMap.value("blockHash").toString().toStdString()); tokenEvent.blockNumber = variantMap.value("blockNumber").toLongLong(); tokenEvent.transactionHash = uint256S(variantMap.value("transactionHash").toString().toStdString()); // Parse data std::string data = variantLog.value("data").toString().toStdString(); tokenEvent.value = Token::ToUint256(data); result.push_back(tokenEvent); } } return true; } bool Token::privateKeysDisabled() { if(!d || !d->model) return false; return d->model->wallet().privateKeysDisabled(); }
<% from pwnlib.shellcraft.mips.linux import syscall %> <%page args="fd, file, oflag, vararg"/> <%docstring> Invokes the syscall openat. See 'man 2 openat' for more information. Arguments: fd(int): fd file(char): file oflag(int): oflag vararg(int): vararg </%docstring> ${syscall('SYS_openat', fd, file, oflag, vararg)}
#include <stdio.h> main() { int a,b,c,d; printf("enter value of a&b&d"); scanf("%d%d%d",&a,&b,&d); c=a+b+d; printf("%d",c); return 0; }
; A110549: Period 8: repeat [1, 2, 4, 3, 3, 4, 2, 1]. ; Submitted by Christian Krause ; 1,2,4,3,3,4,2,1,1,2,4,3,3,4,2,1,1,2,4,3,3,4,2,1,1,2,4,3,3,4,2,1,1,2,4,3,3,4,2,1,1,2,4,3,3,4,2,1,1,2,4,3,3,4,2,1,1,2,4,3,3,4,2,1,1,2,4,3,3,4,2,1,1,2,4,3,3,4,2,1,1,2,4,3,3,4,2,1,1,2,4,3,3,4,2,1,1,2,4,3 add $0,1 bin $0,2 mod $0,4 add $0,1
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/iot/model/RetryableFailureType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace IoT { namespace Model { namespace RetryableFailureTypeMapper { static const int FAILED_HASH = HashingUtils::HashString("FAILED"); static const int TIMED_OUT_HASH = HashingUtils::HashString("TIMED_OUT"); static const int ALL_HASH = HashingUtils::HashString("ALL"); RetryableFailureType GetRetryableFailureTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == FAILED_HASH) { return RetryableFailureType::FAILED; } else if (hashCode == TIMED_OUT_HASH) { return RetryableFailureType::TIMED_OUT; } else if (hashCode == ALL_HASH) { return RetryableFailureType::ALL; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<RetryableFailureType>(hashCode); } return RetryableFailureType::NOT_SET; } Aws::String GetNameForRetryableFailureType(RetryableFailureType enumValue) { switch(enumValue) { case RetryableFailureType::FAILED: return "FAILED"; case RetryableFailureType::TIMED_OUT: return "TIMED_OUT"; case RetryableFailureType::ALL: return "ALL"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace RetryableFailureTypeMapper } // namespace Model } // namespace IoT } // namespace Aws
use32 org 0h cld mov cl, 5 cmp ah, 2 jnz start mov ax, 8888h push 0cafebabeh push 0 push 22h push 8888h start: mov edx, 11223344h mov edi, [fs:eax+30h] mov dl, byte [ecx+2] mov edx, [ecx+2] mov edx, [ecx+4444h] mov dx, word [ecx+4444h] mov ecx, [edx+esi+88h] mov ecx, [edx+esi-88h] mov ecx, [edx+esi-12h] mov ecx, [edx+esi+8888h] mov ecx, [edx+esi*2+88h] nop cmp byte [edx+esi*4+80], bl cmp byte [edx+esi*4+80], 0ffh cmp word [edx+esi*4+80], 0ff88h cmp dword [edx+esi*4+80], 0ffffh cmp dword [edx+esi*4+80], 80h cmp dword [edx+esi*4+80], -12h cmp dword [edx+esi*4], 0ffffh cmp dword [edx+esi], 0ffffh cmp dword [edx], 0ffffh cmp edx, 88h loop start ; xor edx, edx
/* * Given a collection of intervals, merge all overlapping intervals. * * Example 1: * * Input: intervals = [[1,3],[2,6],[8,10],[15,18]] * Output: [[1,6],[8,10],[15,18]] * Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. * * Example 2: * * Input: intervals = [[1,4],[4,5]] * Output: [[1,5]] * Explanation: Intervals [1,4] and [4,5] are considered overlapping. */ //------------------------------------Solution----------------------------------- /* * In this, we are first sorting the intervals as these are not in sorted order. * We are taking the first interval out and keeping its value in lower and upper variable (and denoting this interval as previous interval) * , so that we can use it to compare next preceding intervals. * For each consecutive intervals, we will check if the starting of the current interval is smaller than the end of the previous interval and the end value * of the previous interval smaller than the end value of the current interval. Then, we will update the end value of the previous interval with current interval. * If the end of the previous is smaller then the start of the current, then we insert the previous value and update the current interval's value * with previous one i.e current interval value will become the lower and upper. * */ class Solution { public: vector<vector<int>> merge(vector<vector<int>>& intervals) { int size = intervals.size(); vector<vector<int>> solution; if (size <= 0) return solution; sort(intervals.begin(), intervals.end()); int lower = intervals[0][0], upper = intervals[0][1]; for (int i=1; i<size; i++) { vector<int> interval = intervals[i]; if (interval[0] <= upper && upper < interval[1]) { upper = interval[1]; } else if(upper < interval[0]) { solution.push_back({lower, upper}); lower = interval[0]; upper = interval[1]; } } solution.push_back({lower, upper}); return solution; } };
.global s_prepare_buffers s_prepare_buffers: push %r13 push %r15 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_D_ht+0x15aeb, %rsi inc %r13 mov (%rsi), %bx nop nop nop nop and $13577, %r15 lea addresses_UC_ht+0x1d80b, %rdi nop nop cmp $14447, %rcx mov $0x6162636465666768, %r9 movq %r9, (%rdi) nop nop nop nop nop cmp $15313, %r15 lea addresses_normal_ht+0x1590b, %rsi lea addresses_A_ht+0x4c67, %rdi nop nop nop cmp $52545, %rbx mov $102, %rcx rep movsw nop xor %rdi, %rdi pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r15 pop %r13 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %r8 push %rax push %rcx push %rdi push %rsi // Store lea addresses_A+0x1d00b, %rcx nop nop nop nop nop cmp %r8, %r8 movw $0x5152, (%rcx) nop nop sub %rcx, %rcx // Store lea addresses_WT+0x1598b, %r13 nop nop nop nop and $25902, %rax movw $0x5152, (%r13) nop nop nop sub %r12, %r12 // Load lea addresses_D+0x1d42b, %r13 nop nop dec %rdi vmovups (%r13), %ymm7 vextracti128 $1, %ymm7, %xmm7 vpextrq $1, %xmm7, %rsi nop nop nop nop cmp %r12, %r12 // Faulty Load mov $0x4c6c2b000000000b, %rsi nop nop nop nop nop dec %r12 movups (%rsi), %xmm3 vpextrq $1, %xmm3, %rax lea oracles, %rcx and $0xff, %rax shlq $12, %rax mov (%rcx,%rax,1), %rax pop %rsi pop %rdi pop %rcx pop %rax pop %r8 pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_A', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_NC', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 5, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 8, 'same': True}, 'dst': {'type': 'addresses_A_ht', 'congruent': 2, 'same': True}} {'00': 13468} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; A156174: Period 5: repeat [1,-1,1,-1,0]. ; 1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0,1,-1,1,-1,0 mul $0,2 mod $0,5 mov $2,$0 sub $0,2 sub $2,2 mov $1,$2 lpb $0 mov $0,1 mov $1,4 lpe mul $1,6 sub $1,12 div $1,12
MODULE generic_console_vpeek SECTION code_clib PUBLIC generic_console_vpeek EXTERN generic_console_font32 EXTERN generic_console_udg32 EXTERN screendollar EXTERN screendollar_with_count generic_console_vpeek: ld hl,-8 add hl,sp ld sp,hl push hl ;save buffer ; Calculate screen address ld a,c cpl ld d,a ld a,b add a add a cpl ld e,a ld b,8 loop: ld a,(de) ld (hl),a inc hl rlc e dec e rrc e djnz loop pop de ;buffer ld hl,(generic_console_font32) call screendollar jr nc,gotit ld hl,(generic_console_udg32) ld b,128 call screendollar_with_count jr c,gotit add 128 gotit: pop bc pop bc pop bc pop bc ret
// This file contains the 'main' function. Program execution begins and ends there. // Requirement: C++17 #include "Core.h" #include "ItemToolTipBmd.h" int main(int argc, char** argv) { return Convert<ItemToolTipBmd>(argc, argv); }
#INCLUDE "MOTO.H" *************************** * DISC-II * * 13-SECTOR FORMAT * * READ AND WRITE * * SUBROUTINES * * * *************************** * * * * * COPYRIGHT 1978 * * APPLE COMPUTER INC. * * * * ALL RIGHTS RESERVED * * * *************************** * * * MAY 25, 1978 * * WOZ * * R. WIGGINTON * * * *************************** EJECT *************************** * * * CRITICAL TIMING * * REQUIRES PAGE BOUND * * CONSIDERATIONS FOR * * CODE AND DATA * * * * -----CODE----- * * * * VIRTUALLY THE ENTIRE * * 'WRITE' ROUTINE * * MUST NOT CROSS * * PAGE BOUNDARIES. * * * * CRITICAL BRANCHES IN * * THE 'WRITE', 'READ', * * AND 'READ ADR' SUBRS * * WHICH MUST NOT CROSS * * PAGE BOUNDARIES ARE * * NOTED IN COMMENTS. * * * * -----DATA----- * * * * NBUF1, NBUF2, NBUF3, * * NBUF4, AND NBUF5 ARE * * 51-BYTE RAM BUFFERS * * WHICH SHOULD ALL BE * * LOCATED ON A SINGLE * * PAGE BEGINNING WITH * * NBUF1. (NBUF5 IS 52). * * * * NBUF6, NBUF7, AND * * NBUF8 MUST NOT CROSS * * PAGE BOUNDARIES AND * * SHOULD BE LOCATED * * ON A PAGE BEGINNING * * WITH NBUF6. NBUF6 * * AND NBUF7 ARE 51 BYTES * * WHILE NBUF8 IS 52. * * * * NIBLIZING TABLE 'NIBL' * * (32 BYTES) MUST NOT * * CROSS PAGE BOUNDARY. * * CONVERTS 5-BIT NIBLS * * TO 7-BIT NIBLS. * * * * DENIBLIZING TABLE * * 'DNIBL' MUST BE ON A * * PAGE BOUNDARY, BUT * * ONLY DNIBL,$AB TO * * DNIBL,$FF NEED BE * * USED. CONVERTS 7-BIT * * NIBLS TO 5-BIT NIBLS. * * * *************************** EJECT *************************** * * * EQUATES * * * *************************** * * * -----PRENIBL---- * * AND POSTNIBL * * * *************************** BUF EQU $3E ;TWO BYTE POINTER. * * POINTS TO 256-BYTE * USER BUFFER ANYWHERE * IN MEMORY. PRENIBL * CONVERTS USER DATA * (IN BUF) INTO 5-BIT * NIBLS 000ABCDE IN * NBUF1 THROUGH NBUF8 * PRIOR TO 'WRITE'. * POSTNIBL CONVERTS * 5-BIT NIBLS ABCDE000 * BACK TO USER DATA * (IN BUF) AFTER 'READ'. * NBUF1 EQU $3B00 NBUF2 EQU $3B33 ;OBSERVE THESE NBUF3 EQU $3B66 ;PLACEMENTS NBUF4 EQU $3B99 ;RELATIVE TO NBUF5 EQU $3BCC ;PAGE STARTS! NBUF6 EQU $3C00 NBUF7 EQU $3C33 NBUF8 EQU $3C66 ;(TO $BC99) * T0 EQU $26 ;TEMPS USED BY PRENIBL T1 EQU $27 ; AND POSTNIBL. T2 EQU $2A ;TEMP USED BY PRENIBL. * ************************ * * * ----READADR---- * * * ************************ COUNT EQU $26 ;'MUST FIND' COUNT. LAST EQU $26 ;'ODD BIT' NIBLS. CSUM EQU $27 ;CHECKSUM BYTE. CSSTV EQU $2C ;FOUR BYTES, * CHECKSUM, SECTOR, TRACK, AND VOLUME. * ************************ * * * ----WRITE---- * * * * USES ALL NBUFS * * AND 32-BYTE * * DATA TABLE 'NIBL' * * * ************************ WTEMP EQU $26 ;TEMP FOR DATA AT NBUF6,0. SLOTZ EQU $27 ;SLOTNUM IN Z-PAG LOC. SLOTABS EQU $678 ;SLOTNUM IN NON-ZPAG LOC. * ************************ * * * -----READ---- * * * * USES ALL NBUFS * * USES LAST 54 BYTES * * OF A CODE PAGE FOR * * USED BYTES OF DNIBL * * TABLE. * * * ************************ IDX EQU $26 ;INDEX INTO (BUF). DNIBL EQU $3A00 ;7-BIT TO 5-BIT NIBLS. * ************************ * * * ---- SEEK ---- * * * ************************ TRKCNT EQU $26 ;HALFTRKS MOVED COUNT. PRIOR EQU $27 ;PRIOR HALFTRACK. TRKN EQU $2A ;DESIRED TRACK. SLOTTEMP EQU $2B ;SLOT NUM TIMES $10. CURTRK EQU $478 ;CURRENT TRACK ON ENTYR. * ************************ * * * ---- MSWAIT ---- * * * ************************ MONTIMEL EQU $46 MONTIMEH EQU $47 * ************************ * * * DEVICE ADDRESS * * ASSIGNMENTS * * * ************************ PHASEOFF EQU $C080 ;STEPPER PHASE OFF. PHASEON EQU $C081 ;STEPPER PHASE ON. Q6L EQU $C08C ;Q7L,Q6L=READ Q6H EQU $C08D ;Q7L,Q6H=SENSE WPROT Q7L EQU $C08E ;Q7H,Q6L=WRITE Q7H EQU $C08F ;Q7H,Q6H=WRITE STORE EJECT **************************** * * * PRENIBLIZE SUBR * * * **************************** * * * CONVERTS 256 BYTES OF * * USER DATA IN (BUF),0 * * TO (BUF),255 INTO 410 * * 5-BIT NIBLS (000ABCDE) * * IN NBUF1 THROUGH NBUF8. * * * * ---- ON ENTRY ---- * * * * BUF IS 2-BYTE POINTER * * TO 256 BYTES OF USER * * DATA. * * * * ---- ON EXIT ----- * * * * A-REG: UNCERTAIN. * * X-REG: UNCERTAIN. * * Y-REG: HOLDS $FF. * * CARRY: UNCERTAIN. * * * * NBUF1 THROUGH NBUF8 * * CONTAIN 5-BIT NIBLS * * OF FORM 000ABCDE. * * * * TEMPS T0, T1, T2 USED. * * * **************************** ORG $3800 * OBJ $B800 PRENIBL LDX #$32 ;INDEX FOR (51) 5-BYTE PASSES. LDY #$0 ;USER BUF INDEX. PNIB1 LDA (BUF),Y ;FIRST OF 5 USER BYTES. STA T0 ;(ONLY 3 LSB'S USED) LSRA LSRA ;5 MSB'S TO LOW BITS. LSRA STA NBUF1,X ;FIRST OF 8 5-BIT NIBLS. INY LDA (BUF),Y ;SECOND OF 5 USER BYTES. STA T1 ;ONLY 3 LSB'S USED) LSRA LSRA ;5 MSB'S TO LOW BITS. LSRA STA NBUF2,X ;SECOND OF 8 5-BIT NIBLS. INY LDA (BUF),Y ;THIRD OF 5 USER BYTES. STA T2 ;(ONLY 3 LSB'S USED) LSRA LSRA ;5 MSB'S TO LOW BITS. LSRA STA NBUF3,X ;THIRD OF 8 5-BIT NIBLS. INY LDA (BUF),Y ;FOURTH OF 5 USER BYTES. LSRA ROL T2 ;LSB INTO T2. LSRA ROL T1 ;NEXT LSB INTO T1. LSRA ROL T0 ;NEXT LSB INTO T0. STA NBUF4,X ;FOURTH OF 8 5-BIT NIBLS. INY LDA (BUF),Y ;FIFTH OF 5 USER BYTES. LSRA ROL T2 ;LSB INTO T2. LSRA ROL T1 ;NEXT LSB INTO T1. LSRA STA NBUF5,X ;FIFTH OF 8 5-BIT NIBLS. LDA T0 ROLA ;NEXT LSB. AND #$1F ;TRUNCATE TO 5 BITS. STA NBUF6,X ;SIXTH OF 8 5-BIT NIBLS. LDA T1 AND #$1F ;TRUNCATE TO 5 BITS. STA NBUF7,X ;SEVENTH OF 8 5-BIT NIBLS. LDA T2 AND #$1F ;TRUNCATE TO 5 BITS. STA NBUF8,X ;EIGHTH OF 8 5-BIT NIBLS. INY DEX ;NEXT OF (51) 5-BYTE PASSES. BPL PNIB1 LDA (BUF),Y TAX AND #$7 ;3 LSB'S OF LAST STA NBUF8+$33 ;USER BYTE. TXA LSRA LSRA LSRA ;5 MSB'S OF LAST STA NBUF5+$33 ;USER BYTE. RTS EJECT ************************ * * * WRITE SUBR * * * ************************ * * * WRITES DATA FROM * * NBUF1 TO NBUF8 * * CONVERTING 5-BIT * * TO 7-BIT NIBLS * * VIA 'NIBL' TABLE. : * * * FIRST, NBUF6 TO * * NBUF8, HIGH TO LOW * * THEN, NBUF1 TO * * NBUF5, LOW TO HIGH * * * * ---- ON ENTRY ---- * * * * X-REG: SLOTNUM * * TIMES $10. * * * * NBUF1 TO NBUF8 * * HOLD NIBLS FROM * * PRENIBL SUBR. * * (000ABCDE) * * * * ---- ON EXIT ----- * * * * CARRY SET IF ERROR. * * (W PROT VIOLATION) * * * * IF NO ERROR: * * * * A-REG: UNCERTAIN. * * X-REG: UNCHANGED. * * Y-REG: HOLDS $00. * * CARRY CLEAR. * * * * SLOTABS, SLOTZ, * * AND WTEMP USED. * * * * ---- ASSUMES ---- * * * * 1 USEC CYCLE TIME * * * ************************ WRITE SEC ;ANTICIPATE WPROT ERR. LDA Q6H,X LDA Q7L,X ;SENSE WPROT FLAG. BMI WEXIT ;IF HIGH, THEN ERR. STX SLOTZ ;FOR ZERO PAGE ACCESS. STX SLOTABS ;FOR NON-ZERO PAGE. LDA NBUF6 STA WTEMP ;FOR ZERO-PAGE ACCESS. LDA #$FF ;SYNC DATA. STA Q7H,X ;(5) WRITE 1ST NIBL. ORA Q6L,X ;(4) PHA ;(3) PLA ;(4) CRITICAL TIMING! NOP ;(2) LDY #$A ;(2) FOR 11 NIBLS. WSYNC ORA WTEMP ;(3) FOR TIMING. JSR WNIBL7 ;(13,9,6) WRITE SYNC. DEY ;(2) BNE WSYNC ;(2*) MUST NOT CROSS PAGE! LDA #$D5 ;(2) 1ST DATA MARK. JSR WNIBL9 ;(15,9,6) LDA #$AA ;(2) 2ND DATA MARK. JSR WNIBL9 ;(15,9,6) LDA #$AD ;(2) 3RD DATA MARK. JSR WNIBL9 ;(15,9,6) TYA ;(2) CLEAR CHKSUM. LDY #$9A ;(2) NBUF6-8 INDEX. BNE WDATA1 ;(3) ALWAYS. NO PAGE CROSS!! WDATA0 LDA NBUF6,Y ;(4) PRIOR 5-BIT NIBL. WDATA1 EOR NBUF6-1,Y ;(5) XOR WITH CURRENT. * (NBUF6 MUST BE ON PAGE BOUNDARY FOR TIMING!!) TAX ;(2) INDEX TO 7-BIT NIBL. LDA NIBL,X ;(4) MUST NOT CROSS PAGE! LDX SLOTZ ;(3) CRITICAL TIMING! STA Q6H,X ;(5) WRITE NIBL. LDA Q6L,X ;(4) DEY ;(2) NEXT NIBL. BNE WDATA0 ;(2*) MUST NOT CROSS PAGE! LDA WTEMP ;(3) PRIOR NIBL FROM BUF6. NOP ;(2) CRITICAL TIMING. WDATA2 EOR NBUF1,Y ;(4) XOR NBUF1 NIBL. TAX ;(2) INDEX TO 7-BIT NIBL. LDA NIBL,X ;(4) LDX SLOTABS ;(4) TIMING CRITICAL. STA Q6H,X ;(5) WRITE NIBL. LDA Q6L,X ;(4) LDA NBUF1,Y ;(4) PRIOR 5-BIT NIBL. INY ;(2) NEXT NBUF1 NIBL. BNE WDATA2 ;(2*) MUST NOT CROSS PAGE! TAX ;(2) LAST NIBL AS CHKSUM. LDA NIBL,X ;(4) INDEX TO 7-BIT NIBL. LDX SLOTZ ;(3) JSR WNIBL ;(6,9,6) WRITE CHKSUM. LDA #$DE ;(2) DM4, BIT SLIP MARK. JSR WNIBL9 ;(15,9,6) WRITE IT. LDA #$AA ;(2) DM5, BIT SLIP MARK. JSR WNIBL9 ;(15,9,6) WRITE IT. LDA #$EB ;(2) DM6, BIT SLIP MARK. JSR WNIBL9 ;(15,9,6) WRITE IT. LDA Q7L,X ;OUT OF WRITE MODE. WEXIT LDA Q6L,X ;TO READ MODE. RTS ;RETURN FROM WRITE. ***************************** * * * 7-BIT NIBL WRITE SUBRS * * * * A-REG OR'D PRIOR EXIT * * CARRY CLEARED * * * ***************************** WNIBL9 CLC ;(2) 9 CYCLES, THEN WRITE. WNIBL7 PHA ;(3) 7 CYCLES, THEN WRITE. PLA ;(4) WNIBL STA Q6H,X ;(5) NIBL WRITE SUB. ORA Q6L,X ;(4) CLOBBERS ACC, NOT CARRY. RTS EJECT ************************** * * * READ SUBROUTINE * * * ************************** * * * READS 5-BIT NIBLS * * (ABCDE000) INTO * * NBUF1 THROUGH NBUF8 * * CONVERTING 7-BIT * * NIBLS TO 5-BIT * * VIA 'DNIBL' TABLE * * * * FIRST READS NBUF6 TO * * NBUF8 HIGH TO LOW, * * THEN READS NBUF1 TO * * NBUF5 LOW TO HIGH * * * * ---- ON ENTRY ---- * * * * X-REG: SLOTNUM * * TIMES $10. * * * * READ MODE (Q6L, Q7L) * * * * ---- ON EXIT ----- * * * * CARRY SET IF ERROR. * * * * IF NO ERROR: * * A-REG: HOLDS $AA * * X-REG: UNCHANGED. * * Y-REG: HOLDS $00 * * CARRY CLEAR. * * * * NBUF1 TO NBUF8 * * HOLD 5-BIT * * NIBLS ABCDE000. * * * * USES TEMP 'IDX'. * * * * ---- CAUTION ----- * * * * OBSERVE * * 'NO PAGE CROSS' * * WARNINGS ON * * SOME BRANCHES!! * * * * ---- ASSUMES ---- * * * * 1 USEC CYCLE TIME * * * ************************** READ LDY #$20 ;'MUST FIND' COUNT. RSYNC DEY ;IF CAN'T FIND MARKS BEQ RDERR ;THEN EXIT WITH CARRY SET. RD1 LDA Q6L,X ;READ NIBL. BPL RD1 ;*** NO PAGE CROSS! *** RSYNC1 EOR #$D5 ;DATA MARK 1? BNE RSYNC ;LOOP IF NOT. NOP ;DELAY BETWEEN NIBLS. RD2 LDA Q6L,X BPL RD2 ;*** NO PAGE CROSS! *** CMP #$AA ;DATA MARK 2? BNE RSYNC1 ; (IF NOT, IS IT DM1?) LDY #$9A ;INIT NBUF6 INDEX. * (ADDED NIBL DELAY) RD3 LDA Q6L,X BPL RD3 ;*** NO PAGE CROSS! *** CMP #$AD ;DATA MARK 3? BNE RSYNC1 ; (IF NOT, IS IT DM1?) * (CARRY SET IF DM3!) LDA #$00 ;INIT CHECKSUM. RDATA1 DEY STY IDX RD4 LDY Q6L,X BPL RD4 ;*** NO PAGE CROSS! *** EOR DNIBL,Y ;XOR 5-BIT NIBL. LDY IDX STA NBUF6,Y ;STORE IN NBUF6 PAGE. BNE RDATA1 ;TAKEN IF Y-REG NONZERO. RDATA2 STY IDX RD5 LDY Q6L,X BPL RD5 ;*** NO PAGE CROSS! *** EOR DNIBL,Y ;XOR 5-BIT NIBL. LDY IDX STA NBUF1,Y ;STORE IN NBUF1 PAGE. INY BNE RDATA2 RD6 LDY Q6L,X ;READ 7-BIT CSUM NIBL. BPL RD6 ;*** NO PAGE CROSS! *** CMP DNIBL,Y ;IF LAST NBUF1 NIBL NOT BNE RDERR ;EQUAL CHKSUM NIBL THEN ERR. RD7 LDA Q6L,X BPL RD7 ;*** NO PAGE CROSS! *** CMP #$DE ;FIRST BIT SLIP MARK? BNE RDERR ; (ERR IF NOT) NOP ;DELAY BETWEEN NIBLS. RD8 LDA Q6L,X BPL RD8 ;*** NO PAGE CROSS! *** CMP #$AA ;SECOND BIT SLIP MARK? BEQ RDEXIT ; (DONE IF IT IS) RDERR SEC ;INDICATE 'ERROR EXIT'. RTS ;RETURN FROM READ OR READADR. EJECT **************************** * * * READ ADDRESS FIELD * * * * SUBROUTINE * * * **************************** * * * READS VOLUME, TRACK * * AND SECTOR * * * * ---- ON ENTRY ---- * * * * XREG: SLOTNUM TIMES $10 * * * * READ MODE (Q6L, Q7L) * * * * ---- ON EXIT ----- * * * * CARRY SET IF ERROR. * * * * IF NO ERROR: * * A-REG: HOLDS $AA. * * Y-REG: HOLDS $00. * * X-REG: UNCHANGED. * * CARRY CLEAR. * * * * CSSTV HOLDS CHKSUM, * * SECTOR, TRACK, AND * * VOLUME READ. * * * * USES TEMPS COUNT, * * LAST, CSUM, AND * * 4 BYTES AT CSSTV. * * * * ---- EXPECTS ---- * * * * NORMAL DENSITY NIBLS * * (4-BIT), ODD BITS, * * THEN EVEN. * * * * ---- CAUTION ---- * * * * OBSERVE * * 'NO PAGE CROSS' * * WARNINGS ON * * SOME BRANCHES!! * * * * ---- ASSUMES ---- * * * * 1 USEC CYCLE TIME * * * **************************** RDADR LDY #$F8 STY COUNT ;'MUST FIND' COUNT. RDASYN INY BNE RDA1 ;LOW ORDER OF COUNT. INC COUNT ;(2K NIBLS TO FIND BEQ RDERR ; ADR MARK, ELSE ERR) RDA1 LDA Q6L,X ;READ NIBL. BPL RDA1 ;*** NO PAGE CROSS! *** RDASN1 CMP #$D5 ;ADR MARK 1? BNE RDASYN ; (LOOP IF NOT) NOP ;ADDED NIBL DELAY. RDA2 LDA Q6L,X BPL RDA2 ;*** NO PAGE CROSS! *** CMP #$AA ;ADR MARK 2? BNE RDASN1 ; (IF NOT, IS IT AM1?) LDY #$3 ;INDEX FOR 4-BYTE READ. * (ADDED NIBL DELAY) RDA3 LDA Q6L,X BPL RDA3 ;*** NO PAGE CROSS! *** CMP #$B5 ;ADR MARK 3? BNE RDASN1 ; (IF NOT, IS IT AM1?) * (LEAVES CARRY SET!) LDA #$0 ;INIT CHECKSUM. RDAFLD STA CSUM RDA4 LDA Q6L,X ;READ 'ODD BIT' NIBL. BPL RDA4 ;*** NO PAGE CROSS! *** ROLA ;ALIGN ODD BITS, '1' INTO LSB. STA LAST ; (SAVE THEM) RDA5 LDA Q6L,X ;READ 'EVEN BIT' NIBL. BPL RDA5 ;*** NO PAGE CROSS! *** AND LAST ;MERGE ODD AND EVEN BITS. STA CSSTV,Y ;STORE DATA BYTE. EOR CSUM ;XOR CHECKSUM. DEY BPL RDAFLD ;LOOP ON 4 DATA BYTES. TAY ;IF FINAL CHECKSUM BNE RDERR ; NONZERO, THEN ERROR. RDA6 LDA Q6L,X ;FIRST BIT-SLIP NIBL. BPL RDA6 ;*** NO PAGE CROSS! *** CMP #$DE BNE RDERR ;ERROR IF NONMATCH. NOP ;DELAY BETWEEN NIBLS. RDA7 LDA Q6L,X ;SECOND BIT-SLIP NIBL. BPL RDA7 ;*** NO PAGE CROSS! *** CMP #$AA BNE RDERR ;ERROR IF NONMATCH. RDEXIT CLC ;CLEAR CARRY ON RTS ;NORMAL READ EXITS. EJECT *************************** * * * POSTNIBLIZE SUBR * * * *************************** * * * CONVERTS 5-BIT NIBLS * * OF FORM ABCDE000 IN * * NBUF1 THROUGH NBUF8 * * INTO 256 BYTES OF * * USER DATA IN BUF. * * * * ---- ON ENTRY ---- * * * * X-REG: HOLDS SLOTNUM * * TIMES $10. * * * * BUF IS 2-BYTE POINTER * * TO 256 BYTES OF USER * * DATA TO BE CONVERTED * * TO 5-BIT NIBLS IN * * NBUF1 THROUGH NBUF8 * * PRIOR TO WRITE. * * * * ---- ON EXIT ----- * * * * A-REG: UNCERTAIN. * * Y-REG: HOLDS $FF. * * X-REG: HOLDS $FF. * * CARRY: UNCERTAIN. * * * * 5-BIT NIBLS OF FORM * * 000ABCDE IN 410 * * BYTES FROM NBUF1 * * TO NBUF8. * * * *************************** POSTNIB LDX #$32 ;INDEX FOR 51 PASSES. LDY #$0 ;INDEX TO USER BUF. POSTNB1 LDA NBUF6,X LSRA LSRA LSRA STA T1 LSRA STA T0 LSRA ORA NBUF1,X STA (BUF),Y ;FIRST OF 5 USER BYTES. INY LDA NBUF7,X LSRA LSRA LSRA LSRA ROL T1 LSRA ROL T0 ORA NBUF2,X STA (BUF),Y ;SECOND OF 5 USER BYTES. INY LDA NBUF8,X LSRA LSRA LSRA LSRA ROL T1 LSRA ROL T0 ORA NBUF3,X STA (BUF),Y ;THIRD OF 5 USER BYTES. INY LDA T0 AND #$7 ORA NBUF4,X STA (BUF),Y ;FOURTH OF 5 USER BYTES. INY LDA T1 AND #$7 ORA NBUF5,X STA (BUF),Y ;FIFTH OF 5 USER BYTES. INY DEX ;NEXT OF 51 PASSES. BPL POSTNB1 ;HANDLE LAST USER LDA NBUF8+$33 ; BYTE DIFFERENTLY. LSRA LSRA LSRA ORA NBUF5+$33 STA (BUF),Y RTS EJECT ************************** * * * FAST SEEK SUBROUTINE * * * ************************** * * * ---- ON ENTRY ---- * * * * X-REG HOLDS SLOTNUM * * TIMES $10. * * * * A-REG HOLDS DESIRED * * HALFTRACK. * * (SINGLE PHASE) * * * * CURTRK HOLDS CURRENT * * HALFTRACK. * * * * ---- ON EXIT ----- * * * * A-REG UNCERTAIN. * * Y-REG UNCERTAIN. * * X-REG UNDISTURBED. * * * * CURTRK AND TRKN HOLD * * FINAL HALFTRACK. * * * * PRIOR HOLDS PRIOR * * HALFTRACK IF SEEK * * WAS REQUIRED. * * * * MONTIMEL AND MONTIMEH * * ARE INCREMENTED BY * * THE NUMBER OF * * 100 USEC QUANTUMS * * REQUIRED BY SEEK * * FOR MOTOR ON TIME * * OVERLAP. * * * * --- VARIABLES USED --- * * * * CURTRK, TRKN, COUNT, * * PRIOR, SLOTTEMP * * MONTIMEL, MONTIMEH * * * ************************** SEEK STA TRKN ;TARGET TRACK. CMP CURTRK ;ON DESIRED TRACK? BEQ SEEKXIT ; YES, HIT IT AND RETURN. STX SLOTTEMP ;SAVE X-REG. LDA #$0 STA TRKCNT ;HALFTRACK COUNT. SEEK2 LDA CURTRK ;SAVE CURTRK FOR STA PRIOR ; DELAYED TURNOFF. SEC SBC TRKN ;DELTA-TRACKS. BEQ SEEKEND ;DONE, FINISH SEEK. BCS OUT ;(MOVE OUT, NOT IN) EOR #$FF ;CALC TRKS TO GO. INC CURTRK ;INCR CURRENT TRACK (IN). BCC MINTST ;(ALWAYS TAKEN) OUT ADC #$FE ;CALC TRKS TO GO. DEC CURTRK ;DECR CURRENT TRACK (OUT). MINTST CMP TRKCNT BCC MAXTST ; AND 'TRKS MOVED'. LDA TRKCNT MAXTST CMP #$C BCC STEP ;IF > $B, USE $B. LDA #$B STEP TAY ;ACCELLERATION INDEX. LDA CURTRK AND #$3 ;INDEX TO 'CURRENT ASLA ; PHASE' OF 4-PHASE ORA SLOTTEMP ; STEPPER. TAX LDA PHASEON,X ;HIT NEXT PHASE LDA ONTABLE,Y ; FOR 'ONTIME'. JSR MSWAIT ;(100 USEC INTERVALS) LDA PRIOR AND #$3 ;INDEX TO 'PRIOR PHASE' ASLA ; OF 4-PHASE STEPPER. ORA SLOTTEMP TAX LDA PHASEOFF,X ;PRIOR PHASE OFF, LDA OFFTABLE,Y ; THEN WAIT 'OFFTIME'. JSR MSWAIT ;(100 USEC INTERVALS) INC TRKCNT ;'TRACKS MOVED' COUNT. BNE SEEK2 ;(ALWAYS TAKEN) SEEKEND LDA #$5F ;DELAY 9.5 MSEC FOR JSR MSWAIT ; SETTLING TIME. LDX SLOTTEMP ;RESTORE X-REG. SEEKXIT RTS ;RETURN. EJECT ************************** * * * MSWAIT SUBROUTINE * * * ************************** * * * DELAYS A SPECIFIED * * NUMBER OF 100 USEC * * INTERVALS FOR MOTOR * * ON TIMING. * * * * ---- ON ENTRY ---- * * * * A-REG: HOLDS NUMBER * * OF 100 USEC * * INTERVALS TO * * DELAY. * * * * ---- ON EXIT ----- * * * * A-REG: HOLDS $00. * * X-REG: HOLDS $00. * * Y-REG: UNCHANGED. * * CARRY: SET. * * * * MONTIMEL, MONTIMEH * * ARE INCREMENTED ONCE * * PER 100 USEC INTERVAL* * FOR MOTON ON TIMING. * * * * ---- ASSUMES ---- * * * * 1 USEC CYCLE TIME * * * ************************** MSWAIT LDX #$11 MSW1 DEX ;DELAY 86 USEC. BNE MSW1 INC MONTIMEL BNE MSW2 ;DOUBLE-BYTE INC MONTIMEH ; INCREMENT. MSW2 SEC SBC #$1 ;DONE 'N' INTERVALS? BNE MSWAIT ;(A-REG COUNTS) RTS EJECT ************************** * * * PHASE ON-, OFF-TIME * * TABLES IN 100-USEC * * INTERVALS. (SEEK) * * * ************************** ONTABLE DB $01,$30,$28 DB $24,$20,$1E DB $1D,$1C,$1C DB $1C,$1C,$1C OFFTABLE DB $70,$2C,$26 DB $22,$1F,$1E DB $1D,$1C,$1C DB $1C,$1C,$1C EJECT ************************** * * * 7-BIT TO 5-BIT * * 'DENIBLIZE' TABL * * * * VALID CODES * * $AB TO $FF ONLY. * * ($DA NOT VALID) * * * * ---- CAUTION ---- * * * * INSURE THAT FOLLOWING * * 'RE-ORG' IS OK. * * * ************************** ORG $3AAB * OBJ $BAAB DB $00,$01,$08 DB $10,$18,$02 DB $03,$04,$05 DB $06,$20,$28 DB $30,$07,$09 DB $38,$40,$0A DB $48,$50,$58 DB $0B,$0C,$0D DB $0E,$0F,$11 DB $12,$13,$14 DB $15,$16,$17 DB $19,$1A,$1B DB $1C,$1D,$1E DB $21,$22,$23 DB $24,$60,$68 DB $25,$26,$70 DB $78,$27,$80 DB $88,$90,$29 DB $2A,$2B,$2C DB $2D,$2E,$2F DB $31,$32,$33 DB $98,$A0,$34 DB $A8,$B0,$B8 DB $35,$36,$37 DB $39,$3A,$C0 DB $C8,$D0,$3B DB $3C,$D8,$E0 DB $3E,$E8,$F0 DB $F8 EJECT ************************** * * * 5-BIT TO 7-BIT * * NIBL CONVERSION * * TABLE * * * ************************** * * * CODES $AA, $D5 * * NOT USED * * * ************************** ORG $3C9A * OBJ $BC9A NIBL DB $AB,$AD,$AE DB $AF,$B5,$B6 DB $B7,$BA,$BB DB $BD,$BE,$BF DB $D6,$D7,$DA DB $0DB,$DD,$DE DB $DF,$EA,$EB DB $ED,$EE,$EF DB $F5,$F6,$F7 DB $FA,$FB,$FD DB $FE,$FF DB $1C,$1C,$1C END
extern pit_handler global pit_gate %macro pushall 0 push eax push ecx push ebx push edx push edi push esi push ebp %endmacro %macro popall 0 pop ebp pop esi pop edi pop edx pop ebx pop ecx pop eax %endmacro pit_gate: cli pushall push esp call pit_handler pop esp popall sti iret
; A159528: Numerator of Hermite(n, 15/16). ; Submitted by Christian Krause ; 1,15,97,-2385,-73023,125775,48621345,632724975,-34073850495,-1159018131825,21867803792865,1811560265628975,-3616463755919295,-2836803524344895025,-36534257175323718495,4535538057996196107375,138178844646564481121025,-7216099273077742411088625,-408918655047090447085679775,10492112899464761808862995375,1151871862566495394445318143425,-9581731084132359314009496008625,-3239957532840725009979157609655775,-21617208259694151321436623384548625,9214176852787682159557090652058372225 mov $1,1 mov $2,-1 lpb $0 sub $0,1 mul $1,8 sub $2,$1 sub $1,$2 add $2,$1 div $2,4 sub $1,$2 mul $2,$0 mul $2,64 sub $2,$1 lpe mov $0,$1
.size 8000 .text@48 ei jp lstatint .text@100 jp lbegin .data@143 80 .text@150 lbegin: ld c, 44 ld b, 90 lbegin_waitvblank: ldff a, (c) cmp a, b jrnz lbegin_waitvblank ld hl, 8000 xor a, a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld(hl++), a ld hl, 8010 ld a, ff ld(hl++), a ld(hl++), a ld a, 01 ld b, 32 ld hl, 9a40 lbegin_settilemap: ld(hl++), a dec b jrnz lbegin_settilemap ld a, e4 ldff(47), a ld a, 80 ldff(68), a ld a, ff ld c, 69 ldff(c), a ldff(c), a ld a, aa ldff(c), a ldff(c), a ld a, 55 ldff(c), a ldff(c), a xor a, a ldff(c), a ldff(c), a ld c, 41 ld b, 03 lbegin_waitm3: ldff a, (c) and a, b cmp a, b jrnz lbegin_waitm3 ld a, 20 ldff(c), a ld a, 02 ldff(ff), a xor a, a ldff(0f), a ld c, 42 ld b, 90 ei .text@1000 lstatint: nop nop nop nop nop nop nop nop ldff a, (44) ld d, a ld a, b sub a, d ldff(c), a pop hl xor a, a .text@1029 ldff(c), a
; A038585: Write n in binary, delete 0's. ; 1,1,11,1,11,11,111,1,11,11,111,11,111,111,1111,1,11,11,111,11,111,111,1111,11,111,111,1111,111,1111,1111,11111,1,11,11,111,11,111,111,1111,11,111,111,1111,111,1111,1111,11111,11,111,111,1111,111,1111,1111,11111,111,1111,1111,11111,1111,11111,11111,111111,1,11,11,111,11,111,111,1111,11,111,111,1111,111,1111,1111,11111,11,111,111,1111,111,1111,1111,11111,111,1111,1111,11111,1111,11111,11111,111111,11,111,111,1111,111,1111,1111,11111,111,1111,1111,11111,1111,11111,11111,111111,111,1111,1111,11111,1111,11111,11111,111111,1111,11111,11111,111111,11111,111111,111111,1111111,1,11,11,111,11,111,111,1111,11,111,111,1111,111,1111,1111,11111,11,111,111,1111,111,1111,1111,11111,111,1111,1111,11111,1111,11111,11111,111111,11,111,111,1111,111,1111,1111,11111,111,1111,1111,11111,1111,11111,11111,111111,111,1111,1111,11111,1111,11111,11111,111111,1111,11111,11111,111111,11111,111111,111111,1111111,11,111,111,1111,111,1111,1111,11111,111,1111,1111,11111,1111,11111,11111,111111,111,1111,1111,11111,1111,11111,11111,111111,1111,11111,11111,111111,11111,111111,111111,1111111,111,1111,1111,11111,1111,11111,11111,111111,1111,11111,11111,111111,11111,111111,111111,1111111,1111,11111,11111,111111,11111,111111,111111,1111111,11111,111111,111111 add $0,1 cal $0,255745 ; a(1) = 1; for n > 1, a(n) = 11*10^{A000120(n-1)-1}. mov $1,$0 div $1,99 mul $1,10 add $1,1
; A155464: a(n) = 7*a(n-1) - 7*a(n-2) + a(n-3) for n > 2; a(0) = 0, a(1) = 51, a(2) = 340. ; 0,51,340,2023,11832,69003,402220,2344351,13663920,79639203,464171332,2705388823,15768161640,91903581051,535653324700,3122016367183,18196444878432,106056652903443,618143472542260,3602804182350151 add $0,1 mul $0,2 sub $0,1 mov $1,1 lpb $0 sub $0,1 add $1,$3 mov $2,$1 add $1,$3 add $2,13 mov $3,$2 lpe div $1,28 mul $1,17
dnl HP-PA mpn_add_n -- Add two limb vectors of the same length > 0 and store dnl sum in a third limb vector. dnl Copyright 1992, 1994, 2000-2002 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 INPUT PARAMETERS C res_ptr gr26 C s1_ptr gr25 C s2_ptr gr24 C size gr23 C One might want to unroll this as for other processors, but it turns out that C the data cache contention after a store makes such unrolling useless. We C can't come under 5 cycles/limb anyway. ASM_START() PROLOGUE(mpn_add_n) ldws,ma 4(0,%r25),%r20 ldws,ma 4(0,%r24),%r19 addib,= -1,%r23,L(end) C check for (SIZE == 1) add %r20,%r19,%r28 C add first limbs ignoring cy LDEF(loop) ldws,ma 4(0,%r25),%r20 ldws,ma 4(0,%r24),%r19 stws,ma %r28,4(0,%r26) addib,<> -1,%r23,L(loop) addc %r20,%r19,%r28 LDEF(end) stws %r28,0(0,%r26) bv 0(%r2) addc %r0,%r0,%r28 EPILOGUE()
/// @file jump_position.hpp #pragma once #include <boost/optional.hpp> #include <chrono> #include "adm/detail/named_option_helper.hpp" #include "adm/detail/named_type.hpp" #include "adm/export.h" namespace adm { /// @brief Tag for NamedType ::JumpPositionFlag struct JumpPositionFlagTag {}; /// @brief NamedType for jumpPositionFlag parameter using JumpPositionFlag = detail::NamedType<bool, JumpPositionFlagTag>; /// @brief Tag for NamedType ::InterpolationLength struct interpolationLengthTag {}; /// @brief NamedType for interpolationLength parameter using InterpolationLength = detail::NamedType<std::chrono::nanoseconds, interpolationLengthTag>; /// @brief Tag for JumpPosition class struct JumpPositionTag {}; /** * @brief ADM parameter class to specify a jump position */ class JumpPosition { public: typedef JumpPositionTag tag; /** * @brief Constructor template * * Templated constructor which accepts a variable number of ADM parameters * in random order after the mandatory ADM parameters. */ template <typename... Parameters> explicit JumpPosition(Parameters... optionalNamedArgs); /** * @brief ADM parameter getter template * * Templated getter with the wanted ADM parameter type as template * argument. If currently no value is available trying to get the adm * parameter will result in an exception. Check with the has method before */ template <typename Parameter> Parameter get() const; /** * @brief ADM parameter has template * * Templated has method with the ADM parameter type as template argument. * Returns true if the ADM parameter is set or has a default value. */ template <typename Parameter> bool has() const; /** * @brief ADM parameter isDefault template * * Templated isDefault method with the ADM parameter type as template * argument. Returns true if the ADM parameter is the default value. */ template <typename Parameter> bool isDefault() const; /// @brief JumpPositionFlag setter ADM_EXPORT void set(JumpPositionFlag objectDivergenceFlag); /// @brief InterpolationLength setter ADM_EXPORT void set(InterpolationLength interpolationLength); /** * @brief ADM parameter unset template * * Templated unset method with the ADM parameter type as template * argument. Removes an ADM parameter if it is optional or resets it to * the default value if there is one. */ template <typename Parameter> void unset(); /** * @brief Print overview to ostream */ ADM_EXPORT void print(std::ostream &os) const; private: ADM_EXPORT JumpPositionFlag get(detail::ParameterTraits<JumpPositionFlag>::tag) const; ADM_EXPORT InterpolationLength get(detail::ParameterTraits<InterpolationLength>::tag) const; ADM_EXPORT bool has(detail::ParameterTraits<JumpPositionFlag>::tag) const; ADM_EXPORT bool has( detail::ParameterTraits<InterpolationLength>::tag) const; template <typename Tag> bool isDefault(Tag) const { return false; } ADM_EXPORT bool isDefault( detail::ParameterTraits<JumpPositionFlag>::tag) const; ADM_EXPORT bool isDefault( detail::ParameterTraits<InterpolationLength>::tag) const; ADM_EXPORT void unset(detail::ParameterTraits<JumpPositionFlag>::tag); ADM_EXPORT void unset(detail::ParameterTraits<InterpolationLength>::tag); boost::optional<JumpPositionFlag> jumpPositionFlag_; boost::optional<InterpolationLength> interpolationLength_; static const JumpPositionFlag jumpPositionFlagDefault_; static const InterpolationLength interpolationLengthDefault_; }; // ---- Free Functions ---- // /// @brief Helper function to check if the ::JumpPositionFlag of a /// JumpPosition is true ADM_EXPORT bool isEnabled(JumpPosition &jumpPosition); /// @brief Helper function to set the ::JumpPositionFlag of a JumpPosition /// to true ADM_EXPORT void enable(JumpPosition &jumpPosition); /// @brief Helper function to set the ::JumpPositionFlag of a JumpPosition /// to false ADM_EXPORT void disable(JumpPosition &jumpPosition); /// @brief Parse interpolationLength ADM_EXPORT InterpolationLength parseInterpolationLength(const std::string &length); /// @brief Format interpolationLength ADM_EXPORT std::string formatInterpolationLength( const InterpolationLength length); // ---- Implementation ---- // template <typename... Parameters> JumpPosition::JumpPosition(Parameters... optionalNamedArgs) { detail::setNamedOptionHelper( this, std::forward<Parameters>(optionalNamedArgs)...); }; template <typename Parameter> Parameter JumpPosition::get() const { typedef typename detail::ParameterTraits<Parameter>::tag Tag; return get(Tag()); } template <typename Parameter> bool JumpPosition::has() const { typedef typename detail::ParameterTraits<Parameter>::tag Tag; return has(Tag()); } template <typename Parameter> bool JumpPosition::isDefault() const { typedef typename detail::ParameterTraits<Parameter>::tag Tag; return isDefault(Tag()); } template <typename Parameter> void JumpPosition::unset() { typedef typename detail::ParameterTraits<Parameter>::tag Tag; return unset(Tag()); } } // namespace adm
public read_timestamp_counter public cpu_ident public MandelbrotLineSSE2x64Two .code ; x64 __fastcall: ; ; RCX: 1st integer argument ; RDX: 2nd integer argument ; R8: 3rd integer argument ; R9: 4th integer argument ; ; XMM0: 1st floating point parameter ; XMM1: 2nd floating point parameter ; XMM2: 3rd floating point parameter ; XMM3: 4th floating point parameter ; ; - Integer arguments beyond the first four are passed on the stack. ; - Floating point arguments beyond the first four are passed on the stack. ; - The this pointer is considered an integer argument and is passed in RCX. ; - When mixing integer and floating point arguments, an argument of one type ; also takes up one register of the opposite kind. So, if two arguments are ; passed, the first an int and the second a float, the float is passed in ; XMM1, not in XMM0. ; ; RAX: Integer return. ; XMM0: Floating point return ; ; Must be preserved across calls: RBX, RBP, RDI, RSI, R12, R13, R14, R15 and XMM6 to XMM15. ; Can be destroyed: RAX, RCX, RDX, R8, R9, R10, and R11. ; ; register usage: http://msdn.microsoft.com/en-us/library/9z1stfyw(VS.80).aspx ; ; Mandelbrot calc: ; ; double zi(0), zr(0), zr2(0), zi2(0); ; while(--iter && zr2 + zi2 > 4) { ; zi = 2 * zr * zi + ci; ; zr = (zr2 - zi2) + cr; ; zr2 = zr * zr; ; zi2 = zi * zi; ; } ; ; __int64 q = calc_sse2_x64(cr0, ci0, cr1, ci1, bailout); ; cr0 xmm0 ; ci0 xmm1 ; cr1 xmm2 ; ci1 xmm3 ; bailout rsp + 20 ; return rax align 8 MandelbrotLineSSE2x64Two proc frame ; FRAME SETUP push rbp .pushreg rbp sub rsp, 0200h .allocstack 0200h lea rbp, [rsp + 080] .setframe rbp, 080h movdqa [rbp], xmm5 .Savexmm128 xmm5, 080h + 0 movdqa [rbp + 010h], xmm6 .Savexmm128 xmm6, 080h + 010h movdqa [rbp + 020h], xmm7 .Savexmm128 xmm7, 080h + 020h movdqa [rbp + 030h], xmm8 .Savexmm128 xmm8, 080h + 030h movdqa [rbp + 040h], xmm9 .Savexmm128 xmm9, 080h + 040h movdqa [rbp + 050h], xmm10 .Savexmm128 xmm10, 080h + 050h movdqa [rbp + 060h], xmm11 .Savexmm128 xmm11, 080h + 060h movdqa [rbp + 070h], xmm12 .Savexmm128 xmm12, 080h + 070h movdqa [rbp + 080h], xmm13 .Savexmm128 xmm13, 080h + 080h movdqa [rbp + 090h], xmm14 .Savexmm128 xmm14, 080h + 090h movdqa [rbp + 100h], xmm15 .Savexmm128 xmm15, 080h + 100h .endprolog ; Attempt to make code faster by turning on ; faster handling of denormals. stmxcsr cw1 mov eax, cw1 or eax, 001000000001000000b ; 5432109876543210 mov cw2, eax ldmxcsr cw2 ; Get bailout from the stack. mov ecx, [rsp+230h] ; initial values for Z are zero xorpd xmm12, xmm12 ; zr1 zr0 xorpd xmm13, xmm13 ; zi1 zi0 xorpd xmm14, xmm14 ; zr21 zr20 xorpd xmm15, xmm15 ; zi21 zi20 movapd xmm6, fours ; two copies of exit test: 4.0 4.0 shufpd xmm0, xmm2, 0 ; cr1 cr0 shufpd xmm1, xmm3, 0 ; ci1 ci0 mov r10, 0 mov r11, 0 mov r8, rcx ; preserve the bailout value ;mov r8, 2000 ; preserve the bailout value ;mov rcx, 2000 l1: ; zi = 2 * zr * zi + ci; mulpd xmm13, xmm12 ; zr * zi addpd xmm13, xmm13 ; * 2 addpd xmm13, xmm1 ; + ci ; zr = (zr2 - zi2) + cr movapd xmm11, xmm14 ; subpd xmm11, xmm15 ; zr2 - zi2 addpd xmm11, xmm0 ; + cr movapd xmm12, xmm11 ; zr2 = zr * zr movapd xmm14, xmm12 mulpd xmm14, xmm14 ; zi2 = zi * zi; movapd xmm15, xmm13 mulpd xmm15, xmm15 ; zr2 + zi2 movapd xmm11, xmm14 addpd xmm11, xmm15 ; set bits if less than 4.0 4.0 cmpltpd xmm11, xmm6 ; extract 2-bit sign mask of from xmm and store in r32 movmskpd rdx, xmm11 cmp rdx, 0 je done ; two counters in one register ror edx, 1 add r10, rdx ; limit iterations to bailout dec rcx jne l1 done: ; split the two counters in r10 into r10 and r11 mov r11, r10 and r10, 07fffffffh shr r11, 31 ; set counters that reached bailout to zero xor r9, r9 cmp r10, r8 cmove r10, r9 cmp r11, r8 cmove r11, r9 ; join two counters into one return register mov rax, r10 shl rax, 32 or rax, r11 mov rcx, 0 ; UNPREP movdqa xmm5, [rbp] movdqa xmm6, [rbp + 010h] movdqa xmm7, [rbp + 020h] movdqa xmm8, [rbp + 030h] movdqa xmm9, [rbp + 040h] movdqa xmm10, [rbp + 050h] movdqa xmm11, [rbp + 060h] movdqa xmm12, [rbp + 070h] movdqa xmm13, [rbp + 080h] movdqa xmm14, [rbp + 090h] movdqa xmm15, [rbp + 100h] ;ldmxcsr cw1 ; official epilog add rsp, 0200h pop rbp ret align 16 fours real8 4.0 real8 4.0 .data cw1 dword 0 cw2 dword 0 .code align 8 MandelbrotLineSSE2x64Two endp ;------------------------------------------------------------------------------------------- ; void ReadTimeStampCounter (void *pui64Clocks (rcx)); ; ; Query the cpu for clock count. ; Returns non-zero if the rdtsc instruction is available and clock count in *pui64Clocks. ; Returns zero if the rdtsc instruction is non available. Sets *pui64Clocks = 0. ;------------------------------------------------------------------------------------------- ;align 8 read_timestamp_counter proc frame ;.allocstack 0 .endprolog rdtsc ; query the clock stamp counter mov dword ptr [rcx], eax ; *pui64Clocks(low dword) = eax mov dword ptr [rcx + 4], edx ; *pui64Clocks(high dword) = edx ret ;align 8 read_timestamp_counter endp ;------------------------------------------------------------------------------------------- ; BOOL cpu_ident (DWORD aCpuInfo [4] (rcx), size_t InstructionRequestLevel (rdx)); ; ; Returns zero if the InstructionRequestLevel is not supported. ; Returns non-zero if the InstructionRequestLevel is supported. ;------------------------------------------------------------------------------------------- ;align 8 cpu_ident proc frame sub rsp, 8 ;.allocstack 8 mov [rsp], rbx ; Save rbx. .Savereg rbx, 0 .endprolog mov r8, rdx ; r8 = Instruction level request mov r9, rcx ; r9 -> dword array xor rax, rax ; rax = 0 cpuid cmp r8, rax ; Is the instruction level supported? jg short NotSupported ; No. Our requested instruction level ; is greater than the supported level. mov rax, r8 ; Yes, r8 <= the supported level. cpuid mov [r9], eax mov [r9 + 4], ebx mov [r9 + 8], ecx mov [r9 + 12], edx mov rax, -1 ; return non-zero jmp short Done ;align 8 NotSupported: xor rax, rax ; return zero mov [r9], rax ; and set all array values to zero mov [r9 + 4], rax mov [r9 + 8], rax mov [r9 + 12], rax ;align 8 Done: mov rbx, [rsp] add rsp, 8 ret ;align 8 cpu_ident endp end
;************************************************************************** ; MSR ECClib, an efficient and secure elliptic curve cryptographic library ; ; Copyright (c) Microsoft Corporation. All rights reserved. ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use these files 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. ; ; ; Abstract: field operations over GF(2^256-189) ; ; This software is based on the article by Joppe Bos, Craig Costello, ; Patrick Longa and Michael Naehrig, "Selecting elliptic curves for ; cryptography: an efficiency and security analysis", preprint available ; at http://eprint.iacr.org/2014/130. ;************************************************************************** include macamd64.inc P256_0 equ 18446744073709551427 ; Prime p = 2^256-189 P256_1 equ 18446744073709551615 P256_c equ 189 ; Value c in p = 2^256-c .code ;**************************************************************************************** ; (Constant-time) field multiplication using integer multiplication by product scanning ; Operation: c [r8] = a [rcx] * b [rdx] mod p, p = 2^256-189 ; NOTE: input should have r8 != rcx and r8 != rdx ; Inputs: a, b in [0, p-1] ; Output: c in [0, p-1] ;**************************************************************************************** NESTED_ENTRY fpmul256_a, _TEXT00 rex_push_reg rbx push_reg rdi push_reg r12 push_reg r13 END_PROLOGUE mov rbx, rdx mov rax, [rbx] mul qword ptr [rcx] ; a0*b0 mov r13, rax ; C0 mov r9, rdx xor r11, r11 mov rax, [rbx] mul qword ptr [rcx+8] ; a1*b0 add r9, rax mov r10, rdx adc r10, 0 mov rax, [rbx+8] ; a0*b1 mul qword ptr [rcx] add r9, rax adc r10, rdx ;adc r11, 0 setc r11b mov [r8+8], r9 ; C1 xor r9, r9 mov rax, [rbx] mul qword ptr [rcx+16] ; a2*b0 add r10, rax adc r11, rdx ;adc r9, 0 mov rax, [rbx+8] mul qword ptr [rcx+8] ; a1*b1 add r10, rax adc r11, rdx ;adc r9, 0 setc r9b mov rax, [rbx+16] mul qword ptr [rcx] ; a0*b2 add r10, rax mov [r8+16], r10 ; C2 adc r11, rdx adc r9, 0 xor r10, r10 mov rax, [rbx] mul qword ptr [rcx+24] ; a3*b0 add r11, rax adc r9, rdx ;adc r10, 0 setc r10b mov rax,[rbx+8] mul qword ptr [rcx+16] ; a2*b1 add r11, rax adc r9, rdx adc r10, 0 mov rax,[rbx+16] mul qword ptr [rcx+8] ; a1*b2 add r11, rax adc r9, rdx adc r10, 0 mov rax, [rbx+24] mul qword ptr [rcx] ; a0*b3 add r11, rax mov [r8+24], r11 ; C3 adc r9, rdx adc r10, 0 xor r11, r11 mov rax, [rbx+8] mul qword ptr [rcx+24] ; a3*b1 add r9, rax adc r10, rdx ;adc r11, 0 setc r11b mov rax, [rbx+16] mul qword ptr [rcx+16] ; a2*b2 add r9, rax adc r10, rdx adc r11, 0 mov rax, [rbx+24] mul qword ptr [rcx+8] ; a1*b3 add r9, rax mov rdi, r9 ; rdi = C4 adc r10, rdx adc r11, 0 xor r9, r9 mov rax, [rbx+16] mul qword ptr [rcx+24] ; a3*b2 add r10, rax adc r11, rdx ;adc r9, 0 setc r9b mov rax, [rbx+24] mul qword ptr [rcx+16] ; a2*b3 add r10, rax ; r10 = C5 adc r11, rdx adc r9, 0 mov rax, [rbx+24] mul qword ptr [rcx+24] ; a3*b3 add r11, rax ; r11 = C6 adc r9, rdx ; r9 = C7 ; Reduction mov rax, P256_c mul rdi add r13, rax ; r13 = partial0 adc rdx, 0 mov rdi, rdx xor r12, r12 mov rax, P256_c mul r10 add rax, rdi ;adc r12, 0 setc r12b mov r10, [r8+8] add r10, rax ; r10 = partial1 adc r12, rdx xor rdi, rdi mov rax, P256_c mul r11 add rax, r12 ;adc rdi, 0 setb dil mov r11, [r8+16] add r11, rax ; r11 = partial2 adc rdi, rdx xor r12, r12 mov rax, P256_c mul r9 add rax, rdi adc r12, 1 mov r9, [r8+24] add r9, rax ; r9 = partial3 adc rdx, r12 ; rdx = partial4 + 1 xor r12, r12 mov rax, P256_c mul rdx add r13, rax ; r13 = partial0 adc r10, 0 ; r10 = partial1 adc r11, 0 ; r11 = partial2 adc r9, 0 ; r9 = partial3 mov rax, P256_c ; final correction cmovc rax, r12 sub r13, rax mov [r8], r13 sbb r10, 0 mov [r8+8], r10 sbb r11, 0 mov [r8+16], r11 sbb r9, 0 mov [r8+24], r9 ifdef BEGIN_EPILOGUE BEGIN_EPILOGUE endif pop r13 pop r12 pop rdi pop rbx ret NESTED_END fpmul256_a, _TEXT00 ;**************************************************************************************** ; (Constant-time) field squaring using integer multiplication by product scanning ; Operation: c [rdx] = a [rcx]^2 mod p, p = 2^256-189 ; NOTE: input should have rdx != rcx ; Input: a in [0, p-1] ; Output: c in [0, p-1] ;**************************************************************************************** NESTED_ENTRY fpsqr256_a, _TEXT00 rex_push_reg rbx push_reg rdi push_reg r12 push_reg r13 END_PROLOGUE mov rbx, rdx xor r10, r10 mov rax, [rcx] mul qword ptr [rcx+8] add rax, rax mov r8, rax adc rdx, rdx mov r9, rdx ;adc r10, 0 ; 2*a0*a1 setb r10b mov rax, [rcx] mul qword ptr rax ; a0^2 mov [rbx], rax ; C0 add r8, rdx mov [rbx+8], r8 ; C1 adc r9, 0 xor rdi, rdi mov rax, [rcx] mul qword ptr [rcx+16] add rax, rax mov r8, rax adc rdx, rdx mov r11, rdx ;adc rdi, 0 ; 2*a0*a2 setb dil mov rax, [rcx+8] mul qword ptr [rcx+8] ; a1^2 add r8, rax adc r11, rdx adc rdi, 0 mov rax, [rcx] mul qword ptr [rcx+24] ; a0*a3 add r8, r9 mov [rbx+16], r8 ; C2 adc r11, r10 adc rdi, 0 mov r8, rax mov r10, rdx xor r9, r9 mov rax, [rcx+8] mul qword ptr [rcx+16] ; a1*a2 add r8, rax adc r10, rdx ;adc r9, 0 setb r9b add r8, r8 adc r10, r10 adc r9, r9 mov rax, [rcx+8] mul qword ptr [rcx+24] ; a1*a3 add r8, r11 mov [rbx+24], r8 ; C3 adc r10, rdi adc r9, 0 xor rdi, rdi add rax, rax ; 2*a1*a3 mov r8, rax adc rdx, rdx mov r11, rdx ;adc rdi, 0 setb dil mov rax, [rcx+16] mul qword ptr [rcx+16] ; a2^2 add r8, r10 adc r9, r11 adc rdi, 0 add r8, rax ; r8 = C4 ; mov [rbx+32], r8 adc r9, rdx adc rdi, 0 xor r11, r11 mov rax, [rcx+16] mul qword ptr [rcx+24] add rax, rax adc rdx, rdx ;adc r11, 0 ; 2*a2*a3 setb r11b add r9, rax ; r9 = C5 ; mov [rbx+40], r9 adc rdi, rdx adc r11, 0 mov rax, [rcx+24] mul qword ptr rax ; a3^2 add rdi, rax ; rdi = C6 ; mov [rbx+48], rdi adc r11, rdx ; r11 = C7 ; mov [rbx+56], r11 ; Reduction mov rax, P256_c mul qword ptr r8 mov r8, [rbx] add r8, rax ; r8 = partial0 adc rdx, 0 mov r10, rdx xor r12, r12 mov rax, P256_c mul qword ptr r9 add rax, r10 ;adc r12, 0 setb r12b mov r9, [rbx+8] add r9, rax ; r9 = partial1 adc r12, rdx xor rcx, rcx mov rax, P256_c mul qword ptr rdi add rax, r12 ;adc rcx, 0 setb cl mov rdi, [rbx+16] add rdi, rax ; rdi = partial2 adc rcx, rdx xor r10, r10 mov rax, P256_c mul qword ptr r11 add rax, rcx adc r10, 1 mov r11, [rbx+24] add r11, rax ; r11 = partial3 adc r10, rdx ; r10 = partial4 + 1 xor r12, r12 mov rax, P256_c mul qword ptr r10 add r8, rax ; r8 = partial0 adc r9, 0 ; r9 = partial1 adc rdi, 0 ; rdi = partial2 adc r11, 0 ; r11 = partial3 mov rax, P256_c ; final correction cmovc rax, r12 sub r8, rax mov [rbx], r8 sbb r9, 0 mov [rbx+8], r9 sbb rdi, 0 mov [rbx+16], rdi sbb r11, 0 mov [rbx+24], r11 ifdef BEGIN_EPILOGUE BEGIN_EPILOGUE endif pop r13 pop r12 pop rdi pop rbx ret NESTED_END fpsqr256_a, _TEXT00 ;**************************************************************************************** ; (Constant-time) field addition ; Operation: c [r8] = a [rcx] + b [rdx] mod p, p = 2^256-189 ; Inputs: a, b in [0, p-1] ; Output: c in [0, p-1] ;**************************************************************************************** LEAF_ENTRY fpadd256_a, _TEXT00 mov r9, [rcx] ; a + P256_c add r9, P256_c mov r10, [rcx+8] adc r10, 0 mov r11, [rcx+16] adc r11, 0 mov rax, [rcx+24] adc rax, 0 mov rcx, [rdx] ; (a+P256_c) + b add r9, rcx mov rcx, [rdx+8] adc r10, rcx mov rcx, [rdx+16] adc r11, rcx mov rcx, [rdx+24] adc rax, rcx mov rdx, 0 ; if (carry) then c = (a+P256_c) + b mov rcx, P256_c ; else c = (a+P256_c) + b - P256_c cmovc rcx, rdx sub r9, rcx mov [r8], r9 sbb r10, 0 mov [r8+8], r10 sbb r11, 0 mov [r8+16], r11 sbb rax, 0 mov [r8+24], rax ret LEAF_END fpadd256_a, _TEXT00 ;**************************************************************************************** ; (Constant-time) field subtraction ; Operation: c [r8] = a [rcx] + b [rdx] mod p, p = 2^256-189 ; Input: a, b in [0, p-1] ; Output: c in [0, p-1] ;**************************************************************************************** NESTED_ENTRY fpsub256_a, _TEXT00 rex_push_reg r12 END_PROLOGUE xor rax, rax ; a - b mov r9, [rcx] sub r9, [rdx] mov r10, [rcx+8] sbb r10, [rdx+8] mov r11, [rcx+16] sbb r11, [rdx+16] mov r12, [rcx+24] sbb r12, [rdx+24] mov rcx, P256_c ; if (carry) then c = (a-b) - P256_c cmovnc rcx, rax ; else c = a - b sub r9, rcx mov [r8], r9 sbb r10, 0 mov [r8+8], r10 sbb r11, 0 mov [r8+16], r11 sbb r12, 0 mov [r8+24], r12 ifdef BEGIN_EPILOGUE BEGIN_EPILOGUE endif pop r12 ret NESTED_END fpsub256_a, _TEXT00 ;**************************************************************************************** ; (Constant-time) field division by 2 ; Operation: a [rdx] = a [rcx]/2 mod p, p = 2^256-189 ; Input: a in [0, p-1] ; Output: c in [0, p-1] ;**************************************************************************************** LEAF_ENTRY fpdiv2_256_a, _TEXT00 xor r9, r9 mov r8, [rcx] bt r8, 0 mov r11, P256_0 cmovnc r11, r9 mov rax, P256_1 cmovnc rax, r9 add r8, r11 ; if (a mod 2 = 1) then temp = a + p mov r9, [rcx+8] ; else temp = a + 0 adc r9, rax mov r10, [rcx+16] adc r10, rax mov r11, [rcx+24] adc r11, rax mov rax, 0 adc rax, 0 shrd r8, r9, 1 ; c = temp/2 mov [rdx], r8 shrd r9, r10, 1 mov [rdx+8], r9 shrd r10, r11, 1 mov [rdx+16], r10 shrd r11, rax, 1 mov [rdx+24], r11 ret LEAF_END fpdiv2_256_a, _TEXT00 ;**************************************************************************************** ; (Constant-time) field negation and subtraction from a modulus ; Operation: a [rdx] = modulus [rcx] - a [rdx] ; if modulus = p = 2^256-189, then this performs a field negation -a (mod p) ; Input: a in [0, modulus-1] ; Output: a in [0, modulus-1], rax = 1 (TRUE) if a <= modulus ;**************************************************************************************** LEAF_ENTRY fpneg256_a, _TEXT00 xor rax, rax mov r9, [rcx] ; a = modulus - a sub r9, [rdx] mov [rdx], r9 mov r9, [rcx+8] sbb r9, [rdx+8] mov [rdx+8], r9 mov r9, [rcx+16] sbb r9, [rdx+16] mov [rdx+16], r9 mov r9, [rcx+24] sbb r9, [rdx+24] mov [rdx+24], r9 setnb al ret LEAF_END fpneg256_a, _TEXT00 ;********************************************************************************************************************* ; (Constant-time) Evaluation for the complete addition ; Operation: if [rcx] = 0 (P=-Q) then index=0, if [rdx] = 0 (P infinity) then index=1, if [r8] = 0 (P=Q) then index=2, ; else index=3 ; Output: if index(rax)=3 then mask [r9] = 0xff...ff, else mask [r9] = 0 ;********************************************************************************************************************** NESTED_ENTRY complete_eval_Jac256, _TEXT00 rex_push_reg r12 END_PROLOGUE xor rax, rax mov r11, 3 ; index 3 (P+Q) mov r12, [rcx] mov r10, [rcx+8] or r12, r10 mov r10, [rcx+16] or r12, r10 mov r10, [rcx+24] or r12, r10 cmovnz rax, r11 ; index 0 (P=-Q) if [rcx]=0 mov r11, 2 mov r10, [r8] or r12, r10 mov r10, [r8+8] or r12, r10 mov r10, [r8+16] or r12, r10 mov r10, [r8+24] or r12, r10 cmovz rax, r11 ; index 2 (P=Q) if [rcx] & [r8]=0 mov r11, 1 mov r12, [rdx] mov r10, [rdx+8] or r12, r10 mov r10, [rdx+16] or r12, r10 mov r10, [rdx+24] or r12, r10 cmovz rax, r11 ; index 1 (P infinity) if [rdx]=0 xor rcx, rcx mov r10, 18446744073709551615 mov r11, rax sub r11, 3 cmovz rcx, r10 ; mask = 0xff...f if index=3, else mask = 0 mov [r9], rcx ifdef BEGIN_EPILOGUE BEGIN_EPILOGUE endif pop r12 ret NESTED_END complete_eval_Jac256, _TEXT00 ;******************************************************************************************* ; (Constant-time) Field element selection for the complete addition ; Operation: if (r9)=0 then c [r8] = a [rcx], else if (r9) = 0xff...ff then c [r8] = b [rdx] ;******************************************************************************************* NESTED_ENTRY complete_select_Jac256, _TEXT00 alloc_stack 8 END_PROLOGUE xor rax, rax ;sub rsp, 8 mov [rsp], r9 vbroadcastss ymm0, DWORD PTR [rsp] vmovdqu ymm1, YMMWORD PTR [rcx] ; ymm1=a vmovdqu ymm2, YMMWORD PTR [rdx] ; ymm2=b vblendvpd ymm3, ymm1, ymm2, ymm0 ; if ymm0=0 then ymm3=a else ymm3=b vmovdqu YMMWORD PTR [r8], ymm3 mov [rsp], rax ; Clean stack add rsp, 8 ifdef BEGIN_EPILOGUE BEGIN_EPILOGUE endif ret NESTED_END complete_select_Jac256, _TEXT00 ;**************************************************************************************** ; (Constant-time) Point extraction from 4-LUT for the complete mixed addition ; Operation: use index (rdx) to extract point from [rcx] and pass it to [r8] ;**************************************************************************************** NESTED_ENTRY complete_lut4_Jac256, _TEXT00 alloc_stack 8 END_PROLOGUE xor rax, rax mov r11, 18446744073709551615 ;sub rsp, 8 vmovdqu ymm0, YMMWORD PTR [rcx] ; Load table[0] vmovdqu ymm1, YMMWORD PTR [rcx+32] vmovdqu ymm2, YMMWORD PTR [rcx+64] dec rdx ; Pass over table[1] cmovnz rax, r11 mov [rsp], rax vbroadcastss ymm4, DWORD PTR [rsp] vmovdqu ymm5, YMMWORD PTR [rcx+96] vblendvpd ymm0, ymm5, ymm0, ymm4 vmovdqu ymm5, YMMWORD PTR [rcx+128] vblendvpd ymm1, ymm5, ymm1, ymm4 vmovdqu ymm5, YMMWORD PTR [rcx+160] vblendvpd ymm2, ymm5, ymm2, ymm4 xor rax, rax ; Pass over table[2] dec rdx cmovnz rax, r11 mov [rsp], rax vbroadcastss ymm4, DWORD PTR [rsp] vmovdqu ymm5, YMMWORD PTR [rcx+192] vblendvpd ymm0, ymm5, ymm0, ymm4 vmovdqu ymm5, YMMWORD PTR [rcx+224] vblendvpd ymm1, ymm5, ymm1, ymm4 vmovdqu ymm5, YMMWORD PTR [rcx+256] vblendvpd ymm2, ymm5, ymm2, ymm4 xor rax, rax ; Pass over table[3] dec rdx cmovz r11, rax mov [rsp], r11 vbroadcastss ymm4, DWORD PTR [rsp] vmovdqu ymm5, YMMWORD PTR [rcx+288] vblendvpd ymm0, ymm5, ymm0, ymm4 vmovdqu ymm5, YMMWORD PTR [rcx+320] vblendvpd ymm1, ymm5, ymm1, ymm4 vmovdqu ymm5, YMMWORD PTR [rcx+352] vblendvpd ymm2, ymm5, ymm2, ymm4 mov [rsp], rax ; Clean stack vmovdqu YMMWORD PTR [r8], ymm0 ; [r8] = table[index] vmovdqu YMMWORD PTR [r8+32], ymm1 vmovdqu YMMWORD PTR [r8+64], ymm2 add rsp, 8 ifdef BEGIN_EPILOGUE BEGIN_EPILOGUE endif ret NESTED_END complete_lut4_Jac256, _TEXT00 ;**************************************************************************************** ; (Constant-time) Point extraction from 5-LUT for the complete addition ; Operation: use index (rdx) to extract point from [rcx] and pass it to [r8] ;**************************************************************************************** NESTED_ENTRY complete_lut5_Jac256, _TEXT00 alloc_stack 8 END_PROLOGUE xor rax, rax mov r11, 18446744073709551615 ;sub rsp, 8 vmovdqu ymm0, YMMWORD PTR [rcx] ; Load table[0] vmovdqu ymm1, YMMWORD PTR [rcx+32] vmovdqu ymm2, YMMWORD PTR [rcx+64] dec rdx ; Pass over table[1] cmovnz rax, r11 mov [rsp], rax vbroadcastss ymm4, DWORD PTR [rsp] vmovdqu ymm5, YMMWORD PTR [rcx+96] vblendvpd ymm0, ymm5, ymm0, ymm4 vmovdqu ymm5, YMMWORD PTR [rcx+128] vblendvpd ymm1, ymm5, ymm1, ymm4 vmovdqu ymm5, YMMWORD PTR [rcx+160] vblendvpd ymm2, ymm5, ymm2, ymm4 xor rax, rax ; Pass over table[2] dec rdx cmovnz rax, r11 mov [rsp], rax vbroadcastss ymm4, DWORD PTR [rsp] vmovdqu ymm5, YMMWORD PTR [rcx+192] vblendvpd ymm0, ymm5, ymm0, ymm4 vmovdqu ymm5, YMMWORD PTR [rcx+224] vblendvpd ymm1, ymm5, ymm1, ymm4 vmovdqu ymm5, YMMWORD PTR [rcx+256] vblendvpd ymm2, ymm5, ymm2, ymm4 xor rax, rax ; Pass over table[3] dec rdx cmovnz rax, r11 mov [rsp], rax vbroadcastss ymm4, DWORD PTR [rsp] vmovdqu ymm5, YMMWORD PTR [rcx+288] vblendvpd ymm0, ymm5, ymm0, ymm4 vmovdqu ymm5, YMMWORD PTR [rcx+320] vblendvpd ymm1, ymm5, ymm1, ymm4 vmovdqu ymm5, YMMWORD PTR [rcx+352] vblendvpd ymm2, ymm5, ymm2, ymm4 xor rax, rax ; Pass over table[4] dec rdx cmovz r11, rax mov [rsp], r11 vbroadcastss ymm4, DWORD PTR [rsp] vmovdqu ymm5, YMMWORD PTR [rcx+384] vblendvpd ymm0, ymm5, ymm0, ymm4 vmovdqu ymm5, YMMWORD PTR [rcx+416] vblendvpd ymm1, ymm5, ymm1, ymm4 vmovdqu ymm5, YMMWORD PTR [rcx+448] vblendvpd ymm2, ymm5, ymm2, ymm4 mov [rsp], rax ; Clean stack vmovdqu YMMWORD PTR [r8], ymm0 ; [r8] = table[index] vmovdqu YMMWORD PTR [r8+32], ymm1 vmovdqu YMMWORD PTR [r8+64], ymm2 add rsp, 8 ifdef BEGIN_EPILOGUE BEGIN_EPILOGUE endif ret NESTED_END complete_lut5_Jac256, _TEXT00 ;**************************************************************************************** ; Zeroing field element ;**************************************************************************************** LEAF_ENTRY fpzero256_a, _TEXT00 xor rax, rax mov [rcx], rax mov [rcx+8], rax mov [rcx+16], rax mov [rcx+24], rax ret LEAF_END fpzero256_a, _TEXT00 END
; ; Startup for special module special_crt0 ;-------- ; Include zcc_opt.def to find out some info ;-------- defc crt0 = 1 INCLUDE "zcc_opt.def" ;-------- ; Some scope definitions ;-------- EXTERN _main ;main() is always external to crt0 code EXTERN asm_im1_handler PUBLIC cleanup ;jp'd to by exit() PUBLIC l_dcal ;jp(hl) IF !CLIB_FGETC_CONS_DELAY defc CLIB_FGETC_CONS_DELAY = 150 ENDIF defc TAR__clib_exit_stack_size = 4 defc TAR__fputc_cons_generic = 1 defc TAR__register_sp = -1 defc CRT_KEY_DEL = 12 defc __CPU_CLOCK = 2000000 defc CONSOLE_COLUMNS = 48 defc CONSOLE_ROWS = 32 INCLUDE "crt/classic/crt_rules.inc" defc CRT_ORG_CODE = 0x0000 org CRT_ORG_CODE if (ASMPC<>$0000) defs CODE_ALIGNMENT_ERROR endif jp program defs $0008-ASMPC if (ASMPC<>$0008) defs CODE_ALIGNMENT_ERROR endif jp restart08 defs $0010-ASMPC if (ASMPC<>$0010) defs CODE_ALIGNMENT_ERROR endif jp restart10 defs $0018-ASMPC if (ASMPC<>$0018) defs CODE_ALIGNMENT_ERROR endif jp restart18 defs $0020-ASMPC if (ASMPC<>$0020) defs CODE_ALIGNMENT_ERROR endif jp restart20 defs $0028-ASMPC if (ASMPC<>$0028) defs CODE_ALIGNMENT_ERROR endif jp restart28 defs $0030-ASMPC if (ASMPC<>$0030) defs CODE_ALIGNMENT_ERROR endif jp restart30 defs $0038-ASMPC if (ASMPC<>$0038) defs CODE_ALIGNMENT_ERROR endif ret ; Restart routines, nothing sorted yet restart08: restart10: restart18: restart20: restart28: restart30: ret program: INCLUDE "crt/classic/crt_init_sp.asm" INCLUDE "crt/classic/crt_init_atexit.asm" call crt0_init_bss ld hl,0 add hl,sp ld (exitsp),hl ei ; Optional definition for auto MALLOC init ; it assumes we have free space between the end of ; the compiled program and the stack pointer IF DEFINED_USING_amalloc INCLUDE "crt/classic/crt_init_amalloc.asm" ENDIF push bc ;argv push bc ;argc call _main pop bc pop bc cleanup: push hl call crt0_exit pop hl jp $c800 l_dcal: jp (hl) ;Used for function pointer calls INCLUDE "crt/classic/crt_runtime_selection.asm" INCLUDE "crt/classic/crt_section.asm"
; A159845: Decimal expansion of (363 + 38*sqrt(2))/359. ; Submitted by Christian Krause ; 1,1,6,0,8,3,5,9,7,5,9,6,1,4,9,7,5,2,6,0,5,7,0,0,3,2,6,3,2,8,6,8,2,0,4,0,9,4,3,0,7,7,3,0,6,7,5,8,8,6,4,6,3,1,4,1,5,2,4,0,6,2,1,1,8,2,0,7,4,6,0,5,6,2,1,6,0,4,4,7,5,6,2,0,1,4,3,3,7,7,8,0,0,6,8,2,5,5,7,0 bin $1,$0 mov $2,2 mov $3,$0 mul $3,4 lpb $3 add $5,$2 add $1,$5 add $2,$1 mov $1,$2 sub $3,1 lpe mul $1,2 add $2,$5 mov $4,10 pow $4,$0 add $5,$2 div $2,6 mul $2,45 add $2,$5 div $2,$4 div $1,$2 mov $0,$1 mod $0,10
segment .data zero: dd 0.0 one: dd 1.0 neg1: dd -1.0 a: dd 1.75 b: dd 122.5 d dd 1.1 e dd 10000000000.0
// // immer: immutable data structures for C++ // Copyright (C) 2016, 2017, 2018 Juan Pedro Bolivar Puente // // This software is distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt // #pragma once #include <cstddef> #include <iterator> #include <type_traits> namespace immer { namespace detail { struct iterator_core_access { template <typename T> static decltype(auto) dereference(T&& x) { return x.dereference(); } template <typename T> static decltype(auto) increment(T&& x) { return x.increment(); } template <typename T> static decltype(auto) decrement(T&& x) { return x.decrement(); } template <typename T1, typename T2> static decltype(auto) equal(T1&& x1, T2&& x2) { return x1.equal(x2); } template <typename T, typename D> static decltype(auto) advance(T&& x, D d) { return x.advance(d); } template <typename T1, typename T2> static decltype(auto) distance_to(T1&& x1, T2&& x2) { return x1.distance_to(x2); } }; /*! * Minimalistic reimplementation of boost::iterator_facade */ template <typename DerivedT, typename IteratorCategoryT, typename T, typename ReferenceT = T&, typename DifferenceTypeT = std::ptrdiff_t, typename PointerT = T*> class iterator_facade { public: using iterator_category = IteratorCategoryT; using value_type = T; using difference_type = DifferenceTypeT; using pointer = PointerT; using reference = ReferenceT; protected: using access_t = iterator_core_access; constexpr static auto is_random_access = std::is_base_of<std::random_access_iterator_tag, IteratorCategoryT>::value; constexpr static auto is_bidirectional = std::is_base_of<std::bidirectional_iterator_tag, IteratorCategoryT>::value; class reference_proxy { friend iterator_facade; DerivedT iter_; reference_proxy(DerivedT iter) : iter_{std::move(iter)} {} public: operator ReferenceT() const { return *iter_; } }; const DerivedT& derived() const { static_assert(std::is_base_of<iterator_facade, DerivedT>::value, "must pass a derived thing"); return *static_cast<const DerivedT*>(this); } DerivedT& derived() { static_assert(std::is_base_of<iterator_facade, DerivedT>::value, "must pass a derived thing"); return *static_cast<DerivedT*>(this); } public: ReferenceT operator*() const { return access_t::dereference(derived()); } PointerT operator->() const { return &access_t::dereference(derived()); } reference_proxy operator[](DifferenceTypeT n) const { static_assert(is_random_access, ""); return derived() + n; } bool operator==(const DerivedT& rhs) const { return access_t::equal(derived(), rhs); } bool operator!=(const DerivedT& rhs) const { return !access_t::equal(derived(), rhs); } DerivedT& operator++() { access_t::increment(derived()); return derived(); } DerivedT operator++(int) { auto tmp = derived(); access_t::increment(derived()); return tmp; } DerivedT& operator--() { static_assert(is_bidirectional || is_random_access, ""); access_t::decrement(derived()); return derived(); } DerivedT operator--(int) { static_assert(is_bidirectional || is_random_access, ""); auto tmp = derived(); access_t::decrement(derived()); return tmp; } DerivedT& operator+=(DifferenceTypeT n) { access_t::advance(derived(), n); return derived(); } DerivedT& operator-=(DifferenceTypeT n) { access_t::advance(derived(), -n); return derived(); } DerivedT operator+(DifferenceTypeT n) const { static_assert(is_random_access, ""); auto tmp = derived(); return tmp += n; } friend DerivedT operator+(DifferenceTypeT n, const DerivedT& i) { static_assert(is_random_access, ""); return i + n; } DerivedT operator-(DifferenceTypeT n) const { static_assert(is_random_access, ""); auto tmp = derived(); return tmp -= n; } DifferenceTypeT operator-(const DerivedT& rhs) const { static_assert(is_random_access, ""); return access_t::distance_to(rhs, derived()); } bool operator<(const DerivedT& rhs) const { static_assert(is_random_access, ""); return access_t::distance_to(derived(), rhs) > 0; } bool operator<=(const DerivedT& rhs) const { static_assert(is_random_access, ""); return access_t::distance_to(derived(), rhs) >= 0; } bool operator>(const DerivedT& rhs) const { static_assert(is_random_access, ""); return access_t::distance_to(derived(), rhs) < 0; } bool operator>=(const DerivedT& rhs) const { static_assert(is_random_access, ""); return access_t::distance_to(derived(), rhs) <= 0; } }; } // namespace detail } // namespace immer
/* * Enable keypress to stop optimization. * * Author: Jason Bunk * Web page: http://sites.google.com/site/jasonbunk * * Copyright (c) 2015 Jason Bunk * 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 "EnableKeyPressToStopOptimization.h" #include "RunSimulation.h" #include "Utils/SUtils.h" #include <thread> #include <fstream> #include <iostream> using std::cout; using std::endl; /*extern*/ BestNLOptScoreSoFar nloptsofar__best_score_data = BestNLOptScoreSoFar(); /*extern*/ bool global__key_has_been_pressed = false; static void WaitingThreadGoHere(bool exit_immediately) { getchar(); cout<<"EnableKeypressToStop's WaitingThreadGoHere() is locking the mutex"<<endl; nloptsofar__best_score_data.my_mutex.lock(); nloptsofar__best_score_data.force_stop = true; nloptsofar__best_score_data.my_mutex.unlock(); cout<<"EnableKeypressToStop told nlopt to halt..."<<endl; /*nloptsofar__best_score_data.thethread->join(); delete nloptsofar__best_score_data.thethread; nloptsofar__best_score_data.thethread = nullptr;*/ /*if(exit_immediately) { exit(0); } global__key_has_been_pressed = true;*/ /* SimulationDebugStats returnedStats; nloptsofar__best_score_data.my_mutex.lock(); cout<<"...prematurely quit. nlopts best score: "<<nloptsofar__best_score_data.my_best_score<<endl; cout<<"this required "<<nloptsofar__best_score_data.num_iterations_so_far<<" function evaluations (simulations)!"<<endl; nloptsofar__best_score_data.my_nloptdata.controllerOwningTheseParams->GetMyController4Dcstyle().givenGridOverride = nloptsofar__best_score_data.my_best_params; std::ofstream * outfile = new std::ofstream(std::string("output/nlopt_results_controller_")+to_istring(nloptsofar__best_score_data.which_algorithm)+std::string(".txt")); (*outfile) << (nloptsofar__best_score_data.my_nloptdata.controllerOwningTheseParams->GetMyController4Dcstyle()); outfile->close(); delete outfile; outfile = nullptr; cout<<"---------------------------------------------- testing this controller, and saving an interpolateable file (for use with controllers with different grids)"<<endl; outfile = new std::ofstream(std::string("output/nlopt_controller_interpolable_")+to_istring(nloptsofar__best_score_data.which_algorithm)+std::string(".out")); nloptsofar__best_score_data.my_nloptdata.testCart->set__theta(nloptsofar__best_score_data.my_nloptdata.initial_theta); nloptsofar__best_score_data.my_nloptdata.testCart->set__omega(nloptsofar__best_score_data.my_nloptdata.initial_omega); nloptsofar__best_score_data.my_nloptdata.testCart->set__cartx(nloptsofar__best_score_data.my_nloptdata.initial_cartx); nloptsofar__best_score_data.my_nloptdata.testCart->set__cartvel(nloptsofar__best_score_data.my_nloptdata.initial_cartv); RunSimulation(nloptsofar__best_score_data.my_nloptdata.testCart, nloptsofar__best_score_data.my_nloptdata.controllerOwningTheseParams, ScoreThatFrame, outfile, true, &returnedStats); returnedStats.Print(); exit(0);*/ } void EnableKeyPressToStopOptimizing(bool exit_when_pressed) { global__key_has_been_pressed = false; std::thread* keypress_waitingthread = new std::thread(WaitingThreadGoHere, exit_when_pressed); }
; ; This file is automatically generated ; ; Do not edit!!! ; ; djm 12/2/2000 ; ; ZSock Lib function: sock_write XLIB sock_write LIB no_zsock INCLUDE "#packages.def" INCLUDE "#zsock.def" .sock_write ld a,r_sock_write call_pkg(tcp_all) ret nc ; We failed..are we installed? cp rc_pnf scf ;signal error ret nz ;Internal error call_pkg(tcp_ayt) jr nc,sock_write jp no_zsock
// Copyright (c) 2012-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <util.h> #include <test/test_veil.h> #include <string> #include <vector> #include <boost/algorithm/string.hpp> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(getarg_tests, BasicTestingSetup) static void ResetArgs(const std::string& strArg) { std::vector<std::string> vecArg; if (strArg.size()) boost::split(vecArg, strArg, boost::is_space(), boost::token_compress_on); // Insert dummy executable name: vecArg.insert(vecArg.begin(), "testbitcoin"); // Convert to char*: std::vector<const char*> vecChar; for (std::string& s : vecArg) vecChar.push_back(s.c_str()); std::string error; gArgs.ParseParameters(vecChar.size(), vecChar.data(), error); } static void SetupArgs(const std::vector<std::string>& args) { gArgs.ClearArgs(); for (const std::string& arg : args) { gArgs.AddArg(arg, "", false, OptionsCategory::OPTIONS); } } BOOST_AUTO_TEST_CASE(boolarg) { SetupArgs({"-foo"}); ResetArgs("-foo"); BOOST_CHECK(gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(gArgs.GetBoolArg("-foo", true)); BOOST_CHECK(!gArgs.GetBoolArg("-fo", false)); BOOST_CHECK(gArgs.GetBoolArg("-fo", true)); BOOST_CHECK(!gArgs.GetBoolArg("-fooo", false)); BOOST_CHECK(gArgs.GetBoolArg("-fooo", true)); ResetArgs("-foo=0"); BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); ResetArgs("-foo=1"); BOOST_CHECK(gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(gArgs.GetBoolArg("-foo", true)); // New 0.6 feature: auto-map -nosomething to !-something: ResetArgs("-nofoo"); BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); ResetArgs("-nofoo=1"); BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); ResetArgs("-foo -nofoo"); // -nofoo should win BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); ResetArgs("-foo=1 -nofoo=1"); // -nofoo should win BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); ResetArgs("-foo=0 -nofoo=0"); // -nofoo=0 should win BOOST_CHECK(gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(gArgs.GetBoolArg("-foo", true)); // New 0.6 feature: treat -- same as -: ResetArgs("--foo=1"); BOOST_CHECK(gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(gArgs.GetBoolArg("-foo", true)); ResetArgs("--nofoo=1"); BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); } BOOST_AUTO_TEST_CASE(stringarg) { SetupArgs({"-foo", "-bar"}); ResetArgs(""); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), ""); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", "eleven"), "eleven"); ResetArgs("-foo -bar"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), ""); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", "eleven"), ""); ResetArgs("-foo="); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), ""); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", "eleven"), ""); ResetArgs("-foo=11"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), "11"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", "eleven"), "11"); ResetArgs("-foo=eleven"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), "eleven"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", "eleven"), "eleven"); } BOOST_AUTO_TEST_CASE(intarg) { SetupArgs({"-foo", "-bar"}); ResetArgs(""); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", 11), 11); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", 0), 0); ResetArgs("-foo -bar"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", 11), 0); BOOST_CHECK_EQUAL(gArgs.GetArg("-bar", 11), 0); ResetArgs("-foo=11 -bar=12"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", 0), 11); BOOST_CHECK_EQUAL(gArgs.GetArg("-bar", 11), 12); ResetArgs("-foo=NaN -bar=NotANumber"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", 1), 0); BOOST_CHECK_EQUAL(gArgs.GetArg("-bar", 11), 0); } BOOST_AUTO_TEST_CASE(doubledash) { SetupArgs({"-foo", "-bar"}); ResetArgs("--foo"); BOOST_CHECK_EQUAL(gArgs.GetBoolArg("-foo", false), true); ResetArgs("--foo=verbose --bar=1"); BOOST_CHECK_EQUAL(gArgs.GetArg("-foo", ""), "verbose"); BOOST_CHECK_EQUAL(gArgs.GetArg("-bar", 0), 1); } BOOST_AUTO_TEST_CASE(boolargno) { SetupArgs({"-foo", "-bar"}); ResetArgs("-nofoo"); BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); ResetArgs("-nofoo=1"); BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); ResetArgs("-nofoo=0"); BOOST_CHECK(gArgs.GetBoolArg("-foo", true)); BOOST_CHECK(gArgs.GetBoolArg("-foo", false)); ResetArgs("-foo --nofoo"); // --nofoo should win BOOST_CHECK(!gArgs.GetBoolArg("-foo", true)); BOOST_CHECK(!gArgs.GetBoolArg("-foo", false)); ResetArgs("-nofoo -foo"); // foo always wins: BOOST_CHECK(gArgs.GetBoolArg("-foo", true)); BOOST_CHECK(gArgs.GetBoolArg("-foo", false)); } BOOST_AUTO_TEST_SUITE_END()
; A033033: Numbers all of whose base 7 digits are odd. ; Submitted by Simon Strandgaard ; 1,3,5,8,10,12,22,24,26,36,38,40,57,59,61,71,73,75,85,87,89,155,157,159,169,171,173,183,185,187,253,255,257,267,269,271,281,283,285,400,402,404,414,416,418,428,430,432,498,500,502,512,514,516,526,528,530,596,598,600,610,612,614,624,626,628,1086,1088,1090,1100,1102,1104,1114,1116,1118,1184,1186,1188,1198,1200,1202,1212,1214,1216,1282,1284,1286,1296,1298,1300,1310,1312,1314,1772,1774,1776,1786,1788,1790,1800 add $0,1 mov $2,1 lpb $0 mul $0,2 sub $0,1 mov $3,$0 div $0,6 mod $3,6 mul $3,$2 add $1,$3 mul $2,7 lpe mov $0,$1
#include "extensions/filters/http/grpc_http1_bridge/http1_bridge_filter.h" #include <cstdint> #include <string> #include <vector> #include "envoy/http/codes.h" #include "common/common/enum_to_int.h" #include "common/common/utility.h" #include "common/grpc/common.h" #include "common/http/headers.h" #include "common/http/http1/codec_impl.h" namespace Envoy { namespace Extensions { namespace HttpFilters { namespace GrpcHttp1Bridge { void Http1BridgeFilter::chargeStat(const Http::HeaderMap& headers) { Grpc::Common::chargeStat(*cluster_, "grpc", grpc_service_, grpc_method_, headers.GrpcStatus()); } Http::FilterHeadersStatus Http1BridgeFilter::decodeHeaders(Http::HeaderMap& headers, bool) { const bool grpc_request = Grpc::Common::hasGrpcContentType(headers); if (grpc_request) { setupStatTracking(headers); } const absl::optional<Http::Protocol>& protocol = decoder_callbacks_->streamInfo().protocol(); ASSERT(protocol); if (protocol.value() != Http::Protocol::Http2 && grpc_request) { do_bridging_ = true; } return Http::FilterHeadersStatus::Continue; } Http::FilterHeadersStatus Http1BridgeFilter::encodeHeaders(Http::HeaderMap& headers, bool end_stream) { if (do_stat_tracking_) { chargeStat(headers); } if (!do_bridging_ || end_stream) { return Http::FilterHeadersStatus::Continue; } else { response_headers_ = &headers; return Http::FilterHeadersStatus::StopIteration; } } Http::FilterDataStatus Http1BridgeFilter::encodeData(Buffer::Instance&, bool end_stream) { if (!do_bridging_ || end_stream) { return Http::FilterDataStatus::Continue; } else { // Buffer until the complete request has been processed. return Http::FilterDataStatus::StopIterationAndBuffer; } } Http::FilterTrailersStatus Http1BridgeFilter::encodeTrailers(Http::HeaderMap& trailers) { if (do_stat_tracking_) { chargeStat(trailers); } if (do_bridging_) { // Here we check for grpc-status. If it's not zero, we change the response code. We assume // that if a reset comes in and we disconnect the HTTP/1.1 client it will raise some type // of exception/error that the response was not complete. const Http::HeaderEntry* grpc_status_header = trailers.GrpcStatus(); if (grpc_status_header) { uint64_t grpc_status_code; // TODO(dnoe): Migrate to pure string_view to eliminate std:string instance (#6580) std::string grpc_status_code_string(grpc_status_header->value().getStringView()); if (!StringUtil::atoull(grpc_status_code_string.c_str(), grpc_status_code) || grpc_status_code != 0) { response_headers_->Status()->value(enumToInt(Http::Code::ServiceUnavailable)); } response_headers_->insertGrpcStatus().value(*grpc_status_header); } const Http::HeaderEntry* grpc_message_header = trailers.GrpcMessage(); if (grpc_message_header) { response_headers_->insertGrpcMessage().value(*grpc_message_header); } // Since we are buffering, set content-length so that HTTP/1.1 callers can better determine // if this is a complete response. response_headers_->insertContentLength().value( encoder_callbacks_->encodingBuffer() ? encoder_callbacks_->encodingBuffer()->length() : 0); } // NOTE: We will still write the trailers, but the HTTP/1.1 codec will just eat them and end // the chunk encoded response which is what we want. return Http::FilterTrailersStatus::Continue; } void Http1BridgeFilter::setupStatTracking(const Http::HeaderMap& headers) { cluster_ = decoder_callbacks_->clusterInfo(); if (!cluster_) { return; } do_stat_tracking_ = Grpc::Common::resolveServiceAndMethod(headers.Path(), &grpc_service_, &grpc_method_); } } // namespace GrpcHttp1Bridge } // namespace HttpFilters } // namespace Extensions } // namespace Envoy
; A100207: a(n) = 4 + 8*n + 10*n^2 + 4*n^3. ; 4,26,92,226,452,794,1276,1922,2756,3802,5084,6626,8452,10586,13052,15874,19076,22682,26716,31202,36164,41626,47612,54146,61252,68954,77276,86242,95876,106202,117244,129026,141572,154906,169052,184034,199876,216602,234236,252802,272324,292826,314332,336866,360452,385114,410876,437762,465796,495002,525404,557026,589892,624026,659452,696194,734276,773722,814556,856802,900484,945626,992252,1040386,1090052,1141274,1194076,1248482,1304516,1362202,1421564,1482626,1545412,1609946,1676252,1744354,1814276,1886042,1959676,2035202,2112644,2192026,2273372,2356706,2442052,2529434,2618876,2710402,2804036,2899802,2997724,3097826,3200132,3304666,3411452,3520514,3631876,3745562,3861596,3980002,4100804,4224026,4349692,4477826,4608452,4741594,4877276,5015522,5156356,5299802,5445884,5594626,5746052,5900186,6057052,6216674,6379076,6544282,6712316,6883202,7056964,7233626,7413212,7595746,7781252,7969754,8161276,8355842,8553476,8754202,8958044,9165026,9375172,9588506,9805052,10024834,10247876,10474202,10703836,10936802,11173124,11412826,11655932,11902466,12152452,12405914,12662876,12923362,13187396,13455002,13726204,14001026,14279492,14561626,14847452,15136994,15430276,15727322,16028156,16332802,16641284,16953626,17269852,17589986,17914052,18242074,18574076,18910082,19250116,19594202,19942364,20294626,20651012,21011546,21376252,21745154,22118276,22495642,22877276,23263202,23653444,24048026,24446972,24850306,25258052,25670234,26086876,26508002,26933636,27363802,27798524,28237826,28681732,29130266,29583452,30041314,30503876,30971162,31443196,31920002,32401604,32888026,33379292,33875426,34376452,34882394,35393276,35909122,36429956,36955802,37486684,38022626,38563652,39109786,39661052,40217474,40779076,41345882,41917916,42495202,43077764,43665626,44258812,44857346,45461252,46070554,46685276,47305442,47931076,48562202,49198844,49841026,50488772,51142106,51801052,52465634,53135876,53811802,54493436,55180802,55873924,56572826,57277532,57988066,58704452,59426714,60154876,60888962,61628996,62375002 add $0,1 mov $1,2 mul $1,$0 bin $1,2 mul $1,$0 add $1,1 mul $1,2
; A056992: Digital roots of square numbers A000290. ; 1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4,1,9,1,4,9,7,7,9,4 mov $1,$0 add $0,2 mul $1,$0 mod $1,9 add $1,1
user/_sh: file format elf64-littleriscv Disassembly of section .text: 0000000000000000 <getcmd>: exit(0); } int getcmd(char *buf, int nbuf) { 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: e04a sd s2,0(sp) a: 1000 addi s0,sp,32 c: 84aa mv s1,a0 e: 892e mv s2,a1 fprintf(2, "$ "); 10: 00001597 auipc a1,0x1 14: 2e858593 addi a1,a1,744 # 12f8 <malloc+0xe8> 18: 4509 li a0,2 1a: 00001097 auipc ra,0x1 1e: 10a080e7 jalr 266(ra) # 1124 <fprintf> memset(buf, 0, nbuf); 22: 864a mv a2,s2 24: 4581 li a1,0 26: 8526 mv a0,s1 28: 00001097 auipc ra,0x1 2c: b9e080e7 jalr -1122(ra) # bc6 <memset> gets(buf, nbuf); 30: 85ca mv a1,s2 32: 8526 mv a0,s1 34: 00001097 auipc ra,0x1 38: bdc080e7 jalr -1060(ra) # c10 <gets> if(buf[0] == 0) // EOF 3c: 0004c503 lbu a0,0(s1) 40: 00153513 seqz a0,a0 return -1; return 0; } 44: 40a00533 neg a0,a0 48: 60e2 ld ra,24(sp) 4a: 6442 ld s0,16(sp) 4c: 64a2 ld s1,8(sp) 4e: 6902 ld s2,0(sp) 50: 6105 addi sp,sp,32 52: 8082 ret 0000000000000054 <panic>: exit(0); } void panic(char *s) { 54: 1141 addi sp,sp,-16 56: e406 sd ra,8(sp) 58: e022 sd s0,0(sp) 5a: 0800 addi s0,sp,16 5c: 862a mv a2,a0 fprintf(2, "%s\n", s); 5e: 00001597 auipc a1,0x1 62: 2a258593 addi a1,a1,674 # 1300 <malloc+0xf0> 66: 4509 li a0,2 68: 00001097 auipc ra,0x1 6c: 0bc080e7 jalr 188(ra) # 1124 <fprintf> exit(1); 70: 4505 li a0,1 72: 00001097 auipc ra,0x1 76: d58080e7 jalr -680(ra) # dca <exit> 000000000000007a <fork1>: } int fork1(void) { 7a: 1141 addi sp,sp,-16 7c: e406 sd ra,8(sp) 7e: e022 sd s0,0(sp) 80: 0800 addi s0,sp,16 int pid; pid = fork(); 82: 00001097 auipc ra,0x1 86: d40080e7 jalr -704(ra) # dc2 <fork> if(pid == -1) 8a: 57fd li a5,-1 8c: 00f50663 beq a0,a5,98 <fork1+0x1e> panic("fork"); return pid; } 90: 60a2 ld ra,8(sp) 92: 6402 ld s0,0(sp) 94: 0141 addi sp,sp,16 96: 8082 ret panic("fork"); 98: 00001517 auipc a0,0x1 9c: 27050513 addi a0,a0,624 # 1308 <malloc+0xf8> a0: 00000097 auipc ra,0x0 a4: fb4080e7 jalr -76(ra) # 54 <panic> 00000000000000a8 <runcmd>: { a8: 7179 addi sp,sp,-48 aa: f406 sd ra,40(sp) ac: f022 sd s0,32(sp) ae: ec26 sd s1,24(sp) b0: 1800 addi s0,sp,48 if(cmd == 0) b2: c10d beqz a0,d4 <runcmd+0x2c> b4: 84aa mv s1,a0 switch(cmd->type){ b6: 4118 lw a4,0(a0) b8: 4795 li a5,5 ba: 02e7e263 bltu a5,a4,de <runcmd+0x36> be: 00056783 lwu a5,0(a0) c2: 078a slli a5,a5,0x2 c4: 00001717 auipc a4,0x1 c8: 34470713 addi a4,a4,836 # 1408 <malloc+0x1f8> cc: 97ba add a5,a5,a4 ce: 439c lw a5,0(a5) d0: 97ba add a5,a5,a4 d2: 8782 jr a5 exit(1); d4: 4505 li a0,1 d6: 00001097 auipc ra,0x1 da: cf4080e7 jalr -780(ra) # dca <exit> panic("runcmd"); de: 00001517 auipc a0,0x1 e2: 23250513 addi a0,a0,562 # 1310 <malloc+0x100> e6: 00000097 auipc ra,0x0 ea: f6e080e7 jalr -146(ra) # 54 <panic> if(ecmd->argv[0] == 0) ee: 6508 ld a0,8(a0) f0: c515 beqz a0,11c <runcmd+0x74> exec(ecmd->argv[0], ecmd->argv); f2: 00848593 addi a1,s1,8 f6: 00001097 auipc ra,0x1 fa: d0c080e7 jalr -756(ra) # e02 <exec> fprintf(2, "exec %s failed\n", ecmd->argv[0]); fe: 6490 ld a2,8(s1) 100: 00001597 auipc a1,0x1 104: 21858593 addi a1,a1,536 # 1318 <malloc+0x108> 108: 4509 li a0,2 10a: 00001097 auipc ra,0x1 10e: 01a080e7 jalr 26(ra) # 1124 <fprintf> exit(0); 112: 4501 li a0,0 114: 00001097 auipc ra,0x1 118: cb6080e7 jalr -842(ra) # dca <exit> exit(1); 11c: 4505 li a0,1 11e: 00001097 auipc ra,0x1 122: cac080e7 jalr -852(ra) # dca <exit> close(rcmd->fd); 126: 5148 lw a0,36(a0) 128: 00001097 auipc ra,0x1 12c: cca080e7 jalr -822(ra) # df2 <close> if(open(rcmd->file, rcmd->mode) < 0){ 130: 508c lw a1,32(s1) 132: 6888 ld a0,16(s1) 134: 00001097 auipc ra,0x1 138: cd6080e7 jalr -810(ra) # e0a <open> 13c: 00054763 bltz a0,14a <runcmd+0xa2> runcmd(rcmd->cmd); 140: 6488 ld a0,8(s1) 142: 00000097 auipc ra,0x0 146: f66080e7 jalr -154(ra) # a8 <runcmd> fprintf(2, "open %s failed\n", rcmd->file); 14a: 6890 ld a2,16(s1) 14c: 00001597 auipc a1,0x1 150: 1dc58593 addi a1,a1,476 # 1328 <malloc+0x118> 154: 4509 li a0,2 156: 00001097 auipc ra,0x1 15a: fce080e7 jalr -50(ra) # 1124 <fprintf> exit(1); 15e: 4505 li a0,1 160: 00001097 auipc ra,0x1 164: c6a080e7 jalr -918(ra) # dca <exit> if(fork1() == 0) 168: 00000097 auipc ra,0x0 16c: f12080e7 jalr -238(ra) # 7a <fork1> 170: c919 beqz a0,186 <runcmd+0xde> wait(0); 172: 4501 li a0,0 174: 00001097 auipc ra,0x1 178: c5e080e7 jalr -930(ra) # dd2 <wait> runcmd(lcmd->right); 17c: 6888 ld a0,16(s1) 17e: 00000097 auipc ra,0x0 182: f2a080e7 jalr -214(ra) # a8 <runcmd> runcmd(lcmd->left); 186: 6488 ld a0,8(s1) 188: 00000097 auipc ra,0x0 18c: f20080e7 jalr -224(ra) # a8 <runcmd> if(pipe(p) < 0) 190: fd840513 addi a0,s0,-40 194: 00001097 auipc ra,0x1 198: c46080e7 jalr -954(ra) # dda <pipe> 19c: 04054363 bltz a0,1e2 <runcmd+0x13a> if(fork1() == 0){ 1a0: 00000097 auipc ra,0x0 1a4: eda080e7 jalr -294(ra) # 7a <fork1> 1a8: c529 beqz a0,1f2 <runcmd+0x14a> if(fork1() == 0){ 1aa: 00000097 auipc ra,0x0 1ae: ed0080e7 jalr -304(ra) # 7a <fork1> 1b2: cd25 beqz a0,22a <runcmd+0x182> close(p[0]); 1b4: fd842503 lw a0,-40(s0) 1b8: 00001097 auipc ra,0x1 1bc: c3a080e7 jalr -966(ra) # df2 <close> close(p[1]); 1c0: fdc42503 lw a0,-36(s0) 1c4: 00001097 auipc ra,0x1 1c8: c2e080e7 jalr -978(ra) # df2 <close> wait(0); 1cc: 4501 li a0,0 1ce: 00001097 auipc ra,0x1 1d2: c04080e7 jalr -1020(ra) # dd2 <wait> wait(0); 1d6: 4501 li a0,0 1d8: 00001097 auipc ra,0x1 1dc: bfa080e7 jalr -1030(ra) # dd2 <wait> break; 1e0: bf0d j 112 <runcmd+0x6a> panic("pipe"); 1e2: 00001517 auipc a0,0x1 1e6: 15650513 addi a0,a0,342 # 1338 <malloc+0x128> 1ea: 00000097 auipc ra,0x0 1ee: e6a080e7 jalr -406(ra) # 54 <panic> close(1); 1f2: 4505 li a0,1 1f4: 00001097 auipc ra,0x1 1f8: bfe080e7 jalr -1026(ra) # df2 <close> dup(p[1]); 1fc: fdc42503 lw a0,-36(s0) 200: 00001097 auipc ra,0x1 204: c42080e7 jalr -958(ra) # e42 <dup> close(p[0]); 208: fd842503 lw a0,-40(s0) 20c: 00001097 auipc ra,0x1 210: be6080e7 jalr -1050(ra) # df2 <close> close(p[1]); 214: fdc42503 lw a0,-36(s0) 218: 00001097 auipc ra,0x1 21c: bda080e7 jalr -1062(ra) # df2 <close> runcmd(pcmd->left); 220: 6488 ld a0,8(s1) 222: 00000097 auipc ra,0x0 226: e86080e7 jalr -378(ra) # a8 <runcmd> close(0); 22a: 00001097 auipc ra,0x1 22e: bc8080e7 jalr -1080(ra) # df2 <close> dup(p[0]); 232: fd842503 lw a0,-40(s0) 236: 00001097 auipc ra,0x1 23a: c0c080e7 jalr -1012(ra) # e42 <dup> close(p[0]); 23e: fd842503 lw a0,-40(s0) 242: 00001097 auipc ra,0x1 246: bb0080e7 jalr -1104(ra) # df2 <close> close(p[1]); 24a: fdc42503 lw a0,-36(s0) 24e: 00001097 auipc ra,0x1 252: ba4080e7 jalr -1116(ra) # df2 <close> runcmd(pcmd->right); 256: 6888 ld a0,16(s1) 258: 00000097 auipc ra,0x0 25c: e50080e7 jalr -432(ra) # a8 <runcmd> if(fork1() == 0) 260: 00000097 auipc ra,0x0 264: e1a080e7 jalr -486(ra) # 7a <fork1> 268: ea0515e3 bnez a0,112 <runcmd+0x6a> runcmd(bcmd->cmd); 26c: 6488 ld a0,8(s1) 26e: 00000097 auipc ra,0x0 272: e3a080e7 jalr -454(ra) # a8 <runcmd> 0000000000000276 <execcmd>: //PAGEBREAK! // Constructors struct cmd* execcmd(void) { 276: 1101 addi sp,sp,-32 278: ec06 sd ra,24(sp) 27a: e822 sd s0,16(sp) 27c: e426 sd s1,8(sp) 27e: 1000 addi s0,sp,32 struct execcmd *cmd; cmd = malloc(sizeof(*cmd)); 280: 0a800513 li a0,168 284: 00001097 auipc ra,0x1 288: f8c080e7 jalr -116(ra) # 1210 <malloc> 28c: 84aa mv s1,a0 memset(cmd, 0, sizeof(*cmd)); 28e: 0a800613 li a2,168 292: 4581 li a1,0 294: 00001097 auipc ra,0x1 298: 932080e7 jalr -1742(ra) # bc6 <memset> cmd->type = EXEC; 29c: 4785 li a5,1 29e: c09c sw a5,0(s1) return (struct cmd*)cmd; } 2a0: 8526 mv a0,s1 2a2: 60e2 ld ra,24(sp) 2a4: 6442 ld s0,16(sp) 2a6: 64a2 ld s1,8(sp) 2a8: 6105 addi sp,sp,32 2aa: 8082 ret 00000000000002ac <redircmd>: struct cmd* redircmd(struct cmd *subcmd, char *file, char *efile, int mode, int fd) { 2ac: 7139 addi sp,sp,-64 2ae: fc06 sd ra,56(sp) 2b0: f822 sd s0,48(sp) 2b2: f426 sd s1,40(sp) 2b4: f04a sd s2,32(sp) 2b6: ec4e sd s3,24(sp) 2b8: e852 sd s4,16(sp) 2ba: e456 sd s5,8(sp) 2bc: e05a sd s6,0(sp) 2be: 0080 addi s0,sp,64 2c0: 8b2a mv s6,a0 2c2: 8aae mv s5,a1 2c4: 8a32 mv s4,a2 2c6: 89b6 mv s3,a3 2c8: 893a mv s2,a4 struct redircmd *cmd; cmd = malloc(sizeof(*cmd)); 2ca: 02800513 li a0,40 2ce: 00001097 auipc ra,0x1 2d2: f42080e7 jalr -190(ra) # 1210 <malloc> 2d6: 84aa mv s1,a0 memset(cmd, 0, sizeof(*cmd)); 2d8: 02800613 li a2,40 2dc: 4581 li a1,0 2de: 00001097 auipc ra,0x1 2e2: 8e8080e7 jalr -1816(ra) # bc6 <memset> cmd->type = REDIR; 2e6: 4789 li a5,2 2e8: c09c sw a5,0(s1) cmd->cmd = subcmd; 2ea: 0164b423 sd s6,8(s1) cmd->file = file; 2ee: 0154b823 sd s5,16(s1) cmd->efile = efile; 2f2: 0144bc23 sd s4,24(s1) cmd->mode = mode; 2f6: 0334a023 sw s3,32(s1) cmd->fd = fd; 2fa: 0324a223 sw s2,36(s1) return (struct cmd*)cmd; } 2fe: 8526 mv a0,s1 300: 70e2 ld ra,56(sp) 302: 7442 ld s0,48(sp) 304: 74a2 ld s1,40(sp) 306: 7902 ld s2,32(sp) 308: 69e2 ld s3,24(sp) 30a: 6a42 ld s4,16(sp) 30c: 6aa2 ld s5,8(sp) 30e: 6b02 ld s6,0(sp) 310: 6121 addi sp,sp,64 312: 8082 ret 0000000000000314 <pipecmd>: struct cmd* pipecmd(struct cmd *left, struct cmd *right) { 314: 7179 addi sp,sp,-48 316: f406 sd ra,40(sp) 318: f022 sd s0,32(sp) 31a: ec26 sd s1,24(sp) 31c: e84a sd s2,16(sp) 31e: e44e sd s3,8(sp) 320: 1800 addi s0,sp,48 322: 89aa mv s3,a0 324: 892e mv s2,a1 struct pipecmd *cmd; cmd = malloc(sizeof(*cmd)); 326: 4561 li a0,24 328: 00001097 auipc ra,0x1 32c: ee8080e7 jalr -280(ra) # 1210 <malloc> 330: 84aa mv s1,a0 memset(cmd, 0, sizeof(*cmd)); 332: 4661 li a2,24 334: 4581 li a1,0 336: 00001097 auipc ra,0x1 33a: 890080e7 jalr -1904(ra) # bc6 <memset> cmd->type = PIPE; 33e: 478d li a5,3 340: c09c sw a5,0(s1) cmd->left = left; 342: 0134b423 sd s3,8(s1) cmd->right = right; 346: 0124b823 sd s2,16(s1) return (struct cmd*)cmd; } 34a: 8526 mv a0,s1 34c: 70a2 ld ra,40(sp) 34e: 7402 ld s0,32(sp) 350: 64e2 ld s1,24(sp) 352: 6942 ld s2,16(sp) 354: 69a2 ld s3,8(sp) 356: 6145 addi sp,sp,48 358: 8082 ret 000000000000035a <listcmd>: struct cmd* listcmd(struct cmd *left, struct cmd *right) { 35a: 7179 addi sp,sp,-48 35c: f406 sd ra,40(sp) 35e: f022 sd s0,32(sp) 360: ec26 sd s1,24(sp) 362: e84a sd s2,16(sp) 364: e44e sd s3,8(sp) 366: 1800 addi s0,sp,48 368: 89aa mv s3,a0 36a: 892e mv s2,a1 struct listcmd *cmd; cmd = malloc(sizeof(*cmd)); 36c: 4561 li a0,24 36e: 00001097 auipc ra,0x1 372: ea2080e7 jalr -350(ra) # 1210 <malloc> 376: 84aa mv s1,a0 memset(cmd, 0, sizeof(*cmd)); 378: 4661 li a2,24 37a: 4581 li a1,0 37c: 00001097 auipc ra,0x1 380: 84a080e7 jalr -1974(ra) # bc6 <memset> cmd->type = LIST; 384: 4791 li a5,4 386: c09c sw a5,0(s1) cmd->left = left; 388: 0134b423 sd s3,8(s1) cmd->right = right; 38c: 0124b823 sd s2,16(s1) return (struct cmd*)cmd; } 390: 8526 mv a0,s1 392: 70a2 ld ra,40(sp) 394: 7402 ld s0,32(sp) 396: 64e2 ld s1,24(sp) 398: 6942 ld s2,16(sp) 39a: 69a2 ld s3,8(sp) 39c: 6145 addi sp,sp,48 39e: 8082 ret 00000000000003a0 <backcmd>: struct cmd* backcmd(struct cmd *subcmd) { 3a0: 1101 addi sp,sp,-32 3a2: ec06 sd ra,24(sp) 3a4: e822 sd s0,16(sp) 3a6: e426 sd s1,8(sp) 3a8: e04a sd s2,0(sp) 3aa: 1000 addi s0,sp,32 3ac: 892a mv s2,a0 struct backcmd *cmd; cmd = malloc(sizeof(*cmd)); 3ae: 4541 li a0,16 3b0: 00001097 auipc ra,0x1 3b4: e60080e7 jalr -416(ra) # 1210 <malloc> 3b8: 84aa mv s1,a0 memset(cmd, 0, sizeof(*cmd)); 3ba: 4641 li a2,16 3bc: 4581 li a1,0 3be: 00001097 auipc ra,0x1 3c2: 808080e7 jalr -2040(ra) # bc6 <memset> cmd->type = BACK; 3c6: 4795 li a5,5 3c8: c09c sw a5,0(s1) cmd->cmd = subcmd; 3ca: 0124b423 sd s2,8(s1) return (struct cmd*)cmd; } 3ce: 8526 mv a0,s1 3d0: 60e2 ld ra,24(sp) 3d2: 6442 ld s0,16(sp) 3d4: 64a2 ld s1,8(sp) 3d6: 6902 ld s2,0(sp) 3d8: 6105 addi sp,sp,32 3da: 8082 ret 00000000000003dc <gettoken>: char whitespace[] = " \t\r\n\v"; char symbols[] = "<|>&;()"; int gettoken(char **ps, char *es, char **q, char **eq) { 3dc: 7139 addi sp,sp,-64 3de: fc06 sd ra,56(sp) 3e0: f822 sd s0,48(sp) 3e2: f426 sd s1,40(sp) 3e4: f04a sd s2,32(sp) 3e6: ec4e sd s3,24(sp) 3e8: e852 sd s4,16(sp) 3ea: e456 sd s5,8(sp) 3ec: e05a sd s6,0(sp) 3ee: 0080 addi s0,sp,64 3f0: 8a2a mv s4,a0 3f2: 892e mv s2,a1 3f4: 8ab2 mv s5,a2 3f6: 8b36 mv s6,a3 char *s; int ret; s = *ps; 3f8: 6104 ld s1,0(a0) while(s < es && strchr(whitespace, *s)) 3fa: 00001997 auipc s3,0x1 3fe: 06698993 addi s3,s3,102 # 1460 <whitespace> 402: 00b4fd63 bgeu s1,a1,41c <gettoken+0x40> 406: 0004c583 lbu a1,0(s1) 40a: 854e mv a0,s3 40c: 00000097 auipc ra,0x0 410: 7e0080e7 jalr 2016(ra) # bec <strchr> 414: c501 beqz a0,41c <gettoken+0x40> s++; 416: 0485 addi s1,s1,1 while(s < es && strchr(whitespace, *s)) 418: fe9917e3 bne s2,s1,406 <gettoken+0x2a> if(q) 41c: 000a8463 beqz s5,424 <gettoken+0x48> *q = s; 420: 009ab023 sd s1,0(s5) ret = *s; 424: 0004c783 lbu a5,0(s1) 428: 00078a9b sext.w s5,a5 switch(*s){ 42c: 03c00713 li a4,60 430: 06f76563 bltu a4,a5,49a <gettoken+0xbe> 434: 03a00713 li a4,58 438: 00f76e63 bltu a4,a5,454 <gettoken+0x78> 43c: cf89 beqz a5,456 <gettoken+0x7a> 43e: 02600713 li a4,38 442: 00e78963 beq a5,a4,454 <gettoken+0x78> 446: fd87879b addiw a5,a5,-40 44a: 0ff7f793 andi a5,a5,255 44e: 4705 li a4,1 450: 06f76c63 bltu a4,a5,4c8 <gettoken+0xec> case '(': case ')': case ';': case '&': case '<': s++; 454: 0485 addi s1,s1,1 ret = 'a'; while(s < es && !strchr(whitespace, *s) && !strchr(symbols, *s)) s++; break; } if(eq) 456: 000b0463 beqz s6,45e <gettoken+0x82> *eq = s; 45a: 009b3023 sd s1,0(s6) while(s < es && strchr(whitespace, *s)) 45e: 00001997 auipc s3,0x1 462: 00298993 addi s3,s3,2 # 1460 <whitespace> 466: 0124fd63 bgeu s1,s2,480 <gettoken+0xa4> 46a: 0004c583 lbu a1,0(s1) 46e: 854e mv a0,s3 470: 00000097 auipc ra,0x0 474: 77c080e7 jalr 1916(ra) # bec <strchr> 478: c501 beqz a0,480 <gettoken+0xa4> s++; 47a: 0485 addi s1,s1,1 while(s < es && strchr(whitespace, *s)) 47c: fe9917e3 bne s2,s1,46a <gettoken+0x8e> *ps = s; 480: 009a3023 sd s1,0(s4) return ret; } 484: 8556 mv a0,s5 486: 70e2 ld ra,56(sp) 488: 7442 ld s0,48(sp) 48a: 74a2 ld s1,40(sp) 48c: 7902 ld s2,32(sp) 48e: 69e2 ld s3,24(sp) 490: 6a42 ld s4,16(sp) 492: 6aa2 ld s5,8(sp) 494: 6b02 ld s6,0(sp) 496: 6121 addi sp,sp,64 498: 8082 ret switch(*s){ 49a: 03e00713 li a4,62 49e: 02e79163 bne a5,a4,4c0 <gettoken+0xe4> s++; 4a2: 00148693 addi a3,s1,1 if(*s == '>'){ 4a6: 0014c703 lbu a4,1(s1) 4aa: 03e00793 li a5,62 s++; 4ae: 0489 addi s1,s1,2 ret = '+'; 4b0: 02b00a93 li s5,43 if(*s == '>'){ 4b4: faf701e3 beq a4,a5,456 <gettoken+0x7a> s++; 4b8: 84b6 mv s1,a3 ret = *s; 4ba: 03e00a93 li s5,62 4be: bf61 j 456 <gettoken+0x7a> switch(*s){ 4c0: 07c00713 li a4,124 4c4: f8e788e3 beq a5,a4,454 <gettoken+0x78> while(s < es && !strchr(whitespace, *s) && !strchr(symbols, *s)) 4c8: 00001997 auipc s3,0x1 4cc: f9898993 addi s3,s3,-104 # 1460 <whitespace> 4d0: 00001a97 auipc s5,0x1 4d4: f88a8a93 addi s5,s5,-120 # 1458 <symbols> 4d8: 0324f563 bgeu s1,s2,502 <gettoken+0x126> 4dc: 0004c583 lbu a1,0(s1) 4e0: 854e mv a0,s3 4e2: 00000097 auipc ra,0x0 4e6: 70a080e7 jalr 1802(ra) # bec <strchr> 4ea: e505 bnez a0,512 <gettoken+0x136> 4ec: 0004c583 lbu a1,0(s1) 4f0: 8556 mv a0,s5 4f2: 00000097 auipc ra,0x0 4f6: 6fa080e7 jalr 1786(ra) # bec <strchr> 4fa: e909 bnez a0,50c <gettoken+0x130> s++; 4fc: 0485 addi s1,s1,1 while(s < es && !strchr(whitespace, *s) && !strchr(symbols, *s)) 4fe: fc991fe3 bne s2,s1,4dc <gettoken+0x100> if(eq) 502: 06100a93 li s5,97 506: f40b1ae3 bnez s6,45a <gettoken+0x7e> 50a: bf9d j 480 <gettoken+0xa4> ret = 'a'; 50c: 06100a93 li s5,97 510: b799 j 456 <gettoken+0x7a> 512: 06100a93 li s5,97 516: b781 j 456 <gettoken+0x7a> 0000000000000518 <peek>: int peek(char **ps, char *es, char *toks) { 518: 7139 addi sp,sp,-64 51a: fc06 sd ra,56(sp) 51c: f822 sd s0,48(sp) 51e: f426 sd s1,40(sp) 520: f04a sd s2,32(sp) 522: ec4e sd s3,24(sp) 524: e852 sd s4,16(sp) 526: e456 sd s5,8(sp) 528: 0080 addi s0,sp,64 52a: 8a2a mv s4,a0 52c: 892e mv s2,a1 52e: 8ab2 mv s5,a2 char *s; s = *ps; 530: 6104 ld s1,0(a0) while(s < es && strchr(whitespace, *s)) 532: 00001997 auipc s3,0x1 536: f2e98993 addi s3,s3,-210 # 1460 <whitespace> 53a: 00b4fd63 bgeu s1,a1,554 <peek+0x3c> 53e: 0004c583 lbu a1,0(s1) 542: 854e mv a0,s3 544: 00000097 auipc ra,0x0 548: 6a8080e7 jalr 1704(ra) # bec <strchr> 54c: c501 beqz a0,554 <peek+0x3c> s++; 54e: 0485 addi s1,s1,1 while(s < es && strchr(whitespace, *s)) 550: fe9917e3 bne s2,s1,53e <peek+0x26> *ps = s; 554: 009a3023 sd s1,0(s4) return *s && strchr(toks, *s); 558: 0004c583 lbu a1,0(s1) 55c: 4501 li a0,0 55e: e991 bnez a1,572 <peek+0x5a> } 560: 70e2 ld ra,56(sp) 562: 7442 ld s0,48(sp) 564: 74a2 ld s1,40(sp) 566: 7902 ld s2,32(sp) 568: 69e2 ld s3,24(sp) 56a: 6a42 ld s4,16(sp) 56c: 6aa2 ld s5,8(sp) 56e: 6121 addi sp,sp,64 570: 8082 ret return *s && strchr(toks, *s); 572: 8556 mv a0,s5 574: 00000097 auipc ra,0x0 578: 678080e7 jalr 1656(ra) # bec <strchr> 57c: 00a03533 snez a0,a0 580: b7c5 j 560 <peek+0x48> 0000000000000582 <parseredirs>: return cmd; } struct cmd* parseredirs(struct cmd *cmd, char **ps, char *es) { 582: 7159 addi sp,sp,-112 584: f486 sd ra,104(sp) 586: f0a2 sd s0,96(sp) 588: eca6 sd s1,88(sp) 58a: e8ca sd s2,80(sp) 58c: e4ce sd s3,72(sp) 58e: e0d2 sd s4,64(sp) 590: fc56 sd s5,56(sp) 592: f85a sd s6,48(sp) 594: f45e sd s7,40(sp) 596: f062 sd s8,32(sp) 598: ec66 sd s9,24(sp) 59a: 1880 addi s0,sp,112 59c: 8a2a mv s4,a0 59e: 89ae mv s3,a1 5a0: 8932 mv s2,a2 int tok; char *q, *eq; while(peek(ps, es, "<>")){ 5a2: 00001b97 auipc s7,0x1 5a6: dbeb8b93 addi s7,s7,-578 # 1360 <malloc+0x150> tok = gettoken(ps, es, 0, 0); if(gettoken(ps, es, &q, &eq) != 'a') 5aa: 06100c13 li s8,97 panic("missing file for redirection"); switch(tok){ 5ae: 03c00c93 li s9,60 while(peek(ps, es, "<>")){ 5b2: a02d j 5dc <parseredirs+0x5a> panic("missing file for redirection"); 5b4: 00001517 auipc a0,0x1 5b8: d8c50513 addi a0,a0,-628 # 1340 <malloc+0x130> 5bc: 00000097 auipc ra,0x0 5c0: a98080e7 jalr -1384(ra) # 54 <panic> case '<': cmd = redircmd(cmd, q, eq, O_RDONLY, 0); 5c4: 4701 li a4,0 5c6: 4681 li a3,0 5c8: f9043603 ld a2,-112(s0) 5cc: f9843583 ld a1,-104(s0) 5d0: 8552 mv a0,s4 5d2: 00000097 auipc ra,0x0 5d6: cda080e7 jalr -806(ra) # 2ac <redircmd> 5da: 8a2a mv s4,a0 switch(tok){ 5dc: 03e00b13 li s6,62 5e0: 02b00a93 li s5,43 while(peek(ps, es, "<>")){ 5e4: 865e mv a2,s7 5e6: 85ca mv a1,s2 5e8: 854e mv a0,s3 5ea: 00000097 auipc ra,0x0 5ee: f2e080e7 jalr -210(ra) # 518 <peek> 5f2: c925 beqz a0,662 <parseredirs+0xe0> tok = gettoken(ps, es, 0, 0); 5f4: 4681 li a3,0 5f6: 4601 li a2,0 5f8: 85ca mv a1,s2 5fa: 854e mv a0,s3 5fc: 00000097 auipc ra,0x0 600: de0080e7 jalr -544(ra) # 3dc <gettoken> 604: 84aa mv s1,a0 if(gettoken(ps, es, &q, &eq) != 'a') 606: f9040693 addi a3,s0,-112 60a: f9840613 addi a2,s0,-104 60e: 85ca mv a1,s2 610: 854e mv a0,s3 612: 00000097 auipc ra,0x0 616: dca080e7 jalr -566(ra) # 3dc <gettoken> 61a: f9851de3 bne a0,s8,5b4 <parseredirs+0x32> switch(tok){ 61e: fb9483e3 beq s1,s9,5c4 <parseredirs+0x42> 622: 03648263 beq s1,s6,646 <parseredirs+0xc4> 626: fb549fe3 bne s1,s5,5e4 <parseredirs+0x62> break; case '>': cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1); break; case '+': // >> cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1); 62a: 4705 li a4,1 62c: 20100693 li a3,513 630: f9043603 ld a2,-112(s0) 634: f9843583 ld a1,-104(s0) 638: 8552 mv a0,s4 63a: 00000097 auipc ra,0x0 63e: c72080e7 jalr -910(ra) # 2ac <redircmd> 642: 8a2a mv s4,a0 break; 644: bf61 j 5dc <parseredirs+0x5a> cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1); 646: 4705 li a4,1 648: 20100693 li a3,513 64c: f9043603 ld a2,-112(s0) 650: f9843583 ld a1,-104(s0) 654: 8552 mv a0,s4 656: 00000097 auipc ra,0x0 65a: c56080e7 jalr -938(ra) # 2ac <redircmd> 65e: 8a2a mv s4,a0 break; 660: bfb5 j 5dc <parseredirs+0x5a> } } return cmd; } 662: 8552 mv a0,s4 664: 70a6 ld ra,104(sp) 666: 7406 ld s0,96(sp) 668: 64e6 ld s1,88(sp) 66a: 6946 ld s2,80(sp) 66c: 69a6 ld s3,72(sp) 66e: 6a06 ld s4,64(sp) 670: 7ae2 ld s5,56(sp) 672: 7b42 ld s6,48(sp) 674: 7ba2 ld s7,40(sp) 676: 7c02 ld s8,32(sp) 678: 6ce2 ld s9,24(sp) 67a: 6165 addi sp,sp,112 67c: 8082 ret 000000000000067e <parseexec>: return cmd; } struct cmd* parseexec(char **ps, char *es) { 67e: 7159 addi sp,sp,-112 680: f486 sd ra,104(sp) 682: f0a2 sd s0,96(sp) 684: eca6 sd s1,88(sp) 686: e8ca sd s2,80(sp) 688: e4ce sd s3,72(sp) 68a: e0d2 sd s4,64(sp) 68c: fc56 sd s5,56(sp) 68e: f85a sd s6,48(sp) 690: f45e sd s7,40(sp) 692: f062 sd s8,32(sp) 694: ec66 sd s9,24(sp) 696: 1880 addi s0,sp,112 698: 8a2a mv s4,a0 69a: 8aae mv s5,a1 char *q, *eq; int tok, argc; struct execcmd *cmd; struct cmd *ret; if(peek(ps, es, "(")) 69c: 00001617 auipc a2,0x1 6a0: ccc60613 addi a2,a2,-820 # 1368 <malloc+0x158> 6a4: 00000097 auipc ra,0x0 6a8: e74080e7 jalr -396(ra) # 518 <peek> 6ac: e905 bnez a0,6dc <parseexec+0x5e> 6ae: 89aa mv s3,a0 return parseblock(ps, es); ret = execcmd(); 6b0: 00000097 auipc ra,0x0 6b4: bc6080e7 jalr -1082(ra) # 276 <execcmd> 6b8: 8c2a mv s8,a0 cmd = (struct execcmd*)ret; argc = 0; ret = parseredirs(ret, ps, es); 6ba: 8656 mv a2,s5 6bc: 85d2 mv a1,s4 6be: 00000097 auipc ra,0x0 6c2: ec4080e7 jalr -316(ra) # 582 <parseredirs> 6c6: 84aa mv s1,a0 while(!peek(ps, es, "|)&;")){ 6c8: 008c0913 addi s2,s8,8 6cc: 00001b17 auipc s6,0x1 6d0: cbcb0b13 addi s6,s6,-836 # 1388 <malloc+0x178> if((tok=gettoken(ps, es, &q, &eq)) == 0) break; if(tok != 'a') 6d4: 06100c93 li s9,97 panic("syntax"); cmd->argv[argc] = q; cmd->eargv[argc] = eq; argc++; if(argc >= MAXARGS) 6d8: 4ba9 li s7,10 while(!peek(ps, es, "|)&;")){ 6da: a0b1 j 726 <parseexec+0xa8> return parseblock(ps, es); 6dc: 85d6 mv a1,s5 6de: 8552 mv a0,s4 6e0: 00000097 auipc ra,0x0 6e4: 1bc080e7 jalr 444(ra) # 89c <parseblock> 6e8: 84aa mv s1,a0 ret = parseredirs(ret, ps, es); } cmd->argv[argc] = 0; cmd->eargv[argc] = 0; return ret; } 6ea: 8526 mv a0,s1 6ec: 70a6 ld ra,104(sp) 6ee: 7406 ld s0,96(sp) 6f0: 64e6 ld s1,88(sp) 6f2: 6946 ld s2,80(sp) 6f4: 69a6 ld s3,72(sp) 6f6: 6a06 ld s4,64(sp) 6f8: 7ae2 ld s5,56(sp) 6fa: 7b42 ld s6,48(sp) 6fc: 7ba2 ld s7,40(sp) 6fe: 7c02 ld s8,32(sp) 700: 6ce2 ld s9,24(sp) 702: 6165 addi sp,sp,112 704: 8082 ret panic("syntax"); 706: 00001517 auipc a0,0x1 70a: c6a50513 addi a0,a0,-918 # 1370 <malloc+0x160> 70e: 00000097 auipc ra,0x0 712: 946080e7 jalr -1722(ra) # 54 <panic> ret = parseredirs(ret, ps, es); 716: 8656 mv a2,s5 718: 85d2 mv a1,s4 71a: 8526 mv a0,s1 71c: 00000097 auipc ra,0x0 720: e66080e7 jalr -410(ra) # 582 <parseredirs> 724: 84aa mv s1,a0 while(!peek(ps, es, "|)&;")){ 726: 865a mv a2,s6 728: 85d6 mv a1,s5 72a: 8552 mv a0,s4 72c: 00000097 auipc ra,0x0 730: dec080e7 jalr -532(ra) # 518 <peek> 734: e131 bnez a0,778 <parseexec+0xfa> if((tok=gettoken(ps, es, &q, &eq)) == 0) 736: f9040693 addi a3,s0,-112 73a: f9840613 addi a2,s0,-104 73e: 85d6 mv a1,s5 740: 8552 mv a0,s4 742: 00000097 auipc ra,0x0 746: c9a080e7 jalr -870(ra) # 3dc <gettoken> 74a: c51d beqz a0,778 <parseexec+0xfa> if(tok != 'a') 74c: fb951de3 bne a0,s9,706 <parseexec+0x88> cmd->argv[argc] = q; 750: f9843783 ld a5,-104(s0) 754: 00f93023 sd a5,0(s2) cmd->eargv[argc] = eq; 758: f9043783 ld a5,-112(s0) 75c: 04f93823 sd a5,80(s2) argc++; 760: 2985 addiw s3,s3,1 if(argc >= MAXARGS) 762: 0921 addi s2,s2,8 764: fb7999e3 bne s3,s7,716 <parseexec+0x98> panic("too many args"); 768: 00001517 auipc a0,0x1 76c: c1050513 addi a0,a0,-1008 # 1378 <malloc+0x168> 770: 00000097 auipc ra,0x0 774: 8e4080e7 jalr -1820(ra) # 54 <panic> cmd->argv[argc] = 0; 778: 098e slli s3,s3,0x3 77a: 99e2 add s3,s3,s8 77c: 0009b423 sd zero,8(s3) cmd->eargv[argc] = 0; 780: 0409bc23 sd zero,88(s3) return ret; 784: b79d j 6ea <parseexec+0x6c> 0000000000000786 <parsepipe>: { 786: 7179 addi sp,sp,-48 788: f406 sd ra,40(sp) 78a: f022 sd s0,32(sp) 78c: ec26 sd s1,24(sp) 78e: e84a sd s2,16(sp) 790: e44e sd s3,8(sp) 792: 1800 addi s0,sp,48 794: 892a mv s2,a0 796: 89ae mv s3,a1 cmd = parseexec(ps, es); 798: 00000097 auipc ra,0x0 79c: ee6080e7 jalr -282(ra) # 67e <parseexec> 7a0: 84aa mv s1,a0 if(peek(ps, es, "|")){ 7a2: 00001617 auipc a2,0x1 7a6: bee60613 addi a2,a2,-1042 # 1390 <malloc+0x180> 7aa: 85ce mv a1,s3 7ac: 854a mv a0,s2 7ae: 00000097 auipc ra,0x0 7b2: d6a080e7 jalr -662(ra) # 518 <peek> 7b6: e909 bnez a0,7c8 <parsepipe+0x42> } 7b8: 8526 mv a0,s1 7ba: 70a2 ld ra,40(sp) 7bc: 7402 ld s0,32(sp) 7be: 64e2 ld s1,24(sp) 7c0: 6942 ld s2,16(sp) 7c2: 69a2 ld s3,8(sp) 7c4: 6145 addi sp,sp,48 7c6: 8082 ret gettoken(ps, es, 0, 0); 7c8: 4681 li a3,0 7ca: 4601 li a2,0 7cc: 85ce mv a1,s3 7ce: 854a mv a0,s2 7d0: 00000097 auipc ra,0x0 7d4: c0c080e7 jalr -1012(ra) # 3dc <gettoken> cmd = pipecmd(cmd, parsepipe(ps, es)); 7d8: 85ce mv a1,s3 7da: 854a mv a0,s2 7dc: 00000097 auipc ra,0x0 7e0: faa080e7 jalr -86(ra) # 786 <parsepipe> 7e4: 85aa mv a1,a0 7e6: 8526 mv a0,s1 7e8: 00000097 auipc ra,0x0 7ec: b2c080e7 jalr -1236(ra) # 314 <pipecmd> 7f0: 84aa mv s1,a0 return cmd; 7f2: b7d9 j 7b8 <parsepipe+0x32> 00000000000007f4 <parseline>: { 7f4: 7179 addi sp,sp,-48 7f6: f406 sd ra,40(sp) 7f8: f022 sd s0,32(sp) 7fa: ec26 sd s1,24(sp) 7fc: e84a sd s2,16(sp) 7fe: e44e sd s3,8(sp) 800: e052 sd s4,0(sp) 802: 1800 addi s0,sp,48 804: 892a mv s2,a0 806: 89ae mv s3,a1 cmd = parsepipe(ps, es); 808: 00000097 auipc ra,0x0 80c: f7e080e7 jalr -130(ra) # 786 <parsepipe> 810: 84aa mv s1,a0 while(peek(ps, es, "&")){ 812: 00001a17 auipc s4,0x1 816: b86a0a13 addi s4,s4,-1146 # 1398 <malloc+0x188> 81a: 8652 mv a2,s4 81c: 85ce mv a1,s3 81e: 854a mv a0,s2 820: 00000097 auipc ra,0x0 824: cf8080e7 jalr -776(ra) # 518 <peek> 828: c105 beqz a0,848 <parseline+0x54> gettoken(ps, es, 0, 0); 82a: 4681 li a3,0 82c: 4601 li a2,0 82e: 85ce mv a1,s3 830: 854a mv a0,s2 832: 00000097 auipc ra,0x0 836: baa080e7 jalr -1110(ra) # 3dc <gettoken> cmd = backcmd(cmd); 83a: 8526 mv a0,s1 83c: 00000097 auipc ra,0x0 840: b64080e7 jalr -1180(ra) # 3a0 <backcmd> 844: 84aa mv s1,a0 846: bfd1 j 81a <parseline+0x26> if(peek(ps, es, ";")){ 848: 00001617 auipc a2,0x1 84c: b5860613 addi a2,a2,-1192 # 13a0 <malloc+0x190> 850: 85ce mv a1,s3 852: 854a mv a0,s2 854: 00000097 auipc ra,0x0 858: cc4080e7 jalr -828(ra) # 518 <peek> 85c: e911 bnez a0,870 <parseline+0x7c> } 85e: 8526 mv a0,s1 860: 70a2 ld ra,40(sp) 862: 7402 ld s0,32(sp) 864: 64e2 ld s1,24(sp) 866: 6942 ld s2,16(sp) 868: 69a2 ld s3,8(sp) 86a: 6a02 ld s4,0(sp) 86c: 6145 addi sp,sp,48 86e: 8082 ret gettoken(ps, es, 0, 0); 870: 4681 li a3,0 872: 4601 li a2,0 874: 85ce mv a1,s3 876: 854a mv a0,s2 878: 00000097 auipc ra,0x0 87c: b64080e7 jalr -1180(ra) # 3dc <gettoken> cmd = listcmd(cmd, parseline(ps, es)); 880: 85ce mv a1,s3 882: 854a mv a0,s2 884: 00000097 auipc ra,0x0 888: f70080e7 jalr -144(ra) # 7f4 <parseline> 88c: 85aa mv a1,a0 88e: 8526 mv a0,s1 890: 00000097 auipc ra,0x0 894: aca080e7 jalr -1334(ra) # 35a <listcmd> 898: 84aa mv s1,a0 return cmd; 89a: b7d1 j 85e <parseline+0x6a> 000000000000089c <parseblock>: { 89c: 7179 addi sp,sp,-48 89e: f406 sd ra,40(sp) 8a0: f022 sd s0,32(sp) 8a2: ec26 sd s1,24(sp) 8a4: e84a sd s2,16(sp) 8a6: e44e sd s3,8(sp) 8a8: 1800 addi s0,sp,48 8aa: 84aa mv s1,a0 8ac: 892e mv s2,a1 if(!peek(ps, es, "(")) 8ae: 00001617 auipc a2,0x1 8b2: aba60613 addi a2,a2,-1350 # 1368 <malloc+0x158> 8b6: 00000097 auipc ra,0x0 8ba: c62080e7 jalr -926(ra) # 518 <peek> 8be: c12d beqz a0,920 <parseblock+0x84> gettoken(ps, es, 0, 0); 8c0: 4681 li a3,0 8c2: 4601 li a2,0 8c4: 85ca mv a1,s2 8c6: 8526 mv a0,s1 8c8: 00000097 auipc ra,0x0 8cc: b14080e7 jalr -1260(ra) # 3dc <gettoken> cmd = parseline(ps, es); 8d0: 85ca mv a1,s2 8d2: 8526 mv a0,s1 8d4: 00000097 auipc ra,0x0 8d8: f20080e7 jalr -224(ra) # 7f4 <parseline> 8dc: 89aa mv s3,a0 if(!peek(ps, es, ")")) 8de: 00001617 auipc a2,0x1 8e2: ada60613 addi a2,a2,-1318 # 13b8 <malloc+0x1a8> 8e6: 85ca mv a1,s2 8e8: 8526 mv a0,s1 8ea: 00000097 auipc ra,0x0 8ee: c2e080e7 jalr -978(ra) # 518 <peek> 8f2: cd1d beqz a0,930 <parseblock+0x94> gettoken(ps, es, 0, 0); 8f4: 4681 li a3,0 8f6: 4601 li a2,0 8f8: 85ca mv a1,s2 8fa: 8526 mv a0,s1 8fc: 00000097 auipc ra,0x0 900: ae0080e7 jalr -1312(ra) # 3dc <gettoken> cmd = parseredirs(cmd, ps, es); 904: 864a mv a2,s2 906: 85a6 mv a1,s1 908: 854e mv a0,s3 90a: 00000097 auipc ra,0x0 90e: c78080e7 jalr -904(ra) # 582 <parseredirs> } 912: 70a2 ld ra,40(sp) 914: 7402 ld s0,32(sp) 916: 64e2 ld s1,24(sp) 918: 6942 ld s2,16(sp) 91a: 69a2 ld s3,8(sp) 91c: 6145 addi sp,sp,48 91e: 8082 ret panic("parseblock"); 920: 00001517 auipc a0,0x1 924: a8850513 addi a0,a0,-1400 # 13a8 <malloc+0x198> 928: fffff097 auipc ra,0xfffff 92c: 72c080e7 jalr 1836(ra) # 54 <panic> panic("syntax - missing )"); 930: 00001517 auipc a0,0x1 934: a9050513 addi a0,a0,-1392 # 13c0 <malloc+0x1b0> 938: fffff097 auipc ra,0xfffff 93c: 71c080e7 jalr 1820(ra) # 54 <panic> 0000000000000940 <nulterminate>: // NUL-terminate all the counted strings. struct cmd* nulterminate(struct cmd *cmd) { 940: 1101 addi sp,sp,-32 942: ec06 sd ra,24(sp) 944: e822 sd s0,16(sp) 946: e426 sd s1,8(sp) 948: 1000 addi s0,sp,32 94a: 84aa mv s1,a0 struct execcmd *ecmd; struct listcmd *lcmd; struct pipecmd *pcmd; struct redircmd *rcmd; if(cmd == 0) 94c: c521 beqz a0,994 <nulterminate+0x54> return 0; switch(cmd->type){ 94e: 4118 lw a4,0(a0) 950: 4795 li a5,5 952: 04e7e163 bltu a5,a4,994 <nulterminate+0x54> 956: 00056783 lwu a5,0(a0) 95a: 078a slli a5,a5,0x2 95c: 00001717 auipc a4,0x1 960: ac470713 addi a4,a4,-1340 # 1420 <malloc+0x210> 964: 97ba add a5,a5,a4 966: 439c lw a5,0(a5) 968: 97ba add a5,a5,a4 96a: 8782 jr a5 case EXEC: ecmd = (struct execcmd*)cmd; for(i=0; ecmd->argv[i]; i++) 96c: 651c ld a5,8(a0) 96e: c39d beqz a5,994 <nulterminate+0x54> 970: 01050793 addi a5,a0,16 *ecmd->eargv[i] = 0; 974: 67b8 ld a4,72(a5) 976: 00070023 sb zero,0(a4) for(i=0; ecmd->argv[i]; i++) 97a: 07a1 addi a5,a5,8 97c: ff87b703 ld a4,-8(a5) 980: fb75 bnez a4,974 <nulterminate+0x34> 982: a809 j 994 <nulterminate+0x54> break; case REDIR: rcmd = (struct redircmd*)cmd; nulterminate(rcmd->cmd); 984: 6508 ld a0,8(a0) 986: 00000097 auipc ra,0x0 98a: fba080e7 jalr -70(ra) # 940 <nulterminate> *rcmd->efile = 0; 98e: 6c9c ld a5,24(s1) 990: 00078023 sb zero,0(a5) bcmd = (struct backcmd*)cmd; nulterminate(bcmd->cmd); break; } return cmd; } 994: 8526 mv a0,s1 996: 60e2 ld ra,24(sp) 998: 6442 ld s0,16(sp) 99a: 64a2 ld s1,8(sp) 99c: 6105 addi sp,sp,32 99e: 8082 ret nulterminate(pcmd->left); 9a0: 6508 ld a0,8(a0) 9a2: 00000097 auipc ra,0x0 9a6: f9e080e7 jalr -98(ra) # 940 <nulterminate> nulterminate(pcmd->right); 9aa: 6888 ld a0,16(s1) 9ac: 00000097 auipc ra,0x0 9b0: f94080e7 jalr -108(ra) # 940 <nulterminate> break; 9b4: b7c5 j 994 <nulterminate+0x54> nulterminate(lcmd->left); 9b6: 6508 ld a0,8(a0) 9b8: 00000097 auipc ra,0x0 9bc: f88080e7 jalr -120(ra) # 940 <nulterminate> nulterminate(lcmd->right); 9c0: 6888 ld a0,16(s1) 9c2: 00000097 auipc ra,0x0 9c6: f7e080e7 jalr -130(ra) # 940 <nulterminate> break; 9ca: b7e9 j 994 <nulterminate+0x54> nulterminate(bcmd->cmd); 9cc: 6508 ld a0,8(a0) 9ce: 00000097 auipc ra,0x0 9d2: f72080e7 jalr -142(ra) # 940 <nulterminate> break; 9d6: bf7d j 994 <nulterminate+0x54> 00000000000009d8 <parsecmd>: { 9d8: 7179 addi sp,sp,-48 9da: f406 sd ra,40(sp) 9dc: f022 sd s0,32(sp) 9de: ec26 sd s1,24(sp) 9e0: e84a sd s2,16(sp) 9e2: 1800 addi s0,sp,48 9e4: fca43c23 sd a0,-40(s0) es = s + strlen(s); 9e8: 84aa mv s1,a0 9ea: 00000097 auipc ra,0x0 9ee: 1b2080e7 jalr 434(ra) # b9c <strlen> 9f2: 1502 slli a0,a0,0x20 9f4: 9101 srli a0,a0,0x20 9f6: 94aa add s1,s1,a0 cmd = parseline(&s, es); 9f8: 85a6 mv a1,s1 9fa: fd840513 addi a0,s0,-40 9fe: 00000097 auipc ra,0x0 a02: df6080e7 jalr -522(ra) # 7f4 <parseline> a06: 892a mv s2,a0 peek(&s, es, ""); a08: 00001617 auipc a2,0x1 a0c: 9d060613 addi a2,a2,-1584 # 13d8 <malloc+0x1c8> a10: 85a6 mv a1,s1 a12: fd840513 addi a0,s0,-40 a16: 00000097 auipc ra,0x0 a1a: b02080e7 jalr -1278(ra) # 518 <peek> if(s != es){ a1e: fd843603 ld a2,-40(s0) a22: 00961e63 bne a2,s1,a3e <parsecmd+0x66> nulterminate(cmd); a26: 854a mv a0,s2 a28: 00000097 auipc ra,0x0 a2c: f18080e7 jalr -232(ra) # 940 <nulterminate> } a30: 854a mv a0,s2 a32: 70a2 ld ra,40(sp) a34: 7402 ld s0,32(sp) a36: 64e2 ld s1,24(sp) a38: 6942 ld s2,16(sp) a3a: 6145 addi sp,sp,48 a3c: 8082 ret fprintf(2, "leftovers: %s\n", s); a3e: 00001597 auipc a1,0x1 a42: 9a258593 addi a1,a1,-1630 # 13e0 <malloc+0x1d0> a46: 4509 li a0,2 a48: 00000097 auipc ra,0x0 a4c: 6dc080e7 jalr 1756(ra) # 1124 <fprintf> panic("syntax"); a50: 00001517 auipc a0,0x1 a54: 92050513 addi a0,a0,-1760 # 1370 <malloc+0x160> a58: fffff097 auipc ra,0xfffff a5c: 5fc080e7 jalr 1532(ra) # 54 <panic> 0000000000000a60 <main>: { a60: 7139 addi sp,sp,-64 a62: fc06 sd ra,56(sp) a64: f822 sd s0,48(sp) a66: f426 sd s1,40(sp) a68: f04a sd s2,32(sp) a6a: ec4e sd s3,24(sp) a6c: e852 sd s4,16(sp) a6e: e456 sd s5,8(sp) a70: 0080 addi s0,sp,64 while((fd = open("console", O_RDWR)) >= 0){ a72: 00001497 auipc s1,0x1 a76: 97e48493 addi s1,s1,-1666 # 13f0 <malloc+0x1e0> a7a: 4589 li a1,2 a7c: 8526 mv a0,s1 a7e: 00000097 auipc ra,0x0 a82: 38c080e7 jalr 908(ra) # e0a <open> a86: 00054963 bltz a0,a98 <main+0x38> if(fd >= 3){ a8a: 4789 li a5,2 a8c: fea7d7e3 bge a5,a0,a7a <main+0x1a> close(fd); a90: 00000097 auipc ra,0x0 a94: 362080e7 jalr 866(ra) # df2 <close> while(getcmd(buf, sizeof(buf)) >= 0){ a98: 00001497 auipc s1,0x1 a9c: 9d848493 addi s1,s1,-1576 # 1470 <buf.1146> if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){ aa0: 06300913 li s2,99 aa4: 02000993 li s3,32 if(chdir(buf+3) < 0) aa8: 00001a17 auipc s4,0x1 aac: 9cba0a13 addi s4,s4,-1589 # 1473 <buf.1146+0x3> fprintf(2, "cannot cd %s\n", buf+3); ab0: 00001a97 auipc s5,0x1 ab4: 948a8a93 addi s5,s5,-1720 # 13f8 <malloc+0x1e8> ab8: a819 j ace <main+0x6e> if(fork1() == 0) aba: fffff097 auipc ra,0xfffff abe: 5c0080e7 jalr 1472(ra) # 7a <fork1> ac2: c925 beqz a0,b32 <main+0xd2> wait(0); ac4: 4501 li a0,0 ac6: 00000097 auipc ra,0x0 aca: 30c080e7 jalr 780(ra) # dd2 <wait> while(getcmd(buf, sizeof(buf)) >= 0){ ace: 06400593 li a1,100 ad2: 8526 mv a0,s1 ad4: fffff097 auipc ra,0xfffff ad8: 52c080e7 jalr 1324(ra) # 0 <getcmd> adc: 06054763 bltz a0,b4a <main+0xea> if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){ ae0: 0004c783 lbu a5,0(s1) ae4: fd279be3 bne a5,s2,aba <main+0x5a> ae8: 0014c703 lbu a4,1(s1) aec: 06400793 li a5,100 af0: fcf715e3 bne a4,a5,aba <main+0x5a> af4: 0024c783 lbu a5,2(s1) af8: fd3791e3 bne a5,s3,aba <main+0x5a> buf[strlen(buf)-1] = 0; // chop \n afc: 8526 mv a0,s1 afe: 00000097 auipc ra,0x0 b02: 09e080e7 jalr 158(ra) # b9c <strlen> b06: fff5079b addiw a5,a0,-1 b0a: 1782 slli a5,a5,0x20 b0c: 9381 srli a5,a5,0x20 b0e: 97a6 add a5,a5,s1 b10: 00078023 sb zero,0(a5) if(chdir(buf+3) < 0) b14: 8552 mv a0,s4 b16: 00000097 auipc ra,0x0 b1a: 324080e7 jalr 804(ra) # e3a <chdir> b1e: fa0558e3 bgez a0,ace <main+0x6e> fprintf(2, "cannot cd %s\n", buf+3); b22: 8652 mv a2,s4 b24: 85d6 mv a1,s5 b26: 4509 li a0,2 b28: 00000097 auipc ra,0x0 b2c: 5fc080e7 jalr 1532(ra) # 1124 <fprintf> b30: bf79 j ace <main+0x6e> runcmd(parsecmd(buf)); b32: 00001517 auipc a0,0x1 b36: 93e50513 addi a0,a0,-1730 # 1470 <buf.1146> b3a: 00000097 auipc ra,0x0 b3e: e9e080e7 jalr -354(ra) # 9d8 <parsecmd> b42: fffff097 auipc ra,0xfffff b46: 566080e7 jalr 1382(ra) # a8 <runcmd> exit(0); b4a: 4501 li a0,0 b4c: 00000097 auipc ra,0x0 b50: 27e080e7 jalr 638(ra) # dca <exit> 0000000000000b54 <strcpy>: #include "kernel/fcntl.h" #include "user/user.h" char* strcpy(char *s, const char *t) { b54: 1141 addi sp,sp,-16 b56: e422 sd s0,8(sp) b58: 0800 addi s0,sp,16 char *os; os = s; while((*s++ = *t++) != 0) b5a: 87aa mv a5,a0 b5c: 0585 addi a1,a1,1 b5e: 0785 addi a5,a5,1 b60: fff5c703 lbu a4,-1(a1) b64: fee78fa3 sb a4,-1(a5) b68: fb75 bnez a4,b5c <strcpy+0x8> ; return os; } b6a: 6422 ld s0,8(sp) b6c: 0141 addi sp,sp,16 b6e: 8082 ret 0000000000000b70 <strcmp>: int strcmp(const char *p, const char *q) { b70: 1141 addi sp,sp,-16 b72: e422 sd s0,8(sp) b74: 0800 addi s0,sp,16 while(*p && *p == *q) b76: 00054783 lbu a5,0(a0) b7a: cb91 beqz a5,b8e <strcmp+0x1e> b7c: 0005c703 lbu a4,0(a1) b80: 00f71763 bne a4,a5,b8e <strcmp+0x1e> p++, q++; b84: 0505 addi a0,a0,1 b86: 0585 addi a1,a1,1 while(*p && *p == *q) b88: 00054783 lbu a5,0(a0) b8c: fbe5 bnez a5,b7c <strcmp+0xc> return (uchar)*p - (uchar)*q; b8e: 0005c503 lbu a0,0(a1) } b92: 40a7853b subw a0,a5,a0 b96: 6422 ld s0,8(sp) b98: 0141 addi sp,sp,16 b9a: 8082 ret 0000000000000b9c <strlen>: uint strlen(const char *s) { b9c: 1141 addi sp,sp,-16 b9e: e422 sd s0,8(sp) ba0: 0800 addi s0,sp,16 int n; for(n = 0; s[n]; n++) ba2: 00054783 lbu a5,0(a0) ba6: cf91 beqz a5,bc2 <strlen+0x26> ba8: 0505 addi a0,a0,1 baa: 87aa mv a5,a0 bac: 4685 li a3,1 bae: 9e89 subw a3,a3,a0 bb0: 00f6853b addw a0,a3,a5 bb4: 0785 addi a5,a5,1 bb6: fff7c703 lbu a4,-1(a5) bba: fb7d bnez a4,bb0 <strlen+0x14> ; return n; } bbc: 6422 ld s0,8(sp) bbe: 0141 addi sp,sp,16 bc0: 8082 ret for(n = 0; s[n]; n++) bc2: 4501 li a0,0 bc4: bfe5 j bbc <strlen+0x20> 0000000000000bc6 <memset>: void* memset(void *dst, int c, uint n) { bc6: 1141 addi sp,sp,-16 bc8: e422 sd s0,8(sp) bca: 0800 addi s0,sp,16 char *cdst = (char *) dst; int i; for(i = 0; i < n; i++){ bcc: ce09 beqz a2,be6 <memset+0x20> bce: 87aa mv a5,a0 bd0: fff6071b addiw a4,a2,-1 bd4: 1702 slli a4,a4,0x20 bd6: 9301 srli a4,a4,0x20 bd8: 0705 addi a4,a4,1 bda: 972a add a4,a4,a0 cdst[i] = c; bdc: 00b78023 sb a1,0(a5) for(i = 0; i < n; i++){ be0: 0785 addi a5,a5,1 be2: fee79de3 bne a5,a4,bdc <memset+0x16> } return dst; } be6: 6422 ld s0,8(sp) be8: 0141 addi sp,sp,16 bea: 8082 ret 0000000000000bec <strchr>: char* strchr(const char *s, char c) { bec: 1141 addi sp,sp,-16 bee: e422 sd s0,8(sp) bf0: 0800 addi s0,sp,16 for(; *s; s++) bf2: 00054783 lbu a5,0(a0) bf6: cb99 beqz a5,c0c <strchr+0x20> if(*s == c) bf8: 00f58763 beq a1,a5,c06 <strchr+0x1a> for(; *s; s++) bfc: 0505 addi a0,a0,1 bfe: 00054783 lbu a5,0(a0) c02: fbfd bnez a5,bf8 <strchr+0xc> return (char*)s; return 0; c04: 4501 li a0,0 } c06: 6422 ld s0,8(sp) c08: 0141 addi sp,sp,16 c0a: 8082 ret return 0; c0c: 4501 li a0,0 c0e: bfe5 j c06 <strchr+0x1a> 0000000000000c10 <gets>: char* gets(char *buf, int max) { c10: 711d addi sp,sp,-96 c12: ec86 sd ra,88(sp) c14: e8a2 sd s0,80(sp) c16: e4a6 sd s1,72(sp) c18: e0ca sd s2,64(sp) c1a: fc4e sd s3,56(sp) c1c: f852 sd s4,48(sp) c1e: f456 sd s5,40(sp) c20: f05a sd s6,32(sp) c22: ec5e sd s7,24(sp) c24: 1080 addi s0,sp,96 c26: 8baa mv s7,a0 c28: 8a2e mv s4,a1 int i, cc; char c; for(i=0; i+1 < max; ){ c2a: 892a mv s2,a0 c2c: 4481 li s1,0 cc = read(0, &c, 1); if(cc < 1) break; buf[i++] = c; if(c == '\n' || c == '\r') c2e: 4aa9 li s5,10 c30: 4b35 li s6,13 for(i=0; i+1 < max; ){ c32: 89a6 mv s3,s1 c34: 2485 addiw s1,s1,1 c36: 0344d863 bge s1,s4,c66 <gets+0x56> cc = read(0, &c, 1); c3a: 4605 li a2,1 c3c: faf40593 addi a1,s0,-81 c40: 4501 li a0,0 c42: 00000097 auipc ra,0x0 c46: 1a0080e7 jalr 416(ra) # de2 <read> if(cc < 1) c4a: 00a05e63 blez a0,c66 <gets+0x56> buf[i++] = c; c4e: faf44783 lbu a5,-81(s0) c52: 00f90023 sb a5,0(s2) if(c == '\n' || c == '\r') c56: 01578763 beq a5,s5,c64 <gets+0x54> c5a: 0905 addi s2,s2,1 c5c: fd679be3 bne a5,s6,c32 <gets+0x22> for(i=0; i+1 < max; ){ c60: 89a6 mv s3,s1 c62: a011 j c66 <gets+0x56> c64: 89a6 mv s3,s1 break; } buf[i] = '\0'; c66: 99de add s3,s3,s7 c68: 00098023 sb zero,0(s3) return buf; } c6c: 855e mv a0,s7 c6e: 60e6 ld ra,88(sp) c70: 6446 ld s0,80(sp) c72: 64a6 ld s1,72(sp) c74: 6906 ld s2,64(sp) c76: 79e2 ld s3,56(sp) c78: 7a42 ld s4,48(sp) c7a: 7aa2 ld s5,40(sp) c7c: 7b02 ld s6,32(sp) c7e: 6be2 ld s7,24(sp) c80: 6125 addi sp,sp,96 c82: 8082 ret 0000000000000c84 <stat>: int stat(const char *n, struct stat *st) { c84: 1101 addi sp,sp,-32 c86: ec06 sd ra,24(sp) c88: e822 sd s0,16(sp) c8a: e426 sd s1,8(sp) c8c: e04a sd s2,0(sp) c8e: 1000 addi s0,sp,32 c90: 892e mv s2,a1 int fd; int r; fd = open(n, O_RDONLY); c92: 4581 li a1,0 c94: 00000097 auipc ra,0x0 c98: 176080e7 jalr 374(ra) # e0a <open> if(fd < 0) c9c: 02054563 bltz a0,cc6 <stat+0x42> ca0: 84aa mv s1,a0 return -1; r = fstat(fd, st); ca2: 85ca mv a1,s2 ca4: 00000097 auipc ra,0x0 ca8: 17e080e7 jalr 382(ra) # e22 <fstat> cac: 892a mv s2,a0 close(fd); cae: 8526 mv a0,s1 cb0: 00000097 auipc ra,0x0 cb4: 142080e7 jalr 322(ra) # df2 <close> return r; } cb8: 854a mv a0,s2 cba: 60e2 ld ra,24(sp) cbc: 6442 ld s0,16(sp) cbe: 64a2 ld s1,8(sp) cc0: 6902 ld s2,0(sp) cc2: 6105 addi sp,sp,32 cc4: 8082 ret return -1; cc6: 597d li s2,-1 cc8: bfc5 j cb8 <stat+0x34> 0000000000000cca <atoi>: int atoi(const char *s) { cca: 1141 addi sp,sp,-16 ccc: e422 sd s0,8(sp) cce: 0800 addi s0,sp,16 int n; n = 0; while('0' <= *s && *s <= '9') cd0: 00054603 lbu a2,0(a0) cd4: fd06079b addiw a5,a2,-48 cd8: 0ff7f793 andi a5,a5,255 cdc: 4725 li a4,9 cde: 02f76963 bltu a4,a5,d10 <atoi+0x46> ce2: 86aa mv a3,a0 n = 0; ce4: 4501 li a0,0 while('0' <= *s && *s <= '9') ce6: 45a5 li a1,9 n = n*10 + *s++ - '0'; ce8: 0685 addi a3,a3,1 cea: 0025179b slliw a5,a0,0x2 cee: 9fa9 addw a5,a5,a0 cf0: 0017979b slliw a5,a5,0x1 cf4: 9fb1 addw a5,a5,a2 cf6: fd07851b addiw a0,a5,-48 while('0' <= *s && *s <= '9') cfa: 0006c603 lbu a2,0(a3) cfe: fd06071b addiw a4,a2,-48 d02: 0ff77713 andi a4,a4,255 d06: fee5f1e3 bgeu a1,a4,ce8 <atoi+0x1e> return n; } d0a: 6422 ld s0,8(sp) d0c: 0141 addi sp,sp,16 d0e: 8082 ret n = 0; d10: 4501 li a0,0 d12: bfe5 j d0a <atoi+0x40> 0000000000000d14 <memmove>: void* memmove(void *vdst, const void *vsrc, int n) { d14: 1141 addi sp,sp,-16 d16: e422 sd s0,8(sp) d18: 0800 addi s0,sp,16 char *dst; const char *src; dst = vdst; src = vsrc; if (src > dst) { d1a: 02b57663 bgeu a0,a1,d46 <memmove+0x32> while(n-- > 0) d1e: 02c05163 blez a2,d40 <memmove+0x2c> d22: fff6079b addiw a5,a2,-1 d26: 1782 slli a5,a5,0x20 d28: 9381 srli a5,a5,0x20 d2a: 0785 addi a5,a5,1 d2c: 97aa add a5,a5,a0 dst = vdst; d2e: 872a mv a4,a0 *dst++ = *src++; d30: 0585 addi a1,a1,1 d32: 0705 addi a4,a4,1 d34: fff5c683 lbu a3,-1(a1) d38: fed70fa3 sb a3,-1(a4) while(n-- > 0) d3c: fee79ae3 bne a5,a4,d30 <memmove+0x1c> src += n; while(n-- > 0) *--dst = *--src; } return vdst; } d40: 6422 ld s0,8(sp) d42: 0141 addi sp,sp,16 d44: 8082 ret dst += n; d46: 00c50733 add a4,a0,a2 src += n; d4a: 95b2 add a1,a1,a2 while(n-- > 0) d4c: fec05ae3 blez a2,d40 <memmove+0x2c> d50: fff6079b addiw a5,a2,-1 d54: 1782 slli a5,a5,0x20 d56: 9381 srli a5,a5,0x20 d58: fff7c793 not a5,a5 d5c: 97ba add a5,a5,a4 *--dst = *--src; d5e: 15fd addi a1,a1,-1 d60: 177d addi a4,a4,-1 d62: 0005c683 lbu a3,0(a1) d66: 00d70023 sb a3,0(a4) while(n-- > 0) d6a: fee79ae3 bne a5,a4,d5e <memmove+0x4a> d6e: bfc9 j d40 <memmove+0x2c> 0000000000000d70 <memcmp>: int memcmp(const void *s1, const void *s2, uint n) { d70: 1141 addi sp,sp,-16 d72: e422 sd s0,8(sp) d74: 0800 addi s0,sp,16 const char *p1 = s1, *p2 = s2; while (n-- > 0) { d76: ca05 beqz a2,da6 <memcmp+0x36> d78: fff6069b addiw a3,a2,-1 d7c: 1682 slli a3,a3,0x20 d7e: 9281 srli a3,a3,0x20 d80: 0685 addi a3,a3,1 d82: 96aa add a3,a3,a0 if (*p1 != *p2) { d84: 00054783 lbu a5,0(a0) d88: 0005c703 lbu a4,0(a1) d8c: 00e79863 bne a5,a4,d9c <memcmp+0x2c> return *p1 - *p2; } p1++; d90: 0505 addi a0,a0,1 p2++; d92: 0585 addi a1,a1,1 while (n-- > 0) { d94: fed518e3 bne a0,a3,d84 <memcmp+0x14> } return 0; d98: 4501 li a0,0 d9a: a019 j da0 <memcmp+0x30> return *p1 - *p2; d9c: 40e7853b subw a0,a5,a4 } da0: 6422 ld s0,8(sp) da2: 0141 addi sp,sp,16 da4: 8082 ret return 0; da6: 4501 li a0,0 da8: bfe5 j da0 <memcmp+0x30> 0000000000000daa <memcpy>: void * memcpy(void *dst, const void *src, uint n) { daa: 1141 addi sp,sp,-16 dac: e406 sd ra,8(sp) dae: e022 sd s0,0(sp) db0: 0800 addi s0,sp,16 return memmove(dst, src, n); db2: 00000097 auipc ra,0x0 db6: f62080e7 jalr -158(ra) # d14 <memmove> } dba: 60a2 ld ra,8(sp) dbc: 6402 ld s0,0(sp) dbe: 0141 addi sp,sp,16 dc0: 8082 ret 0000000000000dc2 <fork>: # generated by usys.pl - do not edit #include "kernel/syscall.h" .global fork fork: li a7, SYS_fork dc2: 4885 li a7,1 ecall dc4: 00000073 ecall ret dc8: 8082 ret 0000000000000dca <exit>: .global exit exit: li a7, SYS_exit dca: 4889 li a7,2 ecall dcc: 00000073 ecall ret dd0: 8082 ret 0000000000000dd2 <wait>: .global wait wait: li a7, SYS_wait dd2: 488d li a7,3 ecall dd4: 00000073 ecall ret dd8: 8082 ret 0000000000000dda <pipe>: .global pipe pipe: li a7, SYS_pipe dda: 4891 li a7,4 ecall ddc: 00000073 ecall ret de0: 8082 ret 0000000000000de2 <read>: .global read read: li a7, SYS_read de2: 4895 li a7,5 ecall de4: 00000073 ecall ret de8: 8082 ret 0000000000000dea <write>: .global write write: li a7, SYS_write dea: 48c1 li a7,16 ecall dec: 00000073 ecall ret df0: 8082 ret 0000000000000df2 <close>: .global close close: li a7, SYS_close df2: 48d5 li a7,21 ecall df4: 00000073 ecall ret df8: 8082 ret 0000000000000dfa <kill>: .global kill kill: li a7, SYS_kill dfa: 4899 li a7,6 ecall dfc: 00000073 ecall ret e00: 8082 ret 0000000000000e02 <exec>: .global exec exec: li a7, SYS_exec e02: 489d li a7,7 ecall e04: 00000073 ecall ret e08: 8082 ret 0000000000000e0a <open>: .global open open: li a7, SYS_open e0a: 48bd li a7,15 ecall e0c: 00000073 ecall ret e10: 8082 ret 0000000000000e12 <mknod>: .global mknod mknod: li a7, SYS_mknod e12: 48c5 li a7,17 ecall e14: 00000073 ecall ret e18: 8082 ret 0000000000000e1a <unlink>: .global unlink unlink: li a7, SYS_unlink e1a: 48c9 li a7,18 ecall e1c: 00000073 ecall ret e20: 8082 ret 0000000000000e22 <fstat>: .global fstat fstat: li a7, SYS_fstat e22: 48a1 li a7,8 ecall e24: 00000073 ecall ret e28: 8082 ret 0000000000000e2a <link>: .global link link: li a7, SYS_link e2a: 48cd li a7,19 ecall e2c: 00000073 ecall ret e30: 8082 ret 0000000000000e32 <mkdir>: .global mkdir mkdir: li a7, SYS_mkdir e32: 48d1 li a7,20 ecall e34: 00000073 ecall ret e38: 8082 ret 0000000000000e3a <chdir>: .global chdir chdir: li a7, SYS_chdir e3a: 48a5 li a7,9 ecall e3c: 00000073 ecall ret e40: 8082 ret 0000000000000e42 <dup>: .global dup dup: li a7, SYS_dup e42: 48a9 li a7,10 ecall e44: 00000073 ecall ret e48: 8082 ret 0000000000000e4a <getpid>: .global getpid getpid: li a7, SYS_getpid e4a: 48ad li a7,11 ecall e4c: 00000073 ecall ret e50: 8082 ret 0000000000000e52 <sbrk>: .global sbrk sbrk: li a7, SYS_sbrk e52: 48b1 li a7,12 ecall e54: 00000073 ecall ret e58: 8082 ret 0000000000000e5a <sleep>: .global sleep sleep: li a7, SYS_sleep e5a: 48b5 li a7,13 ecall e5c: 00000073 ecall ret e60: 8082 ret 0000000000000e62 <uptime>: .global uptime uptime: li a7, SYS_uptime e62: 48b9 li a7,14 ecall e64: 00000073 ecall ret e68: 8082 ret 0000000000000e6a <connect>: .global connect connect: li a7, SYS_connect e6a: 48d9 li a7,22 ecall e6c: 00000073 ecall ret e70: 8082 ret 0000000000000e72 <ntas>: .global ntas ntas: li a7, SYS_ntas e72: 48dd li a7,23 ecall e74: 00000073 ecall ret e78: 8082 ret 0000000000000e7a <putc>: static char digits[] = "0123456789ABCDEF"; static void putc(int fd, char c) { e7a: 1101 addi sp,sp,-32 e7c: ec06 sd ra,24(sp) e7e: e822 sd s0,16(sp) e80: 1000 addi s0,sp,32 e82: feb407a3 sb a1,-17(s0) write(fd, &c, 1); e86: 4605 li a2,1 e88: fef40593 addi a1,s0,-17 e8c: 00000097 auipc ra,0x0 e90: f5e080e7 jalr -162(ra) # dea <write> } e94: 60e2 ld ra,24(sp) e96: 6442 ld s0,16(sp) e98: 6105 addi sp,sp,32 e9a: 8082 ret 0000000000000e9c <printint>: static void printint(int fd, int xx, int base, int sgn) { e9c: 7139 addi sp,sp,-64 e9e: fc06 sd ra,56(sp) ea0: f822 sd s0,48(sp) ea2: f426 sd s1,40(sp) ea4: f04a sd s2,32(sp) ea6: ec4e sd s3,24(sp) ea8: 0080 addi s0,sp,64 eaa: 84aa mv s1,a0 char buf[16]; int i, neg; uint x; neg = 0; if(sgn && xx < 0){ eac: c299 beqz a3,eb2 <printint+0x16> eae: 0805c863 bltz a1,f3e <printint+0xa2> neg = 1; x = -xx; } else { x = xx; eb2: 2581 sext.w a1,a1 neg = 0; eb4: 4881 li a7,0 eb6: fc040693 addi a3,s0,-64 } i = 0; eba: 4701 li a4,0 do{ buf[i++] = digits[x % base]; ebc: 2601 sext.w a2,a2 ebe: 00000517 auipc a0,0x0 ec2: 58250513 addi a0,a0,1410 # 1440 <digits> ec6: 883a mv a6,a4 ec8: 2705 addiw a4,a4,1 eca: 02c5f7bb remuw a5,a1,a2 ece: 1782 slli a5,a5,0x20 ed0: 9381 srli a5,a5,0x20 ed2: 97aa add a5,a5,a0 ed4: 0007c783 lbu a5,0(a5) ed8: 00f68023 sb a5,0(a3) }while((x /= base) != 0); edc: 0005879b sext.w a5,a1 ee0: 02c5d5bb divuw a1,a1,a2 ee4: 0685 addi a3,a3,1 ee6: fec7f0e3 bgeu a5,a2,ec6 <printint+0x2a> if(neg) eea: 00088b63 beqz a7,f00 <printint+0x64> buf[i++] = '-'; eee: fd040793 addi a5,s0,-48 ef2: 973e add a4,a4,a5 ef4: 02d00793 li a5,45 ef8: fef70823 sb a5,-16(a4) efc: 0028071b addiw a4,a6,2 while(--i >= 0) f00: 02e05863 blez a4,f30 <printint+0x94> f04: fc040793 addi a5,s0,-64 f08: 00e78933 add s2,a5,a4 f0c: fff78993 addi s3,a5,-1 f10: 99ba add s3,s3,a4 f12: 377d addiw a4,a4,-1 f14: 1702 slli a4,a4,0x20 f16: 9301 srli a4,a4,0x20 f18: 40e989b3 sub s3,s3,a4 putc(fd, buf[i]); f1c: fff94583 lbu a1,-1(s2) f20: 8526 mv a0,s1 f22: 00000097 auipc ra,0x0 f26: f58080e7 jalr -168(ra) # e7a <putc> while(--i >= 0) f2a: 197d addi s2,s2,-1 f2c: ff3918e3 bne s2,s3,f1c <printint+0x80> } f30: 70e2 ld ra,56(sp) f32: 7442 ld s0,48(sp) f34: 74a2 ld s1,40(sp) f36: 7902 ld s2,32(sp) f38: 69e2 ld s3,24(sp) f3a: 6121 addi sp,sp,64 f3c: 8082 ret x = -xx; f3e: 40b005bb negw a1,a1 neg = 1; f42: 4885 li a7,1 x = -xx; f44: bf8d j eb6 <printint+0x1a> 0000000000000f46 <vprintf>: } // Print to the given fd. Only understands %d, %x, %p, %s. void vprintf(int fd, const char *fmt, va_list ap) { f46: 7119 addi sp,sp,-128 f48: fc86 sd ra,120(sp) f4a: f8a2 sd s0,112(sp) f4c: f4a6 sd s1,104(sp) f4e: f0ca sd s2,96(sp) f50: ecce sd s3,88(sp) f52: e8d2 sd s4,80(sp) f54: e4d6 sd s5,72(sp) f56: e0da sd s6,64(sp) f58: fc5e sd s7,56(sp) f5a: f862 sd s8,48(sp) f5c: f466 sd s9,40(sp) f5e: f06a sd s10,32(sp) f60: ec6e sd s11,24(sp) f62: 0100 addi s0,sp,128 char *s; int c, i, state; state = 0; for(i = 0; fmt[i]; i++){ f64: 0005c903 lbu s2,0(a1) f68: 18090f63 beqz s2,1106 <vprintf+0x1c0> f6c: 8aaa mv s5,a0 f6e: 8b32 mv s6,a2 f70: 00158493 addi s1,a1,1 state = 0; f74: 4981 li s3,0 if(c == '%'){ state = '%'; } else { putc(fd, c); } } else if(state == '%'){ f76: 02500a13 li s4,37 if(c == 'd'){ f7a: 06400c13 li s8,100 printint(fd, va_arg(ap, int), 10, 1); } else if(c == 'l') { f7e: 06c00c93 li s9,108 printint(fd, va_arg(ap, uint64), 10, 0); } else if(c == 'x') { f82: 07800d13 li s10,120 printint(fd, va_arg(ap, int), 16, 0); } else if(c == 'p') { f86: 07000d93 li s11,112 putc(fd, digits[x >> (sizeof(uint64) * 8 - 4)]); f8a: 00000b97 auipc s7,0x0 f8e: 4b6b8b93 addi s7,s7,1206 # 1440 <digits> f92: a839 j fb0 <vprintf+0x6a> putc(fd, c); f94: 85ca mv a1,s2 f96: 8556 mv a0,s5 f98: 00000097 auipc ra,0x0 f9c: ee2080e7 jalr -286(ra) # e7a <putc> fa0: a019 j fa6 <vprintf+0x60> } else if(state == '%'){ fa2: 01498f63 beq s3,s4,fc0 <vprintf+0x7a> for(i = 0; fmt[i]; i++){ fa6: 0485 addi s1,s1,1 fa8: fff4c903 lbu s2,-1(s1) fac: 14090d63 beqz s2,1106 <vprintf+0x1c0> c = fmt[i] & 0xff; fb0: 0009079b sext.w a5,s2 if(state == 0){ fb4: fe0997e3 bnez s3,fa2 <vprintf+0x5c> if(c == '%'){ fb8: fd479ee3 bne a5,s4,f94 <vprintf+0x4e> state = '%'; fbc: 89be mv s3,a5 fbe: b7e5 j fa6 <vprintf+0x60> if(c == 'd'){ fc0: 05878063 beq a5,s8,1000 <vprintf+0xba> } else if(c == 'l') { fc4: 05978c63 beq a5,s9,101c <vprintf+0xd6> } else if(c == 'x') { fc8: 07a78863 beq a5,s10,1038 <vprintf+0xf2> } else if(c == 'p') { fcc: 09b78463 beq a5,s11,1054 <vprintf+0x10e> printptr(fd, va_arg(ap, uint64)); } else if(c == 's'){ fd0: 07300713 li a4,115 fd4: 0ce78663 beq a5,a4,10a0 <vprintf+0x15a> s = "(null)"; while(*s != 0){ putc(fd, *s); s++; } } else if(c == 'c'){ fd8: 06300713 li a4,99 fdc: 0ee78e63 beq a5,a4,10d8 <vprintf+0x192> putc(fd, va_arg(ap, uint)); } else if(c == '%'){ fe0: 11478863 beq a5,s4,10f0 <vprintf+0x1aa> putc(fd, c); } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); fe4: 85d2 mv a1,s4 fe6: 8556 mv a0,s5 fe8: 00000097 auipc ra,0x0 fec: e92080e7 jalr -366(ra) # e7a <putc> putc(fd, c); ff0: 85ca mv a1,s2 ff2: 8556 mv a0,s5 ff4: 00000097 auipc ra,0x0 ff8: e86080e7 jalr -378(ra) # e7a <putc> } state = 0; ffc: 4981 li s3,0 ffe: b765 j fa6 <vprintf+0x60> printint(fd, va_arg(ap, int), 10, 1); 1000: 008b0913 addi s2,s6,8 1004: 4685 li a3,1 1006: 4629 li a2,10 1008: 000b2583 lw a1,0(s6) 100c: 8556 mv a0,s5 100e: 00000097 auipc ra,0x0 1012: e8e080e7 jalr -370(ra) # e9c <printint> 1016: 8b4a mv s6,s2 state = 0; 1018: 4981 li s3,0 101a: b771 j fa6 <vprintf+0x60> printint(fd, va_arg(ap, uint64), 10, 0); 101c: 008b0913 addi s2,s6,8 1020: 4681 li a3,0 1022: 4629 li a2,10 1024: 000b2583 lw a1,0(s6) 1028: 8556 mv a0,s5 102a: 00000097 auipc ra,0x0 102e: e72080e7 jalr -398(ra) # e9c <printint> 1032: 8b4a mv s6,s2 state = 0; 1034: 4981 li s3,0 1036: bf85 j fa6 <vprintf+0x60> printint(fd, va_arg(ap, int), 16, 0); 1038: 008b0913 addi s2,s6,8 103c: 4681 li a3,0 103e: 4641 li a2,16 1040: 000b2583 lw a1,0(s6) 1044: 8556 mv a0,s5 1046: 00000097 auipc ra,0x0 104a: e56080e7 jalr -426(ra) # e9c <printint> 104e: 8b4a mv s6,s2 state = 0; 1050: 4981 li s3,0 1052: bf91 j fa6 <vprintf+0x60> printptr(fd, va_arg(ap, uint64)); 1054: 008b0793 addi a5,s6,8 1058: f8f43423 sd a5,-120(s0) 105c: 000b3983 ld s3,0(s6) putc(fd, '0'); 1060: 03000593 li a1,48 1064: 8556 mv a0,s5 1066: 00000097 auipc ra,0x0 106a: e14080e7 jalr -492(ra) # e7a <putc> putc(fd, 'x'); 106e: 85ea mv a1,s10 1070: 8556 mv a0,s5 1072: 00000097 auipc ra,0x0 1076: e08080e7 jalr -504(ra) # e7a <putc> 107a: 4941 li s2,16 putc(fd, digits[x >> (sizeof(uint64) * 8 - 4)]); 107c: 03c9d793 srli a5,s3,0x3c 1080: 97de add a5,a5,s7 1082: 0007c583 lbu a1,0(a5) 1086: 8556 mv a0,s5 1088: 00000097 auipc ra,0x0 108c: df2080e7 jalr -526(ra) # e7a <putc> for (i = 0; i < (sizeof(uint64) * 2); i++, x <<= 4) 1090: 0992 slli s3,s3,0x4 1092: 397d addiw s2,s2,-1 1094: fe0914e3 bnez s2,107c <vprintf+0x136> printptr(fd, va_arg(ap, uint64)); 1098: f8843b03 ld s6,-120(s0) state = 0; 109c: 4981 li s3,0 109e: b721 j fa6 <vprintf+0x60> s = va_arg(ap, char*); 10a0: 008b0993 addi s3,s6,8 10a4: 000b3903 ld s2,0(s6) if(s == 0) 10a8: 02090163 beqz s2,10ca <vprintf+0x184> while(*s != 0){ 10ac: 00094583 lbu a1,0(s2) 10b0: c9a1 beqz a1,1100 <vprintf+0x1ba> putc(fd, *s); 10b2: 8556 mv a0,s5 10b4: 00000097 auipc ra,0x0 10b8: dc6080e7 jalr -570(ra) # e7a <putc> s++; 10bc: 0905 addi s2,s2,1 while(*s != 0){ 10be: 00094583 lbu a1,0(s2) 10c2: f9e5 bnez a1,10b2 <vprintf+0x16c> s = va_arg(ap, char*); 10c4: 8b4e mv s6,s3 state = 0; 10c6: 4981 li s3,0 10c8: bdf9 j fa6 <vprintf+0x60> s = "(null)"; 10ca: 00000917 auipc s2,0x0 10ce: 36e90913 addi s2,s2,878 # 1438 <malloc+0x228> while(*s != 0){ 10d2: 02800593 li a1,40 10d6: bff1 j 10b2 <vprintf+0x16c> putc(fd, va_arg(ap, uint)); 10d8: 008b0913 addi s2,s6,8 10dc: 000b4583 lbu a1,0(s6) 10e0: 8556 mv a0,s5 10e2: 00000097 auipc ra,0x0 10e6: d98080e7 jalr -616(ra) # e7a <putc> 10ea: 8b4a mv s6,s2 state = 0; 10ec: 4981 li s3,0 10ee: bd65 j fa6 <vprintf+0x60> putc(fd, c); 10f0: 85d2 mv a1,s4 10f2: 8556 mv a0,s5 10f4: 00000097 auipc ra,0x0 10f8: d86080e7 jalr -634(ra) # e7a <putc> state = 0; 10fc: 4981 li s3,0 10fe: b565 j fa6 <vprintf+0x60> s = va_arg(ap, char*); 1100: 8b4e mv s6,s3 state = 0; 1102: 4981 li s3,0 1104: b54d j fa6 <vprintf+0x60> } } } 1106: 70e6 ld ra,120(sp) 1108: 7446 ld s0,112(sp) 110a: 74a6 ld s1,104(sp) 110c: 7906 ld s2,96(sp) 110e: 69e6 ld s3,88(sp) 1110: 6a46 ld s4,80(sp) 1112: 6aa6 ld s5,72(sp) 1114: 6b06 ld s6,64(sp) 1116: 7be2 ld s7,56(sp) 1118: 7c42 ld s8,48(sp) 111a: 7ca2 ld s9,40(sp) 111c: 7d02 ld s10,32(sp) 111e: 6de2 ld s11,24(sp) 1120: 6109 addi sp,sp,128 1122: 8082 ret 0000000000001124 <fprintf>: void fprintf(int fd, const char *fmt, ...) { 1124: 715d addi sp,sp,-80 1126: ec06 sd ra,24(sp) 1128: e822 sd s0,16(sp) 112a: 1000 addi s0,sp,32 112c: e010 sd a2,0(s0) 112e: e414 sd a3,8(s0) 1130: e818 sd a4,16(s0) 1132: ec1c sd a5,24(s0) 1134: 03043023 sd a6,32(s0) 1138: 03143423 sd a7,40(s0) va_list ap; va_start(ap, fmt); 113c: fe843423 sd s0,-24(s0) vprintf(fd, fmt, ap); 1140: 8622 mv a2,s0 1142: 00000097 auipc ra,0x0 1146: e04080e7 jalr -508(ra) # f46 <vprintf> } 114a: 60e2 ld ra,24(sp) 114c: 6442 ld s0,16(sp) 114e: 6161 addi sp,sp,80 1150: 8082 ret 0000000000001152 <printf>: void printf(const char *fmt, ...) { 1152: 711d addi sp,sp,-96 1154: ec06 sd ra,24(sp) 1156: e822 sd s0,16(sp) 1158: 1000 addi s0,sp,32 115a: e40c sd a1,8(s0) 115c: e810 sd a2,16(s0) 115e: ec14 sd a3,24(s0) 1160: f018 sd a4,32(s0) 1162: f41c sd a5,40(s0) 1164: 03043823 sd a6,48(s0) 1168: 03143c23 sd a7,56(s0) va_list ap; va_start(ap, fmt); 116c: 00840613 addi a2,s0,8 1170: fec43423 sd a2,-24(s0) vprintf(1, fmt, ap); 1174: 85aa mv a1,a0 1176: 4505 li a0,1 1178: 00000097 auipc ra,0x0 117c: dce080e7 jalr -562(ra) # f46 <vprintf> } 1180: 60e2 ld ra,24(sp) 1182: 6442 ld s0,16(sp) 1184: 6125 addi sp,sp,96 1186: 8082 ret 0000000000001188 <free>: static Header base; static Header *freep; void free(void *ap) { 1188: 1141 addi sp,sp,-16 118a: e422 sd s0,8(sp) 118c: 0800 addi s0,sp,16 Header *bp, *p; bp = (Header*)ap - 1; 118e: ff050693 addi a3,a0,-16 for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 1192: 00000797 auipc a5,0x0 1196: 2d67b783 ld a5,726(a5) # 1468 <freep> 119a: a805 j 11ca <free+0x42> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ bp->s.size += p->s.ptr->s.size; 119c: 4618 lw a4,8(a2) 119e: 9db9 addw a1,a1,a4 11a0: feb52c23 sw a1,-8(a0) bp->s.ptr = p->s.ptr->s.ptr; 11a4: 6398 ld a4,0(a5) 11a6: 6318 ld a4,0(a4) 11a8: fee53823 sd a4,-16(a0) 11ac: a091 j 11f0 <free+0x68> } else bp->s.ptr = p->s.ptr; if(p + p->s.size == bp){ p->s.size += bp->s.size; 11ae: ff852703 lw a4,-8(a0) 11b2: 9e39 addw a2,a2,a4 11b4: c790 sw a2,8(a5) p->s.ptr = bp->s.ptr; 11b6: ff053703 ld a4,-16(a0) 11ba: e398 sd a4,0(a5) 11bc: a099 j 1202 <free+0x7a> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 11be: 6398 ld a4,0(a5) 11c0: 00e7e463 bltu a5,a4,11c8 <free+0x40> 11c4: 00e6ea63 bltu a3,a4,11d8 <free+0x50> { 11c8: 87ba mv a5,a4 for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 11ca: fed7fae3 bgeu a5,a3,11be <free+0x36> 11ce: 6398 ld a4,0(a5) 11d0: 00e6e463 bltu a3,a4,11d8 <free+0x50> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 11d4: fee7eae3 bltu a5,a4,11c8 <free+0x40> if(bp + bp->s.size == p->s.ptr){ 11d8: ff852583 lw a1,-8(a0) 11dc: 6390 ld a2,0(a5) 11de: 02059713 slli a4,a1,0x20 11e2: 9301 srli a4,a4,0x20 11e4: 0712 slli a4,a4,0x4 11e6: 9736 add a4,a4,a3 11e8: fae60ae3 beq a2,a4,119c <free+0x14> bp->s.ptr = p->s.ptr; 11ec: fec53823 sd a2,-16(a0) if(p + p->s.size == bp){ 11f0: 4790 lw a2,8(a5) 11f2: 02061713 slli a4,a2,0x20 11f6: 9301 srli a4,a4,0x20 11f8: 0712 slli a4,a4,0x4 11fa: 973e add a4,a4,a5 11fc: fae689e3 beq a3,a4,11ae <free+0x26> } else p->s.ptr = bp; 1200: e394 sd a3,0(a5) freep = p; 1202: 00000717 auipc a4,0x0 1206: 26f73323 sd a5,614(a4) # 1468 <freep> } 120a: 6422 ld s0,8(sp) 120c: 0141 addi sp,sp,16 120e: 8082 ret 0000000000001210 <malloc>: return freep; } void* malloc(uint nbytes) { 1210: 7139 addi sp,sp,-64 1212: fc06 sd ra,56(sp) 1214: f822 sd s0,48(sp) 1216: f426 sd s1,40(sp) 1218: f04a sd s2,32(sp) 121a: ec4e sd s3,24(sp) 121c: e852 sd s4,16(sp) 121e: e456 sd s5,8(sp) 1220: e05a sd s6,0(sp) 1222: 0080 addi s0,sp,64 Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 1224: 02051493 slli s1,a0,0x20 1228: 9081 srli s1,s1,0x20 122a: 04bd addi s1,s1,15 122c: 8091 srli s1,s1,0x4 122e: 0014899b addiw s3,s1,1 1232: 0485 addi s1,s1,1 if((prevp = freep) == 0){ 1234: 00000517 auipc a0,0x0 1238: 23453503 ld a0,564(a0) # 1468 <freep> 123c: c515 beqz a0,1268 <malloc+0x58> base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 123e: 611c ld a5,0(a0) if(p->s.size >= nunits){ 1240: 4798 lw a4,8(a5) 1242: 02977f63 bgeu a4,s1,1280 <malloc+0x70> 1246: 8a4e mv s4,s3 1248: 0009871b sext.w a4,s3 124c: 6685 lui a3,0x1 124e: 00d77363 bgeu a4,a3,1254 <malloc+0x44> 1252: 6a05 lui s4,0x1 1254: 000a0b1b sext.w s6,s4 p = sbrk(nu * sizeof(Header)); 1258: 004a1a1b slliw s4,s4,0x4 p->s.size = nunits; } freep = prevp; return (void*)(p + 1); } if(p == freep) 125c: 00000917 auipc s2,0x0 1260: 20c90913 addi s2,s2,524 # 1468 <freep> if(p == (char*)-1) 1264: 5afd li s5,-1 1266: a88d j 12d8 <malloc+0xc8> base.s.ptr = freep = prevp = &base; 1268: 00000797 auipc a5,0x0 126c: 27078793 addi a5,a5,624 # 14d8 <base> 1270: 00000717 auipc a4,0x0 1274: 1ef73c23 sd a5,504(a4) # 1468 <freep> 1278: e39c sd a5,0(a5) base.s.size = 0; 127a: 0007a423 sw zero,8(a5) if(p->s.size >= nunits){ 127e: b7e1 j 1246 <malloc+0x36> if(p->s.size == nunits) 1280: 02e48b63 beq s1,a4,12b6 <malloc+0xa6> p->s.size -= nunits; 1284: 4137073b subw a4,a4,s3 1288: c798 sw a4,8(a5) p += p->s.size; 128a: 1702 slli a4,a4,0x20 128c: 9301 srli a4,a4,0x20 128e: 0712 slli a4,a4,0x4 1290: 97ba add a5,a5,a4 p->s.size = nunits; 1292: 0137a423 sw s3,8(a5) freep = prevp; 1296: 00000717 auipc a4,0x0 129a: 1ca73923 sd a0,466(a4) # 1468 <freep> return (void*)(p + 1); 129e: 01078513 addi a0,a5,16 if((p = morecore(nunits)) == 0) return 0; } } 12a2: 70e2 ld ra,56(sp) 12a4: 7442 ld s0,48(sp) 12a6: 74a2 ld s1,40(sp) 12a8: 7902 ld s2,32(sp) 12aa: 69e2 ld s3,24(sp) 12ac: 6a42 ld s4,16(sp) 12ae: 6aa2 ld s5,8(sp) 12b0: 6b02 ld s6,0(sp) 12b2: 6121 addi sp,sp,64 12b4: 8082 ret prevp->s.ptr = p->s.ptr; 12b6: 6398 ld a4,0(a5) 12b8: e118 sd a4,0(a0) 12ba: bff1 j 1296 <malloc+0x86> hp->s.size = nu; 12bc: 01652423 sw s6,8(a0) free((void*)(hp + 1)); 12c0: 0541 addi a0,a0,16 12c2: 00000097 auipc ra,0x0 12c6: ec6080e7 jalr -314(ra) # 1188 <free> return freep; 12ca: 00093503 ld a0,0(s2) if((p = morecore(nunits)) == 0) 12ce: d971 beqz a0,12a2 <malloc+0x92> for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 12d0: 611c ld a5,0(a0) if(p->s.size >= nunits){ 12d2: 4798 lw a4,8(a5) 12d4: fa9776e3 bgeu a4,s1,1280 <malloc+0x70> if(p == freep) 12d8: 00093703 ld a4,0(s2) 12dc: 853e mv a0,a5 12de: fef719e3 bne a4,a5,12d0 <malloc+0xc0> p = sbrk(nu * sizeof(Header)); 12e2: 8552 mv a0,s4 12e4: 00000097 auipc ra,0x0 12e8: b6e080e7 jalr -1170(ra) # e52 <sbrk> if(p == (char*)-1) 12ec: fd5518e3 bne a0,s5,12bc <malloc+0xac> return 0; 12f0: 4501 li a0,0 12f2: bf45 j 12a2 <malloc+0x92>
; A021311: Decimal expansion of 1/307. ; Submitted by Jamie Morken(s2.) ; 0,0,3,2,5,7,3,2,8,9,9,0,2,2,8,0,1,3,0,2,9,3,1,5,9,6,0,9,1,2,0,5,2,1,1,7,2,6,3,8,4,3,6,4,8,2,0,8,4,6,9,0,5,5,3,7,4,5,9,2,8,3,3,8,7,6,2,2,1,4,9,8,3,7,1,3,3,5,5,0,4,8,8,5,9,9,3,4,8,5,3,4,2,0,1,9,5,4,3 seq $0,173833 ; 10^n - 3. div $0,307 mod $0,10
// Copyright (c) 2014-2017 The zaap Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "privatesend-client.h" #include "coincontrol.h" #include "consensus/validation.h" #include "core_io.h" #include "init.h" #include "masternode-sync.h" #include "masternodeman.h" #include "script/sign.h" #include "txmempool.h" #include "util.h" #include "utilmoneystr.h" #include <memory> CPrivateSendClient privateSendClient; void CPrivateSendClient::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv, CConnman& connman) { if(fMasterNode) return; if(fLiteMode) return; // ignore all zaap related functionality if(!masternodeSync.IsBlockchainSynced()) return; if(strCommand == NetMsgType::DSQUEUE) { TRY_LOCK(cs_darksend, lockRecv); if(!lockRecv) return; if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrint("privatesend", "DSQUEUE -- incompatible version! nVersion: %d\n", pfrom->nVersion); return; } CDarksendQueue dsq; vRecv >> dsq; // process every dsq only once BOOST_FOREACH(CDarksendQueue q, vecDarksendQueue) { if(q == dsq) { // LogPrint("privatesend", "DSQUEUE -- %s seen\n", dsq.ToString()); return; } } LogPrint("privatesend", "DSQUEUE -- %s new\n", dsq.ToString()); if(dsq.IsExpired()) return; masternode_info_t infoMn; if(!mnodeman.GetMasternodeInfo(dsq.vin.prevout, infoMn)) return; if(!dsq.CheckSignature(infoMn.pubKeyMasternode)) { // we probably have outdated info mnodeman.AskForMN(pfrom, dsq.vin.prevout, connman); return; } // if the queue is ready, submit if we can if(dsq.fReady) { if(!infoMixingMasternode.fInfoValid) return; if(infoMixingMasternode.addr != infoMn.addr) { LogPrintf("DSQUEUE -- message doesn't match current Masternode: infoMixingMasternode=%s, addr=%s\n", infoMixingMasternode.addr.ToString(), infoMn.addr.ToString()); return; } if(nState == POOL_STATE_QUEUE) { LogPrint("privatesend", "DSQUEUE -- PrivateSend queue (%s) is ready on masternode %s\n", dsq.ToString(), infoMn.addr.ToString()); SubmitDenominate(connman); } } else { BOOST_FOREACH(CDarksendQueue q, vecDarksendQueue) { if(q.vin == dsq.vin) { // no way same mn can send another "not yet ready" dsq this soon LogPrint("privatesend", "DSQUEUE -- Masternode %s is sending WAY too many dsq messages\n", infoMn.addr.ToString()); return; } } int nThreshold = infoMn.nLastDsq + mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION)/5; LogPrint("privatesend", "DSQUEUE -- nLastDsq: %d threshold: %d nDsqCount: %d\n", infoMn.nLastDsq, nThreshold, mnodeman.nDsqCount); //don't allow a few nodes to dominate the queuing process if(infoMn.nLastDsq != 0 && nThreshold > mnodeman.nDsqCount) { LogPrint("privatesend", "DSQUEUE -- Masternode %s is sending too many dsq messages\n", infoMn.addr.ToString()); return; } if(!mnodeman.AllowMixing(dsq.vin.prevout)) return; LogPrint("privatesend", "DSQUEUE -- new PrivateSend queue (%s) from masternode %s\n", dsq.ToString(), infoMn.addr.ToString()); if(infoMixingMasternode.fInfoValid && infoMixingMasternode.vin.prevout == dsq.vin.prevout) { dsq.fTried = true; } vecDarksendQueue.push_back(dsq); dsq.Relay(connman); } } else if(strCommand == NetMsgType::DSSTATUSUPDATE) { if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrintf("DSSTATUSUPDATE -- incompatible version! nVersion: %d\n", pfrom->nVersion); return; } if(!infoMixingMasternode.fInfoValid) return; if(infoMixingMasternode.addr != pfrom->addr) { //LogPrintf("DSSTATUSUPDATE -- message doesn't match current Masternode: infoMixingMasternode %s addr %s\n", infoMixingMasternode.addr.ToString(), pfrom->addr.ToString()); return; } int nMsgSessionID; int nMsgState; int nMsgEntriesCount; int nMsgStatusUpdate; int nMsgMessageID; vRecv >> nMsgSessionID >> nMsgState >> nMsgEntriesCount >> nMsgStatusUpdate >> nMsgMessageID; LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgSessionID %d nMsgState: %d nEntriesCount: %d nMsgStatusUpdate: %d nMsgMessageID %d\n", nMsgSessionID, nMsgState, nEntriesCount, nMsgStatusUpdate, nMsgMessageID); if(nMsgState < POOL_STATE_MIN || nMsgState > POOL_STATE_MAX) { LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgState is out of bounds: %d\n", nMsgState); return; } if(nMsgStatusUpdate < STATUS_REJECTED || nMsgStatusUpdate > STATUS_ACCEPTED) { LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgStatusUpdate is out of bounds: %d\n", nMsgStatusUpdate); return; } if(nMsgMessageID < MSG_POOL_MIN || nMsgMessageID > MSG_POOL_MAX) { LogPrint("privatesend", "DSSTATUSUPDATE -- nMsgMessageID is out of bounds: %d\n", nMsgMessageID); return; } LogPrint("privatesend", "DSSTATUSUPDATE -- GetMessageByID: %s\n", CPrivateSend::GetMessageByID(PoolMessage(nMsgMessageID))); if(!CheckPoolStateUpdate(PoolState(nMsgState), nMsgEntriesCount, PoolStatusUpdate(nMsgStatusUpdate), PoolMessage(nMsgMessageID), nMsgSessionID)) { LogPrint("privatesend", "DSSTATUSUPDATE -- CheckPoolStateUpdate failed\n"); } } else if(strCommand == NetMsgType::DSFINALTX) { if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrintf("DSFINALTX -- incompatible version! nVersion: %d\n", pfrom->nVersion); return; } if(!infoMixingMasternode.fInfoValid) return; if(infoMixingMasternode.addr != pfrom->addr) { //LogPrintf("DSFINALTX -- message doesn't match current Masternode: infoMixingMasternode %s addr %s\n", infoMixingMasternode.addr.ToString(), pfrom->addr.ToString()); return; } int nMsgSessionID; CTransaction txNew; vRecv >> nMsgSessionID >> txNew; if(nSessionID != nMsgSessionID) { LogPrint("privatesend", "DSFINALTX -- message doesn't match current PrivateSend session: nSessionID: %d nMsgSessionID: %d\n", nSessionID, nMsgSessionID); return; } LogPrint("privatesend", "DSFINALTX -- txNew %s", txNew.ToString()); //check to see if input is spent already? (and probably not confirmed) SignFinalTransaction(txNew, pfrom, connman); } else if(strCommand == NetMsgType::DSCOMPLETE) { if(pfrom->nVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) { LogPrintf("DSCOMPLETE -- incompatible version! nVersion: %d\n", pfrom->nVersion); return; } if(!infoMixingMasternode.fInfoValid) return; if(infoMixingMasternode.addr != pfrom->addr) { LogPrint("privatesend", "DSCOMPLETE -- message doesn't match current Masternode: infoMixingMasternode=%s addr=%s\n", infoMixingMasternode.addr.ToString(), pfrom->addr.ToString()); return; } int nMsgSessionID; int nMsgMessageID; vRecv >> nMsgSessionID >> nMsgMessageID; if(nMsgMessageID < MSG_POOL_MIN || nMsgMessageID > MSG_POOL_MAX) { LogPrint("privatesend", "DSCOMPLETE -- nMsgMessageID is out of bounds: %d\n", nMsgMessageID); return; } if(nSessionID != nMsgSessionID) { LogPrint("privatesend", "DSCOMPLETE -- message doesn't match current PrivateSend session: nSessionID: %d nMsgSessionID: %d\n", nSessionID, nMsgSessionID); return; } LogPrint("privatesend", "DSCOMPLETE -- nMsgSessionID %d nMsgMessageID %d (%s)\n", nMsgSessionID, nMsgMessageID, CPrivateSend::GetMessageByID(PoolMessage(nMsgMessageID))); CompletedTransaction(PoolMessage(nMsgMessageID)); } } void CPrivateSendClient::ResetPool() { nCachedLastSuccessBlock = 0; txMyCollateral = CMutableTransaction(); vecMasternodesUsed.clear(); UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); } void CPrivateSendClient::SetNull() { // Client side nEntriesCount = 0; fLastEntryAccepted = false; infoMixingMasternode = masternode_info_t(); CPrivateSendBase::SetNull(); } // // Unlock coins after mixing fails or succeeds // void CPrivateSendClient::UnlockCoins() { while(true) { TRY_LOCK(pwalletMain->cs_wallet, lockWallet); if(!lockWallet) {MilliSleep(50); continue;} BOOST_FOREACH(COutPoint outpoint, vecOutPointLocked) pwalletMain->UnlockCoin(outpoint); break; } vecOutPointLocked.clear(); } std::string CPrivateSendClient::GetStatus() { static int nStatusMessageProgress = 0; nStatusMessageProgress += 10; std::string strSuffix = ""; if(WaitForAnotherBlock() || !masternodeSync.IsBlockchainSynced()) return strAutoDenomResult; switch(nState) { case POOL_STATE_IDLE: return _("PrivateSend is idle."); case POOL_STATE_QUEUE: if( nStatusMessageProgress % 70 <= 30) strSuffix = "."; else if(nStatusMessageProgress % 70 <= 50) strSuffix = ".."; else if(nStatusMessageProgress % 70 <= 70) strSuffix = "..."; return strprintf(_("Submitted to masternode, waiting in queue %s"), strSuffix);; case POOL_STATE_ACCEPTING_ENTRIES: if(nEntriesCount == 0) { nStatusMessageProgress = 0; return strAutoDenomResult; } else if(fLastEntryAccepted) { if(nStatusMessageProgress % 10 > 8) { fLastEntryAccepted = false; nStatusMessageProgress = 0; } return _("PrivateSend request complete:") + " " + _("Your transaction was accepted into the pool!"); } else { if( nStatusMessageProgress % 70 <= 40) return strprintf(_("Submitted following entries to masternode: %u / %d"), nEntriesCount, CPrivateSend::GetMaxPoolTransactions()); else if(nStatusMessageProgress % 70 <= 50) strSuffix = "."; else if(nStatusMessageProgress % 70 <= 60) strSuffix = ".."; else if(nStatusMessageProgress % 70 <= 70) strSuffix = "..."; return strprintf(_("Submitted to masternode, waiting for more entries ( %u / %d ) %s"), nEntriesCount, CPrivateSend::GetMaxPoolTransactions(), strSuffix); } case POOL_STATE_SIGNING: if( nStatusMessageProgress % 70 <= 40) return _("Found enough users, signing ..."); else if(nStatusMessageProgress % 70 <= 50) strSuffix = "."; else if(nStatusMessageProgress % 70 <= 60) strSuffix = ".."; else if(nStatusMessageProgress % 70 <= 70) strSuffix = "..."; return strprintf(_("Found enough users, signing ( waiting %s )"), strSuffix); case POOL_STATE_ERROR: return _("PrivateSend request incomplete:") + " " + strLastMessage + " " + _("Will retry..."); case POOL_STATE_SUCCESS: return _("PrivateSend request complete:") + " " + strLastMessage; default: return strprintf(_("Unknown state: id = %u"), nState); } } bool CPrivateSendClient::GetMixingMasternodeInfo(masternode_info_t& mnInfoRet) { mnInfoRet = infoMixingMasternode.fInfoValid ? infoMixingMasternode : masternode_info_t(); return infoMixingMasternode.fInfoValid; } bool CPrivateSendClient::IsMixingMasternode(const CNode* pnode) { return infoMixingMasternode.fInfoValid && pnode->addr == infoMixingMasternode.addr; } // // Check the mixing progress and send client updates if a Masternode // void CPrivateSendClient::CheckPool() { // reset if we're here for 10 seconds if((nState == POOL_STATE_ERROR || nState == POOL_STATE_SUCCESS) && GetTimeMillis() - nTimeLastSuccessfulStep >= 10000) { LogPrint("privatesend", "CPrivateSendClient::CheckPool -- timeout, RESETTING\n"); UnlockCoins(); if (nState == POOL_STATE_ERROR) { keyHolderStorage.ReturnAll(); } else { keyHolderStorage.KeepAll(); } SetNull(); } } // // Check for various timeouts (queue objects, mixing, etc) // void CPrivateSendClient::CheckTimeout() { CheckQueue(); if(!fEnablePrivateSend && !fMasterNode) return; // catching hanging sessions if(!fMasterNode) { switch(nState) { case POOL_STATE_ERROR: LogPrint("privatesend", "CPrivateSendClient::CheckTimeout -- Pool error -- Running CheckPool\n"); CheckPool(); break; case POOL_STATE_SUCCESS: LogPrint("privatesend", "CPrivateSendClient::CheckTimeout -- Pool success -- Running CheckPool\n"); CheckPool(); break; default: break; } } int nLagTime = fMasterNode ? 0 : 10000; // if we're the client, give the server a few extra seconds before resetting. int nTimeout = (nState == POOL_STATE_SIGNING) ? PRIVATESEND_SIGNING_TIMEOUT : PRIVATESEND_QUEUE_TIMEOUT; bool fTimeout = GetTimeMillis() - nTimeLastSuccessfulStep >= nTimeout*1000 + nLagTime; if(nState != POOL_STATE_IDLE && fTimeout) { LogPrint("privatesend", "CPrivateSendClient::CheckTimeout -- %s timed out (%ds) -- restting\n", (nState == POOL_STATE_SIGNING) ? "Signing" : "Session", nTimeout); UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); SetState(POOL_STATE_ERROR); strLastMessage = _("Session timed out."); } } // // Execute a mixing denomination via a Masternode. // This is only ran from clients // bool CPrivateSendClient::SendDenominate(const std::vector<CTxDSIn>& vecTxDSIn, const std::vector<CTxOut>& vecTxOut, CConnman& connman) { if(fMasterNode) { LogPrintf("CPrivateSendClient::SendDenominate -- PrivateSend from a Masternode is not supported currently.\n"); return false; } if(txMyCollateral == CMutableTransaction()) { LogPrintf("CPrivateSendClient:SendDenominate -- PrivateSend collateral not set\n"); return false; } // lock the funds we're going to use BOOST_FOREACH(CTxIn txin, txMyCollateral.vin) vecOutPointLocked.push_back(txin.prevout); for (const auto& txdsin : vecTxDSIn) vecOutPointLocked.push_back(txdsin.prevout); // we should already be connected to a Masternode if(!nSessionID) { LogPrintf("CPrivateSendClient::SendDenominate -- No Masternode has been selected yet.\n"); UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); return false; } if(!CheckDiskSpace()) { UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); fEnablePrivateSend = false; LogPrintf("CPrivateSendClient::SendDenominate -- Not enough disk space, disabling PrivateSend.\n"); return false; } SetState(POOL_STATE_ACCEPTING_ENTRIES); strLastMessage = ""; LogPrintf("CPrivateSendClient::SendDenominate -- Added transaction to pool.\n"); //check it against the memory pool to make sure it's valid { CValidationState validationState; CMutableTransaction tx; for (const auto& txdsin : vecTxDSIn) { LogPrint("privatesend", "CPrivateSendClient::SendDenominate -- txdsin=%s\n", txdsin.ToString()); tx.vin.push_back(txdsin); } BOOST_FOREACH(const CTxOut& txout, vecTxOut) { LogPrint("privatesend", "CPrivateSendClient::SendDenominate -- txout=%s\n", txout.ToString()); tx.vout.push_back(txout); } LogPrintf("CPrivateSendClient::SendDenominate -- Submitting partial tx %s", tx.ToString()); mempool.PrioritiseTransaction(tx.GetHash(), tx.GetHash().ToString(), 1000, 0.1*COIN); TRY_LOCK(cs_main, lockMain); if(!lockMain || !AcceptToMemoryPool(mempool, validationState, CTransaction(tx), false, NULL, false, true, true)) { LogPrintf("CPrivateSendClient::SendDenominate -- AcceptToMemoryPool() failed! tx=%s", tx.ToString()); UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); return false; } } // store our entry for later use CDarkSendEntry entry(vecTxDSIn, vecTxOut, txMyCollateral); vecEntries.push_back(entry); RelayIn(entry, connman); nTimeLastSuccessfulStep = GetTimeMillis(); return true; } // Incoming message from Masternode updating the progress of mixing bool CPrivateSendClient::CheckPoolStateUpdate(PoolState nStateNew, int nEntriesCountNew, PoolStatusUpdate nStatusUpdate, PoolMessage nMessageID, int nSessionIDNew) { if(fMasterNode) return false; // do not update state when mixing client state is one of these if(nState == POOL_STATE_IDLE || nState == POOL_STATE_ERROR || nState == POOL_STATE_SUCCESS) return false; strAutoDenomResult = _("Masternode:") + " " + CPrivateSend::GetMessageByID(nMessageID); // if rejected at any state if(nStatusUpdate == STATUS_REJECTED) { LogPrintf("CPrivateSendClient::CheckPoolStateUpdate -- entry is rejected by Masternode\n"); UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); SetState(POOL_STATE_ERROR); strLastMessage = CPrivateSend::GetMessageByID(nMessageID); return true; } if(nStatusUpdate == STATUS_ACCEPTED && nState == nStateNew) { if(nStateNew == POOL_STATE_QUEUE && nSessionID == 0 && nSessionIDNew != 0) { // new session id should be set only in POOL_STATE_QUEUE state nSessionID = nSessionIDNew; nTimeLastSuccessfulStep = GetTimeMillis(); LogPrintf("CPrivateSendClient::CheckPoolStateUpdate -- set nSessionID to %d\n", nSessionID); return true; } else if(nStateNew == POOL_STATE_ACCEPTING_ENTRIES && nEntriesCount != nEntriesCountNew) { nEntriesCount = nEntriesCountNew; nTimeLastSuccessfulStep = GetTimeMillis(); fLastEntryAccepted = true; LogPrintf("CPrivateSendClient::CheckPoolStateUpdate -- new entry accepted!\n"); return true; } } // only situations above are allowed, fail in any other case return false; } // // After we receive the finalized transaction from the Masternode, we must // check it to make sure it's what we want, then sign it if we agree. // If we refuse to sign, it's possible we'll be charged collateral // bool CPrivateSendClient::SignFinalTransaction(const CTransaction& finalTransactionNew, CNode* pnode, CConnman& connman) { if(fMasterNode || pnode == NULL) return false; finalMutableTransaction = finalTransactionNew; LogPrintf("CPrivateSendClient::SignFinalTransaction -- finalMutableTransaction=%s", finalMutableTransaction.ToString()); // Make sure it's BIP69 compliant sort(finalMutableTransaction.vin.begin(), finalMutableTransaction.vin.end(), CompareInputBIP69()); sort(finalMutableTransaction.vout.begin(), finalMutableTransaction.vout.end(), CompareOutputBIP69()); if(finalMutableTransaction.GetHash() != finalTransactionNew.GetHash()) { LogPrintf("CPrivateSendClient::SignFinalTransaction -- WARNING! Masternode %s is not BIP69 compliant!\n", infoMixingMasternode.vin.prevout.ToStringShort()); UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); return false; } std::vector<CTxIn> sigs; //make sure my inputs/outputs are present, otherwise refuse to sign BOOST_FOREACH(const CDarkSendEntry entry, vecEntries) { BOOST_FOREACH(const CTxDSIn txdsin, entry.vecTxDSIn) { /* Sign my transaction and all outputs */ int nMyInputIndex = -1; CScript prevPubKey = CScript(); CTxIn txin = CTxIn(); for(unsigned int i = 0; i < finalMutableTransaction.vin.size(); i++) { if(finalMutableTransaction.vin[i] == txdsin) { nMyInputIndex = i; prevPubKey = txdsin.prevPubKey; txin = txdsin; } } if(nMyInputIndex >= 0) { //might have to do this one input at a time? int nFoundOutputsCount = 0; CAmount nValue1 = 0; CAmount nValue2 = 0; for (const auto& txoutFinal : finalMutableTransaction.vout) { for (const auto& txout: entry.vecTxOut) { if(txoutFinal == txout) { nFoundOutputsCount++; nValue1 += txoutFinal.nValue; } } } for (const auto& txout : entry.vecTxOut) nValue2 += txout.nValue; int nTargetOuputsCount = entry.vecTxOut.size(); if(nFoundOutputsCount < nTargetOuputsCount || nValue1 != nValue2) { // in this case, something went wrong and we'll refuse to sign. It's possible we'll be charged collateral. But that's // better then signing if the transaction doesn't look like what we wanted. LogPrintf("CPrivateSendClient::SignFinalTransaction -- My entries are not correct! Refusing to sign: nFoundOutputsCount: %d, nTargetOuputsCount: %d\n", nFoundOutputsCount, nTargetOuputsCount); UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); return false; } const CKeyStore& keystore = *pwalletMain; LogPrint("privatesend", "CPrivateSendClient::SignFinalTransaction -- Signing my input %i\n", nMyInputIndex); if(!SignSignature(keystore, prevPubKey, finalMutableTransaction, nMyInputIndex, int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))) { // changes scriptSig LogPrint("privatesend", "CPrivateSendClient::SignFinalTransaction -- Unable to sign my own transaction!\n"); // not sure what to do here, it will timeout...? } sigs.push_back(finalMutableTransaction.vin[nMyInputIndex]); LogPrint("privatesend", "CPrivateSendClient::SignFinalTransaction -- nMyInputIndex: %d, sigs.size(): %d, scriptSig=%s\n", nMyInputIndex, (int)sigs.size(), ScriptToAsmStr(finalMutableTransaction.vin[nMyInputIndex].scriptSig)); } } } if(sigs.empty()) { LogPrintf("CPrivateSendClient::SignFinalTransaction -- can't sign anything!\n"); UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); return false; } // push all of our signatures to the Masternode LogPrintf("CPrivateSendClient::SignFinalTransaction -- pushing sigs to the masternode, finalMutableTransaction=%s", finalMutableTransaction.ToString()); connman.PushMessage(pnode, NetMsgType::DSSIGNFINALTX, sigs); SetState(POOL_STATE_SIGNING); nTimeLastSuccessfulStep = GetTimeMillis(); return true; } // mixing transaction was completed (failed or successful) void CPrivateSendClient::CompletedTransaction(PoolMessage nMessageID) { if(fMasterNode) return; if(nMessageID == MSG_SUCCESS) { LogPrintf("CompletedTransaction -- success\n"); nCachedLastSuccessBlock = nCachedBlockHeight; keyHolderStorage.KeepAll(); } else { LogPrintf("CompletedTransaction -- error\n"); keyHolderStorage.ReturnAll(); } UnlockCoins(); SetNull(); strLastMessage = CPrivateSend::GetMessageByID(nMessageID); } bool CPrivateSendClient::WaitForAnotherBlock() { if(!masternodeSync.IsMasternodeListSynced()) return true; if(fPrivateSendMultiSession) return false; return nCachedBlockHeight - nCachedLastSuccessBlock < nMinBlocksToWait; } bool CPrivateSendClient::CheckAutomaticBackup() { switch(nWalletBackups) { case 0: LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- Automatic backups disabled, no mixing available.\n"); strAutoDenomResult = _("Automatic backups disabled") + ", " + _("no mixing available."); fEnablePrivateSend = false; // stop mixing pwalletMain->nKeysLeftSinceAutoBackup = 0; // no backup, no "keys since last backup" return false; case -1: // Automatic backup failed, nothing else we can do until user fixes the issue manually. // There is no way to bring user attention in daemon mode so we just update status and // keep spaming if debug is on. LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- ERROR! Failed to create automatic backup.\n"); strAutoDenomResult = _("ERROR! Failed to create automatic backup") + ", " + _("see debug.log for details."); return false; case -2: // We were able to create automatic backup but keypool was not replenished because wallet is locked. // There is no way to bring user attention in daemon mode so we just update status and // keep spaming if debug is on. LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- WARNING! Failed to create replenish keypool, please unlock your wallet to do so.\n"); strAutoDenomResult = _("WARNING! Failed to replenish keypool, please unlock your wallet to do so.") + ", " + _("see debug.log for details."); return false; } if(pwalletMain->nKeysLeftSinceAutoBackup < PRIVATESEND_KEYS_THRESHOLD_STOP) { // We should never get here via mixing itself but probably smth else is still actively using keypool LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- Very low number of keys left: %d, no mixing available.\n", pwalletMain->nKeysLeftSinceAutoBackup); strAutoDenomResult = strprintf(_("Very low number of keys left: %d") + ", " + _("no mixing available."), pwalletMain->nKeysLeftSinceAutoBackup); // It's getting really dangerous, stop mixing fEnablePrivateSend = false; return false; } else if(pwalletMain->nKeysLeftSinceAutoBackup < PRIVATESEND_KEYS_THRESHOLD_WARNING) { // Low number of keys left but it's still more or less safe to continue LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- Very low number of keys left: %d\n", pwalletMain->nKeysLeftSinceAutoBackup); strAutoDenomResult = strprintf(_("Very low number of keys left: %d"), pwalletMain->nKeysLeftSinceAutoBackup); if(fCreateAutoBackups) { LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- Trying to create new backup.\n"); std::string warningString; std::string errorString; if(!AutoBackupWallet(pwalletMain, "", warningString, errorString)) { if(!warningString.empty()) { // There were some issues saving backup but yet more or less safe to continue LogPrintf("CPrivateSendClient::CheckAutomaticBackup -- WARNING! Something went wrong on automatic backup: %s\n", warningString); } if(!errorString.empty()) { // Things are really broken LogPrintf("CPrivateSendClient::CheckAutomaticBackup -- ERROR! Failed to create automatic backup: %s\n", errorString); strAutoDenomResult = strprintf(_("ERROR! Failed to create automatic backup") + ": %s", errorString); return false; } } } else { // Wait for smth else (e.g. GUI action) to create automatic backup for us return false; } } LogPrint("privatesend", "CPrivateSendClient::CheckAutomaticBackup -- Keys left since latest backup: %d\n", pwalletMain->nKeysLeftSinceAutoBackup); return true; } // // Passively run mixing in the background to anonymize funds based on the given configuration. // bool CPrivateSendClient::DoAutomaticDenominating(CConnman& connman, bool fDryRun) { if(fMasterNode) return false; // no client-side mixing on masternodes if(!fEnablePrivateSend) return false; if(!pwalletMain || pwalletMain->IsLocked(true)) return false; if(nState != POOL_STATE_IDLE) return false; if(!masternodeSync.IsMasternodeListSynced()) { strAutoDenomResult = _("Can't mix while sync in progress."); return false; } if(!CheckAutomaticBackup()) return false; if(GetEntriesCount() > 0) { strAutoDenomResult = _("Mixing in progress..."); return false; } TRY_LOCK(cs_darksend, lockDS); if(!lockDS) { strAutoDenomResult = _("Lock is already in place."); return false; } if(!fDryRun && pwalletMain->IsLocked(true)) { strAutoDenomResult = _("Wallet is locked."); return false; } if(WaitForAnotherBlock()) { LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- Last successful PrivateSend action was too recent\n"); strAutoDenomResult = _("Last successful PrivateSend action was too recent."); return false; } if(mnodeman.size() == 0) { LogPrint("privatesend", "CPrivateSendClient::DoAutomaticDenominating -- No Masternodes detected\n"); strAutoDenomResult = _("No Masternodes detected."); return false; } CAmount nValueMin = CPrivateSend::GetSmallestDenomination(); // if there are no confirmed DS collateral inputs yet if(!pwalletMain->HasCollateralInputs()) { // should have some additional amount for them nValueMin += CPrivateSend::GetMaxCollateralAmount(); } // including denoms but applying some restrictions CAmount nBalanceNeedsAnonymized = pwalletMain->GetNeedsToBeAnonymizedBalance(nValueMin); // anonymizable balance is way too small if(nBalanceNeedsAnonymized < nValueMin) { LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- Not enough funds to anonymize\n"); strAutoDenomResult = _("Not enough funds to anonymize."); return false; } // excluding denoms CAmount nBalanceAnonimizableNonDenom = pwalletMain->GetAnonymizableBalance(true); // denoms CAmount nBalanceDenominatedConf = pwalletMain->GetDenominatedBalance(); CAmount nBalanceDenominatedUnconf = pwalletMain->GetDenominatedBalance(true); CAmount nBalanceDenominated = nBalanceDenominatedConf + nBalanceDenominatedUnconf; LogPrint("privatesend", "CPrivateSendClient::DoAutomaticDenominating -- nValueMin: %f, nBalanceNeedsAnonymized: %f, nBalanceAnonimizableNonDenom: %f, nBalanceDenominatedConf: %f, nBalanceDenominatedUnconf: %f, nBalanceDenominated: %f\n", (float)nValueMin/COIN, (float)nBalanceNeedsAnonymized/COIN, (float)nBalanceAnonimizableNonDenom/COIN, (float)nBalanceDenominatedConf/COIN, (float)nBalanceDenominatedUnconf/COIN, (float)nBalanceDenominated/COIN); if(fDryRun) return true; // Check if we have should create more denominated inputs i.e. // there are funds to denominate and denominated balance does not exceed // max amount to mix yet. if(nBalanceAnonimizableNonDenom >= nValueMin + CPrivateSend::GetCollateralAmount() && nBalanceDenominated < nPrivateSendAmount*COIN) return CreateDenominated(connman); //check if we have the collateral sized inputs if(!pwalletMain->HasCollateralInputs()) return !pwalletMain->HasCollateralInputs(false) && MakeCollateralAmounts(connman); if(nSessionID) { strAutoDenomResult = _("Mixing in progress..."); return false; } // Initial phase, find a Masternode // Clean if there is anything left from previous session UnlockCoins(); keyHolderStorage.ReturnAll(); SetNull(); // should be no unconfirmed denoms in non-multi-session mode if(!fPrivateSendMultiSession && nBalanceDenominatedUnconf > 0) { LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- Found unconfirmed denominated outputs, will wait till they confirm to continue.\n"); strAutoDenomResult = _("Found unconfirmed denominated outputs, will wait till they confirm to continue."); return false; } //check our collateral and create new if needed std::string strReason; if(txMyCollateral == CMutableTransaction()) { if(!pwalletMain->CreateCollateralTransaction(txMyCollateral, strReason)) { LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- create collateral error:%s\n", strReason); return false; } } else { if(!CPrivateSend::IsCollateralValid(txMyCollateral)) { LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- invalid collateral, recreating...\n"); if(!pwalletMain->CreateCollateralTransaction(txMyCollateral, strReason)) { LogPrintf("CPrivateSendClient::DoAutomaticDenominating -- create collateral error: %s\n", strReason); return false; } } } int nMnCountEnabled = mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION); // If we've used 90% of the Masternode list then drop the oldest first ~30% int nThreshold_high = nMnCountEnabled * 0.9; int nThreshold_low = nThreshold_high * 0.7; LogPrint("privatesend", "Checking vecMasternodesUsed: size: %d, threshold: %d\n", (int)vecMasternodesUsed.size(), nThreshold_high); if((int)vecMasternodesUsed.size() > nThreshold_high) { vecMasternodesUsed.erase(vecMasternodesUsed.begin(), vecMasternodesUsed.begin() + vecMasternodesUsed.size() - nThreshold_low); LogPrint("privatesend", " vecMasternodesUsed: new size: %d, threshold: %d\n", (int)vecMasternodesUsed.size(), nThreshold_high); } bool fUseQueue = GetRandInt(100) > 33; // don't use the queues all of the time for mixing unless we are a liquidity provider if((nLiquidityProvider || fUseQueue) && JoinExistingQueue(nBalanceNeedsAnonymized, connman)) return true; // do not initiate queue if we are a liquidity provider to avoid useless inter-mixing if(nLiquidityProvider) return false; if(StartNewQueue(nValueMin, nBalanceNeedsAnonymized, connman)) return true; strAutoDenomResult = _("No compatible Masternode found."); return false; } bool CPrivateSendClient::JoinExistingQueue(CAmount nBalanceNeedsAnonymized, CConnman& connman) { std::vector<CAmount> vecStandardDenoms = CPrivateSend::GetStandardDenominations(); // Look through the queues and see if anything matches BOOST_FOREACH(CDarksendQueue& dsq, vecDarksendQueue) { // only try each queue once if(dsq.fTried) continue; dsq.fTried = true; if(dsq.IsExpired()) continue; masternode_info_t infoMn; if(!mnodeman.GetMasternodeInfo(dsq.vin.prevout, infoMn)) { LogPrintf("CPrivateSendClient::JoinExistingQueue -- dsq masternode is not in masternode list, masternode=%s\n", dsq.vin.prevout.ToStringShort()); continue; } if(infoMn.nProtocolVersion < MIN_PRIVATESEND_PEER_PROTO_VERSION) continue; std::vector<int> vecBits; if(!CPrivateSend::GetDenominationsBits(dsq.nDenom, vecBits)) { // incompatible denom continue; } // mixing rate limit i.e. nLastDsq check should already pass in DSQUEUE ProcessMessage // in order for dsq to get into vecDarksendQueue, so we should be safe to mix already, // no need for additional verification here LogPrint("privatesend", "CPrivateSendClient::JoinExistingQueue -- found valid queue: %s\n", dsq.ToString()); CAmount nValueInTmp = 0; std::vector<CTxDSIn> vecTxDSInTmp; std::vector<COutput> vCoinsTmp; // Try to match their denominations if possible, select at least 1 denominations if(!pwalletMain->SelectCoinsByDenominations(dsq.nDenom, vecStandardDenoms[vecBits.front()], nBalanceNeedsAnonymized, vecTxDSInTmp, vCoinsTmp, nValueInTmp, 0, nPrivateSendRounds)) { LogPrintf("CPrivateSendClient::JoinExistingQueue -- Couldn't match denominations %d %d (%s)\n", vecBits.front(), dsq.nDenom, CPrivateSend::GetDenominationsToString(dsq.nDenom)); continue; } vecMasternodesUsed.push_back(dsq.vin.prevout); bool fSkip = false; connman.ForNode(infoMn.addr, CConnman::AllNodes, [&fSkip](CNode* pnode) { fSkip = pnode->fDisconnect || pnode->fMasternode; return true; }); if (fSkip) { LogPrintf("CPrivateSendClient::JoinExistingQueue -- skipping masternode connection, addr=%s\n", infoMn.addr.ToString()); continue; } LogPrintf("CPrivateSendClient::JoinExistingQueue -- attempt to connect to masternode from queue, addr=%s\n", infoMn.addr.ToString()); // connect to Masternode and submit the queue request CNode* pnode = connman.ConnectNode(CAddress(infoMn.addr, NODE_NETWORK), NULL, true); if(pnode) { infoMixingMasternode = infoMn; nSessionDenom = dsq.nDenom; connman.PushMessage(pnode, NetMsgType::DSACCEPT, nSessionDenom, txMyCollateral); LogPrintf("CPrivateSendClient::JoinExistingQueue -- connected (from queue), sending DSACCEPT: nSessionDenom: %d (%s), addr=%s\n", nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom), pnode->addr.ToString()); strAutoDenomResult = _("Mixing in progress..."); SetState(POOL_STATE_QUEUE); nTimeLastSuccessfulStep = GetTimeMillis(); return true; } else { LogPrintf("CPrivateSendClient::JoinExistingQueue -- can't connect, addr=%s\n", infoMn.addr.ToString()); strAutoDenomResult = _("Error connecting to Masternode."); continue; } } return false; } bool CPrivateSendClient::StartNewQueue(CAmount nValueMin, CAmount nBalanceNeedsAnonymized, CConnman& connman) { int nTries = 0; int nMnCountEnabled = mnodeman.CountEnabled(MIN_PRIVATESEND_PEER_PROTO_VERSION); // ** find the coins we'll use std::vector<CTxIn> vecTxIn; CAmount nValueInTmp = 0; if(!pwalletMain->SelectCoinsDark(nValueMin, nBalanceNeedsAnonymized, vecTxIn, nValueInTmp, 0, nPrivateSendRounds)) { // this should never happen LogPrintf("CPrivateSendClient::StartNewQueue -- Can't mix: no compatible inputs found!\n"); strAutoDenomResult = _("Can't mix: no compatible inputs found!"); return false; } // otherwise, try one randomly while(nTries < 10) { masternode_info_t infoMn = mnodeman.FindRandomNotInVec(vecMasternodesUsed, MIN_PRIVATESEND_PEER_PROTO_VERSION); if(!infoMn.fInfoValid) { LogPrintf("CPrivateSendClient::StartNewQueue -- Can't find random masternode!\n"); strAutoDenomResult = _("Can't find random Masternode."); return false; } vecMasternodesUsed.push_back(infoMn.vin.prevout); if(infoMn.nLastDsq != 0 && infoMn.nLastDsq + nMnCountEnabled/5 > mnodeman.nDsqCount) { LogPrintf("CPrivateSendClient::StartNewQueue -- Too early to mix on this masternode!" " masternode=%s addr=%s nLastDsq=%d CountEnabled/5=%d nDsqCount=%d\n", infoMn.vin.prevout.ToStringShort(), infoMn.addr.ToString(), infoMn.nLastDsq, nMnCountEnabled/5, mnodeman.nDsqCount); nTries++; continue; } bool fSkip = false; connman.ForNode(infoMn.addr, CConnman::AllNodes, [&fSkip](CNode* pnode) { fSkip = pnode->fDisconnect || pnode->fMasternode; return true; }); if (fSkip) { LogPrintf("CPrivateSendClient::StartNewQueue -- skipping masternode connection, addr=%s\n", infoMn.addr.ToString()); nTries++; continue; } LogPrintf("CPrivateSendClient::StartNewQueue -- attempt %d connection to Masternode %s\n", nTries, infoMn.addr.ToString()); CNode* pnode = connman.ConnectNode(CAddress(infoMn.addr, NODE_NETWORK), NULL, true); if(pnode) { LogPrintf("CPrivateSendClient::StartNewQueue -- connected, addr=%s\n", infoMn.addr.ToString()); infoMixingMasternode = infoMn; std::vector<CAmount> vecAmounts; pwalletMain->ConvertList(vecTxIn, vecAmounts); // try to get a single random denom out of vecAmounts while(nSessionDenom == 0) { nSessionDenom = CPrivateSend::GetDenominationsByAmounts(vecAmounts); } connman.PushMessage(pnode, NetMsgType::DSACCEPT, nSessionDenom, txMyCollateral); LogPrintf("CPrivateSendClient::StartNewQueue -- connected, sending DSACCEPT, nSessionDenom: %d (%s)\n", nSessionDenom, CPrivateSend::GetDenominationsToString(nSessionDenom)); strAutoDenomResult = _("Mixing in progress..."); SetState(POOL_STATE_QUEUE); nTimeLastSuccessfulStep = GetTimeMillis(); return true; } else { LogPrintf("CPrivateSendClient::StartNewQueue -- can't connect, addr=%s\n", infoMn.addr.ToString()); nTries++; continue; } } return false; } bool CPrivateSendClient::SubmitDenominate(CConnman& connman) { std::string strError; std::vector<CTxDSIn> vecTxDSInRet; std::vector<CTxOut> vecTxOutRet; // Submit transaction to the pool if we get here if (nLiquidityProvider) { // Try to use only inputs with the same number of rounds starting from the lowest number of rounds possible for(int i = 0; i< nPrivateSendRounds; i++) { if(PrepareDenominate(i, i + 1, strError, vecTxDSInRet, vecTxOutRet)) { LogPrintf("CPrivateSendClient::SubmitDenominate -- Running PrivateSend denominate for %d rounds, success\n", i); return SendDenominate(vecTxDSInRet, vecTxOutRet, connman); } LogPrint("privatesend", "CPrivateSendClient::SubmitDenominate -- Running PrivateSend denominate for %d rounds, error: %s\n", i, strError); } } else { // Try to use only inputs with the same number of rounds starting from the highest number of rounds possible for(int i = nPrivateSendRounds; i > 0; i--) { if(PrepareDenominate(i - 1, i, strError, vecTxDSInRet, vecTxOutRet)) { LogPrintf("CPrivateSendClient::SubmitDenominate -- Running PrivateSend denominate for %d rounds, success\n", i); return SendDenominate(vecTxDSInRet, vecTxOutRet, connman); } LogPrint("privatesend", "CPrivateSendClient::SubmitDenominate -- Running PrivateSend denominate for %d rounds, error: %s\n", i, strError); } } // We failed? That's strange but let's just make final attempt and try to mix everything if(PrepareDenominate(0, nPrivateSendRounds, strError, vecTxDSInRet, vecTxOutRet)) { LogPrintf("CPrivateSendClient::SubmitDenominate -- Running PrivateSend denominate for all rounds, success\n"); return SendDenominate(vecTxDSInRet, vecTxOutRet, connman); } // Should never actually get here but just in case LogPrintf("CPrivateSendClient::SubmitDenominate -- Running PrivateSend denominate for all rounds, error: %s\n", strError); strAutoDenomResult = strError; return false; } bool CPrivateSendClient::PrepareDenominate(int nMinRounds, int nMaxRounds, std::string& strErrorRet, std::vector<CTxDSIn>& vecTxDSInRet, std::vector<CTxOut>& vecTxOutRet) { if(!pwalletMain) { strErrorRet = "Wallet is not initialized"; return false; } if (pwalletMain->IsLocked(true)) { strErrorRet = "Wallet locked, unable to create transaction!"; return false; } if (GetEntriesCount() > 0) { strErrorRet = "Already have pending entries in the PrivateSend pool"; return false; } // make sure returning vectors are empty before filling them up vecTxDSInRet.clear(); vecTxOutRet.clear(); // ** find the coins we'll use std::vector<CTxDSIn> vecTxDSIn; std::vector<COutput> vCoins; CAmount nValueIn = 0; /* Select the coins we'll use if nMinRounds >= 0 it means only denominated inputs are going in and coming out */ std::vector<int> vecBits; if (!CPrivateSend::GetDenominationsBits(nSessionDenom, vecBits)) { strErrorRet = "Incorrect session denom"; return false; } std::vector<CAmount> vecStandardDenoms = CPrivateSend::GetStandardDenominations(); bool fSelected = pwalletMain->SelectCoinsByDenominations(nSessionDenom, vecStandardDenoms[vecBits.front()], CPrivateSend::GetMaxPoolAmount(), vecTxDSIn, vCoins, nValueIn, nMinRounds, nMaxRounds); if (nMinRounds >= 0 && !fSelected) { strErrorRet = "Can't select current denominated inputs"; return false; } LogPrintf("CPrivateSendClient::PrepareDenominate -- max value: %f\n", (double)nValueIn/COIN); { LOCK(pwalletMain->cs_wallet); for (auto& txin : vecTxDSIn) { pwalletMain->LockCoin(txin.prevout); } } CAmount nValueLeft = nValueIn; // Try to add every needed denomination, repeat up to 5-PRIVATESEND_ENTRY_MAX_SIZE times. // NOTE: No need to randomize order of inputs because they were // initially shuffled in CWallet::SelectCoinsByDenominations already. int nStep = 0; int nStepsMax = 5 + GetRandInt(PRIVATESEND_ENTRY_MAX_SIZE-5+1); while (nStep < nStepsMax) { BOOST_FOREACH(int nBit, vecBits) { CAmount nValueDenom = vecStandardDenoms[nBit]; if (nValueLeft - nValueDenom < 0) continue; // Note: this relies on a fact that both vectors MUST have same size std::vector<CTxDSIn>::iterator it = vecTxDSIn.begin(); std::vector<COutput>::iterator it2 = vCoins.begin(); while (it2 != vCoins.end()) { // we have matching inputs if ((*it2).tx->vout[(*it2).i].nValue == nValueDenom) { // add new input in resulting vector vecTxDSInRet.push_back(*it); // remove corresponting items from initial vectors vecTxDSIn.erase(it); vCoins.erase(it2); CScript scriptDenom = keyHolderStorage.AddKey(pwalletMain); // add new output CTxOut txout(nValueDenom, scriptDenom); vecTxOutRet.push_back(txout); // subtract denomination amount nValueLeft -= nValueDenom; // step is complete break; } ++it; ++it2; } } if(nValueLeft == 0) break; nStep++; } { // unlock unused coins LOCK(pwalletMain->cs_wallet); for (auto& txin : vecTxDSIn) { pwalletMain->UnlockCoin(txin.prevout); } } if (CPrivateSend::GetDenominations(vecTxOutRet) != nSessionDenom) { // unlock used coins on failure LOCK(pwalletMain->cs_wallet); for (auto& txin : vecTxDSInRet) { pwalletMain->UnlockCoin(txin.prevout); } keyHolderStorage.ReturnAll(); strErrorRet = "Can't make current denominated outputs"; return false; } // We also do not care about full amount as long as we have right denominations return true; } // Create collaterals by looping through inputs grouped by addresses bool CPrivateSendClient::MakeCollateralAmounts(CConnman& connman) { std::vector<CompactTallyItem> vecTally; if(!pwalletMain->SelectCoinsGrouppedByAddresses(vecTally, false)) { LogPrint("privatesend", "CPrivateSendClient::MakeCollateralAmounts -- SelectCoinsGrouppedByAddresses can't find any inputs!\n"); return false; } // First try to use only non-denominated funds BOOST_FOREACH(CompactTallyItem& item, vecTally) { if(!MakeCollateralAmounts(item, false, connman)) continue; return true; } // There should be at least some denominated funds we should be able to break in pieces to continue mixing BOOST_FOREACH(CompactTallyItem& item, vecTally) { if(!MakeCollateralAmounts(item, true, connman)) continue; return true; } // If we got here then smth is terribly broken actually LogPrintf("CPrivateSendClient::MakeCollateralAmounts -- ERROR: Can't make collaterals!\n"); return false; } // Split up large inputs or create fee sized inputs bool CPrivateSendClient::MakeCollateralAmounts(const CompactTallyItem& tallyItem, bool fTryDenominated, CConnman& connman) { LOCK2(cs_main, pwalletMain->cs_wallet); // denominated input is always a single one, so we can check its amount directly and return early if(!fTryDenominated && tallyItem.vecTxIn.size() == 1 && CPrivateSend::IsDenominatedAmount(tallyItem.nAmount)) return false; CWalletTx wtx; CAmount nFeeRet = 0; int nChangePosRet = -1; std::string strFail = ""; std::vector<CRecipient> vecSend; // make our collateral address CReserveKey reservekeyCollateral(pwalletMain); // make our change address CReserveKey reservekeyChange(pwalletMain); CScript scriptCollateral; CPubKey vchPubKey; assert(reservekeyCollateral.GetReservedKey(vchPubKey, false)); // should never fail, as we just unlocked scriptCollateral = GetScriptForDestination(vchPubKey.GetID()); vecSend.push_back((CRecipient){scriptCollateral, CPrivateSend::GetMaxCollateralAmount(), false}); // try to use non-denominated and not mn-like funds first, select them explicitly CCoinControl coinControl; coinControl.fAllowOtherInputs = false; coinControl.fAllowWatchOnly = false; // send change to the same address so that we were able create more denoms out of it later coinControl.destChange = tallyItem.txdest; BOOST_FOREACH(const CTxIn& txin, tallyItem.vecTxIn) coinControl.Select(txin.prevout); bool fSuccess = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, nFeeRet, nChangePosRet, strFail, &coinControl, true, ONLY_NONDENOMINATED); if(!fSuccess) { LogPrintf("CPrivateSendClient::MakeCollateralAmounts -- ONLY_NONDENOMINATED: %s\n", strFail); // If we failed then most likeky there are not enough funds on this address. if(fTryDenominated) { // Try to also use denominated coins (we can't mix denominated without collaterals anyway). if(!pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, nFeeRet, nChangePosRet, strFail, &coinControl, true, ALL_COINS)) { LogPrintf("CPrivateSendClient::MakeCollateralAmounts -- ALL_COINS Error: %s\n", strFail); reservekeyCollateral.ReturnKey(); return false; } } else { // Nothing else we can do. reservekeyCollateral.ReturnKey(); return false; } } reservekeyCollateral.KeepKey(); LogPrintf("CPrivateSendClient::MakeCollateralAmounts -- txid=%s\n", wtx.GetHash().GetHex()); // use the same nCachedLastSuccessBlock as for DS mixinx to prevent race if(!pwalletMain->CommitTransaction(wtx, reservekeyChange, &connman)) { LogPrintf("CPrivateSendClient::MakeCollateralAmounts -- CommitTransaction failed!\n"); return false; } nCachedLastSuccessBlock = nCachedBlockHeight; return true; } // Create denominations by looping through inputs grouped by addresses bool CPrivateSendClient::CreateDenominated(CConnman& connman) { LOCK2(cs_main, pwalletMain->cs_wallet); std::vector<CompactTallyItem> vecTally; if(!pwalletMain->SelectCoinsGrouppedByAddresses(vecTally)) { LogPrint("privatesend", "CPrivateSendClient::CreateDenominated -- SelectCoinsGrouppedByAddresses can't find any inputs!\n"); return false; } bool fCreateMixingCollaterals = !pwalletMain->HasCollateralInputs(); BOOST_FOREACH(CompactTallyItem& item, vecTally) { if(!CreateDenominated(item, fCreateMixingCollaterals, connman)) continue; return true; } LogPrintf("CPrivateSendClient::CreateDenominated -- failed!\n"); return false; } // Create denominations bool CPrivateSendClient::CreateDenominated(const CompactTallyItem& tallyItem, bool fCreateMixingCollaterals, CConnman& connman) { std::vector<CRecipient> vecSend; CKeyHolderStorage keyHolderStorageDenom; CAmount nValueLeft = tallyItem.nAmount; nValueLeft -= CPrivateSend::GetCollateralAmount(); // leave some room for fees LogPrintf("CreateDenominated0 nValueLeft: %f\n", (float)nValueLeft/COIN); // ****** Add an output for mixing collaterals ************ / if(fCreateMixingCollaterals) { CScript scriptCollateral = keyHolderStorageDenom.AddKey(pwalletMain); vecSend.push_back((CRecipient){ scriptCollateral, CPrivateSend::GetMaxCollateralAmount(), false }); nValueLeft -= CPrivateSend::GetMaxCollateralAmount(); } // ****** Add outputs for denoms ************ / // try few times - skipping smallest denoms first if there are too many of them already, if failed - use them too int nOutputsTotal = 0; bool fSkip = true; do { std::vector<CAmount> vecStandardDenoms = CPrivateSend::GetStandardDenominations(); BOOST_REVERSE_FOREACH(CAmount nDenomValue, vecStandardDenoms) { if(fSkip) { // Note: denoms are skipped if there are already DENOMS_COUNT_MAX of them // and there are still larger denoms which can be used for mixing // check skipped denoms if(IsDenomSkipped(nDenomValue)) continue; // find new denoms to skip if any (ignore the largest one) if(nDenomValue != vecStandardDenoms.front() && pwalletMain->CountInputsWithAmount(nDenomValue) > DENOMS_COUNT_MAX) { strAutoDenomResult = strprintf(_("Too many %f denominations, removing."), (float)nDenomValue/COIN); LogPrintf("CPrivateSendClient::CreateDenominated -- %s\n", strAutoDenomResult); vecDenominationsSkipped.push_back(nDenomValue); continue; } } int nOutputs = 0; // add each output up to 11 times until it can't be added again while(nValueLeft - nDenomValue >= 0 && nOutputs <= 10) { CScript scriptDenom = keyHolderStorageDenom.AddKey(pwalletMain); vecSend.push_back((CRecipient){ scriptDenom, nDenomValue, false }); //increment outputs and subtract denomination amount nOutputs++; nValueLeft -= nDenomValue; LogPrintf("CreateDenominated1: totalOutputs: %d, nOutputsTotal: %d, nOutputs: %d, nValueLeft: %f\n", nOutputsTotal + nOutputs, nOutputsTotal, nOutputs, (float)nValueLeft/COIN); } nOutputsTotal += nOutputs; if(nValueLeft == 0) break; } LogPrintf("CreateDenominated2: nOutputsTotal: %d, nValueLeft: %f\n", nOutputsTotal, (float)nValueLeft/COIN); // if there were no outputs added, start over without skipping fSkip = !fSkip; } while (nOutputsTotal == 0 && !fSkip); LogPrintf("CreateDenominated3: nOutputsTotal: %d, nValueLeft: %f\n", nOutputsTotal, (float)nValueLeft/COIN); // if we have anything left over, it will be automatically send back as change - there is no need to send it manually CCoinControl coinControl; coinControl.fAllowOtherInputs = false; coinControl.fAllowWatchOnly = false; // send change to the same address so that we were able create more denoms out of it later coinControl.destChange = tallyItem.txdest; BOOST_FOREACH(const CTxIn& txin, tallyItem.vecTxIn) coinControl.Select(txin.prevout); CWalletTx wtx; CAmount nFeeRet = 0; int nChangePosRet = -1; std::string strFail = ""; // make our change address CReserveKey reservekeyChange(pwalletMain); bool fSuccess = pwalletMain->CreateTransaction(vecSend, wtx, reservekeyChange, nFeeRet, nChangePosRet, strFail, &coinControl, true, ONLY_NONDENOMINATED); if(!fSuccess) { LogPrintf("CPrivateSendClient::CreateDenominated -- Error: %s\n", strFail); keyHolderStorageDenom.ReturnAll(); return false; } keyHolderStorageDenom.KeepAll(); if(!pwalletMain->CommitTransaction(wtx, reservekeyChange, &connman)) { LogPrintf("CPrivateSendClient::CreateDenominated -- CommitTransaction failed!\n"); return false; } // use the same nCachedLastSuccessBlock as for DS mixing to prevent race nCachedLastSuccessBlock = nCachedBlockHeight; LogPrintf("CPrivateSendClient::CreateDenominated -- txid=%s\n", wtx.GetHash().GetHex()); return true; } void CPrivateSendClient::RelayIn(const CDarkSendEntry& entry, CConnman& connman) { if(!infoMixingMasternode.fInfoValid) return; connman.ForNode(infoMixingMasternode.addr, [&entry, &connman](CNode* pnode) { LogPrintf("CPrivateSendClient::RelayIn -- found master, relaying message to %s\n", pnode->addr.ToString()); connman.PushMessage(pnode, NetMsgType::DSVIN, entry); return true; }); } void CPrivateSendClient::SetState(PoolState nStateNew) { LogPrintf("CPrivateSendClient::SetState -- nState: %d, nStateNew: %d\n", nState, nStateNew); nState = nStateNew; } void CPrivateSendClient::UpdatedBlockTip(const CBlockIndex *pindex) { nCachedBlockHeight = pindex->nHeight; LogPrint("privatesend", "CPrivateSendClient::UpdatedBlockTip -- nCachedBlockHeight: %d\n", nCachedBlockHeight); } //TODO: Rename/move to core void ThreadCheckPrivateSendClient(CConnman& connman) { if(fLiteMode) return; // disable all zaap specific functionality if(fMasterNode) return; // no client-side mixing on masternodes static bool fOneThread; if(fOneThread) return; fOneThread = true; // Make this thread recognisable as the PrivateSend thread RenameThread("zaap-ps-client"); unsigned int nTick = 0; unsigned int nDoAutoNextRun = nTick + PRIVATESEND_AUTO_TIMEOUT_MIN; while (true) { MilliSleep(1000); if(masternodeSync.IsBlockchainSynced() && !ShutdownRequested()) { nTick++; privateSendClient.CheckTimeout(); if(nDoAutoNextRun == nTick) { privateSendClient.DoAutomaticDenominating(connman); nDoAutoNextRun = nTick + PRIVATESEND_AUTO_TIMEOUT_MIN + GetRandInt(PRIVATESEND_AUTO_TIMEOUT_MAX - PRIVATESEND_AUTO_TIMEOUT_MIN); } } } }
////////////////////////////////////////////////////////////////////////////// // // CLASS - Cloud Loader and ASsembler System // Copyright (C) 2021 Winor Chen // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. // ////////////////////////////////////////////////////////////////////////////// #include <csignal> #include <cstdio> #include <cstdint> #include <cstdlib> #include <cstring> #include <cstdarg> #include <iostream> #include <string> #include <memory> #include "shell.h" namespace priscas { /* Shell for CLASS * * The shell is essentially an interpreter that merely assembles the program * * * wchen329 */ void Shell::Run() { UPString app_brand = branding::APPLICATION_NAME + " " + branding::APPLICATION_VERSION + " " + branding::APPLICATION_DBG; // Set quiet mode UPString header = app_brand + priscas_io::newLine + branding::APPLICATION_DESC + priscas_io::newLine; WriteToOutput(header); // Set shell environment this->shEnv.characterize_Env(args); // Asm input was specified if(shEnv.get_Option_AsmInput()) { if(!shEnv.get_Option_AsmInputSpecified()) { WriteToError("Error: An input file is required (specified through -i [input file] ) in order to run in batch mode.\n"); return; } else { inst_file = fopen(shEnv.get_asmFilenames()[0].c_str(), "r"); } if(inst_file == NULL) { WriteToError("Error: The file specified cannot be opened or doesn't exist.\n"); return; } } else { WriteToOutput("Usage:\n"); WriteToOutput("\t{-i i_filename.s} - assemble file of name i_filename.s\n"); WriteToOutput("\t{-o o_filename.bin} - dump assembly output to file of name o_filename.bin \n"); WriteToOutput("\t{-s bin OR hex OR mif} - specify output format as bin, hex, or MIF\n"); WriteToOutput("\t{-b width - for MIF out, specify the word size of the output (default is the size of the instruction) in bytes}\n"); return; } // Other predicates to check for if(shEnv.get_Option_AsmOutput()) { if(!shEnv.get_Option_AsmOutputSpecified()) { WriteToError("Error: -o requires a filename to be specified.\n"); return; } } if(shEnv.get_Option_AsmStrMode()) { if(!shEnv.get_Option_AsmStrModeSpecified()) { WriteToError("Error: -s requires one of: {bin, hex, mif} as an arguments.\n"); return; } } if(shEnv.get_Option_WordSize()) { if(!shEnv.get_Option_WordSizeSpecified()) { WriteToError("Error: -b requires an integer greater than 0 as its argument\n"); return; } } /* Actual Execution Portion * This is a "double-pass" assembler * First run through: read symbols and map them with a symbol table * Second run through: do the actual assembling */ std::vector<size_t> inst_lengths; /* First, if an input file was specified * (1) collect file symbols * (2) map it to memory assemble that file first * */ if(shEnv.get_Option_AsmInputSpecified()) { UPString_Vec lines; uint32_t equiv_pc = 0; BW_64 asm_pc = 0; char input_f_stream[256]; memset(input_f_stream, 0, sizeof(input_f_stream)); unsigned long line_number = 0; try { while(fgets(input_f_stream, 255, inst_file) != NULL) { line_number++; UPString current_line = UPString(input_f_stream); Arg_Vec parts = chop_string(current_line); // Remove strings that are just whitespace if(parts.empty()) continue; // Symbol assignment: add the symbol to symbol table if(parts[0][parts[0].size() - 1] == ':') { this->jump_syms.insert(parts[0].substr(0, parts[0].size() - 1), equiv_pc); // If the label is the only declaration on this line, continue if(parts.size() == 1) { continue; } // Otherwise assemble this instruction too trim_label(current_line); } // Strip newlines at the back current_line.pop_back(); this->line_number_to_PC.insert(std::pair<unsigned long, unsigned long>(line_number, equiv_pc)); this->PC_to_line_number.insert(std::pair<unsigned long, unsigned long>(equiv_pc, line_number)); this->PC_to_line_string.insert((std::pair<unsigned long, std::string>(equiv_pc, current_line))); equiv_pc = equiv_pc + 4; lines.push_back(current_line); } } catch(mt_exception& e) { WriteToOutput("An error has occurred when writing symbols table:\n\t"); WriteToOutput(e.get_err().c_str()); WriteToOutput(priscas_io::newLine.c_str()); return; } // Add pre-declared program breakpoints, if any while(!this->queued_prog_breakpoints.empty()) { this->add_program_breakpoint(this->queued_prog_breakpoints.front()); this->queued_prog_breakpoints.pop(); } // Now assemble the rest for(size_t itr = 0; itr < lines.size(); itr++) { // Specify the ISA to use customisa theISA; uint64_t bytecount; if(!this->AsmFlash(lines[itr], asm_pc, theISA, bytecount)) { return; } // Increment the PC at which to flash asm_pc = asm_pc.AsUInt64() + bytecount; inst_lengths.push_back(bytecount); } } try { // Write this to program, or remain in memory UPString default_name; switch(shEnv.get_AsmStrMode()) { case asm_ostream::MIF: default_name = "a.mif"; break; case asm_ostream::HEX: default_name = "a.hex"; break; default: default_name = "a.bin"; } UPString fname(default_name); if(shEnv.get_Option_AsmOutput()) { fname = shEnv.get_OutputFilename(); } // Dump the output asm_ostream prg_o(fname.c_str(), shEnv.get_AsmStrMode()); prg_o.set_width(shEnv.get_Wordsize()); uint64_t ind = 0; uint64_t addr = 0; while(addr < prog.get_EOP()) { size_t bt = inst_lengths[ind]; byte_8b buf[1024]; if(bt > 1024) { fprintf(stderr, "FATAL: instruction size too large, must be 1024 bytes or less"); abort(); } for(size_t sz = 0; sz < bt; ++sz) { buf[sz] = prog.read(addr + sz); } prg_o.append(buf, bt); // Increments ++ind; addr += bt; } prg_o.finalize(); fprintf(stdout, "Operation completed succesfully\n"); } catch(mt_exception& mte) { WriteToOutput("An error has occurred:\n"); WriteToOutput(mte.get_err().c_str()); WriteToOutput(priscas_io::newLine.c_str()); } } /* Takes an input string and breaks that string into a vector of several * based off of whitespace and tab delineators * Also removes comments * "Also acknowledges " " and ' ' and \ all used for escaping */ UPString_Vec chop_string(const UPString & input) { UPString commentless_input; size_t real_end = input.size(); for(size_t cind = 0; cind < input.size(); cind++) { if(input[cind] == ';') { real_end = cind; break; } } commentless_input = input.substr(0, real_end); std::vector<std::string> str_vec; std::string built_string = ""; bool has_escaped = false; bool in_quotes = false; // Use a linear search for(size_t ind = 0; ind < commentless_input.size(); ind++) { // If no escaping, then perform syntactical checks if(!has_escaped) { // First acknowledge escaping if(commentless_input[ind] == '\\') { has_escaped = true; continue; } // Detect quotations if(commentless_input[ind] == '\"' || commentless_input[ind] == '\'') { in_quotes = !in_quotes; continue; } // Now if not quoted as well, then a comma, whitespace, tab, or newline delineates that argument is done parsing if(!in_quotes) { if(commentless_input[ind] == ',' || commentless_input[ind] == ' ' || commentless_input[ind] == '\t' || commentless_input[ind] == '\n' || commentless_input[ind] == '\r') { // Check: do not add empty strings if(built_string != "") { str_vec.push_back(built_string); built_string = ""; } continue; } } } built_string += commentless_input[ind]; has_escaped = false; // no matter what, escaping only escapes one... } if(has_escaped || in_quotes) { throw priscas::mt_bad_escape(); } if(built_string != "") str_vec.push_back(built_string); return str_vec; } Shell::Shell() : isQuiet(false), inst_file(nullptr), tw_error(&priscas_io::null_tstream), tw_output(&priscas_io::null_tstream), tw_input(&priscas_io::null_tstream), NoConsoleOutput(false), hasAsmInput(false) { } inline bool Shell::AsmFlash(const UPString& ains, const BW& asm_pc, ISA& isain, uint64_t& byte_count) { Arg_Vec asm_args = chop_string(ains); mBW inst; try { // Here, we write the instruction to memory inst = isain.assemble(asm_args, asm_pc, jump_syms); } catch(priscas::mt_exception& e) { WriteToError("An error occurred while assembling the program.\n"); UPString msg_1 = UPString("Error information: ") + UPString(e.get_err()); WriteToError(msg_1); WriteToError("Line of error:\n"); UPString msg_2 = UPString("\t") + ains + UPString("\n"); WriteToError(msg_2); return false; } // Write the instruction to the program // If big endian, we must reverse (since we are on an intel host) if(isain.get_endian() == ISA_Attrib::CPU_BIG_ENDIAN) { inst->reverse_endian(); } // Now, we can write byte_count = inst->get_bitcount() / 8; for(size_t bind = 0; bind < byte_count; ++bind) { prog.write_next(inst->get_nth_byte(bind)); } return true; } void Shell::declare_program_breakpoint(unsigned long line) { this->queued_prog_breakpoints.push(line); } void Shell::add_program_breakpoint(unsigned long line) { if(this->line_number_to_PC.count(line) > 0) { unsigned long line_pc = this->line_number_to_PC.at(line); this->program_breakpoints.insert(std::pair<unsigned long, unsigned long>(line_pc, line)); std::string o = (std::string("Breakpoint set at line ") + priscas_io::StrTypes::UInt32ToStr(line) + std::string("d\n")); WriteToOutput(o); } else { WriteToError(("Invalid line number. The line number may not be associated with an instruction or may not be in the file.\n")); } } void Shell::WriteToError(std::string& e) { if(!NoConsoleOutput) { std::cerr << e; } *tw_error << e; } void Shell::WriteToError(const char* e) { if(!NoConsoleOutput) { std::cerr << std::string(e); } std::string err = std::string(e); *tw_error << err; } void Shell::WriteToOutput(std::string& o) { if(!isQuiet) { if(!NoConsoleOutput) { std::cout << o; } *tw_output << o; } } void Shell::WriteToOutput(const char* o) { std::string o_str(o); WriteToOutput(o_str); } const UPString& Shell::ReadFromInput() { this->rd_buffer.clear(); bool QUOTES = false; bool ESCAPED = false; if(!NoConsoleOutput) { char in; while((in = fgetc(stdin)) != EOF) { if(in == '\\' && !QUOTES && !ESCAPED) { ESCAPED = true; continue; } if(in == '\"') { QUOTES = (!QUOTES); } if((in == '\n' || in == '\r' ) && !ESCAPED && !QUOTES) { this->rd_buffer += in; break; } this->rd_buffer += in; ESCAPED = false; } } do { *tw_input >> rd_buffer; priscas_osi::sleep(10); } while(rd_buffer == "" && shEnv.get_Mode() == Env::INTERACTIVE); return this->rd_buffer; } std::vector<priscas::NameValueStringPair> scan_for_values(const std::vector<std::string>& input) { std::vector<priscas::NameValueStringPair> vals; for(size_t sind = 0; sind < input.size(); sind++) { const std::string& indc = input[sind]; size_t substr_where = indc.find_first_of('='); // Case: not found, then just use the whole string as the name, with an empty value if(substr_where == -1) { std::string first = input[sind]; std::string second = ""; priscas::NameValueStringPair nv(first, second); vals.push_back(nv); } // Case: empty name. This is an error else if(substr_where == 0) { throw priscas::mt_invalid_cpu_opt("Option specifier (lvalue of = may not be blank) requires name"); } // Case: there is at least one equal sign else { // Use the first equal sign size_t last_where = indc.find_last_of('='); std::string first = indc.substr(0, substr_where); std::string second = indc.substr(substr_where + 1, indc.size()); priscas::NameValueStringPair nv(first, second); vals.push_back(nv); } } return vals; } void Shell::trim_label(UPString& strin) { UPString snew; bool foundcol = false; for(ptrdiff_t sc = 0; sc < strin.size(); ++sc) { if(!foundcol) { if(strin[sc] == ':') { foundcol = true; } continue; } else { snew += strin[sc]; } } strin = snew; } }
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" using namespace Common; using namespace HttpGateway; using namespace Transport; using namespace std; StringLiteral const TraceType("HttpGatewayRequestHandler"); void RequestHandlerBase::HandlerAsyncOperation::OnStart(AsyncOperationSPtr const& thisSPtr) { wstring urlSuffix = MessageContext.GetSuffix(); wstring rawUrl = MessageContext.GetUrl(); wstring const& verb = MessageContext.GetVerb(); ErrorCode error = ErrorCodeValue::Success; auto hstsHeaderValue = HttpGatewayConfig::GetConfig().HttpStrictTransportSecurityHeader; if (!hstsHeaderValue.empty()) { error = MessageContext.SetResponseHeader(Constants::HSTSHeader, hstsHeaderValue); if (!error.IsSuccess()) { WriteInfo(TraceType, "SetHSTSResponseHeader failed with error- {0}", error); OnError(thisSPtr, HttpCommon::HttpStatusCode::InternalServerError, L"Set Strict-Transport-Security header failed"); return; } } if (!GatewayUri::TryParse(owner_.validHandlerUris, verb, rawUrl, urlSuffix, uri_, owner_.allowHierarchicalEntityKeys)) { WriteInfo(TraceType, "Invalid URL - {0}", rawUrl); OnError(thisSPtr, ErrorCodeValue::InvalidArgument); return; } //If client specifies a ClusterId in header and the cluster contains a clusterId setting //we need to ensure that those two match. This is to ensure that a message from //admin client is not forwarded by a rogue cluster to target cluster that it is not //intented for wstring clusterId; error = MessageContext.GetRequestHeader(Constants::ClusterIdHeader, clusterId); if (error.IsSuccess()) { auto expectedId = PaasConfig::GetConfig().ClusterId; if (!expectedId.empty()) { if (!StringUtility::AreEqualCaseInsensitive(clusterId, expectedId)) { WriteInfo(TraceType, "Request clusterId {0} doesnt match expected {1}", clusterId, expectedId); OnError(thisSPtr, ErrorCodeValue::AccessDenied); return; } } } if (!Uri.AllowAnonymous) { auto inner = owner_.server_.BeginCheckAccess( MessageContext, TimeSpan::FromMinutes(Constants::DefaultAccessCheckTimeoutMin), [this](AsyncOperationSPtr const operation) { this->OnAccessCheckComplete(operation, false); }, thisSPtr); OnAccessCheckComplete(inner, true); } else { InvokeHandler(thisSPtr, RoleMask::None); } } void RequestHandlerBase::HandlerAsyncOperation::OnAccessCheckComplete(__in AsyncOperationSPtr const& operation, bool expectedCompletedSynchronously) { if (operation->CompletedSynchronously != expectedCompletedSynchronously) { return; } USHORT statusCode; wstring authHeaderName; wstring authHeaderValue; Transport::RoleMask::Enum role; auto error = owner_.server_.EndCheckAccess(operation, statusCode, authHeaderName, authHeaderValue, role); if (!error.IsSuccess()) { wstring remoteAddress; MessageContext.GetRemoteAddress(remoteAddress); WriteInfo( TraceType, "CheckAccess failed for URL: {0}, from {1}, operation: {2}, responding with ErrorCode: {3} authheader: {4}:{5}, ClientRequestId: {6}", MessageContext.GetUrl(), remoteAddress, Uri.Verb, statusCode, authHeaderName, authHeaderValue, MessageContext.GetClientRequestId()); if (error.IsError(ErrorCodeValue::InvalidCredentials)) { if (!authHeaderName.empty()) { MessageContext.SetResponseHeader(authHeaderName, authHeaderValue); } OnError(operation->Parent, statusCode, Constants::StatusDescriptionUnauthorized); } else { OnError(operation->Parent, error); } return; } InvokeHandler(operation->Parent, role); } void RequestHandlerBase::HandlerAsyncOperation::InvokeHandler( __in AsyncOperationSPtr const& thisSPtr, __in Transport::RoleMask::Enum requestRole) { auto &server = static_cast<HttpGatewayImpl&>(owner_.server_); if (requestRole == RoleMask::Admin || requestRole == RoleMask::None) { SetFabricClient(server.AdminClient); } else if (requestRole == RoleMask::User) { SetFabricClient(server.UserClient); } else { Assert::CodingError("Unknown client role {0}", requestRole); } UpdateRequestTimeout(); if (Uri.Verb == Constants::HttpPostVerb || Uri.Verb == Constants::HttpPutVerb || Uri.Verb == Constants::HttpDeleteVerb) { this->GetRequestBody(thisSPtr); } else { LogRequest(); Uri.Handler(thisSPtr); } } void RequestHandlerBase::HandlerAsyncOperation::GetRequestBody(Common::AsyncOperationSPtr const& thisSPtr) { auto inner = MessageContext.BeginGetMessageBody( [this](AsyncOperationSPtr const& operation) { this->OnGetBodyComplete(operation, false); }, thisSPtr); OnGetBodyComplete(inner, true); } void RequestHandlerBase::HandlerAsyncOperation::OnGetBodyComplete(__in AsyncOperationSPtr const& operation, __in bool expectedCompletedSynchronously) { if (operation->CompletedSynchronously != expectedCompletedSynchronously) { return; } auto error = MessageContext.EndGetMessageBody(operation, body_); if (!error.IsSuccess()) { OnError(operation->Parent, error); return; } LogRequest(); Uri.Handler(operation->Parent); } void RequestHandlerBase::HandlerAsyncOperation::OnError( AsyncOperationSPtr const& thisSPtr, ErrorCode const & error) { ByteBufferUPtr responseBody; ErrorBody errorBody = ErrorBody::CreateErrorBodyFromErrorCode(error); ErrorCode innerError = JsonSerialize(errorBody, responseBody); if (!innerError.IsSuccess()) { Common::Assert::CodingError("OnError cannot serialize json message {0}", error.ToHResult()); } innerError = SetContentTypeResponseHeaders(Constants::JsonContentType); if (!innerError.IsSuccess()) { TryComplete(thisSPtr, innerError); return; } WriteInfo( TraceType, "Responding with error {0} {1} for ClientRequestId {2}.", errorBody.GetErrorCode(), errorBody.GetErrorMessage(), MessageContext.GetClientRequestId()); AsyncOperationSPtr operation = messageContext_->BeginSendResponse( error, move(responseBody), [this, error](AsyncOperationSPtr const& operation) { this->messageContext_->EndSendResponse(operation); this->TryComplete(operation->Parent, error); }, thisSPtr); } void RequestHandlerBase::HandlerAsyncOperation::OnError(Common::AsyncOperationSPtr const& thisSPtr, __in USHORT statusCode, __in wstring const& statusDescription) { ByteBufferUPtr emptyBody; wstring statusDesc; if (statusCode == Constants::StatusAuthenticate) { statusDesc = *Constants::StatusDescriptionUnauthorized; } else if (statusCode == Constants::StatusUnauthorized) { statusDesc = *Constants::StatusDescriptionClientCertificateRequired; } else { statusDesc = statusDescription; } WriteInfo( TraceType, "Responding with header: {0}, description: {1} for ClientRequestId {2}.", statusCode, statusDesc, MessageContext.GetClientRequestId()); AsyncOperationSPtr operation = messageContext_->BeginSendResponse( statusCode, statusDesc, move(emptyBody), [this](AsyncOperationSPtr const& operation) { auto error = this->messageContext_->EndSendResponse(operation); this->TryComplete(operation->Parent, error); }, thisSPtr); } void RequestHandlerBase::HandlerAsyncOperation::OnSuccess(AsyncOperationSPtr const& thisSPtr, __in ByteBufferUPtr bufferUPtr) { OnSuccess(thisSPtr, move(bufferUPtr), *HttpGateway::Constants::JsonContentType); } void RequestHandlerBase::HandlerAsyncOperation::OnSuccess(AsyncOperationSPtr const& thisSPtr, __in ByteBufferUPtr bufferUPtr, __in wstring const& contentType) { auto error = SetContentTypeResponseHeaders(contentType); if (!error.IsSuccess()) { TryComplete(thisSPtr, error); return; } AsyncOperationSPtr operation = messageContext_->BeginSendResponse( ErrorCode::Success(), move(bufferUPtr), [this](AsyncOperationSPtr const& operation) { auto error = this->messageContext_->EndSendResponse(operation); this->TryComplete(operation->Parent, error); }, thisSPtr); } void RequestHandlerBase::HandlerAsyncOperation::OnSuccess(AsyncOperationSPtr const& thisSPtr, __in ByteBufferUPtr bufferUPtr, __in USHORT statusCode, __in wstring const &description) { auto error = SetContentTypeResponseHeaders(Constants::JsonContentType); if (!error.IsSuccess()) { TryComplete(thisSPtr, error); return; } AsyncOperationSPtr operation = messageContext_->BeginSendResponse( statusCode, description, move(bufferUPtr), [this](AsyncOperationSPtr const& operation) { auto error = this->messageContext_->EndSendResponse(operation); this->TryComplete(operation->Parent, error); }, thisSPtr); } ErrorCode RequestHandlerBase::HandlerAsyncOperation::End(__in AsyncOperationSPtr const& operation) { auto thisPtr = AsyncOperation::End<HandlerAsyncOperation>(operation); ASSERT_IF(thisPtr->messageContext_ == nullptr, "Message context not valid"); return thisPtr->Error; } void RequestHandlerBase::HandlerAsyncOperation::UpdateRequestTimeout() { wstring timeoutString; if (uri_.GetItem(Constants::TimeoutString, timeoutString)) { uint timeout; if (StringUtility::TryFromWString<uint>(timeoutString, timeout, 10)) { timeout_ = TimeSpan::FromSeconds(timeout); } else { WriteWarning( TraceType, "Invalid timeout - {0} was specified in uri for ClientRequestId {1}, using default timeout.", timeoutString, MessageContext.GetClientRequestId()); } } } void RequestHandlerBase::HandlerAsyncOperation::LogRequest() { wstring remoteAddress; MessageContext.GetRemoteAddress(remoteAddress); WriteInfo( TraceType, "Dispatching URL {0}, from {1}, operation: {2}, Anonymous: {3}, Role: {4}, Body: {5}, ClientRequestId: {6}", MessageContext.GetUrl(), remoteAddress, Uri.Verb, Uri.AllowAnonymous, client_->ClientRole, GetMessageBodyForTrace(), MessageContext.GetClientRequestId()); } string RequestHandlerBase::HandlerAsyncOperation::GetMessageBodyForTrace() { if (Uri.Verb == Constants::HttpPostVerb) { return string((char*)(Body->data()), Body->size()); } else { return string(); } } void RequestHandlerBase::HandlerAsyncOperation::SetFabricClient(__in FabricClientWrapperSPtr const& client) { client_ = client; } ErrorCode RequestHandlerBase::HandlerAsyncOperation::SetContentTypeResponseHeaders(__in wstring const& contentType) { if (!contentType.empty()) { auto error = MessageContext.SetResponseHeader(Constants::ContentTypeHeader, contentType); if (!error.IsSuccess()) { return error; } // Set x-content-type-options: nosniff header in the response. error = MessageContext.SetResponseHeader(Constants::ContentTypeOptionsHeader, Constants::ContentTypeNoSniffValue); return error; } return ErrorCode::Success(); } #if !defined(PLATFORM_UNIX) void RequestHandlerBase::HandlerAsyncOperation::GetAdditionalHeadersToSend( std::unordered_map<std::wstring, std::wstring>& headers) { headers = additionalHeaders_; } void RequestHandlerBase::HandlerAsyncOperation::SetAdditionalHeadersToSend( std::unordered_map<std::wstring, std::wstring>&& headers) { additionalHeaders_ = move(headers); } void RequestHandlerBase::HandlerAsyncOperation::SetServiceName(std::wstring serviceName) { serviceName_ = serviceName; } void RequestHandlerBase::HandlerAsyncOperation::GetServiceName( std::wstring& serviceName) { serviceName = serviceName_; } #endif
; A211905: Number of lower triangular n X n arrays colored with integers 0 upwards introduced in row major order, with no element equal to any horizontal or vertical neighbor, and containing the value n(n+1)/2-2. ; 0,2,10,34,86,181,337,575,919,1396,2036,2872,3940,5279,6931,8941,11357,14230,17614,21566,26146,31417,37445,44299,52051,60776,70552,81460,93584,107011,121831,138137,156025,175594,196946,220186,245422,272765,302329,334231,368591,405532,445180,487664,533116,581671,633467,688645,747349,809726,875926,946102,1020410,1099009,1182061,1269731,1362187,1459600,1562144,1669996,1783336,1902347,2027215,2158129,2295281,2438866,2589082,2746130,2910214,3081541,3260321,3446767,3641095,3843524,4054276,4273576 add $0,2 mov $1,$0 mul $0,2 bin $1,2 trn $1,2 bin $1,2 add $1,$0 mov $0,$1 sub $0,4
Map_7D712: dc.w word_7D718-Map_7D712 dc.w word_7D74A-Map_7D712 dc.w word_7D77C-Map_7D712 word_7D718: dc.w 8 dc.b 8, 9, $60, $38, $FF, $E8 dc.b 8, 9, $60, $3E, 0, 0 dc.b $E8, $E, $40, 0, $FF, $E0 dc.b $E8, $E, $48, 0, 0, 0 dc.b 0, $C, $40, $C, $FF, $E0 dc.b 8, 5, $40, $10, $FF, $F0 dc.b 0, $C, $40, $14, 0, 0 dc.b 8, 5, $40, $18, 0, 0 word_7D74A: dc.w 8 dc.b 8, 9, $60, $38, $FF, $E8 dc.b 8, 9, $60, $3E, 0, 0 dc.b $E8, $E, $40, $1C, $FF, $E0 dc.b $E8, $E, $48, $1C, 0, 0 dc.b 0, $C, $40, $28, $FF, $E0 dc.b 8, 5, $40, $2C, $FF, $F0 dc.b 0, $C, $40, $30, 0, 0 dc.b 8, 5, $40, $34, 0, 0 word_7D77C: dc.w 6 dc.b $E8, $E, 0, 0, $FF, $E0 dc.b $E8, $E, 8, 0, 0, 0 dc.b 0, $C, 0, $C, $FF, $E0 dc.b 8, 5, 0, $10, $FF, $F0 dc.b 0, $C, 0, $14, 0, 0 dc.b 8, 5, 0, $18, 0, 0
; A178733: a(n) = n XOR 7n, where XOR is bitwise XOR. ; Submitted by Jon Maiga ; 0,6,12,22,24,38,44,54,48,54,76,70,88,86,108,102,96,102,108,150,152,134,140,182,176,182,172,166,216,214,204,198,192,198,204,214,216,294,300,310,304,310,268,262,280,278,364,358,352,358,364,342,344,326,332,438 mov $5,$0 mul $5,7 mov $2,$5 mov $4,1 lpb $2 mov $2,$5 mov $3,$0 div $0,2 add $3,$5 mod $3,2 mul $3,$4 add $1,$3 sub $2,1 mul $4,2 div $5,2 lpe mov $0,$1
;--- DOS stub program. It does: ;--- - check if cpu supports PAE feature ;--- - check that image is PE it can handle ;--- - allocates XMS memory and loads the image ;--- - initializes IDT ;--- - setup PAE paging tables (using unreal mode) ;--- - switch to 32-bit protected mode, PAE paging enabled ;--- - init segment registers to FLAT mode, calls PE entry point. ;--- ;--- Note: requires at least JWasm v2. ;--- To create the binary enter: ;--- JWasm -mz Dos32pae.asm .model small DGROUP group _TEXT .stack 5120 .dosseg .586p option casemap:none include peimage.inc include dpmi.inc ?IRQ0TORM equ 1 ;1=route IRQ 0 (clock) to real-mode ?IRQ1TORM equ 1 ;1=route IRQ 1 (keyb) to real-mode ;--- define "conventional" memory region seen by the application. ;--- default is 00000-FFFFF (begin 0, size 256 pages). ;--- ?CONVBEG: if the begin isn't 0, physical page 0 will be mapped in ;--- somewhere else, because access to the IVT is necessary (int 31h, ax=300h). ;--- ?CONVSIZE: it's possible to reduce the size, if there's no ;--- need to access the BIOS in protected-mode. ?CONVBEG equ 0 ;start page of "conventional" memory ?CONVSIZE equ 256 ;size of "conventional" memory in 4k-pages ?MPIC equ 78h ;base master PIC ?SPIC equ 70h ;base slave PIC ?I31301 equ 1 ;1=support int 31h, ax=301h ?I31504 equ 1 ;1=support int 31h, ax=504h (uncommitted memory only) ?I31518 equ 1 ;1=support int 31h, ax=518h map physical memory ?DIRVIO equ 1 ;1=direct video output for int 41h, 0=use BIOS ?I31SETTG equ 1 ;1=allow int 31h to alter task gate CS:EIP, 0=int 31h resets exception 8 to interrupt gate ife ?CONVBEG ?PG0ADDR equ 0 ?IDTADDR equ (?CONVBEG+?CONVSIZE)*4096 ;linear address of IDT else ?PG0ADDR equ (?CONVBEG+?CONVSIZE)*4096 ?IDTADDR equ ?PG0ADDR+1000h ;linear address of IDT endif ;--- there's half a page free after the IDT (unlike in Dos64stb) ;--- use the first half of this half-page for a "kernel stack" in the main TSS ;--- and the second half for an alternative double-fault stack ;--- (former not really needed since we really only provide for ring-0 operation, ;--- but it doesn't really do any harm to have it there...) ?KSTKADR equ ?IDTADDR+0C00h ?DFSTKADR equ ?IDTADDR+0FFCh ifdef __JWASM__ option MZ:sizeof IMAGE_DOS_HEADER ;set min size of MZ header if jwasm's -mz option is used endif lf equ 10 EMM struct ;XMS block move struct _size dd ? srchdl dw ? srcofs dd ? dsthdl dw ? dstofs dd ? EMM ends TSS struct ;Standard 386 TSS _res dw ? ;reserved Blink dw ? ESP_r0 dd ? SS_r0 dd ? ;only the bottom word may be filled ESP_r1 dd ? SS_r1 dd ? ;only the bottom word may be filled ESP_r2 dd ? SS_r2 dd ? ;only the bottom word may be filled TSS_CR3 dd ? ;physical address page directory (=CR3) TSS_EIP dd ? TSS_EFL dd ? TSS_EAX dd ? TSS_ECX dd ? TSS_EDX dd ? TSS_EBX dd ? TSS_ESP dd ? TSS_EBP dd ? TSS_ESI dd ? TSS_EDI dd ? TSS_ES dd ? TSS_CS dd ? TSS_SS dd ? TSS_DS dd ? TSS_FS dd ? TSS_GS dd ? TSS_LDT dd ? _res2 dw ? ;reserved IOPB dw ? TSS ends sizeTSS equ sizeof TSS ;--- a segment consisting of two EMS pages used as a buffer for page tables ;--- (and some other data) for copying to XM when Unreal is unavailable PTbuflayout struct ;--- first EMS page, first 4k page: curPT dq 200h dup(?) ;--- first EMS page, second 4k page: curPD dq 200h dup(?) ;--- first EMS page, third 4k page: PDPT dq 4 dup(?) pCurPT dq ? ; physical address of swapped-in PT pCurPD dq ? ; physical address of swapped-in PD pPDPT dq ? ; physical address of swapped-in PDPT align 1000h ;--- first EMS page, fourth 4k page (unused): _unused dq 200h dup(?) ;--- second EMS page, first 4k page: vcpiPT dd 400h dup(?) ;--- second EMS page, second 4k page: vcpiPD dd 400h dup(?) ;--- second EMS page, third 4k page: blank db 400h dup(?) ; 1k of zeros embadrs dq 180h dup(?) ; store qwords representing EMB base physical addresses PTbuflayout ends ;--- define a string CStr macro text:vararg local sym .const sym db text,0 .code exitm <offset sym> endm ifdef _DEBUG dprintf proto c text:ptr byte, args:vararg @dprintf macro text:req,args:vararg local sym CONST segment sym db text,10,0 CONST ends ifb <args> invoke dprintf, offset sym else invoke dprintf, offset sym, args endif endm else @dprintf textequ <;> endif @wait macro ;debug help: wait for ESC key local sm1 sm1: in al,64h ;key from keyboard arrived? test al,1 jz sm1 in al,60h cmp al,81h ;wait for ESC released jnz sm1 endm @fatexit macro text local sym mov dx,offset sym mov ah,9 int 21h mov ah,4Ch int 21h .const sym db text,13,10,'$' .code endm @lidt macro addr if ?IDTADDR ge 1000000h ;is IDT linear address below 16M? db 66h endif lidt addr endm @rep macro cmd ;if 32-bit string opcode is used in 16-bit db 67h rep cmd endm .code SEL_FLATCS equ 1*8 SEL_FLATDS equ 2*8 SEL_CODE16 equ 3*8 SEL_DATA16 equ 4*8 SEL_TSS equ 5*8 SEL_DFTSS equ 6*8 SEL_VCPICS equ 7*8 GDT dq 0 ; null descriptor dw -1,0,9A00h,00CFh ; flat code descriptor dw -1,0,9200h,00CFh ; flat data descriptor dw -1,0,9A00h,0000h ; 16-bit DGROUP code descriptor dw -1,0,9200h,0000h ; 16-bit DGROUP data descriptor dw sizeTSS-1,offset maintss,8900h,0040h ; main TSS dw sizeTSS-1,offset dflttss,8900h,0040h ; #DF TSS sizeGDT equ $-GDT dq 3 dup(?) sizeGDT_VCPI equ $-GDT inVCPImode equ (word ptr cs:[GDTR] == sizeGDT_VCPI-1) GDTR label fword ; Global Descriptors Table Register dw sizeGDT-1 ; limit of GDT (size minus one) dd offset GDT ; linear address of GDT IDTR label fword ; Interrupt Descriptor Table Register dw 256*8-1 ; limit of IDT (size minus one) dd ?IDTADDR ; linear address of IDT nullidt label fword dw 3FFh dd 0 .data ;--- the main TSS will not be switched to, so it doesn't need the PDBR filled in maintss TSS <0,0,?KSTKADR,SEL_FLATDS,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0DFFFh> ; max possible IOPB offset to ensure NO IOPB! ;--- double-fault task gate TSS - will be switched to for #DF! dflttss TSS <0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,?DFSTKADR,0,0,0,SEL_FLATDS,SEL_FLATCS,SEL_FLATDS,SEL_FLATDS,SEL_FLATDS,SEL_FLATDS,0,0,0DFFFh> ; max possible IOPB offset to ensure NO IOPB! ;--- since this TSS needs a PDBR set (for switching), just store our CR3 here. pPageDir equ dflttss.TSS_CR3 xmsaddr dd ? ;seg:offs address of XMS entry PhysBase dd ? ;physical page image base ;pPageDir dd ? ;physical address page directory (=CR3) wStkBot dw ?,? ;real-mode stack bottom, offset & segment dwESP dd ? ;protected-mode ESP dw SEL_FLATDS retad label fword dd offset start32 dw SEL_FLATCS dwCSIP dd ? ;real mode CS:IP to be called adjust dd ? ;offset to adjust EMB to page boundary fname dd ? ;image's file name in environment block nxtLinAddr dd ? fhandle dw -1 ;DOS file handle for image wFlags dw ? ;used to temporarily store real mode flags xmsidx dw 0 if ?MPIC ne 8 bPICM db ? endif if ?SPIC ne 70h bPICS db ? endif vPIC label word vPICM db 8 ;saved master PIC vector vPICS db 70h ;saved slave PIC vector PTbufseg dw -1 ;low mem buffer for page tables if Unreal Mode unavailable emshdl dw -1 V86pgs dd ? vcpiadr label fword dd ? dw SEL_VCPICS ;--- don't move the saved IVT vectors to .data? ;--- this leaves the full _BSS and CONST space ;--- as extra real-mode stack space. if ?MPIC ne 8 storedIntM label dword dd 8 dup (?) endif if ?SPIC ne 70h storedIntS label dword dd 8 dup (?) endif ;--- persistent EMM block used for setting up page tables without Unreal emm3 EMM <> ;--- VCPI control structure vcpiCR3 dd ? ; not the PAE CR3, a 32-bit one! vcpiGDT dd offset GDTR vcpiIDT dd offset IDTR vcpiLDT dw 0 vcpiTSS dw SEL_TSS vcpiEIP dd ? vcpiCS dw SEL_CODE16 _DATA1 segment word "DATA" DGROUP group _DATA1 MEMBLK struct 4 wHdl dw ? dwAddr dd ? MEMBLK ends ;--- the table is put BEHIND the .data segment ;--- because the items in .const and .data? ;--- are used during init only - hence the xms handle ;--- table can grow dynamically. xmshdltab label MEMBLK xms1 MEMBLK <0,0> ;handle of allocated XMS block _DATA1 ends .const intstruc struct intno db ? ofs dw ? intstruc ends ;--- table of pm interrupts that the stub wants to handle inttab label intstruc intstruc <?MPIC+0, lowword offset clock> intstruc <?MPIC+1, lowword offset keyboard> intstruc <21h, lowword offset int21> intstruc <31h, lowword offset int31> intstruc <41h, lowword offset int41> endinttab equ $ .data? nthdr IMAGE_NT_HEADERS <> sechdr IMAGE_SECTION_HEADER <> emm EMM <> emm2 EMM <> .code ;--- 16bit start/exit code CreateAddrSpace proto stdcall linaddr:dword, pages:dword, physpage:dword MapPages proto stdcall linaddr:dword, pages:dword, physpage:dword assume ds:DGROUP start16 proc mov eax,cs mov ds,ax shl eax,4 add dword ptr [GDTR+2], eax ; convert offset to linear address add [vcpiGDT], eax ; convert offset to linear address add [vcpiIDT], eax ; convert offset to linear address mov word ptr [GDT + SEL_CODE16 + 2], ax mov word ptr [GDT + SEL_DATA16 + 2], ax add word ptr [GDT + SEL_TSS + 2], ax add word ptr [GDT + SEL_DFTSS + 2], ax shr eax,16 mov byte ptr [GDT + SEL_CODE16 + 4], al mov byte ptr [GDT + SEL_DATA16 + 4], al mov byte ptr [GDT + SEL_TSS + 4], al mov byte ptr [GDT + SEL_DFTSS + 4], al mov ax,ss mov dx,es sub ax,dx mov bx,sp shr bx,4 add bx,ax mov ah,4Ah int 21h ; free unused memory push cs pop es mov ax,ss mov dx,cs sub ax,dx shl ax,4 add ax,sp push ds pop ss mov sp,ax ; make a TINY model, CS=SS=DS=ES mov wStkBot+0,ax mov wStkBot+2,ss smsw ax test al,1 jz @F ;--- not in RM - therefore can't use Unreal... xor ax,ax mov [PTbufseg],ax ;--- need VCPI to take control, so check for that... mov ah,0DEh int 67h mov word ptr [GDTR],sizeGDT_VCPI-1 ; 3 extra GDT entries needed! test ah,ah jz @F @fatexit "Mode is V86 and no VCPI. Need REAL mode to switch to PAE paging mode!" @@: xor edx,edx mov eax,1 ; test if pae paging is supported cpuid bt edx,6 jc @F @fatexit "PAE paging not supported." @@: mov ax,4300h int 2fh ;XMS host available? test al,80h jnz @F @fatexit "No XMS host detected." @@: push es mov ax,4310h int 2fh mov word ptr [xmsaddr+0],bx mov word ptr [xmsaddr+2],es pop es mov ah,5 ;local enable A20 call xmsaddr ;--- do VCPI setup work if necessary before transferring stuff into XMS mem .if inVCPImode mov ah,41h ; get page frame address int 67h test ah,ah jnz @@tryumb mov [PTbufseg],bx ;--- allocate two EMS pages (i.e. eight 4k pages) ;--- first EMS page for temporary storage of PDPT/PDs/PTs before copying to XM ;--- second one for VCPI PT and VCPI PD (latter with only one entry) ;--- lots of space "wasted" here (it could all be compressed into one EMS page) ;--- but this strategy is reusable for Dos64Stb (where four-level paging makes ;--- better use of the first EMS page) mov ebx,2 mov ah,43h ; allocate pages int 67h test ah,ah jnz @@tryumb mov [emshdl],dx mov ax,4400h ; map handle page, to zeroth "physical" page xor bx,bx ; map the first EMS page of this handle int 67h test ah,ah jnz @@tryumb mov ax,4401h ; map handle page, to first "physical" page mov bx,1 ; map the second EMS page of this handle int 67h test ah,ah jz @@PTbufallocated @@tryumb: ;--- no EMS page frame - try an XMS UMB instead... mov ah,10h ; request UMB mov dx,sizeof PTbuflayout SHR 4 call xmsaddr cmp ax,1 jne @@tryconv mov [PTbufseg],bx jz @@PTbufallocated @@tryconv: ;--- agh, we need to allocate 28k of conventional memory! :( mov ah,48h ; request UMB mov bx,sizeof PTbuflayout SHR 4 int 21h mov [PTbufseg],ax jnc @@PTbufallocated @fatexit "Unable to allocate low-memory PT buffer" @@PTbufallocated: ;--- clear the EMS pages mov es,[PTbufseg] xor di,di mov cx,sizeof PTbuflayout SHR 2 xor eax,eax cld rep stosd mov ax,0DE01h ; get protected mode interface mov edi,PTbuflayout.vcpiPT ; second EMS page in the page frame mov si,offset GDT+SEL_VCPICS ; DS:SI points to descriptors int 67h mov dword ptr [vcpiadr],ebx sub edi,PTbuflayout.vcpiPT mov ecx,edi shr ecx,2 ; convert to page count mov [V86pgs],ecx ;--- clear bits 9-11 of all the PT entries, as per the VCPI standard @@: and byte ptr es:[ecx*4-3],0F1h ; byte index n*4 - 3, where n > 0 loop @B .if !([PTbufseg] & 0FFh) ;--- get the physical addx of the PT we just filled in ;--- (but only if it's page-aligned!) mov di,[PTbufseg] add di,PTbuflayout.vcpiPT SHR 4 ; convert offset to segment delta ;shl edi,4 ; paragraphs to bytes ;shr edi,12 ; bytes to pages ;shl edi,2 ; page count to PT index shr di,6 add di,PTbuflayout.vcpiPT mov ebx,[es:di] ; physical addx of VCPI PT add di,4 mov ecx,[es:di] ; physical addx of empty PD (very next page) and cx,0F000h ; get just the addx, no attrs mov di,PTbuflayout.vcpiPD mov [es:di],ebx ; put the PT addx at the beginning of the PD mov vcpiCR3,ecx ; address of the PD for VCPI switch .endif push ds pop es .endif push es mov ah,51h int 21h mov es,bx mov es,es:[002Ch] xor di,di xor al,al mov cx,-1 @@: repnz scasb cmp byte ptr es:[di],0 jnz @B add di,3 mov word ptr fname+0,di mov word ptr fname+2,es pop es push ds lds dx,fname mov ax,3D00h int 21h pop ds mov bp,CStr("cannot open file") jc @error mov fhandle,ax mov bx,ax ;--- load the file header sub sp,4096 mov cx,sizeof IMAGE_DOS_HEADER mov dx,sp mov ah,3Fh int 21h cmp ax,cx mov bp, CStr("invalid file format") jnz @error movzx edx,dx cmp word ptr [edx].IMAGE_DOS_HEADER.e_magic,"ZM" mov bp, CStr("invalid file format (no MZ header)") jnz @error cmp word ptr [edx].IMAGE_DOS_HEADER.e_lfarlc,sizeof IMAGE_DOS_HEADER mov bp, CStr("invalid file format (MZ header too small)") jc @error mov cx,word ptr [edx].IMAGE_DOS_HEADER.e_lfanew+2 mov dx,word ptr [edx].IMAGE_DOS_HEADER.e_lfanew+0 mov ax,4200h int 21h mov dx,offset nthdr mov cx,sizeof nthdr mov ah,3Fh int 21h cmp ax,cx mov bp, CStr("invalid file format (cannot locate PE header)") jnz @error cmp dword ptr nthdr.Signature,"EP" mov bp, CStr("invalid file format (no PE header)") jnz @error cmp nthdr.FileHeader.Machine,IMAGE_FILE_MACHINE_I386 mov bp, CStr("not a 32-bit binary") jnz @error if 0 test nthdr.FileHeader.Characteristics,IMAGE_FILE_RELOCS_STRIPPED mov bp, CStr("relocations stripped, cannot load") jnz @error endif cmp nthdr.OptionalHeader.Subsystem,IMAGE_SUBSYSTEM_NATIVE mov bp, CStr("subsystem not native, cannot load") jnz @error cmp nthdr.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT*sizeof IMAGE_DATA_DIRECTORY].Size_,0 mov bp, CStr("image contains imports, cannot load") jnz @error mov edx, nthdr.OptionalHeader.SizeOfImage add edx, dword ptr nthdr.OptionalHeader.SizeOfStackReserve mov bp, CStr("image + stack > 4GB") jc @error shr edx,12 ;convert to 4k pages ;--- calculate space for page tables (each PT covers 2 MB) mov eax,edx shr eax,9 add eax,2 ;add 2 pages (max overhead) add edx,eax ;--- add space for IDT and page tables ;--- needed: 1 page for IDT + PDPT ;--- max 4 pages for PD (4 * 512 * PDEs ) ;--- total: 5 pages add edx, 5 .if inVCPImode && ([PTbufseg] & 0FFh) ;--- PTbufseg not page-aligned, so need to move VCPI PT/PD (2 pages) into XM too add edx,2 .endif inc edx ;extra page since we need to align to page boundary shl edx, 2 ;convert to kB mov esi, edx mov ah,89h call xmsaddr cmp ax,1 mov bp, CStr("XMS memory allocation failed") jnz @error mov xms1.wHdl,dx inc xmsidx mov emm.dsthdl,dx mov ah,0Ch ;lock EMB call xmsaddr cmp ax,1 mov bp, CStr("cannot lock EMB") jnz @error push dx push bx pop edi .if ([PTbufseg] != 0) && ([PTbufseg] != -1) mov es,[PTbufseg] mov dword ptr [es:PTbuflayout.embadrs],edi push ds pop es .endif push edi call ClearRegion mov bp, CStr("cannot clear EMB") jc @error ;--- align to page boundary pop eax add eax,1000h-1 and ax, 0f000h push eax sub ax,bx movzx eax,ax mov emm.dstofs,eax mov adjust, eax pop eax shr eax,12 mov PhysBase, eax ;--- copy the PE header into extended memory mov ecx, sizeof nthdr mov emm.srchdl, 0 mov word ptr emm.srcofs+0, offset nthdr mov word ptr emm.srcofs+2, ds mov si,offset emm call copy2x_ordie ;--- read image sections and copy them to extended memory mov di,sp mov bx,fhandle mov cx,nthdr.FileHeader.NumberOfSections .while cx push cx mov dx,offset sechdr mov cx,sizeof sechdr mov ah,3Fh int 21h cmp ax,cx mov bp, CStr("error reading section headers") jnz @error mov si,offset emm call copy2x_ordie call readsection pop cx dec cx .endw mov ah,3Eh int 21h mov fhandle,-1 ;--- create IDT .if inVCPImode ;--- check if anyone has reprogrammed the PIC, and setup our IDT accordingly mov ax,0DE0Ah int 67h mov vPICM,bl mov vPICS,cl .if vPIC != 7008h mov [inttab.intno],bl ; clock vector (IRQ0) inc bl mov [inttab.intno+sizeof intstruc],bl ; kbd vector (IRQ1) .endif .endif mov ebx, _TEXT32 shl ebx, 4 add dword ptr [retad],ebx mov cx,32 mov edx, offset exception make_exc_gates: lea eax,[ebx+edx] stosw .if ecx == 24 ; 32-8 - i.e. this is the double-fault gate mov [dflttss.TSS_EIP],eax mov eax,SEL_DFTSS stosw mov ax,8500h ; Task Gate .else mov ax,SEL_FLATCS stosw mov ax,8E00h ; Interrupt Gate .endif stosd add edx,4 loop make_exc_gates mov cx,256-32 mov edx,offset swint mov si, 8F00h call make_int_gates mov di,sp lea di,[di+?MPIC*8] mov cx,8 mov edx,offset Irq0007 mov si, 8E00h call make_int_gates mov di,sp lea di,[di+?SPIC*8] mov cx,8 mov edx,offset Irq080F call make_int_gates ;--- setup IRQ0, IRQ1, Int21, Int31, Int41 mov si, offset inttab .while si < endinttab lodsb movzx di,al shl di,3 add di,sp lodsw movzx eax,ax add eax, ebx mov [di+0],ax shr eax,16 mov [di+6],ax .endw ;--- copy IDT to extended memory mov di, sp mov word ptr emm.srcofs+0,sp mov eax,nthdr.OptionalHeader.SizeOfImage add eax,nthdr.OptionalHeader.SizeOfStackReserve add eax,adjust mov emm.dstofs, eax mov si,offset emm mov ecx,800h call copy2x_ordie add sp,4096 ;--- setup page directories and tables mov esi,nthdr.OptionalHeader.SizeOfImage add esi,nthdr.OptionalHeader.SizeOfStackReserve mov eax,nthdr.OptionalHeader.ImageBase add eax,esi mov nxtLinAddr, eax shr esi,12 push esi ;size of image+stack in pages add esi,PhysBase ;--- esi = next free physical page ;--- first page is used for IDT and page dir mov eax,esi shl eax,12 add eax, 800h mov [pPageDir],eax push esi inc esi .if inVCPImode && ([PTbufseg] & 0FFh) ;--- PTbufseg not page-aligned, so need to move VCPI PT/PD (2 pages) into XM too mov es,[PTbufseg] mov word ptr emm.srcofs+2,es mov word ptr emm.srcofs+0,PTbuflayout.vcpiPT add emm.dstofs, 800h ; move to the next page mov eax,esi shl eax,12 mov [es:PTbuflayout.vcpiPD],eax or [es:PTbuflayout.vcpiPD],11b add eax, 1000h mov [vcpiCR3],eax push ds pop es push esi mov si,offset emm mov ecx,2000h call copy2x_ordie pop esi add esi,2 .endif ife ?CONVBEG invoke CreateAddrSpace, ?CONVBEG*4096, ?CONVSIZE+1, esi add esi, eax else invoke CreateAddrSpace, ?CONVBEG*4096, ?CONVSIZE+2, esi add esi, eax invoke MapPages, ?PG0ADDR, 1, 0 endif invoke MapPages, ?CONVBEG*4096, ?CONVSIZE, ?CONVBEG pop eax invoke MapPages, ?IDTADDR, 1, eax mov eax,[esp] invoke CreateAddrSpace, nthdr.OptionalHeader.ImageBase, eax, esi pop eax mov bp,CStr("Cannot map image in address space") jc @error invoke MapPages, nthdr.OptionalHeader.ImageBase, eax, PhysBase ;--- disable int 23h termination (myint23) ;--- or exit program (@@exit2) ; mov dx,offset myint23 mov dx,offset @@exit2 mov ax,2523h int 21h cmp vPIC,7008h jne @F call setints if ?MPIC ne 8 in al,21h mov bPICM,al endif if ?SPIC ne 70h in al,0A1h mov bPICS,al endif @@: @dprintf "start16: switching to pm" cli cmp vPIC,7008h jne @F mov dx,?SPIC shl 8 or ?MPIC call setpic @@: call switch2pm ;--- now load: ;--- esi = value of image's EIP ;--- ebx = image start linear address mov ebx,cs:nthdr.OptionalHeader.ImageBase mov ecx,cs:nthdr.OptionalHeader.SizeOfStackReserve add ecx,cs:nthdr.OptionalHeader.SizeOfImage add ecx,ebx mov esi,cs:nthdr.OptionalHeader.AddressOfEntryPoint add esi,ebx mov ax,SEL_FLATDS mov ss,ax mov esp,ecx mov ds,ax mov es,ax xor ax,ax mov fs,ax mov gs,ax .if !inVCPImode mov ax,SEL_TSS ltr ax .endif sti ; call HandleRelocs jmp cs:[retad] @error:: mov si,bp nextchar: lodsb and al,al jz done mov dl,al mov ah,2 int 21h jmp nextchar done: mov dx,offset @dotnewline mov ah,9 int 21 jmp @@exit @dotnewline db '.',13,10,'$' make_int_gates: lea eax, [ebx+edx] stosw mov ax,SEL_FLATCS stosw mov ax,si ;int/trap gate stosd loop make_int_gates ret start16 endp ;--- clear region, edi=addr, esi=size in kB ClearRegion proc ;--- clear the whole block call EnableUnreal jc @F mov ecx,esi shl ecx,8 ;kb to dword xor eax,eax;clears CF @rep stosd push ds pop es ret @@: ;--- no Unreal, need to use fiddly XMS helpers instead... push esi mov ecx,esi call FindXmsHdl mov [emm3.srchdl],0 mov si,[PTbufseg] mov word ptr [emm3.srcofs],PTbuflayout.blank mov word ptr [emm3.srcofs+2],si mov si,offset emm3 @@: push ecx mov ecx,400h call copy2x pop ecx jc @F loop @B @@: pop esi ret ClearRegion endp ;--- create address space ;--- linaddr: start linear address space to create ;--- pages: no of pages to map ;--- physpage: start physical memory pages used for paging (physical address >> 12) CreateAddrSpace proc stdcall uses es esi di linaddr:dword, pages:dword, physpage:dword @dprintf "CreateAddrSpace(%lX, %lX, %lX) enter", linaddr, pages, physpage call EnableUnreal setc dh movzx di,dh ; Use DI to track if Unreal is unavailable mov esi, physpage .while pages mov eax,linaddr shr eax,9 push eax shr eax,9 push eax ;--- 2 offsets pushed: ;--- 1. bits 0-11 offset in PT (linaddr [12-20]) ;--- 2. bits 0-11 offset in PD (linaddr [21-29]) shr eax,9 ;--- 3. bits 0-11 offset in PDPT (linaddr [30-31]) and eax,0018h mov cx,2 mov ebx,pPageDir @@: .if di call CopyInTable jnc copytabok shl cx,2 add sp,cx stc jmp exit copytabok: .endif add ebx,eax mov edx,es:[ebx] .if (edx == 0) ;does PDPTE/PDE exist? mov edx,esi ; the paging tables must be below 4GB - if this ; is to change, we cannot use unreal mode here anymore! ; sub eax,eax ; shld eax,edx,12 shl edx,12 cmp cx,2 ;don't set bit 1 for PDPTE adc dl,dl shl dl,1 or dl,1 mov es:[ebx+0],edx ; mov es:[ebx+4],eax inc esi .endif pop eax and eax,0ff8h mov ebx,edx ; and bx,0FC00h and bx,0F000h loop @B .if di call CopyInTable jc exit .endif add ebx,eax test dword ptr es:[ebx],1 stc jnz exit add linaddr,1000h dec pages .endw .if di ;--- swap out the page tables mov cx,3 ; loop three times... mov es,[PTbufseg] mov di,PTbuflayout.pPDPT @@: mov ebx,[es:di] dec cx ; ... but do so with cx = 2,1,0! call CopyOutTable jc exit inc cx sub di,8 loop @B .endif mov eax,esi sub eax,physpage @dprintf "CreateAddrSpace() ok, esi=%lX, eax=%lX", esi, eax clc ifdef _DEBUG ret exit: @dprintf "CreateAddrSpace() failed, linaddr=%lX, pages=%lX, ebx=%lX", linaddr, pages, ebx stc else exit: endif ret CreateAddrSpace endp ;--- map physical pages in existing address space ;--- linaddr: start linear address space ;--- pages: no of pages to map ;--- physpage: start physical page to map (phys page=phys addr shr 12) ;--- note: physical address of paging tables must be 32-bit. MapPages proc stdcall uses es linaddr:dword, pages:dword, physpage:dword @dprintf "MapPages(%lX, %lX, %lX) enter", linaddr, pages, physpage call EnableUnreal setc dh movzx di,dh ; Use DI to track if Unreal is unavailable .while pages mov eax,linaddr shr eax,9 push eax shr eax,9 push eax shr eax,9 ;--- 1. bits 0-11 offset in PT (linaddr [12-20]) ;--- 2. bits 0-11 offset in PD (linaddr [21-29]) ;--- 3. bits 0-4 offset in PDPT (linaddr [30-31]) mov cx,2 mov ebx,pPageDir and eax,0ff8h @@: .if di call CopyInTable jnc copytabok shl cx,2 add sp,cx stc jmp exit copytabok: .endif add ebx,eax pop eax and eax,0ff8h mov ebx,es:[ebx] and bx,0F000h loop @B .if di call CopyInTable jc exit .endif add ebx,eax mov edx,physpage .if inVCPImode && (edx < cs:[V86pgs]) ;push es mov es,[PTbufseg] add edx,PTbuflayout.vcpiPT SHR 2 mov edx,es:[edx*4] xor eax,eax ;pop es .else sub eax,eax shld eax,edx,12 shl edx,12 or dl,11b .endif mov es:[ebx+0],edx mov es:[ebx+4],eax inc physpage add linaddr,1000h dec pages .endw .if di ;--- swap out the page tables mov cx,3 ; loop three times... mov es,[PTbufseg] mov di,PTbuflayout.pPDPT @@: mov ebx,[es:di] dec cx ; ... but do so with cx = 2,1,0! call CopyOutTable jc exit inc cx sub di,8 loop @B .endif clc exit: ret MapPages endp ;--- copy page table from XMS to EMS/convmem so we can work on it ;--- EBX = physical addx of table ;--- CX = paging level ;--- sets ES:EBX to pointer to copied-in page table CopyInTable proc push eax push edi mov es,[PTbufseg] mov di,PTbuflayout.pCurPT shr 3 add di,cx ; the CXth entry on the list shl di,3 cmp [es:di],ebx ; is the physical addx the same one we've swapped in? setz al xchg [es:di],ebx .if (al == 0) && ebx ;--- if we're swapping in a new table, and there's one there now, swap it out call CopyOutTable jc @F .endif movzx ebx,cx shl bx,12 ; nth paging level corresponds to nth 4k page in buffer .if al == 0 mov edi,[es:di] ;@dprintf "Copying level-%d PT In from %lX", cx, edi call FindXmsHdl ;--- FindXmsHdl filled in the destination, but here it's actually the source! xor di,di xchg di,[emm3.dsthdl] ; make destination handle zero (low mem) mov [emm3.srchdl],di mov edi,[emm3.dstofs] mov [emm3.srcofs],edi ;--- our destination is in the buffer segment ;--- TODO: allocate buffer segment in convmem if it's unset (i.e. zero) ;--- (currently never the case since we have already allocated it in EMS) mov word ptr [emm3.dstofs+2],es mov word ptr [emm3.dstofs],bx push ecx .if cx == 2 mov ecx,20h ; PDPT is only 32 bytes .else mov ecx,1000h ; copy full page .endif push esi mov si,offset emm3 call copy2x pop esi pop ecx .else clc .endif @@: pop edi pop eax ret CopyInTable endp ;--- copy page table from EMS/convmem back out to XMS ;--- EBX = physical addx of table ;--- CX = paging level CopyOutTable proc push eax push edi push esi mov edi,ebx call FindXmsHdl ;--- FindXmsHdl filled in the destination; our source is in the buffer segment mov [emm3.srchdl],0 ; low mem push es mov es,[PTbufseg] movzx edi,cx shl di,12 ; nth paging level corresponds to nth 4k page in buffer mov word ptr [emm3.srcofs+2],es mov word ptr [emm3.srcofs],di mov eax,[es:edi] mov esi,[es:edi+4] ;@dprintf "Copying level-%d PT to %lX from %04X:%04X - starts with %08lX%08lX", cx,ebx,es,di,esi,eax pop es push ecx .if cx == 2 mov ecx,20h ; PDPTE is only 32 bytes .else mov ecx,1000h ; copy full page .endif mov si,offset emm3 call copy2x pop ecx pop esi pop edi pop eax ret CopyOutTable endp EnableUnreal proc .if [PTbufseg] != -1 ;--- if a PT buffer is in use, it means Unreal is unavailable stc ret .endif cli lgdt [GDTR] mov eax,cr0 or al,1 mov cr0,eax jmp @F @@: push SEL_FLATDS pop es and al,0FEh mov cr0,eax jmp @F @@: sti xor ax,ax ; clears carry mov es,ax ret EnableUnreal endp FindXmsHdl proc ;--- take physical addx in edi and fill in emm3 struct with the corresponding ;--- XMS handle and offset (or best guess thereat) push ebx push ebp push si push es mov es,[PTbufseg] xor ebp,ebp not ebp ; track the smallest offset we find - so begin with FFFFFFFFh mov si,xmsidx shl si,3 ;sizeof MEMBLK = 8 .while si ;--- get EMB bases from EMS page mov ebx,dword ptr [es:PTbuflayout.embadrs-8+si] neg ebx add ebx,edi jnc @F ; edi would be a negative offset in this block, so not right cmp ebx,ebp jnb @F ; not the smallest offset we've found ;--- this is the handle with the smallest offset for edi that we've found, ;--- so it's a candidate for the handle that contains edi mov ebp,ebx mov [emm3.dstofs],ebx mov bx,[si+xmshdltab-sizeof MEMBLK].MEMBLK.wHdl mov [emm3.dsthdl],bx ;@dprintf "FindXmsHdl(): (%d/8)th hdl %X candidate for addr %lX (offs=%lX)", si, bx, edi, ebp @@: sub si,sizeof MEMBLK .endw pop es pop si pop ebp pop ebx ret FindXmsHdl endp ;--- switch to real-mode switch2rm proc mov ax,SEL_DATA16 mov fs,ax mov gs,ax ;--- disable paging & protected-mode mov eax,cr0 and eax,7ffffffeh mov cr0, eax jmp far16 ptr @F @@: mov eax,cr4 and al,0DFh ; reset bit 5, disable PAE paging mov cr4,eax .if inVCPImode mov eax,cs:[vcpiCR3] mov cr3,eax mov eax,cr0 or eax,80000001h ; re-enable paging with VCPI-provided settings mov cr0,eax jmp @F @@: push SEL_FLATDS pop ds push ebx mov ebx,esp ;--- setup segments - make a tiny model... movzx eax,cs:[wStkBot+2] push eax ; GS push eax ; FS push eax ; DS push eax ; ES push eax ; SS push ebx ; ESP sub esp,4 ; EFLAGS push eax ; CS pushd offset @F ; EIP mov ax, 0DE0Ch ; switch to VM86 call cs:vcpiadr @@: pop ebx .else lidt cs:[nullidt] ; IDTR=real-mode compatible values .endif ret switch2rm endp ;--- switch to protected-mode switch2pm proc .if inVCPImode mov ax,0DE0Ch push esi push cs:[wStkBot] mov cs:[wStkBot],sp mov esi,cs shl esi,4 add esi,offset vcpiCR3 mov cs:[vcpiEIP],offset @F int 67h @@: mov ax, SEL_DATA16 ;mov ds, ax ;mov es, ax mov ss, ax mov sp, ss:[wStkBot] pop ss:[wStkBot] pop esi mov eax,cr0 and eax,7FFFFFFFh ; turn off paging while we reconfigure it mov cr0,eax .else lgdt cs:[GDTR] @lidt cs:[IDTR] .endif mov eax,cr4 or ax,220h ; enable PAE (bit 5) and OSFXSR (bit 9) mov cr4,eax mov eax,cs:pPageDir mov cr3,eax ;--- enable protected-mode + paging - also clear TS bit? mov eax,cr0 or eax,80000001h mov cr0,eax ret switch2pm endp @popd macro x db 66h pop x endm ;--- call real-mode thru DPMI functions ax=300h/301h. ;--- interrupts disabled, stack switched to 16-bit. ;--- SP-> CS:EIP, RMCS. call_rmode proc call switch2rm ; pop dword ptr cs:retad ;not really needed. this proc is called by int31 only! ; add sp,4 ;skip CS (must be flat cs) popad pop cs:wFlags pop es pop ds pop fs pop gs pop cs:[dwCSIP] lss sp,[esp] cmp ax,4B00h jnz @F int 3 @@: push cs:wFlags ;make an IRET frame call cs:[dwCSIP] lss sp,dword ptr cs:wStkBot push gs push fs push ds push es pushf cli pushad movzx esi,cs:[wStkBot+2] shl esi,4 movzx esp,sp add esi,esp call switch2pm lss esp,fword ptr cs:[dwESP] pushf btr word ptr [esp],14 ;clear NT in eflags popf @popd gs @popd fs @popd es @popd ds mov edi,[esp] cld mov ecx,42/2 rep movsw [edi],[esi] popad iretd call_rmode endp setints proc push 0 pop es if ?MPIC ne 8 mov cx,8 mov bx,?MPIC*4 mov di,offset storedIntM @@: mov eax, es:[bx] mov [di], eax add bx,4 add di,4 loop @B endif if ?SPIC ne 70h mov cx,8 mov bx,?SPIC*4 mov di,offset storedIntS @@: mov eax, es:[bx] mov [di], eax add bx,4 add di,4 loop @B endif push ds push es pop ds if ?MPIC ne 8 mov cx,8 mov si,8*4 mov di,?MPIC*4 rep movsd endif if ?SPIC ne 70h mov cx,8 mov si,70h*4 mov di,?SPIC*4 rep movsd endif pop ds ret setints endp restoreints proc cld push 0 pop es if ?MPIC ne 8 mov cx,8 mov di,?MPIC*4 mov si,offset storedIntM rep movsd endif if ?SPIC ne 70h mov cx,8 mov di,?SPIC*4 mov si,offset storedIntS rep movsd endif ret restoreints endp setpic proc ;--- change IRQ 0-7 to ?MPIC if ?MPIC ne 8 mov al,10001b ; ICW1: initialization out 20h,al mov al,dl ; ICW2: IRQ 0-7: interrupts ?MPIC-?MPIC+7 out 21h,al mov al,100b ; ICW3: slave connected to IRQ2 out 21h,al mov al,1 ; ICW4: Intel environment, manual EOI out 21h,al mov al,bPICM out 21h,al endif ;--- change IRQ 8-F to ?SPIC if ?SPIC ne 70h mov al,10001b ; ICW1: initialization out 0A0h,al mov al,dh ; ICW2: IRQ 8-15: interrupts ?SPIC-?SPIC+7 out 0A1h,al mov al,2 ; ICW3: out 0A1h,al mov al,1 ; ICW4: Intel environment, manual EOI out 0A1h,al mov al,bPICS out 0A1h,al endif .if inVCPImode push bx push cx movzx bx,dl movzx cx,dh mov ax,0DE0Bh call doint67 pop cx pop bx .endif ret setpic endp ;--- int 67h wrapper that just calls it in VM86 mode ;--- but goes through int 31h 0300h in protected mode ;--- might have been easier to put an int 67h gate in our IDT, ;--- but then what if someone installs something else over it... doint67 proc push cs cmp word ptr [esp],_TEXT ;in VM86 mode? lea esp,[esp+2] ;pop cs jne @F int 67h ret @@: sub esp,14h pushad xor ecx,ecx mov [esp].RMCS.rFlags, 0202h mov dword ptr [esp].RMCS.rES,ecx mov dword ptr [esp].RMCS.rFS,ecx mov [esp].RMCS.rSSSP, ecx mov edi,esp mov bx,67h mov ax,0300h int 31h popad lea esp,[esp+14h] ret doint67 endp ;--- switch back to real-mode and exit backtoreal proc cli mov ax,SEL_DATA16 ; set SS, DS and ES to 16bit, 64k data mov ds,ax mov es,ax mov ss,ax movzx esp,wStkBot call switch2rm @@exit2:: mov ax,cs mov ds,ax ; DS=DGROUP lss sp,dword ptr wStkBot ;--- restore PIC and IVT mov dx,vPIC cmp dx,7008h jne @@exit call setpic call restoreints @@exit:: sti mov bx,fhandle cmp bx,-1 jz @F mov ah,3Eh int 21h @@: mov dx,emshdl cmp dx,-1 jz @F mov ah,45h ;deallocate pages int 67h @@: mov si,xmsidx shl si,3 ;sizeof MEMBLK = 8 .while si mov dx,[si+xmshdltab-sizeof MEMBLK].MEMBLK.wHdl mov ah,0dh ;unlock handle call xmsaddr mov ah,0ah ;free EMB call xmsaddr sub si,sizeof MEMBLK .endw cmp xmsaddr,0 jz @F mov ah,6 ;local disable A20 call xmsaddr mov ah,11h ;release UMB mov dx,[PTbufseg] call xmsaddr @@: mov ax,4c00h int 21h backtoreal endp ;--- copy cx bytes to extended memory copy2x proc mov [si].EMM._size,ecx push ecx push bx mov ah,0bh call xmsaddr pop bx pop ecx add [si].EMM.dstofs,ecx .if ax == 1 clc .else stc .endif ret copy2x endp copy2x_ordie proc call copy2x mov bp, CStr("error copying to extended memory") jc @error ret copy2x_ordie endp ;--- read a section and copy it to extended memory ;--- DI = 4 kB buffer ;--- BX = file handle ;--- sechdr = current section readsection proc mov ax,4201h xor cx,cx xor dx,dx int 21h push dx push ax mov emm2.srchdl, 0 mov word ptr emm2.srcofs+0, di mov word ptr emm2.srcofs+2, ds mov ax,xms1.wHdl mov emm2.dsthdl, ax mov eax, sechdr.VirtualAddress add eax, adjust mov emm2.dstofs, eax mov eax, sechdr.PointerToRawData push eax pop dx pop cx mov ax,4200h int 21h mov esi, sechdr.SizeOfRawData .while esi mov ecx,esi cmp ecx,1000h jb @F mov cx,1000h @@: mov dx,di mov ah,3Fh int 21h cmp ax,cx mov bp, CStr("cannot read section data") jnz @error sub esi, ecx push si mov si,offset emm2 call copy2x_ordie pop si .endw pop dx pop cx mov ax,4200h int 21h ret readsection endp savestate: push eax push ecx mov ax,[esp+8] push ds push es push fs push gs mov ecx, esp push SEL_DATA16 pop ss mov sp,cs:[wStkBot] push ax jmp switch2rm reststate_iretd: cli call switch2pm mov ax,SEL_FLATDS mov ss,ax mov esp,ecx pop gs pop fs pop es pop ds pop ecx pop eax add esp,2 iretd if ?IRQ0TORM clock16 proc call savestate int 08h jmp reststate_iretd clock16 endp endif if ?IRQ1TORM keyboard16 proc call savestate int 09h jmp reststate_iretd keyboard16 endp endif ife ?DIRVIO ;use BIOS for debug output int4116 proc far cli mov bx,ax call savestate mov ax,bx xor bx,bx mov ah,0Eh cmp al,10 jnz @F mov al,13 int 10h mov ax,0E0Ah @@: int 10h reststate_retd:: cli call switch2pm ;modifies flags! mov ax,SEL_FLATDS mov ss,ax mov esp,ecx pop gs pop fs pop es pop ds pop ecx pop eax add esp,2 retd int4116 endp endif if ?I31504 ;--- allocate address space: ;--- EBX: linear address (or 0) ;--- ECX: size in bytes ;--- DX: attributes (bit 0 must be zero [=uncommitted]) ;--- ebx must be page aligned int31_50416 proc far local linad:dword local dwSize:dword local adjLinAddr:byte local handle:word push cs pop ds @dprintf "int31_504( ebx=%lX ecx=%lX dx=%X ) enter", ebx, ecx, dx test bx,0fffh jnz error cmp ebx,0 setz adjLinAddr jnz @F mov ebx,nxtLinAddr @@: ;--- alloc EMB for page tables ;--- ecx=200000h -> 200h PTEs -> 1 PT mov edx,ecx mov dwSize,ecx mov eax,ebx add eax,ecx jz @F jb error @@: mov linad, ebx shr edx,21 mov eax,edx shr eax,9 add edx, eax inc edx ;number of PTs inc edx ;number of PTs inc edx ;add 1 for page alignment shl edx,2 ;convert 4k to 1k mov esi,edx mov ah,89h call xmsaddr cmp ax,1 jnz error mov di,xmsidx shl di,3 add di,offset xmshdltab mov [di].MEMBLK.wHdl,dx mov [di].MEMBLK.dwAddr,ebx mov handle,di inc xmsidx mov ah,0Ch ;lock EMB call xmsaddr cmp ax,1 jnz error push dx push bx pop edi .if ([PTbufseg] != 0) && ([PTbufseg] != -1) push es mov es,[PTbufseg] movzx ebx,xmsidx mov dword ptr [es:PTbuflayout.embadrs-8+ebx*8],edi pop es .endif push edi @dprintf "int31_504() clear region edi=%lX, esi=%lX kB", edi, esi call ClearRegion ;clear region edi, size esi kb pop eax jc error add eax,1000h-1 ;and ax,0F000h shr eax,12 mov esi, dwSize add esi, 1000h-1 shr esi,12 invoke CreateAddrSpace, linad, esi, eax jc error .if adjLinAddr shl esi,12 add nxtLinAddr, esi .endif mov ebx,linad movzx esi,handle clc ret error: stc ret int31_50416 endp endif if ?I31518 ;--- map physical memory ;--- esi=handle ;--- ebx=offset in block ;--- ecx=pages ;--- edi:edx=64-bit physical address int31_51816 proc far push cs pop ds mov ax,si sub ax,offset xmshdltab jc error test al,7 jnz error shr ax,3 cmp ax,xmsidx jae error test bx,0fffh jnz error add ebx,[si].MEMBLK.dwAddr ;--- todo: check if ebx and ebx+ecx are within block shl edi,20 shr edx,12 or edx, edi invoke MapPages, ebx, ecx, edx clc ret error: stc ret int31_51816 endp endif ;--- set/reset PIC from application program int31_a0016 proc far cli mov dx,[cs:vPIC] cmp bl,0 ;restore to standard? jz @F ;--- only change the vectors if nobody else changed them (in VCPI mode) .if dh == 70h mov dh,?SPIC .endif .if dl == 8 mov dl,?MPIC .endif @@: call setpic iretd int31_a0016 endp if 0 ;--- handle base relocations HandleRelocs proc mov edi, PhysBase mov esi, nthdr.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC*sizeof IMAGE_DATA_DIRECTORY].VirtualAddress mov ecx, nthdr.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC*sizeof IMAGE_DATA_DIRECTORY].Size_ mov edx, edi sub edx, dword ptr nthdr.OptionalHeader.ImageBase add esi, edi ;RVA->linear add ecx, esi ;ecx=end of relocs (linear) nextpage: cmp esi, ecx jnc reloc_done push ecx @lodsd ;get RVA of page mov ebx, eax add ebx, edi ;convert RVA to linear address @lodsd lea ecx, [esi+eax-8];ecx=end of relocs for this page xor eax, eax nextreloc: @lodsw test ah,0F0h ;must be < 1000h (size of a page) jz ignreloc and ah,0Fh add [eax+ebx], edx ignreloc: cmp esi, ecx jb nextreloc pop ecx jmp nextpage reloc_done: ret HandleRelocs endp endif ifdef _DEBUG include dprintf.inc endif _TEXT ends @jmp16 macro ofs db 66h,0eah dw offset ofs dw SEL_CODE16 endm @call16 macro ofs db 09ah dd offset ofs dw SEL_CODE16 endm _TEXT32 segment use32 para public 'CODE' assume ds:nothing, es:nothing, ss:nothing start32 proc call esi mov ah,4Ch int 21h start32 endp ;--- debug output helpers ( int 41h ) if ?DIRVIO ; direct video output - don't use BIOS ?VIOCOLS equ ?PG0ADDR+44Ah ?VIOPBEG equ ?PG0ADDR+44Eh ?VIOCSR equ ?PG0ADDR+450h ?VIOPG equ ?PG0ADDR+462h ?VIOCRT equ ?PG0ADDR+463h ?VIOROWS equ ?PG0ADDR+484h ;--- set text mode cursor set_cursor proc pushad push ds push SEL_FLATDS pop ds MOVZX esi, BYTE PTR ds:[?VIOPG] MOVZX ecx, BYTE PTR ds:[esi*2+?VIOCSR+1] ;get cursor pos ROW MOVZX eax, WORD PTR ds:[?VIOCOLS] MUL ecx MOVZX edx, BYTE PTR ds:[esi*2+?VIOCSR+0] ;get cursor pos COL ADD eax, edx movzx ecx,word ptr ds:[?VIOPBEG] shr ecx,1 add ecx, eax mov dx,ds:[?VIOCRT] mov ah,ch mov al,0Eh out dx,ax inc al mov ah,cl out dx,ax pop ds popad ret set_cursor endp ;--- scroll screen up one line ;--- ebp = linear address start of last line scroll_screen proc CLD push esi mov edi,ebp movzx eax,word ptr ds:[?VIOCOLS] push eax MOV CL, ds:[?VIOROWS] lea esi, [edi+2*eax] mul cl mov ecx,eax rep movsw pop ecx mov ax,0720h rep stosw pop esi ret scroll_screen endp ;--- interprets 10 (line feed) WriteChr proc push ds push es pushad push SEL_FLATDS pop ds push ds pop es MOV edi,0B8000h CMP BYTE ptr ds:[?VIOCRT],0B4h JNZ @F XOR DI,DI @@: movzx ebx, WORD PTR ds:[?VIOPBEG] ;page start ADD edi, ebx MOVZX ebx, BYTE PTR ds:[?VIOPG] mov ebp, edi MOVZX ecx, BYTE PTR ds:[ebx*2+?VIOCSR+1] ;ROW MOVZX eax, WORD PTR ds:[?VIOCOLS] MUL ecx MOVZX edx, BYTE PTR ds:[ebx*2+?VIOCSR+0] ;COL ADD eax, edx MOV DH,CL LEA edi, [edi+eax*2] MOV AL, [esp+1Ch] CMP AL, 13 JZ skipchar CMP AL, 10 JZ newline MOV [edi], AL MOV byte ptr [edi+1], 07 INC DL CMP DL, BYTE PTR ds:[?VIOCOLS] JB @F newline: MOV DL, 00 INC DH CMP DH, BYTE PTR ds:[?VIOROWS] JBE @F DEC DH CALL scroll_screen @@: MOV ds:[ebx*2+?VIOCSR],DX skipchar: popad pop es pop ds RET WriteChr endp else WriteChr proc push ebx @call16 int4116 pop ebx ret WriteChr endp endif WriteStrng proc cld @@: lodsb and al,al jz @F mov dl,al xor ax,ax int 41h jmp @B @@: ret WriteStrng endp int41 proc cmp ax,0 jnz @F mov al,dl call WriteChr iretd @@: cmp ax,2 jnz @F call WriteStrng @@: iretd int41 endp WriteDW: push eax shr eax,16 call WriteW pop eax WriteW: push eax shr eax,8 call WriteB pop eax WriteB: ;write Byte in al push eax shr eax,4 call WriteNb pop eax WriteNb: and al,0Fh add al,'0' cmp al,'9' jbe @F add al,7 @@: mov dl,al xor ax,ax int 41h ret ;--- default exception handler ;--- define string in _DATA, not CONST CStr32 macro text:vararg local sym _DATA segment sym db text,0 _DATA ends exitm <offset sym> endm exception: excno = 0 repeat 32 push excno jmp @F excno = excno+1 endm @@: ;--- did we get here via a task gate? mov eax,cr0 btr eax,3 ; TS flag mov cr0,eax ; reset TS before switching back to RM/VM86 setc ch ; but remember if it was the case! push SEL_DATA16 pop ds xor esi,esi mov si, CStr32(lf,"Exception ") mov ax,2 int 41h pop eax .if ch ;--- now reorder the stack if indeed we did come from a task gate pop ebx ; save errcode... push ds:[maintss.TSS_EFL] push ds:[maintss.TSS_CS] push ds:[maintss.TSS_EIP] push ebx .endif push eax call WriteB if 1 mov si, CStr32(" base=") mov ax,2 int 41h mov eax, _TEXT32 shl eax,4 call WriteDW endif mov si, CStr32(" errcode=") mov ax,2 int 41h mov eax,[esp+4] call WriteDW mov si, CStr32(" cs:eip=") mov ax,2 int 41h mov ax,[esp+12] call WriteW mov dl,':' xor ax,ax int 41h mov eax,[esp+8] call WriteDW if 0 mov si, CStr32(" edi=") mov ax,2 int 41h mov eax, edi call WriteDW endif if 1 cmp byte ptr [esp],0Eh jnz @F mov si, CStr32(" cr2=") mov ax,2 int 41h mov eax,cr2 call WriteDW @@: endif if 1 cmp byte ptr [esp],0Ah jnz @F ; TSS error test ch,ch jnz @F ; or task-switched mov si, CStr32(" esp=") mov ax,2 int 41h lea eax,[esp+16] call WriteDW mov si, CStr32(" [esp]=") mov ax,2 int 41h mov eax,[esp+16] call WriteDW mov al,' ' call WriteChr mov eax,[esp+20] call WriteDW mov al,' ' call WriteChr mov eax,[esp+24] call WriteDW mov al,' ' call WriteChr mov eax,[esp+28] call WriteDW @@: endif mov dl,lf xor ax,ax int 41h .if ch ;--- clear NT before we die, if we came from a task gate pushf btr word ptr [esp],14 popf .endif mov ax,4cffh int 21h align 4 ;--- clock and keyboard interrupts clock: ife ?IRQ0TORM push ds push SEL_FLATDS pop ds inc dword ptr ds:[46Ch] pop ds else ;--- route irq 0 (clock) to real-mode @jmp16 clock16 endif Irq0007: push eax Irq0007_1: mov al,20h out 20h,al pop eax swint: iretd Irq080F: push eax mov al,20h out 0A0h,al jmp Irq0007_1 keyboard: ife ?IRQ1TORM push eax in al,60h pop eax jmp Irq0007 else ;--- route irq 1 (kbd) to real-mode @jmp16 keyboard16 endif align 4 ;--- simple int 21h handler. ;--- handles ah=4Ch ;--- any other DOS function is transfered to real-mode int21 proc cmp ah,4Ch jz int21_4c and byte ptr [esp+2*4],0FEh ;clear carry flag sub esp,14h pushad xor ecx,ecx mov [esp].RMCS.rFlags, 0202h mov dword ptr [esp].RMCS.rES,ecx mov dword ptr [esp].RMCS.rFS,ecx mov [esp].RMCS.rSSSP, ecx mov edi,esp mov bx,21h mov ax,0300h int 31h jc int21_carry mov al,byte ptr [esp].RMCS.rFlags mov byte ptr [esp+34h+2*4],al ;set CF,ZF,... jmp @F int21_carry: or byte ptr [esp+34h+2*4],1 ;set carry flag @@: popad lea esp,[esp+14h] iretd int21_4c: @jmp16 backtoreal int21 endp int31 proc and byte ptr [esp+2*4],0FEh ;clear carry flag cmp ax,0300h ;simulate real-mode interrupt? jz int31_300 if ?I31301 cmp ax,0301h ;call real-mode far proc with RETF frame? jz int31_301 endif cmp ax,0202h ;get exception vector? jz int31_202 cmp ax,0203h ;set exception vector? jz int31_203 cmp ax,0204h ;get interrupt vector? jz int31_204 cmp ax,0205h ;set interrupt vector? jz int31_205 if ?I31504 cmp ax,0504h ;allocate uncommitted memory jz int31_504 endif if ?I31518 cmp ax,0518h ;allocate uncommitted memory jz int31_518 endif cmp ax,0A00h ;vendor specifc API jz int31_a00 ret_with_carry: or byte ptr [esp+2*4],1 ;set carry flag iretd align 4 int31_300: int31_301: pushad push ds push es push fs push gs mov esi,edi al_i3130x textequ <byte ptr [esp+11*4]> mov ax,SEL_DATA16 mov es,ax assume es:DGROUP ;--- the contents of the RMCS has to be copied ;--- to conventional memory. We use the DGROUP stack movzx ebx,bl if ?I31301 mov eax,[esi].RMCS.rCSIP cmp al_i3130x,0 jnz @F endif mov eax,[ebx*4 + ?PG0ADDR] @@: mov bx,[wStkBot] sub bx,34h mov edi,ebx mov [dwESP],esp cli cld movsd ;copy 2Ah bytes (8 * std regs,flags,es,ds,fs,gs) movsd movsd movsd movsd movsd movsd movsd movsd movsd movsw add esi,4 ;skip CS:IP in source RMCS stosd ;save CS:IP lodsd ;load SS:SP and eax,eax ;is a real-mode stack set? jnz @F mov eax,dword ptr [wStkBot] ;if no, use the default stack @@: stosd mov ax,SEL_DATA16 mov ss,eax mov esp,ebx ;clear highword ESP, ESP is used inside call_rmode assume es:nothing @jmp16 call_rmode int31_203: cmp bl,20h jae ret_with_carry int31_205: push eax if ?I31SETTG .if bl==8 push ds push SEL_DATA16 pop ds assume ds:DGROUP mov [dflttss.TSS_EIP],edx mov word ptr [dflttss.TSS_CS],cx ;--- handler may IRET with NT, in which case we need the right PDBR in main TSS mov eax,cr3 mov [maintss.TSS_CR3],eax pop ds assume ds:nothing .else endif push edi movzx edi,bl lea edi,[edi*8+?IDTADDR] mov eax,edx cld stosw ;lowword offset mov ax,cx stosw ;CS if ?I31SETTG add edi,2 else ;--- use these two lines to ensure #DF becomes an interrupt gate, if so desired mov ax,8E00h stosw endif shr eax,16 stosw ;hiword offset pop edi if ?I31SETTG .endif endif pop eax iretd int31_202: ;get exception vector BL in CX:EDX cmp bl,20h jae ret_with_carry int31_204: ;get interrupt vector BL in CX:EDX if ?I31SETTG .if bl==8 push ds push SEL_DATA16 pop ds assume ds:DGROUP mov edx,[dflttss.TSS_EIP] mov ecx,[dflttss.TSS_CS] pop ds assume ds:nothing .else endif movzx ecx,bl lea ecx,[ecx*8+?IDTADDR] mov dx,[ecx+6] shl edx,16 mov dx,[ecx+0] mov cx,[ecx+2] if ?I31SETTG .endif endif iretd if ?I31504 int31_504: ;--- create a RMCS onto stack sub esp,2 ;adjustment to make stack dword aligned push 0 pushw DGROUP pushw offset int31_50416 push 0 push 0 pushw 3202h pushad push edi lea edi,[esp+4] mov ax,301h int 31h pop edi jc @F test [esp].RMCS.rFlags,1 jnz @F mov ebx,[esp].RMCS.rEBX mov esi,[esp].RMCS.rESI add esp,34h iretd @@: add esp,34h jmp ret_with_carry endif if ?I31518 int31_518: ;--- create a RMCS onto stack sub esp,2 ;adjustment to make stack dword aligned push 0 pushw DGROUP pushw offset int31_51816 push 0 push 0 pushw 3202h pushad push edi lea edi,[esp+4] mov ax,301h int 31h pop edi jc @F test [esp].RMCS.rFlags,1 jnz @F add esp,34h iretd @@: add esp,34h jmp ret_with_carry endif int31_a00: @jmp16 int31_a0016 int31 endp _TEXT32 ends end start16
// 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 "sandbox/src/service_resolver.h" #include "base/memory/scoped_ptr.h" #include "sandbox/src/sandbox_utils.h" #include "sandbox/src/win_utils.h" namespace { #pragma pack(push, 1) const BYTE kMovEax = 0xB8; const BYTE kMovEdx = 0xBA; const USHORT kCallPtrEdx = 0x12FF; const USHORT kCallEdx = 0xD2FF; const BYTE kRet = 0xC2; const BYTE kNop = 0x90; const USHORT kJmpEdx = 0xE2FF; const USHORT kXorEcx = 0xC933; const ULONG kLeaEdx = 0x0424548D; const ULONG kCallFs1 = 0xC015FF64; const USHORT kCallFs2 = 0; const BYTE kCallFs3 = 0; const BYTE kAddEsp1 = 0x83; const USHORT kAddEsp2 = 0x4C4; const BYTE kJmp32 = 0xE9; const int kMaxService = 1000; // Service code for 32 bit systems. // NOTE: on win2003 "call dword ptr [edx]" is "call edx". struct ServiceEntry { // this struct contains roughly the following code: // 00 mov eax,25h // 05 mov edx,offset SharedUserData!SystemCallStub (7ffe0300) // 0a call dword ptr [edx] // 0c ret 2Ch // 0f nop BYTE mov_eax; // = B8 ULONG service_id; BYTE mov_edx; // = BA ULONG stub; USHORT call_ptr_edx; // = FF 12 BYTE ret; // = C2 USHORT num_params; BYTE nop; ULONG pad1; // Extend the structure to be the same size as the ULONG pad2; // 64 version (Wow64Entry) }; // Service code for a 32 bit process running on a 64 bit os. struct Wow64Entry { // This struct may contain one of two versions of code: // 1. For XP, Vista and 2K3: // 00 b852000000 mov eax, 25h // 05 33c9 xor ecx, ecx // 07 8d542404 lea edx, [esp + 4] // 0b 64ff15c0000000 call dword ptr fs:[0C0h] // 12 c22c00 ret 2Ch // // 2. For Windows 7: // 00 b852000000 mov eax, 25h // 05 33c9 xor ecx, ecx // 07 8d542404 lea edx, [esp + 4] // 0b 64ff15c0000000 call dword ptr fs:[0C0h] // 12 83c404 add esp, 4 // 15 c22c00 ret 2Ch // // So we base the structure on the bigger one: BYTE mov_eax; // = B8 ULONG service_id; USHORT xor_ecx; // = 33 C9 ULONG lea_edx; // = 8D 54 24 04 ULONG call_fs1; // = 64 FF 15 C0 USHORT call_fs2; // = 00 00 BYTE call_fs3; // = 00 BYTE add_esp1; // = 83 or ret USHORT add_esp2; // = C4 04 or num_params BYTE ret; // = C2 USHORT num_params; }; // Make sure that relaxed patching works as expected. COMPILE_ASSERT(sizeof(ServiceEntry) == sizeof(Wow64Entry), wrong_service_len); struct ServiceFullThunk { union { ServiceEntry original; Wow64Entry wow_64; }; int internal_thunk; // Dummy member to the beginning of the internal thunk. }; #pragma pack(pop) }; // namespace namespace sandbox { NTSTATUS ServiceResolverThunk::Setup(const void* target_module, const void* interceptor_module, const char* target_name, const char* interceptor_name, const void* interceptor_entry_point, void* thunk_storage, size_t storage_bytes, size_t* storage_used) { NTSTATUS ret = Init(target_module, interceptor_module, target_name, interceptor_name, interceptor_entry_point, thunk_storage, storage_bytes); if (!NT_SUCCESS(ret)) return ret; relative_jump_ = 0; size_t thunk_bytes = GetThunkSize(); scoped_array<char> thunk_buffer(new char[thunk_bytes]); ServiceFullThunk* thunk = reinterpret_cast<ServiceFullThunk*>( thunk_buffer.get()); if (!IsFunctionAService(&thunk->original) && (!relaxed_ || !SaveOriginalFunction(&thunk->original, thunk_storage))) return STATUS_UNSUCCESSFUL; ret = PerformPatch(thunk, thunk_storage); if (NULL != storage_used) *storage_used = thunk_bytes; return ret; } size_t ServiceResolverThunk::GetThunkSize() const { return offsetof(ServiceFullThunk, internal_thunk) + GetInternalThunkSize(); } bool ServiceResolverThunk::IsFunctionAService(void* local_thunk) const { ServiceEntry function_code; SIZE_T read; if (!::ReadProcessMemory(process_, target_, &function_code, sizeof(function_code), &read)) return false; if (sizeof(function_code) != read) return false; if (kMovEax != function_code.mov_eax || kMovEdx != function_code.mov_edx || (kCallPtrEdx != function_code.call_ptr_edx && kCallEdx != function_code.call_ptr_edx) || kRet != function_code.ret) return false; // Find the system call pointer if we don't already have it. if (kCallEdx != function_code.call_ptr_edx) { DWORD ki_system_call; if (!::ReadProcessMemory(process_, bit_cast<const void*>(function_code.stub), &ki_system_call, sizeof(ki_system_call), &read)) return false; if (sizeof(ki_system_call) != read) return false; HMODULE module_1, module_2; // last check, call_stub should point to a KiXXSystemCall function on ntdll if (!GetModuleHandleHelper(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, bit_cast<const wchar_t*>(ki_system_call), &module_1)) return false; if (NULL != ntdll_base_) { // This path is only taken when running the unit tests. We want to be // able to patch a buffer in memory, so target_ is not inside ntdll. module_2 = ntdll_base_; } else { if (!GetModuleHandleHelper( GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, reinterpret_cast<const wchar_t*>(target_), &module_2)) { return false; } } if (module_1 != module_2) return false; } // Save the verified code memcpy(local_thunk, &function_code, sizeof(function_code)); return true; } NTSTATUS ServiceResolverThunk::PerformPatch(void* local_thunk, void* remote_thunk) { ServiceEntry intercepted_code; size_t bytes_to_write = sizeof(intercepted_code); ServiceFullThunk *full_local_thunk = reinterpret_cast<ServiceFullThunk*>( local_thunk); ServiceFullThunk *full_remote_thunk = reinterpret_cast<ServiceFullThunk*>( remote_thunk); // patch the original code memcpy(&intercepted_code, &full_local_thunk->original, sizeof(intercepted_code)); intercepted_code.mov_eax = kMovEax; intercepted_code.service_id = full_local_thunk->original.service_id; intercepted_code.mov_edx = kMovEdx; intercepted_code.stub = bit_cast<ULONG>(&full_remote_thunk->internal_thunk); intercepted_code.call_ptr_edx = kJmpEdx; if (!win2k_) { intercepted_code.ret = kRet; intercepted_code.num_params = full_local_thunk->original.num_params; intercepted_code.nop = kNop; } else { bytes_to_write = offsetof(ServiceEntry, ret); } if (relative_jump_) { intercepted_code.mov_eax = kJmp32; intercepted_code.service_id = relative_jump_; bytes_to_write = offsetof(ServiceEntry, mov_edx); } // setup the thunk SetInternalThunk(&full_local_thunk->internal_thunk, GetInternalThunkSize(), remote_thunk, interceptor_); size_t thunk_size = GetThunkSize(); // copy the local thunk buffer to the child SIZE_T written; if (!::WriteProcessMemory(process_, remote_thunk, local_thunk, thunk_size, &written)) return STATUS_UNSUCCESSFUL; if (thunk_size != written) return STATUS_UNSUCCESSFUL; // and now change the function to intercept, on the child if (NULL != ntdll_base_) { // running a unit test if (!::WriteProcessMemory(process_, target_, &intercepted_code, bytes_to_write, &written)) return STATUS_UNSUCCESSFUL; } else { if (!WriteProtectedChildMemory(process_, target_, &intercepted_code, bytes_to_write)) return STATUS_UNSUCCESSFUL; } return STATUS_SUCCESS; } bool ServiceResolverThunk::SaveOriginalFunction(void* local_thunk, void* remote_thunk) { ServiceEntry function_code; SIZE_T read; if (!::ReadProcessMemory(process_, target_, &function_code, sizeof(function_code), &read)) return false; if (sizeof(function_code) != read) return false; if (kJmp32 == function_code.mov_eax) { // Plain old entry point patch. The relative jump address follows it. ULONG relative = function_code.service_id; // First, fix our copy of their patch. relative += bit_cast<ULONG>(target_) - bit_cast<ULONG>(remote_thunk); function_code.service_id = relative; // And now, remember how to re-patch it. ServiceFullThunk *full_thunk = reinterpret_cast<ServiceFullThunk*>(remote_thunk); const ULONG kJmp32Size = 5; relative_jump_ = bit_cast<ULONG>(&full_thunk->internal_thunk) - bit_cast<ULONG>(target_) - kJmp32Size; } // Save the verified code memcpy(local_thunk, &function_code, sizeof(function_code)); return true; } bool Wow64ResolverThunk::IsFunctionAService(void* local_thunk) const { Wow64Entry function_code; SIZE_T read; if (!::ReadProcessMemory(process_, target_, &function_code, sizeof(function_code), &read)) return false; if (sizeof(function_code) != read) return false; if (kMovEax != function_code.mov_eax || kXorEcx != function_code.xor_ecx || kLeaEdx != function_code.lea_edx || kCallFs1 != function_code.call_fs1 || kCallFs2 != function_code.call_fs2 || kCallFs3 != function_code.call_fs3) return false; if ((kAddEsp1 == function_code.add_esp1 && kAddEsp2 == function_code.add_esp2 && kRet == function_code.ret) || kRet == function_code.add_esp1) { // Save the verified code memcpy(local_thunk, &function_code, sizeof(function_code)); return true; } return false; } bool Win2kResolverThunk::IsFunctionAService(void* local_thunk) const { ServiceEntry function_code; SIZE_T read; if (!::ReadProcessMemory(process_, target_, &function_code, sizeof(function_code), &read)) return false; if (sizeof(function_code) != read) return false; if (kMovEax != function_code.mov_eax || function_code.service_id > kMaxService) return false; // Save the verified code memcpy(local_thunk, &function_code, sizeof(function_code)); return true; } } // namespace sandbox
code32 format ELF public _getSign1 public _getSign2 public _getSign3 public _isNotNegative public _areSignsOpposite public _signExtendFromWidth public _conditionalClearOrSet public _swapBits public _hasZeroByte public _parity public _getSign164 public _getSign264 public _getSign364 public _isNotNegative64 public _areSignsOpposite64 public _signExtendFromWidth64 public _conditionalClearOrSet64 public _swapBits64 public _hasZeroByte64 public _parity64 section '.text' executable align 16 _getSign1: asr r0, #31 bx lr _getSign2: asr r0, #31 orr r0, #1 bx lr _getSign3: lsr r3, r0, #31 cmp r0, #0 rsble r0, r3, #0 rsbgt r0, r3, #1 bx lr _isNotNegative: mvn r0, r0 lsr r0, #31 bx lr _areSignsOpposite: eor r0, r1 lsr r0, #31 bx lr _signExtendFromWidth: sub r3, r1, #1 mov r2, #1 lsl r2, r3 mvn r3, #0 bic r0, r3, lsl r1 eor r0, r2 sub r0, r2 bx lr _conditionalClearOrSet: rsb r2, #0 eor r2, r0 and r2, r3 eor r0, r2 bx lr _swapBits: str lr, [sp, #-4] lsr ip, r3, r1 eor ip, r3, lsr r0 mvn lr, #0 bic r2, ip, lr, lsl r2 lsl r1, r2, r1 orr r0, r1, r2, lsl r0 eor r0, r3 ldr pc, [sp], #4 _hasZeroByte: ands r3, r0, #255 beq .ret0 lsr r3, r0, #8 ands r3, #255 beq .ret0 lsr r3, r0, #16 and r3, #255 beq .ret0 lsrs r3, r0, #24 movne r0, #1 moveq r0, #0 bx lr .ret0: mov r0, r3 bx lr _parity: eor r0, r0, lsr #16 eor r0, r0, lsr #8 eor r0, r0, lsr #4 and r0, #0xF mov r3, #0x6900 add r3, #0x96 asr r0, r3, r0 and r0, #1 bx lr _getSign164: asr r0, r1, #31 bx lr _getSign264: asr r1, #31 orr r0, r1, #1 bx lr _getSign364: mov r2, r1 cmp r0, #1 sbcs r3, r2, #0 movge r0, #1 movlt r0, #0 sub r0, r2, lsr #31 bx lr _isNotNegative64: mvn r0, r1 lsr r0, #31 bx lr _areSignsOpposite64: eor r3, r1 lsr r0, r3, #31 bx lr _signExtendFromWidth64: push {r4, r5, r6, lr} sub ip, r2, #1 mov r3, #1 sub r6, r2, #33 rsb r5, ip, #32 lsl lr, r3, r6 orr lr, r3, lsr r5 lsl r4, r3, ip mvn ip, #0 sub r6, r2, #32 rsb r5, r2, #32 lsl r3, ip, r2 orr r3, ip, lsl r6 orr r3, ip, lsr r5 bic ip, r0, ip, lsl r2 bic r3, r1, r3 eor r0, ip, r4 eor r1, r3, lr subs r0, r4 sbc r1, lr pop {r4, r5, r6, pc} _conditionalClearOrSet64: push {r4, r5, lr} ldrb ip, [sp, #12] rsb ip, #0 mov r4, ip asr r5, ip, #31 eor ip, r0 eor lr, r5, r1 and ip, r2 and r3, lr eor r0, ip eor r1, r3 pop {r4, r5, pc} _swapBits64: push {r4, r5, r6, r7, r8, r9, r10, fp, lr} sub sp, #12 add r5, sp, #48 ldm r5, {r5, ip} rsb r8, r0, #32 sub r9, r0, #32 lsr lr, r5, r0 orr lr, ip, lsl r8 orr lr, ip, lsr r9 rsb r6, r1, #32 sub r7, r1, #32 lsr r3, r5, r1 orr r3, ip, lsl r6 orr r3, ip, lsr r7 lsr r4, ip, r1 eor lr, r3 eor r3, r4, ip, lsr r0 str r3, [sp, #4] mvn r3, #0 sub fp, r2, #32 rsb r10, r2, #32 lsr r4, r3, r2 orr r4, r3, lsl fp orr r4, r3, lsr r10 bic r3, lr, r3, lsl r2 ldr r2, [sp, #4] bic r4, r2, r4 lsl r2, r4, r0 orr r2, r3, lsl r9 orr r2, r3, lsr r8 lsl r4, r1 orr r4, r3, lsl r7 orr r4, r3, lsr r6 lsl r1, r3, r1 orr r0, r1, r3, lsl r0 orr r4, r2, r4 eor r0, r5 eor r1, r4, ip add sp, #12 pop {r4, r5, r6, r7, r8, r9, r10, fp, pc} _hasZeroByte64: ands r3, r0, #255 beq .ret0 lsr r3, r0, #8 ands r3, #255 beq .ret0 lsr r3, r0, #16 ands r3, #255 beq .ret0 lsrs r0, #24 bxeq lr ands r0, r1, #255 bxeq lr lsr r0, r1, #8 ands r0, #255 bxeq lr lsr r3, r1, #8 ands r0, r3, #255 bxeq lr lsrs r3, r1, #24 movne r0, #1 moveq r0, #0 bx lr .ret0: mov r0, r3 bx lr _parity64: eor r0, r1 eor r0, r0, lsr #16 eor r0, r0, lsr #8 eor r0, r0, lsr #4 and r0, #0xF mov r3, #0x6900 add r3, #0x96 asr r0, r3, r0 and r0, #1 bx lr
; A007420: Berstel sequence: a(n+1) = 2*a(n) - 4*a(n-1) + 4*a(n-2). ; Submitted by Jamie Morken(s4) ; 0,0,1,2,0,-4,0,16,16,-32,-64,64,256,0,-768,-512,2048,3072,-4096,-12288,4096,40960,16384,-114688,-131072,262144,589824,-393216,-2097152,-262144,6291456,5242880,-15728640,-27262976,29360128,104857600,-16777216,-335544320,-184549376,905969664,1207959552,-1946157056,-5100273664,2415919104,17448304640,4831838208,-50465865728,-50465865728,120259084288,240518168576,-201863462912,-884763262976,0,2731599200256,1924145348608,-7078106103808,-10926396801024,14156212207616,43705587204096,-12919261626368 lpb $0 sub $0,1 add $3,1 add $2,$3 add $2,$1 add $3,12 sub $3,$2 add $1,$3 mul $1,2 sub $2,1 mul $3,2 add $3,$2 lpe mov $0,$2 div $0,48
; A151712: a(n) = A048883(n) + 1. ; 2,4,4,10,4,10,10,28,4,10,10,28,10,28,28,82,4,10,10,28,10,28,28,82,10,28,28,82,28,82,82,244,4,10,10,28,10,28,28,82,10,28,28,82,28,82,82,244,10,28,28,82,28,82,82,244,28,82,82,244,82,244,244,730,4,10,10,28,10,28,28 mov $3,1 lpb $3 mov $1,$0 mov $2,$0 sub $3,1 mov $4,1 mul $4,$0 lpb $2 lpb $1 div $4,2 sub $1,$4 lpe mov $0,$1 sub $2,1 lpe mov $1,3 pow $1,$0 lpe div $1,2 mul $1,2 add $1,2
/* * Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved. * Copyright (C) 2008 Collabora Ltd. All rights reserved. * Copyright (C) 2010 Girish Ramakrishnan <girish@forwardbias.in> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "PluginView.h" #if USE(JSC) #include "BridgeJSC.h" #endif #include "Chrome.h" #include "CookieJar.h" #include "Document.h" #include "DocumentLoader.h" #include "Element.h" #include "FocusController.h" #include "Frame.h" #include "FrameLoader.h" #include "FrameLoaderClient.h" #include "FrameTree.h" #include "FrameView.h" #include "GraphicsContext.h" #include "HTMLNames.h" #include "HTMLPlugInElement.h" #include "Image.h" #include "KeyboardEvent.h" #include "MIMETypeRegistry.h" #include "MouseEvent.h" #include "NotImplemented.h" #include "Page.h" #include "PlatformMouseEvent.h" #include "PluginDatabase.h" #include "PluginDebug.h" #include "PluginMainThreadScheduler.h" #include "PluginPackage.h" #include "ProxyServer.h" #include "RenderBox.h" #include "RenderObject.h" #include "ScriptController.h" #include "ScriptValue.h" #include "SecurityOrigin.h" #include "Settings.h" #include "npruntime_impl.h" #include <wtf/ASCIICType.h> #if OS(WINDOWS) && ENABLE(NETSCAPE_PLUGIN_API) #include "PluginMessageThrottlerWin.h" #endif #if defined(ANDROID_PLUGINS) #include "TouchEvent.h" #endif #if USE(JSC) #include "JSDOMBinding.h" #include "JSDOMWindow.h" #include "c_instance.h" #include "runtime_root.h" #include <runtime/JSLock.h> #include <runtime/JSValue.h> using JSC::ExecState; using JSC::JSLock; using JSC::JSObject; using JSC::JSValue; using JSC::UString; #endif #if ENABLE(NETSCAPE_PLUGIN_API) using std::min; using namespace WTF; namespace WebCore { using namespace HTMLNames; static int s_callingPlugin; typedef HashMap<NPP, PluginView*> InstanceMap; static InstanceMap& instanceMap() { static InstanceMap& map = *new InstanceMap; return map; } static String scriptStringIfJavaScriptURL(const KURL& url) { if (!protocolIsJavaScript(url)) return String(); // This returns an unescaped string return decodeURLEscapeSequences(url.string().substring(11)); } PluginView* PluginView::s_currentPluginView = 0; void PluginView::popPopupsStateTimerFired(Timer<PluginView>*) { popPopupsEnabledState(); } IntRect PluginView::windowClipRect() const { // Start by clipping to our bounds. IntRect clipRect(m_windowRect); // Take our element and get the clip rect from the enclosing layer and frame view. RenderLayer* layer = m_element->renderer()->enclosingLayer(); FrameView* parentView = m_element->document()->view(); clipRect.intersect(parentView->windowClipRectForLayer(layer, true)); return clipRect; } void PluginView::setFrameRect(const IntRect& rect) { if (m_element->document()->printing()) return; if (rect != frameRect()) Widget::setFrameRect(rect); updatePluginWidget(); #if OS(WINDOWS) || OS(SYMBIAN) // On Windows and Symbian, always call plugin to change geometry. setNPWindowRect(rect); #elif defined(XP_UNIX) // On Unix, multiple calls to setNPWindow() in windowed mode causes Flash to crash if (m_mode == NP_FULL || !m_isWindowed) setNPWindowRect(rect); #endif } void PluginView::frameRectsChanged() { updatePluginWidget(); } void PluginView::handleEvent(Event* event) { if (!m_plugin || m_isWindowed) return; // Protect the plug-in from deletion while dispatching the event. RefPtr<PluginView> protect(this); if (event->isMouseEvent()) handleMouseEvent(static_cast<MouseEvent*>(event)); else if (event->isKeyboardEvent()) handleKeyboardEvent(static_cast<KeyboardEvent*>(event)); #if defined(ANDROID_PLUGINS) #if ENABLE(TOUCH_EVENTS) else if (event->isTouchEvent()) handleTouchEvent(static_cast<TouchEvent*>(event)); #endif else if (event->type() == eventNames().DOMFocusOutEvent) handleFocusEvent(false); else if (event->type() == eventNames().DOMFocusInEvent) handleFocusEvent(true); #endif #if defined(XP_UNIX) && ENABLE(NETSCAPE_PLUGIN_API) else if (event->type() == eventNames().focusoutEvent) handleFocusOutEvent(); else if (event->type() == eventNames().focusinEvent) handleFocusInEvent(); #endif } void PluginView::init() { if (m_haveInitialized) return; m_haveInitialized = true; if (!m_plugin) { ASSERT(m_status == PluginStatusCanNotFindPlugin); return; } LOG(Plugins, "PluginView::init(): Initializing plug-in '%s'", m_plugin->name().utf8().data()); if (!m_plugin->load()) { m_plugin = 0; m_status = PluginStatusCanNotLoadPlugin; return; } if (!startOrAddToUnstartedList()) { m_status = PluginStatusCanNotLoadPlugin; return; } m_status = PluginStatusLoadedSuccessfully; } bool PluginView::startOrAddToUnstartedList() { if (!m_parentFrame->page()) return false; // We only delay starting the plug-in if we're going to kick off the load // ourselves. Otherwise, the loader will try to deliver data before we've // started the plug-in. if (!m_loadManually && !m_parentFrame->page()->canStartMedia()) { m_parentFrame->document()->addMediaCanStartListener(this); m_isWaitingToStart = true; return true; } return start(); } bool PluginView::start() { if (m_isStarted) return false; m_isWaitingToStart = false; PluginMainThreadScheduler::scheduler().registerPlugin(m_instance); ASSERT(m_plugin); ASSERT(m_plugin->pluginFuncs()->newp); NPError npErr; { PluginView::setCurrentPluginView(this); #if USE(JSC) JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly); #endif setCallingPlugin(true); npErr = m_plugin->pluginFuncs()->newp((NPMIMEType)m_mimeType.utf8().data(), m_instance, m_mode, m_paramCount, m_paramNames, m_paramValues, NULL); setCallingPlugin(false); LOG_NPERROR(npErr); PluginView::setCurrentPluginView(0); } if (npErr != NPERR_NO_ERROR) { m_status = PluginStatusCanNotLoadPlugin; PluginMainThreadScheduler::scheduler().unregisterPlugin(m_instance); return false; } m_isStarted = true; if (!m_url.isEmpty() && !m_loadManually) { FrameLoadRequest frameLoadRequest(m_parentFrame->document()->securityOrigin()); frameLoadRequest.resourceRequest().setHTTPMethod("GET"); frameLoadRequest.resourceRequest().setURL(m_url); #ifdef ANDROID_PLUGINS if (!SecurityOrigin::shouldHideReferrer( m_url, m_parentFrame->loader()->outgoingReferrer())) frameLoadRequest.resourceRequest().setHTTPReferrer( m_parentFrame->loader()->outgoingReferrer()); #endif load(frameLoadRequest, false, 0); } m_status = PluginStatusLoadedSuccessfully; if (!platformStart()) m_status = PluginStatusCanNotLoadPlugin; if (m_status != PluginStatusLoadedSuccessfully) return false; if (parentFrame()->page()) parentFrame()->page()->didStartPlugin(this); return true; } void PluginView::mediaCanStart() { ASSERT(!m_isStarted); if (!start()) parentFrame()->loader()->client()->dispatchDidFailToStartPlugin(this); } PluginView::~PluginView() { LOG(Plugins, "PluginView::~PluginView()"); ASSERT(!m_lifeSupportTimer.isActive()); // If we failed to find the plug-in, we'll return early in our constructor, and // m_instance will be 0. if (m_instance) instanceMap().remove(m_instance); if (m_isWaitingToStart) m_parentFrame->document()->removeMediaCanStartListener(this); stop(); deleteAllValues(m_requests); freeStringArray(m_paramNames, m_paramCount); freeStringArray(m_paramValues, m_paramCount); platformDestroy(); m_parentFrame->script()->cleanupScriptObjectsForPlugin(this); #if PLATFORM(ANDROID) // Since we have no legacy plugins to check, we ignore the quirks check. if (m_plugin) #else if (m_plugin && !(m_plugin->quirks().contains(PluginQuirkDontUnloadPlugin))) #endif m_plugin->unload(); } void PluginView::stop() { if (!m_isStarted) return; if (parentFrame()->page()) parentFrame()->page()->didStopPlugin(this); LOG(Plugins, "PluginView::stop(): Stopping plug-in '%s'", m_plugin->name().utf8().data()); HashSet<RefPtr<PluginStream> > streams = m_streams; HashSet<RefPtr<PluginStream> >::iterator end = streams.end(); for (HashSet<RefPtr<PluginStream> >::iterator it = streams.begin(); it != end; ++it) { (*it)->stop(); disconnectStream((*it).get()); } ASSERT(m_streams.isEmpty()); m_isStarted = false; #if USE(JSC) JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly); #endif #if ENABLE(NETSCAPE_PLUGIN_API) #if defined(XP_WIN) && !PLATFORM(GTK) // Unsubclass the window if (m_isWindowed) { #if OS(WINCE) WNDPROC currentWndProc = (WNDPROC)GetWindowLong(platformPluginWidget(), GWL_WNDPROC); if (currentWndProc == PluginViewWndProc) SetWindowLong(platformPluginWidget(), GWL_WNDPROC, (LONG)m_pluginWndProc); #else WNDPROC currentWndProc = (WNDPROC)GetWindowLongPtr(platformPluginWidget(), GWLP_WNDPROC); if (currentWndProc == PluginViewWndProc) SetWindowLongPtr(platformPluginWidget(), GWLP_WNDPROC, (LONG_PTR)m_pluginWndProc); #endif } #endif // !defined(XP_WIN) || PLATFORM(GTK) #endif // ENABLE(NETSCAPE_PLUGIN_API) #if !defined(XP_MACOSX) // Clear the window m_npWindow.window = 0; if (m_plugin->pluginFuncs()->setwindow && !m_plugin->quirks().contains(PluginQuirkDontSetNullWindowHandleOnDestroy)) { PluginView::setCurrentPluginView(this); setCallingPlugin(true); m_plugin->pluginFuncs()->setwindow(m_instance, &m_npWindow); setCallingPlugin(false); PluginView::setCurrentPluginView(0); } #ifdef XP_UNIX if (m_isWindowed && m_npWindow.ws_info) delete (NPSetWindowCallbackStruct *)m_npWindow.ws_info; m_npWindow.ws_info = 0; #endif #endif // !defined(XP_MACOSX) PluginMainThreadScheduler::scheduler().unregisterPlugin(m_instance); NPSavedData* savedData = 0; PluginView::setCurrentPluginView(this); setCallingPlugin(true); NPError npErr = m_plugin->pluginFuncs()->destroy(m_instance, &savedData); setCallingPlugin(false); LOG_NPERROR(npErr); PluginView::setCurrentPluginView(0); #if ENABLE(NETSCAPE_PLUGIN_API) if (savedData) { // TODO: Actually save this data instead of just discarding it if (savedData->buf) NPN_MemFree(savedData->buf); NPN_MemFree(savedData); } #endif m_instance->pdata = 0; } void PluginView::setCurrentPluginView(PluginView* pluginView) { s_currentPluginView = pluginView; } PluginView* PluginView::currentPluginView() { return s_currentPluginView; } static char* createUTF8String(const String& str) { CString cstr = str.utf8(); char* result = reinterpret_cast<char*>(fastMalloc(cstr.length() + 1)); strncpy(result, cstr.data(), cstr.length() + 1); return result; } void PluginView::performRequest(PluginRequest* request) { if (!m_isStarted) return; // don't let a plugin start any loads if it is no longer part of a document that is being // displayed unless the loads are in the same frame as the plugin. const String& targetFrameName = request->frameLoadRequest().frameName(); if (m_parentFrame->loader()->documentLoader() != m_parentFrame->loader()->activeDocumentLoader() && (targetFrameName.isNull() || m_parentFrame->tree()->find(targetFrameName) != m_parentFrame)) return; KURL requestURL = request->frameLoadRequest().resourceRequest().url(); String jsString = scriptStringIfJavaScriptURL(requestURL); if (jsString.isNull()) { // if this is not a targeted request, create a stream for it. otherwise, // just pass it off to the loader if (targetFrameName.isEmpty()) { RefPtr<PluginStream> stream = PluginStream::create(this, m_parentFrame.get(), request->frameLoadRequest().resourceRequest(), request->sendNotification(), request->notifyData(), plugin()->pluginFuncs(), instance(), m_plugin->quirks()); m_streams.add(stream); stream->start(); } else { // If the target frame is our frame, we could destroy the // PluginView, so we protect it. <rdar://problem/6991251> RefPtr<PluginView> protect(this); m_parentFrame->loader()->load(request->frameLoadRequest().resourceRequest(), targetFrameName, false); // FIXME: <rdar://problem/4807469> This should be sent when the document has finished loading if (request->sendNotification()) { PluginView::setCurrentPluginView(this); #if USE(JSC) JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly); #endif setCallingPlugin(true); m_plugin->pluginFuncs()->urlnotify(m_instance, requestURL.string().utf8().data(), NPRES_DONE, request->notifyData()); setCallingPlugin(false); PluginView::setCurrentPluginView(0); } } return; } // Targeted JavaScript requests are only allowed on the frame that contains the JavaScript plugin // and this has been made sure in ::load. ASSERT(targetFrameName.isEmpty() || m_parentFrame->tree()->find(targetFrameName) == m_parentFrame); // Executing a script can cause the plugin view to be destroyed, so we keep a reference to it. RefPtr<PluginView> protector(this); ScriptValue result = m_parentFrame->script()->executeScript(jsString, request->shouldAllowPopups()); if (targetFrameName.isNull()) { String resultString; #if USE(JSC) ScriptState* scriptState = m_parentFrame->script()->globalObject(pluginWorld())->globalExec(); #elif USE(V8) ScriptState* scriptState = 0; // Not used with V8 #endif CString cstr; if (result.getString(scriptState, resultString)) cstr = resultString.utf8(); RefPtr<PluginStream> stream = PluginStream::create(this, m_parentFrame.get(), request->frameLoadRequest().resourceRequest(), request->sendNotification(), request->notifyData(), plugin()->pluginFuncs(), instance(), m_plugin->quirks()); m_streams.add(stream); stream->sendJavaScriptStream(requestURL, cstr); } } void PluginView::requestTimerFired(Timer<PluginView>* timer) { ASSERT(timer == &m_requestTimer); ASSERT(m_requests.size() > 0); ASSERT(!m_isJavaScriptPaused); PluginRequest* request = m_requests[0]; m_requests.remove(0); // Schedule a new request before calling performRequest since the call to // performRequest can cause the plugin view to be deleted. if (m_requests.size() > 0) m_requestTimer.startOneShot(0); performRequest(request); delete request; } void PluginView::scheduleRequest(PluginRequest* request) { m_requests.append(request); if (!m_isJavaScriptPaused) m_requestTimer.startOneShot(0); } NPError PluginView::load(const FrameLoadRequest& frameLoadRequest, bool sendNotification, void* notifyData) { ASSERT(frameLoadRequest.resourceRequest().httpMethod() == "GET" || frameLoadRequest.resourceRequest().httpMethod() == "POST"); KURL url = frameLoadRequest.resourceRequest().url(); if (url.isEmpty()) return NPERR_INVALID_URL; // Don't allow requests to be made when the document loader is stopping all loaders. DocumentLoader* loader = m_parentFrame->loader()->documentLoader(); if (!loader || loader->isStopping()) return NPERR_GENERIC_ERROR; const String& targetFrameName = frameLoadRequest.frameName(); String jsString = scriptStringIfJavaScriptURL(url); if (!jsString.isNull()) { // Return NPERR_GENERIC_ERROR if JS is disabled. This is what Mozilla does. if (!m_parentFrame->script()->canExecuteScripts(NotAboutToExecuteScript)) return NPERR_GENERIC_ERROR; // For security reasons, only allow JS requests to be made on the frame that contains the plug-in. if (!targetFrameName.isNull() && m_parentFrame->tree()->find(targetFrameName) != m_parentFrame) return NPERR_INVALID_PARAM; } else if (!m_parentFrame->document()->securityOrigin()->canDisplay(url)) return NPERR_GENERIC_ERROR; PluginRequest* request = new PluginRequest(frameLoadRequest, sendNotification, notifyData, arePopupsAllowed()); scheduleRequest(request); return NPERR_NO_ERROR; } static KURL makeURL(const KURL& baseURL, const char* relativeURLString) { String urlString = relativeURLString; // Strip return characters. urlString.replace('\n', ""); urlString.replace('\r', ""); return KURL(baseURL, urlString); } NPError PluginView::getURLNotify(const char* url, const char* target, void* notifyData) { FrameLoadRequest frameLoadRequest(m_parentFrame->document()->securityOrigin()); frameLoadRequest.setFrameName(target); frameLoadRequest.resourceRequest().setHTTPMethod("GET"); frameLoadRequest.resourceRequest().setURL(makeURL(m_baseURL, url)); #ifdef ANDROID_PLUGINS if (!SecurityOrigin::shouldHideReferrer( frameLoadRequest.resourceRequest().url(), m_url)) frameLoadRequest.resourceRequest().setHTTPReferrer(m_url); #endif return load(frameLoadRequest, true, notifyData); } NPError PluginView::getURL(const char* url, const char* target) { FrameLoadRequest frameLoadRequest(m_parentFrame->document()->securityOrigin()); frameLoadRequest.setFrameName(target); frameLoadRequest.resourceRequest().setHTTPMethod("GET"); frameLoadRequest.resourceRequest().setURL(makeURL(m_baseURL, url)); #ifdef ANDROID_PLUGINS if (!SecurityOrigin::shouldHideReferrer( frameLoadRequest.resourceRequest().url(), m_url)) frameLoadRequest.resourceRequest().setHTTPReferrer(m_url); #endif return load(frameLoadRequest, false, 0); } NPError PluginView::postURLNotify(const char* url, const char* target, uint32_t len, const char* buf, NPBool file, void* notifyData) { return handlePost(url, target, len, buf, file, notifyData, true, true); } NPError PluginView::postURL(const char* url, const char* target, uint32_t len, const char* buf, NPBool file) { // As documented, only allow headers to be specified via NPP_PostURL when using a file. return handlePost(url, target, len, buf, file, 0, false, file); } NPError PluginView::newStream(NPMIMEType type, const char* target, NPStream** stream) { notImplemented(); // Unsupported return NPERR_GENERIC_ERROR; } int32_t PluginView::write(NPStream* stream, int32_t len, void* buffer) { notImplemented(); // Unsupported return -1; } NPError PluginView::destroyStream(NPStream* stream, NPReason reason) { if (!stream || PluginStream::ownerForStream(stream) != m_instance) return NPERR_INVALID_INSTANCE_ERROR; PluginStream* browserStream = static_cast<PluginStream*>(stream->ndata); browserStream->cancelAndDestroyStream(reason); return NPERR_NO_ERROR; } void PluginView::status(const char* message) { if (Page* page = m_parentFrame->page()) page->chrome()->setStatusbarText(m_parentFrame.get(), String::fromUTF8(message)); } NPError PluginView::setValue(NPPVariable variable, void* value) { LOG(Plugins, "PluginView::setValue(%s): ", prettyNameForNPPVariable(variable, value).data()); switch (variable) { case NPPVpluginWindowBool: m_isWindowed = value; return NPERR_NO_ERROR; case NPPVpluginTransparentBool: m_isTransparent = value; return NPERR_NO_ERROR; #if defined(XP_MACOSX) case NPPVpluginDrawingModel: { // Can only set drawing model inside NPP_New() if (this != currentPluginView()) return NPERR_GENERIC_ERROR; NPDrawingModel newDrawingModel = NPDrawingModel(uintptr_t(value)); switch (newDrawingModel) { case NPDrawingModelCoreGraphics: m_drawingModel = newDrawingModel; return NPERR_NO_ERROR; #ifndef NP_NO_QUICKDRAW case NPDrawingModelQuickDraw: #endif case NPDrawingModelCoreAnimation: default: LOG(Plugins, "Plugin asked for unsupported drawing model: %s", prettyNameForDrawingModel(newDrawingModel)); return NPERR_GENERIC_ERROR; } } case NPPVpluginEventModel: { // Can only set event model inside NPP_New() if (this != currentPluginView()) return NPERR_GENERIC_ERROR; NPEventModel newEventModel = NPEventModel(uintptr_t(value)); switch (newEventModel) { #ifndef NP_NO_CARBON case NPEventModelCarbon: #endif case NPEventModelCocoa: m_eventModel = newEventModel; return NPERR_NO_ERROR; default: LOG(Plugins, "Plugin asked for unsupported event model: %s", prettyNameForEventModel(newEventModel)); return NPERR_GENERIC_ERROR; } } #endif // defined(XP_MACOSX) #if PLATFORM(QT) && defined(MOZ_PLATFORM_MAEMO) && (MOZ_PLATFORM_MAEMO >= 5) case NPPVpluginWindowlessLocalBool: m_renderToImage = true; return NPERR_NO_ERROR; #endif default: #ifdef PLUGIN_PLATFORM_SETVALUE return platformSetValue(variable, value); #else notImplemented(); return NPERR_GENERIC_ERROR; #endif } } void PluginView::invalidateTimerFired(Timer<PluginView>* timer) { ASSERT(timer == &m_invalidateTimer); for (unsigned i = 0; i < m_invalidRects.size(); i++) invalidateRect(m_invalidRects[i]); m_invalidRects.clear(); } void PluginView::pushPopupsEnabledState(bool state) { m_popupStateStack.append(state); } void PluginView::popPopupsEnabledState() { m_popupStateStack.removeLast(); } bool PluginView::arePopupsAllowed() const { if (!m_popupStateStack.isEmpty()) return m_popupStateStack.last(); return false; } void PluginView::setJavaScriptPaused(bool paused) { if (m_isJavaScriptPaused == paused) return; m_isJavaScriptPaused = paused; if (m_isJavaScriptPaused) m_requestTimer.stop(); else if (!m_requests.isEmpty()) m_requestTimer.startOneShot(0); } #if ENABLE(NETSCAPE_PLUGIN_API) NPObject* PluginView::npObject() { NPObject* object = 0; if (!m_isStarted || !m_plugin || !m_plugin->pluginFuncs()->getvalue) return 0; // On Windows, calling Java's NPN_GetValue can allow the message loop to // run, allowing loading to take place or JavaScript to run. Protect the // PluginView from destruction. <rdar://problem/6978804> RefPtr<PluginView> protect(this); NPError npErr; { PluginView::setCurrentPluginView(this); #if USE(JSC) JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly); #endif setCallingPlugin(true); npErr = m_plugin->pluginFuncs()->getvalue(m_instance, NPPVpluginScriptableNPObject, &object); setCallingPlugin(false); PluginView::setCurrentPluginView(0); } if (npErr != NPERR_NO_ERROR) return 0; return object; } #endif #if USE(JSC) PassRefPtr<JSC::Bindings::Instance> PluginView::bindingInstance() { #if ENABLE(NETSCAPE_PLUGIN_API) NPObject* object = npObject(); if (!object) return 0; if (hasOneRef()) { // The renderer for the PluginView was destroyed during the above call, and // the PluginView will be destroyed when this function returns, so we // return null. return 0; } RefPtr<JSC::Bindings::RootObject> root = m_parentFrame->script()->createRootObject(this); RefPtr<JSC::Bindings::Instance> instance = JSC::Bindings::CInstance::create(object, root.release()); _NPN_ReleaseObject(object); return instance.release(); #else return 0; #endif } #endif NPObject* PluginView::getNPObject() { #if ENABLE(NETSCAPE_PLUGIN_API) if (!m_plugin || !m_plugin->pluginFuncs()->getvalue) return 0; NPObject* object = 0; NPError npErr; { PluginView::setCurrentPluginView(this); setCallingPlugin(true); npErr = m_plugin->pluginFuncs()->getvalue(m_instance, NPPVpluginScriptableNPObject, &object); setCallingPlugin(false); PluginView::setCurrentPluginView(0); } if (npErr != NPERR_NO_ERROR || !object) return 0; // Bindings::CInstance (used in JSC version) retains the object, so in ~PluginView() it calls // cleanupScriptObjectsForPlugin() to releases the object. To maintain the reference count, // don't call _NPN_ReleaseObject(object) here. return object; #else return 0; #endif // NETSCAPE_PLUGIN_API } void PluginView::disconnectStream(PluginStream* stream) { ASSERT(m_streams.contains(stream)); m_streams.remove(stream); } void PluginView::setParameters(const Vector<String>& paramNames, const Vector<String>& paramValues) { ASSERT(paramNames.size() == paramValues.size()); unsigned size = paramNames.size(); unsigned paramCount = 0; m_paramNames = reinterpret_cast<char**>(fastMalloc(sizeof(char*) * size)); m_paramValues = reinterpret_cast<char**>(fastMalloc(sizeof(char*) * size)); for (unsigned i = 0; i < size; i++) { if (m_plugin->quirks().contains(PluginQuirkRemoveWindowlessVideoParam) && equalIgnoringCase(paramNames[i], "windowlessvideo")) continue; if (paramNames[i] == "pluginspage") m_pluginsPage = paramValues[i]; m_paramNames[paramCount] = createUTF8String(paramNames[i]); m_paramValues[paramCount] = createUTF8String(paramValues[i]); paramCount++; } m_paramCount = paramCount; } PluginView::PluginView(Frame* parentFrame, const IntSize& size, PluginPackage* plugin, Element* element, const KURL& url, const Vector<String>& paramNames, const Vector<String>& paramValues, const String& mimeType, bool loadManually) : m_parentFrame(parentFrame) , m_plugin(plugin) , m_element(element) , m_isStarted(false) , m_url(url) , m_baseURL(m_parentFrame->loader()->completeURL(m_parentFrame->document()->baseURL().string())) , m_status(PluginStatusLoadedSuccessfully) , m_requestTimer(this, &PluginView::requestTimerFired) , m_invalidateTimer(this, &PluginView::invalidateTimerFired) , m_popPopupsStateTimer(this, &PluginView::popPopupsStateTimerFired) , m_lifeSupportTimer(this, &PluginView::lifeSupportTimerFired) , m_mode(loadManually ? NP_FULL : NP_EMBED) , m_paramNames(0) , m_paramValues(0) , m_mimeType(mimeType) , m_instance(0) #if defined(XP_MACOSX) , m_isWindowed(false) #else , m_isWindowed(true) #endif , m_isTransparent(false) , m_haveInitialized(false) , m_isWaitingToStart(false) #if defined(XP_UNIX) , m_needsXEmbed(false) #endif #if OS(WINDOWS) && ENABLE(NETSCAPE_PLUGIN_API) , m_pluginWndProc(0) , m_lastMessage(0) , m_isCallingPluginWndProc(false) , m_wmPrintHDC(0) , m_haveUpdatedPluginWidget(false) #endif #if (PLATFORM(QT) && OS(WINDOWS)) || defined(XP_MACOSX) , m_window(0) #endif #if defined(XP_MACOSX) , m_drawingModel(NPDrawingModel(-1)) , m_eventModel(NPEventModel(-1)) , m_contextRef(0) , m_fakeWindow(0) #endif #if defined(XP_UNIX) && ENABLE(NETSCAPE_PLUGIN_API) , m_hasPendingGeometryChange(true) , m_drawable(0) , m_visual(0) , m_colormap(0) , m_pluginDisplay(0) #endif #if PLATFORM(QT) && defined(MOZ_PLATFORM_MAEMO) && (MOZ_PLATFORM_MAEMO >= 5) , m_renderToImage(false) #endif , m_loadManually(loadManually) , m_manualStream(0) , m_isJavaScriptPaused(false) , m_isHalted(false) , m_hasBeenHalted(false) , m_haveCalledSetWindow(false) { #if defined(ANDROID_PLUGINS) platformInit(); #endif if (!m_plugin) { m_status = PluginStatusCanNotFindPlugin; return; } m_instance = &m_instanceStruct; m_instance->ndata = this; m_instance->pdata = 0; instanceMap().add(m_instance, this); setParameters(paramNames, paramValues); memset(&m_npWindow, 0, sizeof(m_npWindow)); #if defined(XP_MACOSX) memset(&m_npCgContext, 0, sizeof(m_npCgContext)); #endif resize(size); } void PluginView::focusPluginElement() { // Focus the plugin if (Page* page = m_parentFrame->page()) page->focusController()->setFocusedFrame(m_parentFrame); m_parentFrame->document()->setFocusedNode(m_element); } void PluginView::didReceiveResponse(const ResourceResponse& response) { if (m_status != PluginStatusLoadedSuccessfully) return; ASSERT(m_loadManually); ASSERT(!m_manualStream); m_manualStream = PluginStream::create(this, m_parentFrame.get(), m_parentFrame->loader()->activeDocumentLoader()->request(), false, 0, plugin()->pluginFuncs(), instance(), m_plugin->quirks()); m_manualStream->setLoadManually(true); m_manualStream->didReceiveResponse(0, response); } void PluginView::didReceiveData(const char* data, int length) { if (m_status != PluginStatusLoadedSuccessfully) return; ASSERT(m_loadManually); ASSERT(m_manualStream); m_manualStream->didReceiveData(0, data, length); } void PluginView::didFinishLoading() { if (m_status != PluginStatusLoadedSuccessfully) return; ASSERT(m_loadManually); ASSERT(m_manualStream); m_manualStream->didFinishLoading(0); } void PluginView::didFail(const ResourceError& error) { if (m_status != PluginStatusLoadedSuccessfully) return; ASSERT(m_loadManually); if (m_manualStream) m_manualStream->didFail(0, error); } void PluginView::setCallingPlugin(bool b) const { if (!m_plugin->quirks().contains(PluginQuirkHasModalMessageLoop)) return; if (b) ++s_callingPlugin; else --s_callingPlugin; ASSERT(s_callingPlugin >= 0); } bool PluginView::isCallingPlugin() { return s_callingPlugin > 0; } PassRefPtr<PluginView> PluginView::create(Frame* parentFrame, const IntSize& size, Element* element, const KURL& url, const Vector<String>& paramNames, const Vector<String>& paramValues, const String& mimeType, bool loadManually) { // if we fail to find a plugin for this MIME type, findPlugin will search for // a plugin by the file extension and update the MIME type, so pass a mutable String String mimeTypeCopy = mimeType; PluginPackage* plugin = PluginDatabase::installedPlugins()->findPlugin(url, mimeTypeCopy); // No plugin was found, try refreshing the database and searching again if (!plugin && PluginDatabase::installedPlugins()->refresh()) { mimeTypeCopy = mimeType; plugin = PluginDatabase::installedPlugins()->findPlugin(url, mimeTypeCopy); } return adoptRef(new PluginView(parentFrame, size, plugin, element, url, paramNames, paramValues, mimeTypeCopy, loadManually)); } void PluginView::freeStringArray(char** stringArray, int length) { if (!stringArray) return; for (int i = 0; i < length; i++) fastFree(stringArray[i]); fastFree(stringArray); } static inline bool startsWithBlankLine(const Vector<char>& buffer) { return buffer.size() > 0 && buffer[0] == '\n'; } static inline int locationAfterFirstBlankLine(const Vector<char>& buffer) { const char* bytes = buffer.data(); unsigned length = buffer.size(); for (unsigned i = 0; i < length - 4; i++) { // Support for Acrobat. It sends "\n\n". if (bytes[i] == '\n' && bytes[i + 1] == '\n') return i + 2; // Returns the position after 2 CRLF's or 1 CRLF if it is the first line. if (bytes[i] == '\r' && bytes[i + 1] == '\n') { i += 2; if (i == 2) return i; else if (bytes[i] == '\n') // Support for Director. It sends "\r\n\n" (3880387). return i + 1; else if (bytes[i] == '\r' && bytes[i + 1] == '\n') // Support for Flash. It sends "\r\n\r\n" (3758113). return i + 2; } } return -1; } static inline const char* findEOL(const char* bytes, unsigned length) { // According to the HTTP specification EOL is defined as // a CRLF pair. Unfortunately, some servers will use LF // instead. Worse yet, some servers will use a combination // of both (e.g. <header>CRLFLF<body>), so findEOL needs // to be more forgiving. It will now accept CRLF, LF or // CR. // // It returns NULL if EOLF is not found or it will return // a pointer to the first terminating character. for (unsigned i = 0; i < length; i++) { if (bytes[i] == '\n') return bytes + i; if (bytes[i] == '\r') { // Check to see if spanning buffer bounds // (CRLF is across reads). If so, wait for // next read. if (i + 1 == length) break; return bytes + i; } } return 0; } static inline String capitalizeRFC822HeaderFieldName(const String& name) { bool capitalizeCharacter = true; String result; for (unsigned i = 0; i < name.length(); i++) { UChar c; if (capitalizeCharacter && name[i] >= 'a' && name[i] <= 'z') c = toASCIIUpper(name[i]); else if (!capitalizeCharacter && name[i] >= 'A' && name[i] <= 'Z') c = toASCIILower(name[i]); else c = name[i]; if (name[i] == '-') capitalizeCharacter = true; else capitalizeCharacter = false; result.append(c); } return result; } static inline HTTPHeaderMap parseRFC822HeaderFields(const Vector<char>& buffer, unsigned length) { const char* bytes = buffer.data(); const char* eol; String lastKey; HTTPHeaderMap headerFields; // Loop ove rlines until we're past the header, or we can't find any more end-of-lines while ((eol = findEOL(bytes, length))) { const char* line = bytes; int lineLength = eol - bytes; // Move bytes to the character after the terminator as returned by findEOL. bytes = eol + 1; if ((*eol == '\r') && (*bytes == '\n')) bytes++; // Safe since findEOL won't return a spanning CRLF. length -= (bytes - line); if (lineLength == 0) // Blank line; we're at the end of the header break; else if (*line == ' ' || *line == '\t') { // Continuation of the previous header if (lastKey.isNull()) { // malformed header; ignore it and continue continue; } else { // Merge the continuation of the previous header String currentValue = headerFields.get(lastKey); String newValue(line, lineLength); headerFields.set(lastKey, currentValue + newValue); } } else { // Brand new header const char* colon; for (colon = line; *colon != ':' && colon != eol; colon++) { // empty loop } if (colon == eol) // malformed header; ignore it and continue continue; else { lastKey = capitalizeRFC822HeaderFieldName(String(line, colon - line)); String value; for (colon++; colon != eol; colon++) { if (*colon != ' ' && *colon != '\t') break; } if (colon == eol) value = ""; else value = String(colon, eol - colon); String oldValue = headerFields.get(lastKey); if (!oldValue.isNull()) { String tmp = oldValue; tmp += ", "; tmp += value; value = tmp; } headerFields.set(lastKey, value); } } } return headerFields; } NPError PluginView::handlePost(const char* url, const char* target, uint32_t len, const char* buf, bool file, void* notifyData, bool sendNotification, bool allowHeaders) { if (!url || !len || !buf) return NPERR_INVALID_PARAM; FrameLoadRequest frameLoadRequest(m_parentFrame->document()->securityOrigin()); HTTPHeaderMap headerFields; Vector<char> buffer; if (file) { NPError readResult = handlePostReadFile(buffer, len, buf); if(readResult != NPERR_NO_ERROR) return readResult; } else { buffer.resize(len); memcpy(buffer.data(), buf, len); } const char* postData = buffer.data(); int postDataLength = buffer.size(); if (allowHeaders) { if (startsWithBlankLine(buffer)) { postData++; postDataLength--; } else { int location = locationAfterFirstBlankLine(buffer); if (location != -1) { // If the blank line is somewhere in the middle of the buffer, everything before is the header headerFields = parseRFC822HeaderFields(buffer, location); unsigned dataLength = buffer.size() - location; // Sometimes plugins like to set Content-Length themselves when they post, // but WebFoundation does not like that. So we will remove the header // and instead truncate the data to the requested length. String contentLength = headerFields.get("Content-Length"); if (!contentLength.isNull()) dataLength = min(contentLength.toInt(), (int)dataLength); headerFields.remove("Content-Length"); postData += location; postDataLength = dataLength; } } } frameLoadRequest.resourceRequest().setHTTPMethod("POST"); frameLoadRequest.resourceRequest().setURL(makeURL(m_baseURL, url)); frameLoadRequest.resourceRequest().addHTTPHeaderFields(headerFields); frameLoadRequest.resourceRequest().setHTTPBody(FormData::create(postData, postDataLength)); frameLoadRequest.setFrameName(target); return load(frameLoadRequest, sendNotification, notifyData); } #ifdef PLUGIN_SCHEDULE_TIMER uint32_t PluginView::scheduleTimer(NPP instance, uint32_t interval, bool repeat, void (*timerFunc)(NPP, uint32_t timerID)) { return m_timerList.schedule(instance, interval, repeat, timerFunc); } void PluginView::unscheduleTimer(NPP instance, uint32_t timerID) { m_timerList.unschedule(instance, timerID); } #endif void PluginView::invalidateWindowlessPluginRect(const IntRect& rect) { if (!isVisible()) return; if (!m_element->renderer()) return; RenderBox* renderer = toRenderBox(m_element->renderer()); IntRect dirtyRect = rect; dirtyRect.move(renderer->borderLeft() + renderer->paddingLeft(), renderer->borderTop() + renderer->paddingTop()); renderer->repaintRectangle(dirtyRect); } void PluginView::paintMissingPluginIcon(GraphicsContext* context, const IntRect& rect) { static RefPtr<Image> nullPluginImage; if (!nullPluginImage) nullPluginImage = Image::loadPlatformResource("nullPlugin"); IntRect imageRect(frameRect().x(), frameRect().y(), nullPluginImage->width(), nullPluginImage->height()); int xOffset = (frameRect().width() - imageRect.width()) / 2; int yOffset = (frameRect().height() - imageRect.height()) / 2; imageRect.move(xOffset, yOffset); if (!rect.intersects(imageRect)) return; context->save(); context->clip(windowClipRect()); context->drawImage(nullPluginImage.get(), ColorSpaceDeviceRGB, imageRect.location()); context->restore(); } static const char* MozillaUserAgent = "Mozilla/5.0 (" #if defined(XP_MACOSX) "Macintosh; U; Intel Mac OS X;" #elif defined(XP_WIN) "Windows; U; Windows NT 5.1;" #elif defined(XP_UNIX) // The Gtk port uses X11 plugins in Mac. #if OS(DARWIN) && PLATFORM(GTK) "X11; U; Intel Mac OS X;" #else "X11; U; Linux i686;" #endif #endif " en-US; rv:1.8.1) Gecko/20061010 Firefox/2.0"; const char* PluginView::userAgent() { #if !PLATFORM(ANDROID) if (m_plugin->quirks().contains(PluginQuirkWantsMozillaUserAgent)) return MozillaUserAgent; #endif if (m_userAgent.isNull()) m_userAgent = m_parentFrame->loader()->userAgent(m_url).utf8(); return m_userAgent.data(); } #if ENABLE(NETSCAPE_PLUGIN_API) const char* PluginView::userAgentStatic() { return MozillaUserAgent; } #endif Node* PluginView::node() const { return m_element; } String PluginView::pluginName() const { return m_plugin->name(); } void PluginView::lifeSupportTimerFired(Timer<PluginView>*) { deref(); } void PluginView::keepAlive() { if (m_lifeSupportTimer.isActive()) return; ref(); m_lifeSupportTimer.startOneShot(0); } #if ENABLE(NETSCAPE_PLUGIN_API) void PluginView::keepAlive(NPP instance) { PluginView* view = instanceMap().get(instance); if (!view) return; view->keepAlive(); } NPError PluginView::getValueStatic(NPNVariable variable, void* value) { LOG(Plugins, "PluginView::getValueStatic(%s)", prettyNameForNPNVariable(variable).data()); NPError result; if (platformGetValueStatic(variable, value, &result)) return result; return NPERR_GENERIC_ERROR; } NPError PluginView::getValue(NPNVariable variable, void* value) { LOG(Plugins, "PluginView::getValue(%s)", prettyNameForNPNVariable(variable).data()); NPError result; if (platformGetValue(variable, value, &result)) return result; if (platformGetValueStatic(variable, value, &result)) return result; switch (variable) { case NPNVWindowNPObject: { if (m_isJavaScriptPaused) return NPERR_GENERIC_ERROR; NPObject* windowScriptObject = m_parentFrame->script()->windowScriptNPObject(); // Return value is expected to be retained, as described here: <http://www.mozilla.org/projects/plugin/npruntime.html> if (windowScriptObject) _NPN_RetainObject(windowScriptObject); void** v = (void**)value; *v = windowScriptObject; return NPERR_NO_ERROR; } case NPNVPluginElementNPObject: { if (m_isJavaScriptPaused) return NPERR_GENERIC_ERROR; NPObject* pluginScriptObject = 0; if (m_element->hasTagName(appletTag) || m_element->hasTagName(embedTag) || m_element->hasTagName(objectTag)) pluginScriptObject = static_cast<HTMLPlugInElement*>(m_element)->getNPObject(); // Return value is expected to be retained, as described here: <http://www.mozilla.org/projects/plugin/npruntime.html> if (pluginScriptObject) _NPN_RetainObject(pluginScriptObject); void** v = (void**)value; *v = pluginScriptObject; return NPERR_NO_ERROR; } case NPNVprivateModeBool: { Page* page = m_parentFrame->page(); if (!page) return NPERR_GENERIC_ERROR; *((NPBool*)value) = !page->settings() || page->settings()->privateBrowsingEnabled(); return NPERR_NO_ERROR; } default: return NPERR_GENERIC_ERROR; } } static Frame* getFrame(Frame* parentFrame, Element* element) { if (parentFrame) return parentFrame; Document* document = element->document(); if (!document) document = element->ownerDocument(); if (document) return document->frame(); return 0; } NPError PluginView::getValueForURL(NPNURLVariable variable, const char* url, char** value, uint32_t* len) { LOG(Plugins, "PluginView::getValueForURL(%s)", prettyNameForNPNURLVariable(variable).data()); NPError result = NPERR_NO_ERROR; switch (variable) { case NPNURLVCookie: { KURL u(m_baseURL, url); if (u.isValid()) { Frame* frame = getFrame(parentFrame(), m_element); if (frame) { const CString cookieStr = cookies(frame->document(), u).utf8(); if (!cookieStr.isNull()) { const int size = cookieStr.length(); *value = static_cast<char*>(NPN_MemAlloc(size+1)); if (*value) { memset(*value, 0, size+1); memcpy(*value, cookieStr.data(), size+1); if (len) *len = size; } else result = NPERR_OUT_OF_MEMORY_ERROR; } } } else result = NPERR_INVALID_URL; break; } case NPNURLVProxy: { KURL u(m_baseURL, url); if (u.isValid()) { Frame* frame = getFrame(parentFrame(), m_element); const FrameLoader* frameLoader = frame ? frame->loader() : 0; const NetworkingContext* context = frameLoader ? frameLoader->networkingContext() : 0; const CString proxyStr = toString(proxyServersForURL(u, context)).utf8(); if (!proxyStr.isNull()) { const int size = proxyStr.length(); *value = static_cast<char*>(NPN_MemAlloc(size+1)); if (*value) { memset(*value, 0, size+1); memcpy(*value, proxyStr.data(), size+1); if (len) *len = size; } else result = NPERR_OUT_OF_MEMORY_ERROR; } } else result = NPERR_INVALID_URL; break; } default: result = NPERR_GENERIC_ERROR; LOG(Plugins, "PluginView::getValueForURL: %s", prettyNameForNPNURLVariable(variable).data()); break; } return result; } NPError PluginView::setValueForURL(NPNURLVariable variable, const char* url, const char* value, uint32_t len) { LOG(Plugins, "PluginView::setValueForURL(%s)", prettyNameForNPNURLVariable(variable).data()); NPError result = NPERR_NO_ERROR; switch (variable) { case NPNURLVCookie: { KURL u(m_baseURL, url); if (u.isValid()) { const String cookieStr = String::fromUTF8(value, len); Frame* frame = getFrame(parentFrame(), m_element); if (frame && !cookieStr.isEmpty()) setCookies(frame->document(), u, cookieStr); } else result = NPERR_INVALID_URL; break; } case NPNURLVProxy: LOG(Plugins, "PluginView::setValueForURL(%s): Plugins are NOT allowed to set proxy information.", prettyNameForNPNURLVariable(variable).data()); result = NPERR_GENERIC_ERROR; break; default: LOG(Plugins, "PluginView::setValueForURL: %s", prettyNameForNPNURLVariable(variable).data()); result = NPERR_GENERIC_ERROR; break; } return result; } NPError PluginView::getAuthenticationInfo(const char* protocol, const char* host, int32_t port, const char* scheme, const char* realm, char** username, uint32_t* ulen, char** password, uint32_t* plen) { LOG(Plugins, "PluginView::getAuthenticationInfo: protocol=%s, host=%s, port=%d", protocol, host, port); notImplemented(); return NPERR_GENERIC_ERROR; } #endif void PluginView::privateBrowsingStateChanged(bool privateBrowsingEnabled) { NPP_SetValueProcPtr setValue = m_plugin->pluginFuncs()->setvalue; if (!setValue) return; PluginView::setCurrentPluginView(this); #if USE(JSC) JSC::JSLock::DropAllLocks dropAllLocks(JSC::SilenceAssertionsOnly); #endif setCallingPlugin(true); NPBool value = privateBrowsingEnabled; setValue(m_instance, NPNVprivateModeBool, &value); setCallingPlugin(false); PluginView::setCurrentPluginView(0); } } // namespace WebCore #endif // ENABLE(NETSCAPE_PLUGIN_API)
///////////////////////////////////////////////////////////////////////////// // Name: src/motif/radiobox.cpp // Purpose: wxRadioBox // Author: Julian Smart // Modified by: // Created: 17/09/98 // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // For compilers that support precompilation, includes "wx.h". #include "wx/wxprec.h" #if wxUSE_RADIOBOX #include "wx/radiobox.h" #ifndef WX_PRECOMP #include "wx/utils.h" #include "wx/arrstr.h" #endif #ifdef __VMS__ #pragma message disable nosimpint #endif #include <Xm/Label.h> #include <Xm/LabelG.h> #include <Xm/ToggleB.h> #include <Xm/ToggleBG.h> #include <Xm/RowColumn.h> #include <Xm/Frame.h> #ifdef __VMS__ #pragma message enable nosimpint #endif #include "wx/motif/private.h" void wxRadioBoxCallback (Widget w, XtPointer clientData, XmToggleButtonCallbackStruct * cbs); IMPLEMENT_DYNAMIC_CLASS(wxRadioBox, wxControl) // Radio box item void wxRadioBox::Init() { m_selectedButton = -1; m_noItems = 0; m_noRowsOrCols = 0; m_labelWidget = (WXWidget) 0; } bool wxRadioBox::Create(wxWindow *parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, int n, const wxString choices[], int majorDim, long style, const wxValidator& val, const wxString& name) { if( !CreateControl( parent, id, pos, size, style, val, name ) ) return false; PreCreation(); m_noItems = (unsigned int)n; m_noRowsOrCols = majorDim; SetMajorDim(majorDim == 0 ? n : majorDim, style); Widget parentWidget = (Widget) parent->GetClientWidget(); Display* dpy = XtDisplay(parentWidget); m_mainWidget = XtVaCreateWidget ("radioboxframe", xmFrameWidgetClass, parentWidget, XmNresizeHeight, True, XmNresizeWidth, True, NULL); wxString label1(GetLabelText(title)); if (!label1.empty()) { wxXmString text(label1); m_labelWidget = (WXWidget) XtVaCreateManagedWidget( label1.mb_str(), #if wxUSE_GADGETS style & wxCOLOURED ? xmLabelWidgetClass : xmLabelGadgetClass, (Widget)m_mainWidget, #else xmLabelWidgetClass, (Widget)m_mainWidget, #endif wxFont::GetFontTag(), m_font.GetFontTypeC(dpy), XmNlabelString, text(), // XmNframeChildType is not in Motif 1.2, nor in Lesstif, // if it was compiled with 1.2 compatibility // TODO: check this still looks OK for Motif 1.2. #if (XmVersion > 1200) XmNframeChildType, XmFRAME_TITLE_CHILD, #else XmNchildType, XmFRAME_TITLE_CHILD, #endif XmNchildVerticalAlignment, XmALIGNMENT_CENTER, NULL); } Arg args[3]; XtSetArg (args[0], XmNorientation, ((style & wxHORIZONTAL) == wxHORIZONTAL ? XmHORIZONTAL : XmVERTICAL)); XtSetArg (args[1], XmNnumColumns, GetMajorDim()); XtSetArg (args[2], XmNadjustLast, False); Widget radioBoxWidget = XmCreateRadioBox ((Widget)m_mainWidget, wxMOTIF_STR("radioBoxWidget"), args, 3); m_radioButtons.reserve(n); m_radioButtonLabels.reserve(n); int i; for (i = 0; i < n; i++) { wxString str(GetLabelText(choices[i])); m_radioButtonLabels.push_back(str); Widget radioItem = XtVaCreateManagedWidget ( str.mb_str(), #if wxUSE_GADGETS xmToggleButtonGadgetClass, radioBoxWidget, #else xmToggleButtonWidgetClass, radioBoxWidget, #endif wxFont::GetFontTag(), m_font.GetFontTypeC(dpy), NULL); m_radioButtons.push_back((WXWidget)radioItem); XtAddCallback (radioItem, XmNvalueChangedCallback, (XtCallbackProc) wxRadioBoxCallback, (XtPointer) this); } SetSelection (0); XtRealizeWidget((Widget)m_mainWidget); XtManageChild (radioBoxWidget); XtManageChild ((Widget)m_mainWidget); PostCreation(); AttachWidget (parent, m_mainWidget, NULL, pos.x, pos.y, size.x, size.y); return true; } bool wxRadioBox::Create(wxWindow *parent, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, const wxArrayString& choices, int majorDim, long style, const wxValidator& val, const wxString& name) { wxCArrayString chs(choices); return Create(parent, id, title, pos, size, chs.GetCount(), chs.GetStrings(), majorDim, style, val, name); } wxRadioBox::~wxRadioBox() { DetachWidget(m_mainWidget); XtDestroyWidget((Widget) m_mainWidget); m_mainWidget = (WXWidget) 0; } void wxRadioBox::SetString(unsigned int item, const wxString& label) { if (!IsValid(item)) return; Widget widget = (Widget)m_radioButtons[item]; if (!label.empty()) { wxString label1(GetLabelText(label)); wxXmString text( label1 ); m_radioButtonLabels[item] = label1; XtVaSetValues (widget, XmNlabelString, text(), XmNlabelType, XmSTRING, NULL); } } void wxRadioBox::SetSelection(int n) { if (!IsValid(n)) return; m_selectedButton = n; m_inSetValue = true; XmToggleButtonSetState ((Widget) m_radioButtons[n], True, False); for (unsigned int i = 0; i < m_noItems; i++) if (i != (unsigned int)n) XmToggleButtonSetState ((Widget) m_radioButtons[i], False, False); m_inSetValue = false; } // Get single selection, for single choice list items int wxRadioBox::GetSelection() const { return m_selectedButton; } // Find string for position wxString wxRadioBox::GetString(unsigned int n) const { if (!IsValid(n)) return wxEmptyString; return m_radioButtonLabels[n]; } void wxRadioBox::DoSetSize(int x, int y, int width, int height, int sizeFlags) { bool managed = XtIsManaged((Widget) m_mainWidget); if (managed) XtUnmanageChild ((Widget) m_mainWidget); int xx = x; int yy = y; AdjustForParentClientOrigin(xx, yy, sizeFlags); if (x > -1 || (sizeFlags & wxSIZE_ALLOW_MINUS_ONE)) XtVaSetValues ((Widget) m_mainWidget, XmNx, xx, NULL); if (y > -1 || (sizeFlags & wxSIZE_ALLOW_MINUS_ONE)) XtVaSetValues ((Widget) m_mainWidget, XmNy, yy, NULL); if (width > 0) XtVaSetValues ((Widget) m_mainWidget, XmNwidth, width, NULL); if (height > 0) XtVaSetValues ((Widget) m_mainWidget, XmNheight, height, NULL); if (managed) XtManageChild ((Widget) m_mainWidget); } // Enable a specific button bool wxRadioBox::Enable(unsigned int n, bool enable) { if (!IsValid(n)) return false; XtSetSensitive ((Widget) m_radioButtons[n], (Boolean) enable); return true; } // Enable all controls bool wxRadioBox::Enable(bool enable) { if ( !wxControl::Enable(enable) ) return false; for (unsigned int i = 0; i < m_noItems; i++) XtSetSensitive ((Widget) m_radioButtons[i], (Boolean) enable); return true; } bool wxRadioBox::Show(bool show) { // TODO: show/hide all children return wxControl::Show(show); } // Show a specific button bool wxRadioBox::Show(unsigned int n, bool show) { // This method isn't complete, and we try do do our best... // It's main purpose isn't for allowing Show/Unshow dynamically, // but rather to provide a way to design wxRadioBox such: // // o Val1 o Val2 o Val3 // o Val4 o Val6 // o Val7 o Val8 o Val9 // // In my case, this is a 'direction' box, and the Show(5,False) is // coupled with an Enable(5,False) // if (!IsValid(n)) return false; XtVaSetValues ((Widget) m_radioButtons[n], XmNindicatorOn, (unsigned char) show, NULL); // Please note that this is all we can do: removing the label // if switching to unshow state. However, when switching // to the on state, it's the prog. resp. to call SetString(item,...) // after this call!! if (!show) wxRadioBox::SetString (n, " "); return true; } // For single selection items only wxString wxRadioBox::GetStringSelection () const { int sel = GetSelection (); if (sel != wxNOT_FOUND) return this->GetString((unsigned int)sel); else return wxEmptyString; } bool wxRadioBox::SetStringSelection (const wxString& s) { int sel = FindString (s); if (sel > -1) { SetSelection (sel); return true; } else return false; } void wxRadioBox::Command (wxCommandEvent & event) { SetSelection (event.GetInt()); ProcessCommand (event); } void wxRadioBox::ChangeFont(bool keepOriginalSize) { wxWindow::ChangeFont(keepOriginalSize); for (unsigned int i = 0; i < m_noItems; i++) { WXWidget radioButton = m_radioButtons[i]; XtVaSetValues ((Widget) radioButton, wxFont::GetFontTag(), m_font.GetFontTypeC(XtDisplay((Widget) GetTopWidget())), NULL); } } void wxRadioBox::ChangeBackgroundColour() { wxWindow::ChangeBackgroundColour(); wxColour colour = *wxBLACK; WXPixel selectPixel = colour.AllocColour(XtDisplay((Widget)m_mainWidget)); for (unsigned int i = 0; i < m_noItems; i++) { WXWidget radioButton = m_radioButtons[i]; wxDoChangeBackgroundColour(radioButton, m_backgroundColour, true); XtVaSetValues ((Widget) radioButton, XmNselectColor, selectPixel, NULL); } } void wxRadioBox::ChangeForegroundColour() { wxWindow::ChangeForegroundColour(); for (unsigned int i = 0; i < m_noItems; i++) { WXWidget radioButton = m_radioButtons[i]; wxDoChangeForegroundColour(radioButton, m_foregroundColour); } } void wxRadioBoxCallback (Widget w, XtPointer clientData, XmToggleButtonCallbackStruct * cbs) { if (!cbs->set) return; wxRadioBox *item = (wxRadioBox *) clientData; int sel = -1; unsigned int i; const wxWidgetArray& buttons = item->GetRadioButtons(); for (i = 0; i < item->GetCount(); i++) if (((Widget)buttons[i]) == w) sel = (int)i; item->SetSel(sel); if (item->InSetValue()) return; wxCommandEvent event (wxEVT_RADIOBOX, item->GetId()); event.SetInt(sel); event.SetString(item->GetStringSelection()); event.SetEventObject(item); item->ProcessCommand (event); } #endif // wxUSE_RADIOBOX
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2016-2018 The BitcoinReal developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "txdb.h" #include "main.h" #include "pow.h" #include "uint256.h" #include "accumulators.h" #include <stdint.h> #include <boost/thread.hpp> using namespace std; using namespace libzerocoin; void static BatchWriteCoins(CLevelDBBatch& batch, const uint256& hash, const CCoins& coins) { if (coins.IsPruned()) batch.Erase(make_pair('c', hash)); else batch.Write(make_pair('c', hash), coins); } void static BatchWriteHashBestChain(CLevelDBBatch& batch, const uint256& hash) { batch.Write('B', hash); } CCoinsViewDB::CCoinsViewDB(size_t nCacheSize, bool fMemory, bool fWipe) : db(GetDataDir() / "chainstate", nCacheSize, fMemory, fWipe) { } bool CCoinsViewDB::GetCoins(const uint256& txid, CCoins& coins) const { return db.Read(make_pair('c', txid), coins); } bool CCoinsViewDB::HaveCoins(const uint256& txid) const { return db.Exists(make_pair('c', txid)); } uint256 CCoinsViewDB::GetBestBlock() const { uint256 hashBestChain; if (!db.Read('B', hashBestChain)) return uint256(0); return hashBestChain; } bool CCoinsViewDB::BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock) { CLevelDBBatch batch; size_t count = 0; size_t changed = 0; for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end();) { if (it->second.flags & CCoinsCacheEntry::DIRTY) { BatchWriteCoins(batch, it->first, it->second.coins); changed++; } count++; CCoinsMap::iterator itOld = it++; mapCoins.erase(itOld); } if (hashBlock != uint256(0)) BatchWriteHashBestChain(batch, hashBlock); LogPrint("coindb", "Committing %u changed transactions (out of %u) to coin database...\n", (unsigned int)changed, (unsigned int)count); return db.WriteBatch(batch); } CBlockTreeDB::CBlockTreeDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "blocks" / "index", nCacheSize, fMemory, fWipe) { } bool CBlockTreeDB::WriteBlockIndex(const CDiskBlockIndex& blockindex) { return Write(make_pair('b', blockindex.GetBlockHash()), blockindex); } bool CBlockTreeDB::WriteBlockFileInfo(int nFile, const CBlockFileInfo& info) { return Write(make_pair('f', nFile), info); } bool CBlockTreeDB::ReadBlockFileInfo(int nFile, CBlockFileInfo& info) { return Read(make_pair('f', nFile), info); } bool CBlockTreeDB::WriteLastBlockFile(int nFile) { return Write('l', nFile); } bool CBlockTreeDB::WriteReindexing(bool fReindexing) { if (fReindexing) return Write('R', '1'); else return Erase('R'); } bool CBlockTreeDB::ReadReindexing(bool& fReindexing) { fReindexing = Exists('R'); return true; } bool CBlockTreeDB::ReadLastBlockFile(int& nFile) { return Read('l', nFile); } bool CCoinsViewDB::GetStats(CCoinsStats& stats) const { /* It seems that there are no "const iterators" for LevelDB. Since we only need read operations on it, use a const-cast to get around that restriction. */ boost::scoped_ptr<leveldb::Iterator> pcursor(const_cast<CLevelDBWrapper*>(&db)->NewIterator()); pcursor->SeekToFirst(); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); stats.hashBlock = GetBestBlock(); ss << stats.hashBlock; CAmount nTotalAmount = 0; while (pcursor->Valid()) { boost::this_thread::interruption_point(); try { leveldb::Slice slKey = pcursor->key(); CDataStream ssKey(slKey.data(), slKey.data() + slKey.size(), SER_DISK, CLIENT_VERSION); char chType; ssKey >> chType; if (chType == 'c') { leveldb::Slice slValue = pcursor->value(); CDataStream ssValue(slValue.data(), slValue.data() + slValue.size(), SER_DISK, CLIENT_VERSION); CCoins coins; ssValue >> coins; uint256 txhash; ssKey >> txhash; ss << txhash; ss << VARINT(coins.nVersion); ss << (coins.fCoinBase ? 'c' : 'n'); ss << VARINT(coins.nHeight); stats.nTransactions++; for (unsigned int i = 0; i < coins.vout.size(); i++) { const CTxOut& out = coins.vout[i]; if (!out.IsNull()) { stats.nTransactionOutputs++; ss << VARINT(i + 1); ss << out; nTotalAmount += out.nValue; } } stats.nSerializedSize += 32 + slValue.size(); ss << VARINT(0); } pcursor->Next(); } catch (std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } } stats.nHeight = mapBlockIndex.find(GetBestBlock())->second->nHeight; stats.hashSerialized = ss.GetHash(); stats.nTotalAmount = nTotalAmount; return true; } bool CBlockTreeDB::ReadTxIndex(const uint256& txid, CDiskTxPos& pos) { return Read(make_pair('t', txid), pos); } bool CBlockTreeDB::WriteTxIndex(const std::vector<std::pair<uint256, CDiskTxPos> >& vect) { CLevelDBBatch batch; for (std::vector<std::pair<uint256, CDiskTxPos> >::const_iterator it = vect.begin(); it != vect.end(); it++) batch.Write(make_pair('t', it->first), it->second); return WriteBatch(batch); } bool CBlockTreeDB::WriteFlag(const std::string& name, bool fValue) { return Write(std::make_pair('F', name), fValue ? '1' : '0'); } bool CBlockTreeDB::ReadFlag(const std::string& name, bool& fValue) { char ch; if (!Read(std::make_pair('F', name), ch)) return false; fValue = ch == '1'; return true; } bool CBlockTreeDB::WriteInt(const std::string& name, int nValue) { return Write(std::make_pair('I', name), nValue); } bool CBlockTreeDB::ReadInt(const std::string& name, int& nValue) { return Read(std::make_pair('I', name), nValue); } bool CBlockTreeDB::LoadBlockIndexGuts() { boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator()); CDataStream ssKeySet(SER_DISK, CLIENT_VERSION); ssKeySet << make_pair('b', uint256(0)); pcursor->Seek(ssKeySet.str()); // Load mapBlockIndex uint256 nPreviousCheckpoint; while (pcursor->Valid()) { boost::this_thread::interruption_point(); try { leveldb::Slice slKey = pcursor->key(); CDataStream ssKey(slKey.data(), slKey.data() + slKey.size(), SER_DISK, CLIENT_VERSION); char chType; ssKey >> chType; if (chType == 'b') { leveldb::Slice slValue = pcursor->value(); CDataStream ssValue(slValue.data(), slValue.data() + slValue.size(), SER_DISK, CLIENT_VERSION); CDiskBlockIndex diskindex; ssValue >> diskindex; // Construct block index object CBlockIndex* pindexNew = InsertBlockIndex(diskindex.GetBlockHash()); pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev); pindexNew->pnext = InsertBlockIndex(diskindex.hashNext); pindexNew->nHeight = diskindex.nHeight; pindexNew->nFile = diskindex.nFile; pindexNew->nDataPos = diskindex.nDataPos; pindexNew->nUndoPos = diskindex.nUndoPos; pindexNew->nVersion = diskindex.nVersion; pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot; pindexNew->nTime = diskindex.nTime; pindexNew->nBits = diskindex.nBits; pindexNew->nNonce = diskindex.nNonce; pindexNew->nStatus = diskindex.nStatus; pindexNew->nTx = diskindex.nTx; //zerocoin pindexNew->nAccumulatorCheckpoint = diskindex.nAccumulatorCheckpoint; pindexNew->mapZerocoinSupply = diskindex.mapZerocoinSupply; pindexNew->vMintDenominationsInBlock = diskindex.vMintDenominationsInBlock; //Proof Of Stake pindexNew->nMint = diskindex.nMint; pindexNew->nMoneySupply = diskindex.nMoneySupply; pindexNew->nFlags = diskindex.nFlags; pindexNew->nStakeModifier = diskindex.nStakeModifier; pindexNew->prevoutStake = diskindex.prevoutStake; pindexNew->nStakeTime = diskindex.nStakeTime; pindexNew->hashProofOfStake = diskindex.hashProofOfStake; if (pindexNew->nHeight <= Params().LAST_POW_BLOCK()) { if (!CheckProofOfWork(pindexNew->GetBlockHash(), pindexNew->nBits)) return error("LoadBlockIndex() : CheckProofOfWork failed: %s", pindexNew->ToString()); } // ppcoin: build setStakeSeen if (pindexNew->IsProofOfStake()) setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime)); //populate accumulator checksum map in memory if(pindexNew->nAccumulatorCheckpoint != 0 && pindexNew->nAccumulatorCheckpoint != nPreviousCheckpoint) { //Don't load any checkpoints that exist before v2 zbr. The accumulator is invalid for v1 and not used. if (pindexNew->nHeight >= Params().Zerocoin_Block_V2_Start()) LoadAccumulatorValuesFromDB(pindexNew->nAccumulatorCheckpoint); nPreviousCheckpoint = pindexNew->nAccumulatorCheckpoint; } pcursor->Next(); } else { break; // if shutdown requested or finished loading block index } } catch (std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } } return true; } CZerocoinDB::CZerocoinDB(size_t nCacheSize, bool fMemory, bool fWipe) : CLevelDBWrapper(GetDataDir() / "zerocoin", nCacheSize, fMemory, fWipe) { } bool CZerocoinDB::WriteCoinMintBatch(const std::vector<std::pair<libzerocoin::PublicCoin, uint256> >& mintInfo) { CLevelDBBatch batch; size_t count = 0; for (std::vector<std::pair<libzerocoin::PublicCoin, uint256> >::const_iterator it=mintInfo.begin(); it != mintInfo.end(); it++) { PublicCoin pubCoin = it->first; uint256 hash = GetPubCoinHash(pubCoin.getValue()); batch.Write(make_pair('m', hash), it->second); ++count; } LogPrint("zero", "Writing %u coin mints to db.\n", (unsigned int)count); return WriteBatch(batch, true); } bool CZerocoinDB::ReadCoinMint(const CBigNum& bnPubcoin, uint256& hashTx) { return ReadCoinMint(GetPubCoinHash(bnPubcoin), hashTx); } bool CZerocoinDB::ReadCoinMint(const uint256& hashPubcoin, uint256& hashTx) { return Read(make_pair('m', hashPubcoin), hashTx); } bool CZerocoinDB::EraseCoinMint(const CBigNum& bnPubcoin) { uint256 hash = GetPubCoinHash(bnPubcoin); return Erase(make_pair('m', hash)); } bool CZerocoinDB::WriteCoinSpendBatch(const std::vector<std::pair<libzerocoin::CoinSpend, uint256> >& spendInfo) { CLevelDBBatch batch; size_t count = 0; for (std::vector<std::pair<libzerocoin::CoinSpend, uint256> >::const_iterator it=spendInfo.begin(); it != spendInfo.end(); it++) { CBigNum bnSerial = it->first.getCoinSerialNumber(); CDataStream ss(SER_GETHASH, 0); ss << bnSerial; uint256 hash = Hash(ss.begin(), ss.end()); batch.Write(make_pair('s', hash), it->second); ++count; } LogPrint("zero", "Writing %u coin spends to db.\n", (unsigned int)count); return WriteBatch(batch, true); } bool CZerocoinDB::ReadCoinSpend(const CBigNum& bnSerial, uint256& txHash) { CDataStream ss(SER_GETHASH, 0); ss << bnSerial; uint256 hash = Hash(ss.begin(), ss.end()); return Read(make_pair('s', hash), txHash); } bool CZerocoinDB::ReadCoinSpend(const uint256& hashSerial, uint256 &txHash) { return Read(make_pair('s', hashSerial), txHash); } bool CZerocoinDB::EraseCoinSpend(const CBigNum& bnSerial) { CDataStream ss(SER_GETHASH, 0); ss << bnSerial; uint256 hash = Hash(ss.begin(), ss.end()); return Erase(make_pair('s', hash)); } bool CZerocoinDB::WipeCoins(std::string strType) { if (strType != "spends" && strType != "mints") return error("%s: did not recognize type %s", __func__, strType); boost::scoped_ptr<leveldb::Iterator> pcursor(NewIterator()); char type = (strType == "spends" ? 's' : 'm'); CDataStream ssKeySet(SER_DISK, CLIENT_VERSION); ssKeySet << make_pair(type, uint256(0)); pcursor->Seek(ssKeySet.str()); // Load mapBlockIndex std::set<uint256> setDelete; while (pcursor->Valid()) { boost::this_thread::interruption_point(); try { leveldb::Slice slKey = pcursor->key(); CDataStream ssKey(slKey.data(), slKey.data() + slKey.size(), SER_DISK, CLIENT_VERSION); char chType; ssKey >> chType; if (chType == type) { leveldb::Slice slValue = pcursor->value(); CDataStream ssValue(slValue.data(), slValue.data() + slValue.size(), SER_DISK, CLIENT_VERSION); uint256 hash; ssValue >> hash; setDelete.insert(hash); pcursor->Next(); } else { break; // if shutdown requested or finished loading block index } } catch (std::exception& e) { return error("%s : Deserialize or I/O error - %s", __func__, e.what()); } } for (auto& hash : setDelete) { if (!Erase(make_pair(type, hash))) LogPrintf("%s: error failed to delete %s\n", __func__, hash.GetHex()); } return true; } bool CZerocoinDB::WriteAccumulatorValue(const uint32_t& nChecksum, const CBigNum& bnValue) { LogPrint("zero","%s : checksum:%d val:%s\n", __func__, nChecksum, bnValue.GetHex()); return Write(make_pair('2', nChecksum), bnValue); } bool CZerocoinDB::ReadAccumulatorValue(const uint32_t& nChecksum, CBigNum& bnValue) { return Read(make_pair('2', nChecksum), bnValue); } bool CZerocoinDB::EraseAccumulatorValue(const uint32_t& nChecksum) { LogPrint("zero", "%s : checksum:%d\n", __func__, nChecksum); return Erase(make_pair('2', nChecksum)); }
; A282285: Least common multiple of 5*n+1 and 5*n-1. ; Submitted by Jon Maiga ; 1,12,99,112,399,312,899,612,1599,1012,2499,1512,3599,2112,4899,2812,6399,3612,8099,4512,9999,5512,12099,6612,14399,7812,16899,9112,19599,10512,22499,12012,25599,13612,28899,15312,32399,17112,36099,19012,39999,21012,44099,23112,48399,25312,52899,27612,57599,30012,62499,32512,67599,35112,72899,37812,78399,40612,84099,43512,89999,46512,96099,49612,102399,52812,108899,56112,115599,59512,122499,63012,129599,66612,136899,70312,144399,74112,152099,78012,159999,82012,168099,86112,176399,90312,184899 mul $0,5 pow $0,2 trn $0,2 add $0,1 dif $0,2
; Mul_and_imul.asm ; Demonstration of the MUL and IMUL instructions ; with 64-bit operands ExitProcess proto WriteHex64 proto Crlf proto .data multiplier qword 10h .code main proc sub rsp,28h ; 64-bit DIV example .data dividend_hi qword 00000108h dividend_lo qword 33300020h divisor qword 00010000h .code mov rdx, dividend_hi mov rax, dividend_lo div divisor ; RAX = 0108000000003330 ; RDX = 0000000000000020 ; IMUL examples mov rax,-4 mov rbx,4 imul rbx ; RAX = -16, RDX = 0FFFFFFFFFFFFFFFF .data multiplicand qword -16 .code imul rax, multiplicand, 4 ; RAX = FFFFFFFFFFFFFFC0 (-64) ; MUL examples mov rax,0AABBBBCCCCDDDDh mul multiplier ; RDX:RAX = 00AABBBBCCCCDDDD0 call Display ; optional mov rax,0FFFF0000FFFF0000h mov rbx,2 mul rbx ; RDX:RAX = 1FFFE0001FFFE0000 call Display ; optional mov ecx,0 ; assign a process return code call ExitProcess ; terminate the program main endp Display proc ; displays RDX:RAX in hexadecimal push rax mov rax,rdx call WriteHex64 pop rax call WriteHex64 call Crlf ret Display endp end
; A025169: a(n) = 2*Fibonacci(2*n+2). ; 2,6,16,42,110,288,754,1974,5168,13530,35422,92736,242786,635622,1664080,4356618,11405774,29860704,78176338,204668310,535828592,1402817466,3672623806,9615053952,25172538050,65902560198,172535142544,451702867434,1182573459758,3096017511840,8105479075762,21220419715446,55555780070576,145446920496282,380784981418270,996908023758528,2609939089857314,6832909245813414,17888788647582928,46833456696935370,122611581443223182,321001287632734176,840392281454979346,2200175556732203862,5760134388741632240,15080227609492692858,39480548439736446334,103361417709716646144,270603704689413492098,708449696358523830150,1854745384386157998352,4855786456799950164906,12712613986013692496366,33282055501241127324192,87133552517709689476210,228118602051887941104438,597222253637954133837104,1563548158861974460406874,4093422222947969247383518,10716718509981933281743680,28056733306997830597847522,73453481411011558511798886,192303710926036844937549136,503457651367098976300848522,1318069243175260083964996430,3450750078158681275594140768,9034180991300783742817425874,23651792895743669952858136854,61921197695930226115756984688,162111800192047008394412817210,424414202880210799067481466942,1111130808448585388808031583616,2908978222465545367356613283906,7615803858948050713261808268102,19938433354378606772428811520400,52199496204187769604024626293098,136660055258184702039645067358894,357780669570366336514910575783584,936681953452914307505086659991858,2452265190788376586000349404191990,6420113618912215450495961552584112,16808075665948269765487535253560346,44004113378932593845966644208096926,115204264470849511772412397370730432,301608680033615941471270547904094370,789621775629998312641399246341552678 mov $2,2 lpb $0 sub $0,1 add $1,$2 add $2,$1 lpe add $1,$2 mov $0,$1
lui $3, 3 ori $2, 10 addu $1, $2, $3 lui $3, 3 ori $2, 10 subu $1, $3, $2 ori $4, 10 ori $5, 10 beq $4, $5 QAQ ori $6, 10 ori $7, 100 QAQ: ori $7, 40 sw $7, 0($7) lw $7, 0($7)
#include <ctime> #include <random> #include <string> #include <unordered_set> #include <iostream> #include <fstream> #include <type_alias.h> #include <types.h> namespace s = std; namespace R = rlgames; // generate perfect hash for each player point combination namespace { std::default_random_engine& get_default_random_engine(){ static std::default_random_engine engine(time(0)); return engine; } } //namespace void generate_file_include(s::fstream& out){ out << "/* This file is auto-generated */\n"; out << "#ifndef RLGAMES_ZOBRIST_HASH\n"; out << "#define RLGAMES_ZOBRIST_HASH\n"; out << "#include <cassert>\n"; out << "\n"; out << "#include <type_alias.h>\n"; out << "#include <types.h>\n"; out << "\n"; out << "namespace rlgames {\n"; out << "\n"; } unsigned get_next_value(s::uniform_int_distribution<unsigned>& dist, s::unordered_set<unsigned>& used){ unsigned value = dist(get_default_random_engine()); while (used.find(value) != used.end()){ value = dist(get_default_random_engine()); } return value; } void generate_hash_table(s::fstream& out){ s::uniform_int_distribution<uint> dist(0x10000000U, 0xFFFFFFFFU); s::unordered_set<uint> used; out << "template <size_t SZ>\n"; out << "uint zobrist_hash(Player player, Pt pt){\n"; out << " assert(player != Player::Unknown);\n"; out << "\n"; out << " uint key = index<SZ>(pt);\n"; out << " key |= (uint)player << 16;\n"; out << " switch (key){\n"; out << std::hex; for (uint i = 0; i < 19 * 19; ++i){ uint value = ((uint)R::Player::Black) << 16U; value |= i; uint hash_value = get_next_value(dist, used); used.insert(hash_value); out << " case 0x" << value << "U: return 0x" << hash_value << "U; break;\n"; } for (uint i = 0; i < 19 * 19; ++i){ uint value = ((uint)R::Player::White) << 16U; value |= i; uint hash_value = get_next_value(dist, used); used.insert(hash_value); out << " case 0x" << value << "U: return 0x" << hash_value << "U; break;\n"; } out << " default: assert(false);\n"; out << " }\n"; out << "}\n"; } void generate_file_suffix(s::fstream& out){ out << "\n"; out << "constexpr uint EMPTY_BOARD = 0U;\n"; out << "\n"; out << "} //rlgames\n"; out << "#endif//RLGAMES_ZOBRIST_HASH\n"; } int main(int argc, char* argv[]){ if (argc != 2){ s::cout << "Usage: " << argv[0] << " <filename>" << s::endl; exit(1); } const char* filename = argv[1]; s::fstream output(filename, s::ios_base::out); generate_file_include(output); generate_hash_table(output); generate_file_suffix(output); output << s::endl; output.close(); }
dc.w word_30F8C-Map_HCZCNZDEZDoor dc.w word_30F9A-Map_HCZCNZDEZDoor dc.w word_30FB4-Map_HCZCNZDEZDoor word_30F8C: dc.w 2 ; DATA XREF: ROM:00030F86o dc.b $E0, $F, 0, 0, $FF, $F0 dc.b 0, $F, 0, 0, $FF, $F0 word_30F9A: dc.w 4 ; DATA XREF: ROM:00030F86o dc.b $E0, 5, 0, 0, $FF, $F8 dc.b $F0, 5, 0, 0, $FF, $F8 dc.b 0, 5, 0, 0, $FF, $F8 dc.b $10, 5, 0, 0, $FF, $F8 word_30FB4: dc.w 4 ; DATA XREF: ROM:00030F86o dc.b $E0, 7, 0, 0, $FF, $F0 dc.b $E0, 7, 8, 0, 0, 0 dc.b 0, 7, 0, 0, $FF, $F0 dc.b 0, 7, 8, 0, 0, 0
; A334573: Partial sums of A334572. ; 1,2,4,6,7,8,11,14,16,17,19,21,22,23,27,31,33,35,37,39,40,41,44,47,49,52,55,57,58,59,64,69,70,71,73,75,76,77,80,83,84,85,87,89,91,92,96,100,102,104,106,108,111,114,117,120,121,122,124,126,127,129,135,141 mov $1,1 lpb $0 mov $2,$0 sub $0,1 seq $2,334572 ; Let x(n, k) be the exponent of prime(k) in the factorization of n, then a(n) = Max_{k} abs(x(n,k)- x(n-1,k)). add $1,$2 lpe mov $0,$1
dnl ARM mpn_addmul_3. dnl Contributed to the GNU project by Torbjörn Granlund. dnl Copyright 2013 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 StrongARM: - C XScale - C ARM11 4.33 C Cortex-A7 3.23 C Cortex-A8 3.19 C Cortex-A9 2.125 C Cortex-A15 2 C TODO C * Use a fast path for n <= KARATSUBA_MUL_THRESHOLD using a jump table, C avoiding the current multiply. C * Start the first multiply or multiplies early. define(`rp',`r0') define(`up',`r1') define(`n', `r2') define(`vp',`r3') define(`v0',`r4') define(`v1',`r5') define(`v2',`r6') define(`u0',`r3') define(`u1',`r14') define(`w0',`r7') define(`w1',`r8') define(`w2',`r9') define(`cy0',`r10') define(`cy1',`r11') define(`cy2',`r12') ASM_START() PROLOGUE(mpn_addmul_3) push { r4-r11, r14 } ldr w0, =0xaaaaaaab C 3^{-1} mod 2^32 ldm vp, { v0,v1,v2 } mov cy0, #0 mov cy1, #0 mov cy2, #0 C Tricky n mod 6 mul w0, w0, n C n * 3^{-1} mod 2^32 and w0, w0, #0xc0000001 C pseudo-CRT mod 3,2 sub n, n, #3 ifdef(`PIC',` add pc, pc, w0, ror $28 nop b L(b0) b L(b2) b L(b4) .word 0xe7f000f0 C udf b L(b3) b L(b5) b L(b1) ',` ldr pc, [pc, w0, ror $28] nop .word L(b0), L(b2), L(b4), 0, L(b3), L(b5), L(b1) ') L(b5): add up, up, #-8 ldr w1, [rp, #0] ldr w2, [rp, #4] ldr u1, [up, #8] b L(lo5) L(b4): add rp, rp, #-4 add up, up, #-12 ldr w2, [rp, #4] ldr w0, [rp, #8] ldr u0, [up, #12] b L(lo4) L(b3): add rp, rp, #-8 add up, up, #-16 ldr w0, [rp, #8] ldr w1, [rp, #12] ldr u1, [up, #16] b L(lo3) L(b1): add rp, rp, #8 ldr w2, [rp, #-8] ldr w0, [rp, #-4] ldr u1, [up, #0] b L(lo1) L(b0): add rp, rp, #4 add up, up, #-4 ldr w0, [rp, #-4] ldr w1, [rp, #0] ldr u0, [up, #4] b L(lo0) L(b2): add rp, rp, #12 add up, up, #4 ldr w1, [rp, #-12] ldr w2, [rp, #-8] ldr u0, [up, #-4] ALIGN(16) L(top): ldr w0, [rp, #-4] umaal w1, cy0, u0, v0 ldr u1, [up, #0] umaal w2, cy1, u0, v1 str w1, [rp, #-12] umaal w0, cy2, u0, v2 L(lo1): ldr w1, [rp, #0] umaal w2, cy0, u1, v0 ldr u0, [up, #4] umaal w0, cy1, u1, v1 str w2, [rp, #-8] umaal w1, cy2, u1, v2 L(lo0): ldr w2, [rp, #4] umaal w0, cy0, u0, v0 ldr u1, [up, #8] umaal w1, cy1, u0, v1 str w0, [rp, #-4] umaal w2, cy2, u0, v2 L(lo5): ldr w0, [rp, #8] umaal w1, cy0, u1, v0 ldr u0, [up, #12] umaal w2, cy1, u1, v1 str w1, [rp, #0] umaal w0, cy2, u1, v2 L(lo4): ldr w1, [rp, #12] umaal w2, cy0, u0, v0 ldr u1, [up, #16] umaal w0, cy1, u0, v1 str w2, [rp, #4] umaal w1, cy2, u0, v2 L(lo3): ldr w2, [rp, #16] umaal w0, cy0, u1, v0 ldr u0, [up, #20] umaal w1, cy1, u1, v1 str w0, [rp, #8] umaal w2, cy2, u1, v2 L(lo2): subs n, n, #6 add up, up, #24 add rp, rp, #24 bge L(top) L(end): umaal w1, cy0, u0, v0 ldr u1, [up, #0] umaal w2, cy1, u0, v1 str w1, [rp, #-12] mov w0, #0 umaal w0, cy2, u0, v2 umaal w2, cy0, u1, v0 umaal w0, cy1, u1, v1 str w2, [rp, #-8] umaal cy1, cy2, u1, v2 adds w0, w0, cy0 str w0, [rp, #-4] adcs w1, cy1, #0 str w1, [rp, #0] adc r0, cy2, #0 pop { r4-r11, pc } EPILOGUE()
// Copyright 2016 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/eh-frame.h" #include "testing/gtest/include/gtest/gtest.h" namespace v8 { namespace internal { // Test enabled only on supported architectures. #if defined(V8_TARGET_ARCH_X64) || defined(V8_TARGET_ARCH_ARM) || \ defined(V8_TARGET_ARCH_ARM64) namespace { class EhFrameIteratorTest : public testing::Test {}; } // namespace TEST_F(EhFrameIteratorTest, Values) { // Assuming little endian. static const byte kEncoded[] = {0xDE, 0xC0, 0xAD, 0xDE, 0xEF, 0xBE, 0xFF}; EhFrameIterator iterator(&kEncoded[0], &kEncoded[0] + sizeof(kEncoded)); EXPECT_EQ(0xDEADC0DE, iterator.GetNextUInt32()); EXPECT_EQ(0xBEEF, iterator.GetNextUInt16()); EXPECT_EQ(0xFF, iterator.GetNextByte()); EXPECT_TRUE(iterator.Done()); } TEST_F(EhFrameIteratorTest, Skip) { static const byte kEncoded[] = {0xDE, 0xAD, 0xC0, 0xDE}; EhFrameIterator iterator(&kEncoded[0], &kEncoded[0] + sizeof(kEncoded)); iterator.Skip(2); EXPECT_EQ(2, iterator.GetCurrentOffset()); EXPECT_EQ(0xC0, iterator.GetNextByte()); iterator.Skip(1); EXPECT_TRUE(iterator.Done()); } TEST_F(EhFrameIteratorTest, ULEB128Decoding) { static const byte kEncoded[] = {0xE5, 0x8E, 0x26}; EhFrameIterator iterator(&kEncoded[0], &kEncoded[0] + sizeof(kEncoded)); EXPECT_EQ(624485u, iterator.GetNextULeb128()); EXPECT_TRUE(iterator.Done()); } TEST_F(EhFrameIteratorTest, SLEB128DecodingPositive) { static const byte kEncoded[] = {0xE5, 0x8E, 0x26}; EhFrameIterator iterator(&kEncoded[0], &kEncoded[0] + sizeof(kEncoded)); EXPECT_EQ(624485, iterator.GetNextSLeb128()); EXPECT_TRUE(iterator.Done()); } TEST_F(EhFrameIteratorTest, SLEB128DecodingNegative) { static const byte kEncoded[] = {0x9B, 0xF1, 0x59}; EhFrameIterator iterator(&kEncoded[0], &kEncoded[0] + sizeof(kEncoded)); EXPECT_EQ(-624485, iterator.GetNextSLeb128()); EXPECT_TRUE(iterator.Done()); } #endif } // namespace internal } // namespace v8
object_const_def ; object_event constants const JUBILIFECITY_DAWNLUCAS_PRES const JUBILIFECITY_LOOKER const JUBILIFECITY_OBJECT2 const JUBILIFECITY_OBJECT3 const JUBILIFECITY_OBJECT4 const JUBILIFECITY_OBJECT5 const JUBILIFECITY_OBJECT6 const JUBILIFECITY_OBJECT7 const JUBILIFECITY_OBJECT8 const JUBILIFECITY_OBJECT9 const JUBILIFECITY_OBJECT10 const JUBILIFECITY_OBJECT11 const JUBILIFECITY_CLOWN_ROWAN const JUBILIFECITY_OBJECT13 const JUBILIFECITY_OBJECT14 JubilifeCity_MapScripts: db 7 ; scene scripts scene_script .Dummy ; SCENE_JUBILIFECITY_FIRST_TIME scene_script .Dummy ; SCENE_JUBILIFECITY_CANT_LEAVE_RIVAL scene_script .Dummy ; SCENE_JUBILIFECITY_START_POKETCH scene_script .Dummy ; SCENE_JUBILIFECITY_CANT_LEAVE_POKETCH scene_script .Dummy ; SCENE_JUBILIFECITY_CANT_LEAVE_GALACTIC scene_script .Dummy ; SCENE_JUBILIFECITY_NO_GLOBAL_TERMINAL scene_script .Dummy ; SCENE_JUBILIFECITY_NOTHING db 2 ; callbacks callback MAPCALLBACK_NEWMAP, .FlyPoint callback MAPCALLBACK_OBJECTS, .Objects .FlyPoint: setflag ENGINE_FLYPOINT_JUBILIFE return .Objects: IF DEF(_DEMO1) checkflag ENGINE_COALBADGE iffalse .SkipDemo moveobject JUBILIFECITY_OBJECT2, 14, 26 .SkipDemo ENDC checkevent EVENT_GALACTIC_IN_JUBILIFE iftrue .MoveGalactic checkevent EVENT_GAVE_PARCEL_TO_RIVAL iffalse .Done moveobject JUBILIFECITY_DAWNLUCAS_PRES, 27, 19 ; reuse for Poketch President .Done: return .MoveGalactic: moveobject JUBILIFECITY_DAWNLUCAS_PRES, 29, 2 moveobject JUBILIFECITY_CLOWN_ROWAN, 28, 3 moveobject JUBILIFECITY_OBJECT13, 27, 2 moveobject JUBILIFECITY_OBJECT14, 27, 3 setmovedata JUBILIFECITY_DAWNLUCAS_PRES, SPRITEMOVEDATA_STANDING_LEFT setmovedata JUBILIFECITY_CLOWN_ROWAN, SPRITEMOVEDATA_STANDING_LEFT setmovedata JUBILIFECITY_OBJECT13, SPRITEMOVEDATA_STANDING_RIGHT setmovedata JUBILIFECITY_OBJECT14, SPRITEMOVEDATA_STANDING_RIGHT return .Dummy: end JubilifeCity_DawnLucasScript1: settableindex 0 sjump JubilifeCity_DawnLucasScript JubilifeCity_DawnLucasScript2: settableindex 1 sjump JubilifeCity_DawnLucasScript JubilifeCity_DawnLucasScript3: settableindex 2 sjump JubilifeCity_DawnLucasScript JubilifeCity_DawnLucasScript4: settableindex 3 JubilifeCity_DawnLucasScript: applymovement JUBILIFECITY_DAWNLUCAS_PRES, .EnterMovement showemote EMOTE_SHOCK, JUBILIFECITY_DAWNLUCAS_PRES, 15 applymovementtable JUBILIFECITY_DAWNLUCAS_PRES, .ApproachPlayerMovement playmusic MUSIC_RIVAL_ENCOUNTER opentext writetextgender .DawnCatchingText, .LucasCatchingText buttonsound readvar VAR_PARTYCOUNT ifless 4, .FewMon writetextgender .DawnManyMonText, .LucasManyMonText sjump .Join .FewMon: writetextgender .DawnFewMonText, .LucasFewMonText .Join: buttonsound writetextgender .DawnLearnMoreText, .LucasLearnMoreText waitbutton closetext moveobject JUBILIFECITY_LOOKER, 30, 21 follow JUBILIFECITY_DAWNLUCAS_PRES, PLAYER applymovementtable JUBILIFECITY_DAWNLUCAS_PRES, .FollowMovement turnobject JUBILIFECITY_LOOKER, DOWN applymovement JUBILIFECITY_DAWNLUCAS_PRES, .FinishFollowMovement opentext writetextgender .DawnThatGuyText, .LucasThatGuyText waitbutton closetext applymovement JUBILIFECITY_LOOKER, .LookerMovement pause 10 applymovement JUBILIFECITY_DAWNLUCAS_PRES, .ToLookerMovement stopfollow applymovement PLAYER, .PlayerToLookerMovement opentext writetextgender .DawnExcuseMeText, .LucasExcuseMeText waitbutton closetext turnobject JUBILIFECITY_LOOKER, DOWN showemote EMOTE_SHOCK, JUBILIFECITY_LOOKER, 15 playmusic MUSIC_MYSTICALMAN_ENCOUNTER opentext writetext .LookerWhatText buttonsound writetext .HowDidYouKnowText buttonsound writetextgender .DawnSmallTalkText, .LucasSmallTalkText buttonsound writetext .KnowBetterText buttonsound writetext .CoverBlownText yesorno iftrue .SaidYes writetext .DontKnowText sjump .YesNoJoin .SaidYes: writetext .StealingIsWrongText .YesNoJoin: buttonsound writetext .ThievesAmongUsText waitbutton ; verbosegiveitem VS_RECORDER ; remove? ; ignore fail case ; writetext .VsRecorderText ; waitbutton closetext turnobject JUBILIFECITY_LOOKER, LEFT pause 10 turnobject JUBILIFECITY_LOOKER, RIGHT pause 10 turnobject JUBILIFECITY_LOOKER, DOWN opentext writetext .HaveARequestText waitbutton closetext applymovement JUBILIFECITY_LOOKER, .LookerExitMovement disappear JUBILIFECITY_LOOKER moveobject JUBILIFECITY_LOOKER, 35, 16 appear JUBILIFECITY_LOOKER special RestartMapMusic opentext writetextgender .DawnSoundsHardText, .LucasSoundsHardText waitbutton closetext applymovement JUBILIFECITY_DAWNLUCAS_PRES, .MoveToSchoolMovement turnobject PLAYER, LEFT opentext writetextgender .DawnSchoolText, .LucasSchoolText waitbutton closetext applymovement PLAYER, .MoveToSchoolMovement turnobject JUBILIFECITY_DAWNLUCAS_PRES, RIGHT opentext writetextgender .DawnYourPalText, .LucasYourPalText waitbutton closetext applymovement JUBILIFECITY_DAWNLUCAS_PRES, .DawnLucasLeaveMovement disappear JUBILIFECITY_DAWNLUCAS_PRES setscene SCENE_JUBILIFECITY_CANT_LEAVE_RIVAL end .DawnCatchingText: text "DAWN: Hi, <PLAYER>!" para "Are you catching" line "#MON?" done .LucasCatchingText: text "LUCAS: Hey," line "<PLAYER>!" para "How many #MON" line "have you caught?" done .DawnManyMonText: text "Wow! You've already" line "got @" text_decimal wScriptVar, 1, 1 text " #MON with" cont "you!" para "At that pace, your" line "#DEX should be" cont "full in no time!" done .LucasManyMonText: text "Whoa! You already" line "have @" text_decimal wScriptVar, 1, 1 text " #MON" cont "with you!" done .DawnFewMonText: text "…Um…" para "I think you'd feel" line "a lot safer if you" cont "were to catch some" cont "more." para "You know, like" line "when you need to" cont "travel to" cont "faraway places." done .LucasFewMonText: text "Huh? I think you" line "should catch some" cont "more." para "It might be more" line "of a challenge" cont "raising a lot of" cont "#MON…" para "But it's worth it." line "The more #MON" cont "you have, the" cont "happier you'll be." done .DawnLearnMoreText: text "Oh, I know! Don't" line "you think it's good" cont "to know more about" cont "#MON?" para "Sure it is! I know" line "just the place." para "Come on! Don't be" line "shy. Follow me!" done .LucasLearnMoreText: text "Hey, that's right!" line "Don't you think it's" cont "better to know a" cont "lot about #MON?" para "Sure it is! There's" line "this great place" cont "for that." para "Come on! It's all" line "right. Follow me." done .DawnThatGuyText: text "DAWN: That man…" line "What is he doing?" done .LucasThatGuyText: text "LUCAS: That guy…" line "What's he doing?" done .DawnExcuseMeText: text "DAWN: Um…" done .LucasExcuseMeText: text "LUCAS: Uh, excuse…" done .LookerWhatText: text "WHAAAT?!" done .HowDidYouKnowText: text "MYSTERIOUS MAN:" line "…How did you know?" para "How did you unmask" line "me as a member of" cont "the INTERNATIONAL" cont "POLICE?!" done .DawnSmallTalkText: text "DAWN: Huh? What? I" line "beg your pardon?" para "I was just making" line "conversation…" done .LucasSmallTalkText: text "LUCAS: Huh? What?" line "Are you kidding?" para "I was just making" line "small talk…" done .KnowBetterText: text "SHADY MAN: …Heh." line "You claim you were" cont "only making conv-" cont "ersation, do you?" para "But, I know better" line "not to believe" cont "that." cont "No, no, no." para "You recognized me" line "right away that I" cont "was someone" cont "extraordinary." para "That is why you" line "spoke to me, no?" para "Your power of" line "observation is" cont "fearsome!" para "Quite admirable," line "you are!" done .CoverBlownText: text "Now that my cover" line "has been blown," cont "let me introduce" cont "myself." para "I am an elite" line "globe-trotting" cont "member of the" cont "INTERNATIONAL" cont "POLICE." para "My name… Ah, no, I" line "shall inform you" cont "only of my code" cont "name." para "My code name, it" line "is LOOKER. It is" cont "what they all call" cont "me." para "Incidentally, is" line "the saying, “Don't" cont "be a thief!”" cont "familiar to you?" done .DontKnowText: text "LOOKER: No? You" line "claim to not know?" para "How could that be?" para "Perhaps your mama" line "has said it, but" cont "you have forgotten" cont "it, like usual?" para "Now listen, my" line "friends. It is" cont "wrong to take what" cont "belongs to others." done .StealingIsWrongText: text "LOOKER: Yes, that" line "is correct." para "Taking that which" line "belongs to others" cont "is wrong." done .ThievesAmongUsText: text "Unfortunately," line "there are some who" cont "do not heed those" cont "words." para "In fact, here in" line "SINNOH, there are" cont "criminals stealing" cont "the #MON of" cont "others." para "I have, therefore," line "been on the look-" cont "out for characters" cont "arousing my sus-" cont "picion." done ; para "Incidentally, you" ; line "are TRAINERS, yes?" ; para "Perhaps you can" ; line "make use of this?" ; done ;.VsRecorderText: ; text "That VS.RECORDER," ; line "is is a nifty dev-" ; cont "ice for recording" ; cont "a match." ; para "I obtained it" ; line "because it is" ; cont "quite popular" ; cont "these days." ; para "But myself, I do" ; line "not do #MON" ; cont "battling often." ; para "It will be in" ; line "better hands with" ; cont "you." ; done .HaveARequestText: text "LOOKER: Also, I" line "have a request." para "If you were to see" line "me again, I ask" cont "that you not talk" cont "to me, for I am on" cont "duty." para "…Actually, yes," line "yes, you may speak" cont "to me. You must." para "Not because I am" line "lonely, no, no!" para "You must inform me" line "of bad guys!" cont "You must inform me" cont "of any happenings!" done .DawnSoundsHardText: text "DAWN: …Working for" line "the INTERNATIONAL" cont "POLICE must be" cont "hard." done .LucasSoundsHardText: text "LUCAS: Working for" line "the INTERNATIONAL" cont "POLICE sounds" cont "hard." done .DawnSchoolText: text "<PLAYER>, here it" line "is. It's the" cont "TRAINER'S SCHOOL." para "The name says" line "it all!" done .LucasSchoolText: text "<PLAYER>, here we" line "are. This is the" cont "TRAINER'S SCHOOL." para "The name says it" line "all!" done .DawnYourPalText: text "I saw your friend" line "<RIVAL> go in" cont "earlier." para "He could still be" line "in there studying." para "OK, bye now!" done .LucasYourPalText: text "Your pal <RIVAL>" line "went in earlier." para "He might still be" line "studying in there." para "OK, see you" line "around!" done .ApproachPlayerMovement: dw .ApproachPlayerMovement1 dw .ApproachPlayerMovement2 dw .ApproachPlayerMovement3 dw .ApproachPlayerMovement4 .FollowMovement: dw .FollowMovement1 dw .FollowMovement2 dw .FollowMovement3 dw .FollowMovement4 .EnterMovement: step DOWN step DOWN step_end .ApproachPlayerMovement1: step DOWN step LEFT step DOWN step_end .ApproachPlayerMovement2: step DOWN step DOWN step_end .ApproachPlayerMovement3: step DOWN step RIGHT step DOWN step_end .ApproachPlayerMovement4: step DOWN step RIGHT step RIGHT step DOWN step_end .FollowMovement1: step UP step RIGHT REPT 10 step UP ENDR step_end .FollowMovement2: REPT 11 step UP ENDR step_end .FollowMovement3: step UP step LEFT REPT 10 step UP ENDR step_end .FollowMovement4: step UP step LEFT step LEFT REPT 10 step UP ENDR step_end .LookerMovement: slow_step LEFT slow_step LEFT step LEFT step DOWN big_step LEFT big_step LEFT fix_facing jump_step RIGHT remove_fixed_facing step_end .PlayerToLookerMovement: step RIGHT .ToLookerMovement: .FinishFollowMovement: step UP step_end .LookerExitMovement: slow_step RIGHT slow_step UP step RIGHT step RIGHT step_sleep 8 big_step UP big_step LEFT big_step UP big_step UP step_end .MoveToSchoolMovement: step DOWN step LEFT step LEFT step_end .DawnLucasLeaveMovement: step DOWN step RIGHT step RIGHT step DOWN step DOWN step DOWN step DOWN step_end JubilifeCity_MapNameSignScript: jumptext .Text .Text: text "JUBILIFE CITY" line "City of Joy" done JubilifeCity_LookerScript: faceplayer checkevent EVENT_GAVE_PARCEL_TO_RIVAL iftrue .Poketch jumptext .SchoolText .Poketch: jumptext .PoketchText .SchoolText: text "Ah, it is you!" para "Have no fear." line "There are no shady" cont "characters about." para "Incidentally, have" line "you visited the" cont "TRAINER'S SCHOOL?" para "Did your friend" line "not guide you" cont "there earlier?" done .PoketchText: text "Ah, it is you!" para "Have no fear." line "There are no shady" cont "characters about." para "Incidentally, have" line "you not obtained" cont "a #TCH?" para "I believe a" line "#TCH is now" cont "free in exchange" cont "for some COUPONS?" done JubilifeCity_GlobalTerminalGuardScript: faceplayer readvar VAR_BADGES ifequal 0, .NoBadges IF DEF(_DEMO1) jumptext .DemoText .DemoText: text "I'm sorry, the" line "GLOBAL TERMINAL is" cont "closed for the" cont "time being." para "Please visit in a" line "later version." done ENDC jumptext .GlobalTerminalText .NoBadges: jumptext .NoBadgesText .GlobalTerminalText: ; change this text text "Past here is the" line "GLOBAL TERMINAL." para "It lets you trade" line "with the whole" cont "world!" para "Trading #MON" line "means connecting" cont "with friends, both" cont "old and new." para "That's awesome!" done .NoBadgesText: ; change this text text "Past here is the" line "GLOBAL TERMINAL," cont "your gateway to" cont "the world!" para "Oh, you don't have" line "any GYM BADGES." para "Sorry, but the" line "GLOBAL TERMINAL is" cont "off-limits if you" cont "don't have a" cont "GYM BADGE." done JubilifeCity_SchoolGuyScript: faceplayer opentext writetext .KnowMuchText yesorno iffalse .SaidNo writetext .KnowledgeableText waitbutton closetext end .SaidNo: writetext .NotKnowledgeableText waitbutton closetext end .KnowMuchText: text "Hello, TRAINER!" para "Do you know much" line "about #MON?" done .KnowledgeableText: text "Ah, I see! You are" line "knowledgeable!" para "I imagine that you" line "wouldn't need to" cont "visit the" cont "TRAINER'S SCHOOL," cont "then." para "But do visit it if" line "you have the time." para "You may discover" line "something new!" done .NotKnowledgeableText: text "Oh, you're not" line "knowledgeable…" para "But not to worry!" line "There's the" cont "TRAINER'S SCHOOL." para "The SCHOOL will" line "teach you the" cont "basics of #MON." done JubilifeCity_TradeKidLScript: jumptextfaceplayer .Text .Text: text "I'm trading #MON" line "with my buddy!" done JubilifeCity_TradeKidRScript: jumptextfaceplayer .Text .Text: text "I made my #MON" line "hold an item" cont "before trading it." para "That will make the" line "other TRAINER" cont "happy!" done JubilifeCity_SixBallsKidScript: jumptextfaceplayer .Text .Text: text "OK, set six" line "# BALLS in my" cont "belt…" para "Yeah, that'll do" line "it. At most, you" cont "can have six" cont "#MON with you." done JubilifeCity_CarvedOutManScript: faceplayer checkflag ENGINE_COALBADGE iftrue .AfterBadge jumptext .CarvedOutText .AfterBadge: jumptext .AfterBadgeText .CarvedOutText: text "JUBILIFE CITY's" line "built on land they" cont "carved out of a" cont "mountain." para "The people and" line "#MON of" cont "OREBURGH CITY" cont "helped out with" cont "that undertaking." done .AfterBadgeText: text "Hello! Let me ask" line "you, have you paid" cont "a visit to the" cont "TV station?" para "If you've never" line "been, you owe it" cont "to yourself to" cont "make the trip." para "And, if you've been" line "there before, it" cont "never hurts to" cont "visit again." para "After all, you can" line "be a star!" para "Or at least dream" line "of being one!" done JubilifeCity_CultureShockGuyScript: jumptextfaceplayer .Text .Text: text "Hiya, where'd you" line "come from?" para "…" para "TWINLEAF TOWN," line "huh…" para "It's a nice place." line "Quiet and all." para "JUBILIFE CITY is a" line "big place, so it" cont "might be a bit of" cont "a shock to you." done JubilifeCity_HappinessLadyScript: jumptextfaceplayer .Text .Text: text "When you walk with" line "your #MON, they" cont "grow friendlier." done JubilifeCity_GroupGuyScript: JubilifeCity_InterviewGirlScript: jumptextfaceplayer .Text .Text: text "Did you see me on" line "TV? I was in an" cont "interview!" done JubilifeCity_Clown1Script: faceplayer checkevent EVENT_GAVE_PARCEL_TO_RIVAL iftrue .DoQuiz jumptext .StickAroundText .DoQuiz: opentext checkevent EVENT_GOT_POKETCH_COUPON_3 iftrue .DoAnswer writetext .QuestionText yesorno iftrue .Correct playsound SFX_WRONG writetext .WrongText waitsfx .Done: waitbutton closetext end .Correct: playsound SFX_ELEVATOR_END writetext .RightText waitsfx buttonsound .DoAnswer: writetext .AnswerText checkevent EVENT_GOT_POKETCH_COUPON_3 iftrue .Done buttonsound writetext .CouponText waitbutton verbosegiveitem COUPON setevent EVENT_GOT_POKETCH_COUPON_3 closetext end .StickAroundText: text "Hi there. You" line "should stick" cont "around." para "We're doing a" line "#TCH campaign" cont "soon." para "Before it starts," line "I think you should" cont "brush up at the" cont "TRAINER'S SCHOOL." done .QuestionText: text "Hi! I'm a #TCH" line "campaign clown!" para "Let's roll out my" line "question!" para "Can a #MON hold" line "an item?" done .WrongText: text "Bzzzzt! That's the" line "wrong answer…" done .RightText: text "Ding-ding! You're" line "absolutely right!" done .AnswerText: text "A #MON may hold" line "a single item." para "Some items become" line "effective as soon" cont "as they are held" cont "by a #MON." para "BERRIES are eaten" line "by #MON as" cont "necessary during" cont "battle." done .CouponText: text "Here you go! Your" line "#TCH COUPON!" done JubilifeCity_Clown2Script: faceplayer opentext checkevent EVENT_GOT_POKETCH_COUPON_1 iftrue .DoAnswer writetext .QuestionText yesorno iftrue .Correct playsound SFX_WRONG writetext .WrongText waitsfx .Done: waitbutton closetext end .Correct: playsound SFX_ELEVATOR_END writetext .RightText waitsfx buttonsound .DoAnswer: writetext .AnswerText checkevent EVENT_GOT_POKETCH_COUPON_1 iftrue .Done buttonsound writetext .CouponText waitbutton verbosegiveitem COUPON setevent EVENT_GOT_POKETCH_COUPON_1 closetext end .QuestionText: text "Hi! I'm a #TCH" line "campaign clown!" para "Let's roll out my" line "question!" para "Does a #MON" line "grow by defeating" cont "others and gaining" cont "EXP. POINTS?" done .WrongText: text "Bzzzzt! That's the" line "wrong answer…" done .RightText: text "Ding-ding! You're" line "absolutely right!" done .AnswerText: text "#MON grow" line "stronger by" cont "defeating other" cont "#MON in battle." para "Some #MON even" line "grow into an" cont "entirely different" cont "form in a process" cont "called evolution." done .CouponText: text "Here you go! Your" line "#TCH COUPON!" done JubilifeCity_Clown3Script: faceplayer opentext checkevent EVENT_GOT_POKETCH_COUPON_2 iftrue .DoAnswer writetext .QuestionText yesorno iftrue .Correct playsound SFX_WRONG writetext .WrongText waitsfx .Done: waitbutton closetext end .Correct: playsound SFX_ELEVATOR_END writetext .RightText waitsfx buttonsound .DoAnswer: writetext .AnswerText checkevent EVENT_GOT_POKETCH_COUPON_2 iftrue .Done buttonsound writetext .CouponText waitbutton verbosegiveitem COUPON setevent EVENT_GOT_POKETCH_COUPON_2 closetext end .QuestionText: text "Hi! I'm a #TCH" line "campaign clown!" para "Let's roll out my" line "question!" para "Just like #MON" line "types, the moves" cont "of #MON also" cont "have types?" done .WrongText: text "Bzzzzt! That's the" line "wrong answer…" done .RightText: text "Ding-ding! You're" line "absolutely right!" done .AnswerText: text "If the #MON's" line "type matches its" cont "move's type, that" cont "move is made much" cont "more powerful!" done .CouponText: text "Here you go! Your" line "#TCH COUPON!" done JubilifeCity_SchoolSignScript: jumptext .Text .Text: text "TRAINER'S SCHOOL" para "The First Step for" line "TRAINERS!" done JubilifeCity_CondoSignScript: jumptext .Text .Text: text "JUBILIFE" line "CONDOMINIUMS" para "Tenants wanted" done JubilifeCity_TVBuildingSignScript: jumptext .Text .Text: text "JUBILIFE TV" para "The Fun-and-Games" line "TV Station!" done JubilifeCity_PoketchBuildingSignScript: jumptext .Text .Text: text "#TCH COMPANY" para "#MON Watches" line "for the World" done JubilifeCity_GlobalTerminalSignScript: jumptext .Text .Text: text "GLOBAL TERMINAL" para "Your Gateway to" line "the Whole World!" done JubilifeCity_PMCSignScript: jumptext .Text .Text: text "Heal your #MON!" line "#MON CENTER" done JubilifeCity_MartSignScript: jumptext .Text .Text: text "All Your Item" line "Needs Fulfilled!" cont "#MON MART" done JubilifeCity_HiddenPotion: hiddenitem POTION, EVENT_JUBILIFE_CITY_HIDDEN_POTION JubilifeCity_GlobalTerminalStopScript: turnobject JUBILIFECITY_OBJECT2, DOWN opentext writetext .CantEnterText waitbutton closetext applymovement PLAYER, .LeaveMovement end .CantEnterText: ; change this text text "Past here is the" line "GLOBAL TERMINAL," cont "your gateway to" cont "the world!" para "Oh, you don't have" line "any GYM BADGES." para "Sorry, but the" line "GLOBAL TERMINAL is" cont "off-limits if you" cont "don't have a" cont "GYM BADGE." done .LeaveMovement: step RIGHT step_end JubilifeCity_CantLeaveRivalScriptU: settableindex 0 sjump JubilifeCity_CantLeaveRivalScript JubilifeCity_CantLeaveRivalScriptD: settableindex 1 JubilifeCity_CantLeaveRivalScript: showemote EMOTE_SHOCK, JUBILIFECITY_LOOKER, 15 turnobject PLAYER, LEFT applymovementtable JUBILIFECITY_LOOKER, .ApproachPlayerMovement opentext writetext .VisitSchoolText waitbutton closetext follow JUBILIFECITY_LOOKER, PLAYER applymovement JUBILIFECITY_LOOKER, .PullBackMovement stopfollow pause 5 applymovementtable JUBILIFECITY_LOOKER, .ReturnMovement end .VisitSchoolText: text "LOOKER: Hello, my" line "friend. Have you" cont "visited the" cont "TRAINER'S SCHOOL?" para "Did your friend" line "not guide you" cont "there earlier?" done .ApproachPlayerMovement: dw .ApproachPlayerMovementU dw .ApproachPlayerMovementD .ReturnMovement: dw .ReturnMovementU dw .ReturnMovementD .ApproachPlayerMovementU: step UP .ApproachPlayerMovementD: step UP step RIGHT step_end .PullBackMovement: step LEFT turn_head RIGHT step_end .ReturnMovementU: step DOWN .ReturnMovementD: step DOWN turn_head UP step_end JubilifeCity_CantLeavePoketchScriptU: settableindex 0 sjump JubilifeCity_CantLeavePoketchScript JubilifeCity_CantLeavePoketchScriptD: settableindex 1 JubilifeCity_CantLeavePoketchScript: showemote EMOTE_SHOCK, JUBILIFECITY_LOOKER, 15 turnobject PLAYER, LEFT applymovementtable JUBILIFECITY_LOOKER, .ApproachPlayerMovement opentext writetext .GetPoketchText waitbutton closetext follow JUBILIFECITY_LOOKER, PLAYER applymovement JUBILIFECITY_LOOKER, .PullBackMovement stopfollow pause 5 applymovementtable JUBILIFECITY_LOOKER, .ReturnMovement end .GetPoketchText: text "LOOKER: Tell me," line "have you not yet" cont "obtained a" cont "#TCH?" para "I believe a" line "#TCH is now" cont "free in exchange" cont "for some COUPONS?" done .ApproachPlayerMovement: dw .ApproachPlayerMovementU dw .ApproachPlayerMovementD .ReturnMovement: dw .ReturnMovementU dw .ReturnMovementD .ApproachPlayerMovementU: step UP .ApproachPlayerMovementD: step UP step RIGHT step_end .PullBackMovement: step LEFT turn_head RIGHT step_end .ReturnMovementU: step DOWN .ReturnMovementD: step DOWN turn_head UP step_end JubilifeCity_StartPoketchScript1: settableindex 0 sjump JubilifeCity_StartPoketchScript JubilifeCity_StartPoketchScript2: settableindex 1 sjump JubilifeCity_StartPoketchScript JubilifeCity_StartPoketchScript3: settableindex 2 sjump JubilifeCity_StartPoketchScript JubilifeCity_StartPoketchScript4: settableindex 3 JubilifeCity_StartPoketchScript: showemote EMOTE_SHOCK, JUBILIFECITY_DAWNLUCAS_PRES, 15 applymovementtable JUBILIFECITY_DAWNLUCAS_PRES, .ApproachPlayerMovement opentext writetext .HaveNoPoketchText buttonsound writetext .IInventedText waitbutton closetext setscene SCENE_JUBILIFECITY_CANT_LEAVE_POKETCH end .HaveNoPoketchText: text "Oh, oh, oh?" para "You call yourself" line "a #MON TRAINER?" para "And yet you have" line "no #TCH?" para "That is," line "#MON WATCH, or" cont "#TCH for short!" para "Oh my, you are a" line "rare case indeed!" done .IInventedText: text "You see, I" line "invented, and now" cont "manufacture," cont "#TCHES." para "Not only that, I'm" line "now conducting the" cont "#TCH promo" cont "campaign!" para "All you have to do" line "is find three" cont "clowins in" cont "JUBILIFE CITY." para "If you can find" line "them…" para "I will gift you a" line "#TCH!" done .ApproachPlayerMovement: dw .ApproachPlayerMovement1 dw .ApproachPlayerMovement2 dw .ApproachPlayerMovement3 dw .ApproachPlayerMovement4 .ApproachPlayerMovement1: step LEFT .ApproachPlayerMovement2: step DOWN step_end .ApproachPlayerMovement4: step RIGHT .ApproachPlayerMovement3: step RIGHT step DOWN step_end JubilifeCity_PresScript: faceplayer checkevent EVENT_GOT_POKETCH_COUPON_1 iffalse .Intro checkevent EVENT_GOT_POKETCH_COUPON_2 iffalse .Intro checkevent EVENT_GOT_POKETCH_COUPON_3 iffalse .Intro opentext writetext .CountText buttonsound takeitem COUPON takeitem COUPON takeitem COUPON writetext .GotPoketchText playsound SFX_ITEM waitsfx setflag ENGINE_POKEGEAR setflag ENGINE_MAP_CARD writetext .AddAppsText waitbutton closetext callstd tableindexfromfacing applymovementtable JUBILIFECITY_DAWNLUCAS_PRES, .LeaveMovement disappear JUBILIFECITY_DAWNLUCAS_PRES setevent EVENT_GOT_POKETCH disappear JUBILIFECITY_LOOKER setscene SCENE_JUBILIFECITY_NO_GLOBAL_TERMINAL clearflag EVENT_POKETCH_COMPANY_1F_PRESIDENT end .Intro: jumptext .IntroText .CountText: text "OK, let me count" line "your COUPONS!" para "I'll use the" line "#TCH here…" para "One, two, three!" line "Bravo! I say," cont "bravo!" para "In return for" line "these COUPONS, I" cont "present you this" cont "#MON WATCH, or" cont "#TCH for short!" done .GotPoketchText: text "<PLAYER> received" line "a #TCH!" done .AddAppsText: ; change this? text "You can add apps" line "to your #TCH to" cont "make it even more" cont "versatile!" para "Touch the #TCH" line "screen and find" cont "the apps that are" cont "right for you!" done .LeaveMovement: dw .LeaveMovement2 dw .LeaveMovement1 dw .LeaveMovement1 dw .LeaveMovement1 .LeaveMovement2: step LEFT step UP .LeaveMovement1: step UP step UP step UP step UP step UP step_end .IntroText: text "The three clowns" line "will each ask you" cont "a skill-testing" cont "question." para "The questions all" line "have to do with" cont "#MON." para "After all, a" line "#TCH is a tool" cont "for #MON" cont "TRAINERS." para "Collect a COUPON" line "from each clown," cont "then come see me," cont "OK?" done JubilifeCity_GalacticScript1: settableindex 0 sjump JubilifeCity_GalacticScript JubilifeCity_GalacticScript2: settableindex 1 sjump JubilifeCity_GalacticScript JubilifeCity_GalacticScript3: settableindex 2 sjump JubilifeCity_GalacticScript JubilifeCity_GalacticScript4: settableindex 3 JubilifeCity_GalacticScript: opentext writetext .NowNowNowText waitbutton closetext turnobject JUBILIFECITY_CLOWN_ROWAN, DOWN showemote EMOTE_SHOCK, JUBILIFECITY_CLOWN_ROWAN, 15 applymovementtable PLAYER, .ApproachMovement opentext writetext .RowanHelloText waitbutton writetext .DifficultText waitbutton turnobject JUBILIFECITY_CLOWN_ROWAN, LEFT writetext .NuisanceText waitbutton turnobject JUBILIFECITY_CLOWN_ROWAN, DOWN writetext .AdultsText waitbutton writetext .PersonalText waitbutton writetext .CivilityText waitbutton turnobject JUBILIFECITY_DAWNLUCAS_PRES, DOWN writetextgender .DawnBattleText, .LucasBattleText waitbutton closetext applymovement JUBILIFECITY_DAWNLUCAS_PRES, .DawnLucasToGruntMovement applymovement PLAYER, .PlayerToGruntMovement winlosstext .WinText, 0 loadtrainer GRUNTM, GRUNTM1 startbattle reloadmapafterbattle opentext writetext .RetreatText waitbutton closetext follow JUBILIFECITY_OBJECT13, JUBILIFECITY_OBJECT14 applymovement JUBILIFECITY_OBJECT13, .RetreatMovement stopfollow disappear JUBILIFECITY_OBJECT13 disappear JUBILIFECITY_OBJECT14 turnobject JUBILIFECITY_CLOWN_ROWAN, DOWN applymovement JUBILIFECITY_DAWNLUCAS_PRES, .ToPlayerMovement opentext writetext .TeamGalacticText waitbutton writetextgender .DawnEvolutionText, .LucasEvolutionText waitbutton writetext .AllOverText waitbutton closetext turnobject PLAYER, DOWN follow JUBILIFECITY_CLOWN_ROWAN, JUBILIFECITY_DAWNLUCAS_PRES applymovement JUBILIFECITY_CLOWN_ROWAN, .RowanLeaveMovement stopfollow disappear JUBILIFECITY_DAWNLUCAS_PRES disappear JUBILIFECITY_CLOWN_ROWAN setscene SCENE_JUBILIFECITY_NOTHING clearevent EVENT_GALACTIC_IN_JUBILIFE end .NowNowNowText: text "MYSTERY MAN: Now," line "now, now, now!" para "PROFESSOR ROWAN," line "you must comply." para "Hand over all your" line "research findings." para "For free," line "naturally." para "Failure to comply" line "will result in a" cont "painful time for" cont "your assistant." done .RowanHelloText: text "ROWAN: Ah," line "<PLAYER>." para "Well?" line "How is the #DEX" cont "progressing?" para "Hm! That's" line "OREBURGH's GYM" cont "BADGE, I see." para "But hadn't I given" line "you your first" cont "#MON only" cont "recently…?" para "Perhaps being a" line "TRAINER is like" cont "second nature to" cont "you." done .DifficultText: text "MYSTERY MAN: Oh," line "PROFESSOR of" cont "#MON, must you" cont "be so difficult?" para "We are speaking to" line "you on business." para "Because this is" line "work for us." para "What we're saying" line "is… we demand you" cont "comply with our" cont "demands." done .NuisanceText: text "ROWAN: Quiet, you" line "lot! Why must you" cont "be a nuisance?" para "Let me list some" line "lessons you still" cont "need to learn." para "1: Don't loiter" line "about for no good" cont "reason." para "2: Don't interrupt" line "others while they" cont "are attempting to" cont "converse." para "3: If you don't get" line "your way, don't" cont "raise your voice." para "4: Don't think that" line "you've grown strong" cont "just because you're" cont "in a group." para "5: What is with" line "those outlandish" cont "outfits you have" cont "on?" done .AdultsText: text "My goodness… You" line "call yourselves" cont "adults?" para "You kids, don't" line "grow up to be like" cont "these sorry" cont "specimens." done .PersonalText: text "MYSTERY MAN: Eeeh!" para "You had to make" line "this personal!" para "You have forced" line "our hand into" cont "making a show of" cont "force!" para "We will make you" line "regret insulting" cont "TEAM GALACTIC!" done .CivilityText: text "ROWAN: You kids," line "give these thugs a" cont "lesson in" cont "civility, please." done .DawnBattleText: text "DAWN: <PLAYER>!" line "Let's battle them!" done .LucasBattleText: text "LUCAS: <PLAYER>!" line "Join me and battle" cont "these guys!" done .WinText: text "How is this" line "madness possible?" para "Losing to kids?" line "This won't do…" para "Time to retreat." done .RetreatText: text "GRUNT 1: You leave" line "us no option. We" cont "will retreat for" cont "now." para "We shall do so" line "because TEAM" cont "GALACTIC is" cont "benevolent to all." done .TeamGalacticText: text "ROWAN: That lot…" line "They called" cont "themselves" cont "TEAM GALACTIC." para "When #MON" line "evolve, they seem" cont "to release some" cont "type of energy…" para "However, I believe" line "that it's a mystic" cont "power far beyond" cont "our control." para "But TEAM GALACTIC" line "seems to be" cont "studying that" cont "power's potential." para "They want to know" line "if it can be used" cont "as energy for" cont "something…" done .DawnEvolutionText: text "DAWN: <PLAYER>, did" line "you know?" para "The PROFESSOR" line "studies the" cont "evolution of" cont "#MON, too." para "According to his" line "research, 90" cont "percent of all" cont "#MON are" cont "somehow tied to" cont "evolution." para "Well, maybe that's" line "the reason those" cont "people tried to" cont "take PROF.ROWAN's" cont "research data by" cont "force." para "That's really" line "unforgivable!" done .LucasEvolutionText: text "LUCAS: <PLAYER>," line "did you know about" cont "this?" para "The PROFESSOR also" line "studies the" cont "evolution of" cont "#MON." para "According to his" line "research, 90" cont "percent of all" cont "#MON are" cont "somehow tied to" cont "evolution!" para "Maybe that's the" line "reason those goons" cont "tried to take the" cont "PROFESSOR's" cont "research data." para "They're not allowed" line "to do that!" done .AllOverText: text "ROWAN: It's all" line "over, so you can" cont "relax now." para "Still, thanks to" line "you two, nothing" cont "came of that" cont "situation." cont "I appreciate that." para "Incidentally," line "<PLAYER>." cont "Kudos to you for" cont "your battling" cont "skill." para "It got me" line "thinking. Why don't" cont "you collect all" cont "the GYM BADGES of" cont "SINNOH?" para "Doing so, you will" line "be sure to" cont "encounter lots of" cont "#MON." para "That, of course," line "means your #DEX" cont "pages will fill" cont "up continuously." para "In other words, it" line "will be of great" cont "help to my" cont "research." para "That said, I've" line "given you your" cont "first #MON and" cont "#DEX as yours" cont "to keep." para "You're free to do" line "with them as you" cont "wish." para "Take care now." done .ApproachMovement: dw .ApproachMovement1 dw .ApproachMovement2 dw .ApproachMovement3 dw .ApproachMovement4 .ApproachMovement1: step RIGHT .ApproachMovement2: step RIGHT .ApproachMovement3: step UP step_end .ApproachMovement4: step LEFT step UP step_end .DawnLucasToGruntMovement: step LEFT step_end .PlayerToGruntMovement: step LEFT turn_head UP step_end .RetreatMovement: step UP step UP step UP step UP step_end .ToPlayerMovement: step LEFT step DOWN step_end .RowanLeaveMovement: step DOWN step DOWN step DOWN step DOWN step DOWN step DOWN step DOWN step_end JubilifeCity_TypeKidScript: faceplayer opentext writetext .WhichTypeText loadmenu .MenuHeader verticalmenu closewindow ifequal 1, .Fire ifequal 2, .Water ; Grass writetext .GrassText waitbutton closetext end .Fire: writetext .FireText waitbutton closetext end .Water: writetext .WaterText waitbutton closetext end .MenuHeader: db MENU_BACKUP_TILES ; flags menu_coords 12, 4, 19, 11 dw .MenuData db 1 ; default option .MenuData: db STATICMENU_DISABLE_B | STATICMENU_CURSOR ; flags db 3 ; items db "FIRE@" db "WATER@" db "GRASS@" .WhichTypeText: text "The way you look…" para "You're obviously a" line "TRAINER!" para "Can you tell me" line "what type of" cont "#MON you like?" done .GrassText: text "You chose the" line "GRASS type?" para "No wonder you look" line "so calm." para "I think you need" line "to watch out you" cont "don't get burned" cont "by fire." done .FireText: text "The FIRE type?" para "You must have a" line "fiery personality." para "You'd better watch" line "out that fire isn't" cont "doused by water," cont "though." done .WaterText: text "A person that" line "likes the WATER" cont "type must be" cont "somewhat cool." para "But beware of" line "being drained by" cont "thirsty grass." done JubilifeCity_MapEvents: db 0, 0 ; filler db 12 ; warp events warp_event 33, 13, JUBILIFE_APARTMENT_NE_1F, 2 warp_event 23, 31, JUBILIFE_APARTMENT_SE_1F, 2 warp_event 9, 29, JUBILIFE_APARTMENT_SW_1F, 2 warp_event 31, 25, JUBILIFE_POKEMON_CENTER_1F, 1 warp_event 31, 19, JUBILIFE_POKEMART, 2 warp_event 11, 11, POKETCH_COMPANY_1F, 1 warp_event 14, 11, POKETCH_COMPANY_1F, 3 warp_event 22, 11, TV_STATION_1F, 1 warp_event 14, 25, POKEMON_COMMUNICATION_CENTER, 1 warp_event 20, 23, TRAINERS_SCHOOL, 1 warp_event 2, 14, JUBILIFE_WEST_GATE, 1 warp_event 2, 15, JUBILIFE_WEST_GATE, 2 db 20 ; coord events coord_event 26, 37, SCENE_JUBILIFECITY_FIRST_TIME, JubilifeCity_DawnLucasScript1 coord_event 27, 37, SCENE_JUBILIFECITY_FIRST_TIME, JubilifeCity_DawnLucasScript2 coord_event 28, 37, SCENE_JUBILIFECITY_FIRST_TIME, JubilifeCity_DawnLucasScript3 coord_event 29, 37, SCENE_JUBILIFECITY_FIRST_TIME, JubilifeCity_DawnLucasScript4 coord_event 37, 14, SCENE_JUBILIFECITY_CANT_LEAVE_RIVAL, JubilifeCity_CantLeaveRivalScriptU coord_event 37, 15, SCENE_JUBILIFECITY_CANT_LEAVE_RIVAL, JubilifeCity_CantLeaveRivalScriptD coord_event 17, 27, SCENE_JUBILIFECITY_CANT_LEAVE_RIVAL, JubilifeCity_GlobalTerminalStopScript coord_event 26, 21, SCENE_JUBILIFECITY_START_POKETCH, JubilifeCity_StartPoketchScript1 coord_event 27, 21, SCENE_JUBILIFECITY_START_POKETCH, JubilifeCity_StartPoketchScript2 coord_event 28, 21, SCENE_JUBILIFECITY_START_POKETCH, JubilifeCity_StartPoketchScript3 coord_event 29, 21, SCENE_JUBILIFECITY_START_POKETCH, JubilifeCity_StartPoketchScript4 coord_event 17, 27, SCENE_JUBILIFECITY_START_POKETCH, JubilifeCity_GlobalTerminalStopScript coord_event 37, 14, SCENE_JUBILIFECITY_CANT_LEAVE_POKETCH, JubilifeCity_CantLeavePoketchScriptU coord_event 37, 15, SCENE_JUBILIFECITY_CANT_LEAVE_POKETCH, JubilifeCity_CantLeavePoketchScriptD coord_event 17, 27, SCENE_JUBILIFECITY_CANT_LEAVE_POKETCH, JubilifeCity_GlobalTerminalStopScript coord_event 17, 27, SCENE_JUBILIFECITY_NO_GLOBAL_TERMINAL, JubilifeCity_GlobalTerminalStopScript coord_event 26, 5, SCENE_JUBILIFECITY_CANT_LEAVE_GALACTIC, JubilifeCity_GalacticScript1 coord_event 27, 5, SCENE_JUBILIFECITY_CANT_LEAVE_GALACTIC, JubilifeCity_GalacticScript2 coord_event 28, 5, SCENE_JUBILIFECITY_CANT_LEAVE_GALACTIC, JubilifeCity_GalacticScript3 coord_event 29, 5, SCENE_JUBILIFECITY_CANT_LEAVE_GALACTIC, JubilifeCity_GalacticScript4 db 12 ; bg events bg_event 31, 31, BGEVENT_READ, JubilifeCity_MapNameSignScript bg_event 36, 13, BGEVENT_READ, JubilifeCity_MapNameSignScript bg_event 30, 8, BGEVENT_READ, JubilifeCity_MapNameSignScript bg_event 5, 13, BGEVENT_READ, JubilifeCity_MapNameSignScript bg_event 24, 22, BGEVENT_READ, JubilifeCity_SchoolSignScript bg_event 30, 12, BGEVENT_READ, JubilifeCity_CondoSignScript bg_event 24, 12, BGEVENT_READ, JubilifeCity_TVBuildingSignScript bg_event 10, 12, BGEVENT_READ, JubilifeCity_PoketchBuildingSignScript bg_event 13, 27, BGEVENT_READ, JubilifeCity_GlobalTerminalSignScript bg_event 32, 25, BGEVENT_READ, JubilifeCity_PMCSignScript bg_event 32, 19, BGEVENT_READ, JubilifeCity_MartSignScript bg_event 11, 16, BGEVENT_ITEM, JubilifeCity_HiddenPotion db 15 ; object events object_event 27, 32, SPRITE_DAWN_LUCAS2, SPRITEMOVEDATA_STANDING_DOWN, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, JubilifeCity_PresScript, EVENT_JUBILIFE_CITY_DAWNLUCAS object_event 35, 16, SPRITE_GENTLEMAN, SPRITEMOVEDATA_STANDING_UP, 0, 0, -1, -1, PAL_NPC_BROWN, OBJECTTYPE_SCRIPT, 0, JubilifeCity_LookerScript, EVENT_JUBILIFE_CITY_LOOKER object_event 17, 26, SPRITE_COOLTRAINER_M, SPRITEMOVEDATA_SPINRANDOM_SLOW, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, JubilifeCity_GlobalTerminalGuardScript, -1 object_event 21, 26, SPRITE_GRAMPS, SPRITEMOVEDATA_SPINRANDOM_SLOW, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, JubilifeCity_SchoolGuyScript, -1 object_event 31, 28, SPRITE_GAMEBOY_KID, SPRITEMOVEDATA_STANDING_RIGHT, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, JubilifeCity_TradeKidLScript, -1 object_event 32, 28, SPRITE_GAMEBOY_KID, SPRITEMOVEDATA_STANDING_LEFT, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, JubilifeCity_TradeKidRScript, -1 object_event 29, 17, SPRITE_YOUNGSTER, SPRITEMOVEDATA_WALK_UP_DOWN, 0, 1, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, JubilifeCity_SixBallsKidScript, -1 object_event 24, 18, SPRITE_GRAMPS, SPRITEMOVEDATA_SPINRANDOM_SLOW, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, JubilifeCity_CarvedOutManScript, -1 object_event 28, 12, SPRITE_COOLTRAINER_M, SPRITEMOVEDATA_WANDER, 1, 1, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, JubilifeCity_CultureShockGuyScript, -1 object_event 13, 15, SPRITE_COOLTRAINER_F, SPRITEMOVEDATA_WALK_LEFT_RIGHT, 1, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, JubilifeCity_HappinessLadyScript, -1 ; object_event 22, 16, SPRITE_COOLTRAINER_M, SPRITEMOVEDATA_SPINRANDOM_SLOW, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, JubilifeCity_GroupGuyScript, -1 object_event 13, 31, SPRITE_YOUNGSTER, SPRITEMOVEDATA_SPINRANDOM_SLOW, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, JubilifeCity_TypeKidScript, -1 object_event 19, 13, SPRITE_TWIN, SPRITEMOVEDATA_WALK_LEFT_RIGHT, 1, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, JubilifeCity_InterviewGirlScript, -1 object_event 22, 12, SPRITE_CLOWN_ROWAN, SPRITEMOVEDATA_SPINRANDOM_SLOW, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, JubilifeCity_Clown1Script, EVENT_JUBILIFE_CITY_CLOWN1 object_event 33, 20, SPRITE_CLOWN_GALACTIC, SPRITEMOVEDATA_SPINRANDOM_SLOW, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, JubilifeCity_Clown2Script, EVENT_JUBILIFE_CITY_CLOWNS object_event 9, 13, SPRITE_CLOWN_GALACTIC, SPRITEMOVEDATA_SPINRANDOM_SLOW, 0, 0, -1, -1, 0, OBJECTTYPE_SCRIPT, 0, JubilifeCity_Clown3Script, EVENT_JUBILIFE_CITY_CLOWNS
//$Id: ParameterFactory.hpp 9513 2011-04-30 21:23:06Z djcinsb $ //------------------------------------------------------------------------------ // ParameterFactory //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002-2011 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other Rights Reserved. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number S-67573-G // // Author: Darrel Conway // Created: 2003/10/28 // /** * This class is the factory class for parameters. */ //------------------------------------------------------------------------------ #ifndef ParameterFactory_hpp #define ParameterFactory_hpp #include "gmatdefs.hpp" #include "Factory.hpp" #include "Parameter.hpp" class GMAT_API ParameterFactory : public Factory { public: Parameter* CreateParameter(const std::string &ofType, const std::string &withName = ""); // default constructor ParameterFactory(); // constructor ParameterFactory(StringArray createList); // copy constructor ParameterFactory(const ParameterFactory &fact); // assignment operator ParameterFactory& operator= (const ParameterFactory &fact); // destructor ~ParameterFactory(); protected: // protected data private: // private data }; #endif // ParameterFactory_hpp
; Like MODE BW80, but faster. _TEXT segment para public 'CODE' org 0100h assume cs:_TEXT,ds:_TEXT,ss:_TEXT _start proc near mov ax,2 int 10h mov ax,4c00h int 21h _start endp _TEXT ends end _start
; A327938: Multiplicative with a(p^e) = p^(e mod p). ; 1,2,3,1,5,6,7,2,9,10,11,3,13,14,15,1,17,18,19,5,21,22,23,6,25,26,1,7,29,30,31,2,33,34,35,9,37,38,39,10,41,42,43,11,45,46,47,3,49,50,51,13,53,2,55,14,57,58,59,15,61,62,63,1,65,66,67,17,69,70,71,18,73,74,75,19,77,78,79,5,3,82,83,21,85,86,87,22,89,90,91,23,93,94,95,6,97,98,99,25 mov $1,$0 seq $1,327939 ; Multiplicative with a(p^e) = p^(e-(e mod p)). div $0,$1 add $0,1
include ksamd64.inc EXTERNDEF ?Te@rdtable@CryptoPP@@3PA_KA:FAR EXTERNDEF ?g_cacheLineSize@CryptoPP@@3IA:FAR EXTERNDEF ?SHA256_K@CryptoPP@@3QBIB:FAR .CODE ALIGN 8 Baseline_Add PROC lea rdx, [rdx+8*rcx] lea r8, [r8+8*rcx] lea r9, [r9+8*rcx] neg rcx ; rcx is negative index jz $1@Baseline_Add mov rax,[r8+8*rcx] add rax,[r9+8*rcx] mov [rdx+8*rcx],rax $0@Baseline_Add: mov rax,[r8+8*rcx+8] adc rax,[r9+8*rcx+8] mov [rdx+8*rcx+8],rax lea rcx,[rcx+2] ; advance index, avoid inc which causes slowdown on Intel Core 2 jrcxz $1@Baseline_Add ; loop until rcx overflows and becomes zero mov rax,[r8+8*rcx] adc rax,[r9+8*rcx] mov [rdx+8*rcx],rax jmp $0@Baseline_Add $1@Baseline_Add: mov rax, 0 adc rax, rax ; store carry into rax (return result register) ret Baseline_Add ENDP ALIGN 8 Baseline_Sub PROC lea rdx, [rdx+8*rcx] lea r8, [r8+8*rcx] lea r9, [r9+8*rcx] neg rcx ; rcx is negative index jz $1@Baseline_Sub mov rax,[r8+8*rcx] sub rax,[r9+8*rcx] mov [rdx+8*rcx],rax $0@Baseline_Sub: mov rax,[r8+8*rcx+8] sbb rax,[r9+8*rcx+8] mov [rdx+8*rcx+8],rax lea rcx,[rcx+2] ; advance index, avoid inc which causes slowdown on Intel Core 2 jrcxz $1@Baseline_Sub ; loop until rcx overflows and becomes zero mov rax,[r8+8*rcx] sbb rax,[r9+8*rcx] mov [rdx+8*rcx],rax jmp $0@Baseline_Sub $1@Baseline_Sub: mov rax, 0 adc rax, rax ; store carry into rax (return result register) ret Baseline_Sub ENDP ALIGN 8 Rijndael_Enc_AdvancedProcessBlocks PROC FRAME rex_push_reg rsi push_reg rdi push_reg rbx push_reg r12 .endprolog mov r8, rcx mov r11, ?Te@rdtable@CryptoPP@@3PA_KA mov edi, DWORD PTR [?g_cacheLineSize@CryptoPP@@3IA] mov rsi, [(r8+16*19)] mov rax, 16 and rax, rsi movdqa xmm3, XMMWORD PTR [rdx+16+rax] movdqa [(r8+16*12)], xmm3 lea rax, [rdx+rax+2*16] sub rax, rsi label0: movdqa xmm0, [rax+rsi] movdqa XMMWORD PTR [(r8+0)+rsi], xmm0 add rsi, 16 cmp rsi, 16*12 jl label0 movdqa xmm4, [rax+rsi] movdqa xmm1, [rdx] mov r12d, [rdx+4*4] mov ebx, [rdx+5*4] mov ecx, [rdx+6*4] mov edx, [rdx+7*4] xor rax, rax label9: mov esi, [r11+rax] add rax, rdi mov esi, [r11+rax] add rax, rdi mov esi, [r11+rax] add rax, rdi mov esi, [r11+rax] add rax, rdi cmp rax, 2048 jl label9 lfence test DWORD PTR [(r8+16*18+8)], 1 jz label8 mov rsi, [(r8+16*14)] movdqu xmm2, [rsi] pxor xmm2, xmm1 psrldq xmm1, 14 movd eax, xmm1 mov al, BYTE PTR [rsi+15] mov r10d, eax movd eax, xmm2 psrldq xmm2, 4 movd edi, xmm2 psrldq xmm2, 4 movzx esi, al xor r12d, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] movzx esi, ah xor edx, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] shr eax, 16 movzx esi, al xor ecx, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] movzx esi, ah xor ebx, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] mov eax, edi movd edi, xmm2 psrldq xmm2, 4 movzx esi, al xor ebx, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] movzx esi, ah xor r12d, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] shr eax, 16 movzx esi, al xor edx, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] movzx esi, ah xor ecx, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] mov eax, edi movd edi, xmm2 movzx esi, al xor ecx, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] movzx esi, ah xor ebx, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] shr eax, 16 movzx esi, al xor r12d, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] movzx esi, ah xor edx, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] mov eax, edi movzx esi, al xor edx, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] movzx esi, ah xor ecx, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] shr eax, 16 movzx esi, al xor ebx, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] psrldq xmm2, 3 mov eax, [(r8+16*12)+0*4] mov edi, [(r8+16*12)+2*4] mov r9d, [(r8+16*12)+3*4] movzx esi, cl xor r9d, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] movzx esi, bl xor edi, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] movzx esi, bh xor r9d, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] shr ebx, 16 movzx esi, bl xor eax, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] movzx esi, bh mov ebx, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] xor ebx, [(r8+16*12)+1*4] movzx esi, ch xor eax, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] shr ecx, 16 movzx esi, dl xor eax, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] movzx esi, dh xor ebx, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] shr edx, 16 movzx esi, ch xor edi, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] movzx esi, cl xor ebx, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] movzx esi, dl xor edi, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] movzx esi, dh xor r9d, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] movd ecx, xmm2 mov edx, r12d mov [(r8+0)+3*4], r9d mov [(r8+0)+0*4], eax mov [(r8+0)+1*4], ebx mov [(r8+0)+2*4], edi jmp label5 label3: mov r12d, [(r8+16*12)+0*4] mov ebx, [(r8+16*12)+1*4] mov ecx, [(r8+16*12)+2*4] mov edx, [(r8+16*12)+3*4] label8: mov rax, [(r8+16*14)] movdqu xmm2, [rax] mov rsi, [(r8+16*14)+8] movdqu xmm5, [rsi] pxor xmm2, xmm1 pxor xmm2, xmm5 movd eax, xmm2 psrldq xmm2, 4 movd edi, xmm2 psrldq xmm2, 4 movzx esi, al xor r12d, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] movzx esi, ah xor edx, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] shr eax, 16 movzx esi, al xor ecx, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] movzx esi, ah xor ebx, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] mov eax, edi movd edi, xmm2 psrldq xmm2, 4 movzx esi, al xor ebx, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] movzx esi, ah xor r12d, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] shr eax, 16 movzx esi, al xor edx, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] movzx esi, ah xor ecx, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] mov eax, edi movd edi, xmm2 movzx esi, al xor ecx, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] movzx esi, ah xor ebx, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] shr eax, 16 movzx esi, al xor r12d, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] movzx esi, ah xor edx, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] mov eax, edi movzx esi, al xor edx, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] movzx esi, ah xor ecx, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] shr eax, 16 movzx esi, al xor ebx, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] movzx esi, ah xor r12d, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] mov eax, r12d add r8, [(r8+16*19)] add r8, 4*16 jmp label2 label1: mov ecx, r10d mov edx, r12d mov eax, [(r8+0)+0*4] mov ebx, [(r8+0)+1*4] xor cl, ch and rcx, 255 label5: add r10d, 1 xor edx, DWORD PTR [r11+rcx*8+3] movzx esi, dl xor ebx, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] movzx esi, dh mov ecx, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] shr edx, 16 xor ecx, [(r8+0)+2*4] movzx esi, dh xor eax, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] movzx esi, dl mov edx, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] xor edx, [(r8+0)+3*4] add r8, [(r8+16*19)] add r8, 3*16 jmp label4 label2: mov r9d, [(r8+0)-4*16+3*4] mov edi, [(r8+0)-4*16+2*4] movzx esi, cl xor r9d, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] mov cl, al movzx esi, ah xor edi, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] shr eax, 16 movzx esi, bl xor edi, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] movzx esi, bh xor r9d, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] shr ebx, 16 movzx esi, al xor r9d, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] movzx esi, ah mov eax, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] movzx esi, bl xor eax, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] movzx esi, bh mov ebx, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] movzx esi, ch xor eax, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] movzx esi, cl xor ebx, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] shr ecx, 16 movzx esi, dl xor eax, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] movzx esi, dh xor ebx, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] shr edx, 16 movzx esi, ch xor edi, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] movzx esi, cl xor ebx, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] movzx esi, dl xor edi, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] movzx esi, dh xor r9d, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] mov ecx, edi xor eax, [(r8+0)-4*16+0*4] xor ebx, [(r8+0)-4*16+1*4] mov edx, r9d label4: mov r9d, [(r8+0)-4*16+7*4] mov edi, [(r8+0)-4*16+6*4] movzx esi, cl xor r9d, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] mov cl, al movzx esi, ah xor edi, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] shr eax, 16 movzx esi, bl xor edi, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] movzx esi, bh xor r9d, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] shr ebx, 16 movzx esi, al xor r9d, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] movzx esi, ah mov eax, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] movzx esi, bl xor eax, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] movzx esi, bh mov ebx, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] movzx esi, ch xor eax, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] movzx esi, cl xor ebx, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] shr ecx, 16 movzx esi, dl xor eax, DWORD PTR [r11+8*rsi+(((3+3) MOD (4))+1)] movzx esi, dh xor ebx, DWORD PTR [r11+8*rsi+(((2+3) MOD (4))+1)] shr edx, 16 movzx esi, ch xor edi, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] movzx esi, cl xor ebx, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] movzx esi, dl xor edi, DWORD PTR [r11+8*rsi+(((1+3) MOD (4))+1)] movzx esi, dh xor r9d, DWORD PTR [r11+8*rsi+(((0+3) MOD (4))+1)] mov ecx, edi xor eax, [(r8+0)-4*16+4*4] xor ebx, [(r8+0)-4*16+5*4] mov edx, r9d add r8, 32 test r8, 255 jnz label2 sub r8, 16*16 movzx esi, ch movzx edi, BYTE PTR [r11+rsi*8+1] movzx esi, dl xor edi, DWORD PTR [r11+rsi*8+0] mov WORD PTR [(r8+16*13)+2], di movzx esi, dh movzx edi, BYTE PTR [r11+rsi*8+1] movzx esi, al xor edi, DWORD PTR [r11+rsi*8+0] mov WORD PTR [(r8+16*13)+6], di shr edx, 16 movzx esi, ah movzx edi, BYTE PTR [r11+rsi*8+1] movzx esi, bl xor edi, DWORD PTR [r11+rsi*8+0] mov WORD PTR [(r8+16*13)+10], di shr eax, 16 movzx esi, bh movzx edi, BYTE PTR [r11+rsi*8+1] movzx esi, cl xor edi, DWORD PTR [r11+rsi*8+0] mov WORD PTR [(r8+16*13)+14], di shr ebx, 16 movzx esi, dh movzx edi, BYTE PTR [r11+rsi*8+1] movzx esi, al xor edi, DWORD PTR [r11+rsi*8+0] mov WORD PTR [(r8+16*13)+12], di shr ecx, 16 movzx esi, ah movzx edi, BYTE PTR [r11+rsi*8+1] movzx esi, bl xor edi, DWORD PTR [r11+rsi*8+0] mov WORD PTR [(r8+16*13)+0], di movzx esi, bh movzx edi, BYTE PTR [r11+rsi*8+1] movzx esi, cl xor edi, DWORD PTR [r11+rsi*8+0] mov WORD PTR [(r8+16*13)+4], di movzx esi, ch movzx edi, BYTE PTR [r11+rsi*8+1] movzx esi, dl xor edi, DWORD PTR [r11+rsi*8+0] mov WORD PTR [(r8+16*13)+8], di mov rax, [(r8+16*14)+16] mov rbx, [(r8+16*14)+24] mov rcx, [(r8+16*18+8)] sub rcx, 16 movdqu xmm2, [rax] pxor xmm2, xmm4 movdqa xmm0, [(r8+16*16)+16] paddq xmm0, [(r8+16*14)+16] movdqa [(r8+16*14)+16], xmm0 pxor xmm2, [(r8+16*13)] movdqu [rbx], xmm2 jle label7 mov [(r8+16*18+8)], rcx test rcx, 1 jnz label1 movdqa xmm0, [(r8+16*16)] paddq xmm0, [(r8+16*14)] movdqa [(r8+16*14)], xmm0 jmp label3 label7: xorps xmm0, xmm0 lea rax, [(r8+0)+7*16] movaps [rax-7*16], xmm0 movaps [rax-6*16], xmm0 movaps [rax-5*16], xmm0 movaps [rax-4*16], xmm0 movaps [rax-3*16], xmm0 movaps [rax-2*16], xmm0 movaps [rax-1*16], xmm0 movaps [rax+0*16], xmm0 movaps [rax+1*16], xmm0 movaps [rax+2*16], xmm0 movaps [rax+3*16], xmm0 movaps [rax+4*16], xmm0 movaps [rax+5*16], xmm0 movaps [rax+6*16], xmm0 pop r12 pop rbx pop rdi pop rsi ret Rijndael_Enc_AdvancedProcessBlocks ENDP ALIGN 8 GCM_AuthenticateBlocks_2K PROC FRAME rex_push_reg rsi push_reg rdi push_reg rbx .endprolog mov rsi, r8 mov r11, r9 movdqa xmm0, [rsi] label0: movdqu xmm4, [rcx] pxor xmm0, xmm4 movd ebx, xmm0 mov eax, 0f0f0f0f0h and eax, ebx shl ebx, 4 and ebx, 0f0f0f0f0h movzx edi, ah movdqa xmm5, XMMWORD PTR [rsi + 32 + 1024 + rdi] movzx edi, al movdqa xmm4, XMMWORD PTR [rsi + 32 + 1024 + rdi] shr eax, 16 movzx edi, ah movdqa xmm3, XMMWORD PTR [rsi + 32 + 1024 + rdi] movzx edi, al movdqa xmm2, XMMWORD PTR [rsi + 32 + 1024 + rdi] psrldq xmm0, 4 movd eax, xmm0 and eax, 0f0f0f0f0h movzx edi, bh pxor xmm5, XMMWORD PTR [rsi + 32 + (1-1)*256 + rdi] movzx edi, bl pxor xmm4, XMMWORD PTR [rsi + 32 + (1-1)*256 + rdi] shr ebx, 16 movzx edi, bh pxor xmm3, XMMWORD PTR [rsi + 32 + (1-1)*256 + rdi] movzx edi, bl pxor xmm2, XMMWORD PTR [rsi + 32 + (1-1)*256 + rdi] movd ebx, xmm0 shl ebx, 4 and ebx, 0f0f0f0f0h movzx edi, ah pxor xmm5, XMMWORD PTR [rsi + 32 + 1024 + 1*256 + rdi] movzx edi, al pxor xmm4, XMMWORD PTR [rsi + 32 + 1024 + 1*256 + rdi] shr eax, 16 movzx edi, ah pxor xmm3, XMMWORD PTR [rsi + 32 + 1024 + 1*256 + rdi] movzx edi, al pxor xmm2, XMMWORD PTR [rsi + 32 + 1024 + 1*256 + rdi] psrldq xmm0, 4 movd eax, xmm0 and eax, 0f0f0f0f0h movzx edi, bh pxor xmm5, XMMWORD PTR [rsi + 32 + (2-1)*256 + rdi] movzx edi, bl pxor xmm4, XMMWORD PTR [rsi + 32 + (2-1)*256 + rdi] shr ebx, 16 movzx edi, bh pxor xmm3, XMMWORD PTR [rsi + 32 + (2-1)*256 + rdi] movzx edi, bl pxor xmm2, XMMWORD PTR [rsi + 32 + (2-1)*256 + rdi] movd ebx, xmm0 shl ebx, 4 and ebx, 0f0f0f0f0h movzx edi, ah pxor xmm5, XMMWORD PTR [rsi + 32 + 1024 + 2*256 + rdi] movzx edi, al pxor xmm4, XMMWORD PTR [rsi + 32 + 1024 + 2*256 + rdi] shr eax, 16 movzx edi, ah pxor xmm3, XMMWORD PTR [rsi + 32 + 1024 + 2*256 + rdi] movzx edi, al pxor xmm2, XMMWORD PTR [rsi + 32 + 1024 + 2*256 + rdi] psrldq xmm0, 4 movd eax, xmm0 and eax, 0f0f0f0f0h movzx edi, bh pxor xmm5, XMMWORD PTR [rsi + 32 + (3-1)*256 + rdi] movzx edi, bl pxor xmm4, XMMWORD PTR [rsi + 32 + (3-1)*256 + rdi] shr ebx, 16 movzx edi, bh pxor xmm3, XMMWORD PTR [rsi + 32 + (3-1)*256 + rdi] movzx edi, bl pxor xmm2, XMMWORD PTR [rsi + 32 + (3-1)*256 + rdi] movd ebx, xmm0 shl ebx, 4 and ebx, 0f0f0f0f0h movzx edi, ah pxor xmm5, XMMWORD PTR [rsi + 32 + 1024 + 3*256 + rdi] movzx edi, al pxor xmm4, XMMWORD PTR [rsi + 32 + 1024 + 3*256 + rdi] shr eax, 16 movzx edi, ah pxor xmm3, XMMWORD PTR [rsi + 32 + 1024 + 3*256 + rdi] movzx edi, al pxor xmm2, XMMWORD PTR [rsi + 32 + 1024 + 3*256 + rdi] movzx edi, bh pxor xmm5, XMMWORD PTR [rsi + 32 + 3*256 + rdi] movzx edi, bl pxor xmm4, XMMWORD PTR [rsi + 32 + 3*256 + rdi] shr ebx, 16 movzx edi, bh pxor xmm3, XMMWORD PTR [rsi + 32 + 3*256 + rdi] movzx edi, bl pxor xmm2, XMMWORD PTR [rsi + 32 + 3*256 + rdi] movdqa xmm0, xmm3 pslldq xmm3, 1 pxor xmm2, xmm3 movdqa xmm1, xmm2 pslldq xmm2, 1 pxor xmm5, xmm2 psrldq xmm0, 15 movd rdi, xmm0 movzx eax, WORD PTR [r11 + rdi*2] shl eax, 8 movdqa xmm0, xmm5 pslldq xmm5, 1 pxor xmm4, xmm5 psrldq xmm1, 15 movd rdi, xmm1 xor ax, WORD PTR [r11 + rdi*2] shl eax, 8 psrldq xmm0, 15 movd rdi, xmm0 xor ax, WORD PTR [r11 + rdi*2] movd xmm0, eax pxor xmm0, xmm4 add rcx, 16 sub rdx, 1 jnz label0 movdqa [rsi], xmm0 pop rbx pop rdi pop rsi ret GCM_AuthenticateBlocks_2K ENDP ALIGN 8 GCM_AuthenticateBlocks_64K PROC FRAME rex_push_reg rsi push_reg rdi .endprolog mov rsi, r8 movdqa xmm0, [rsi] label1: movdqu xmm1, [rcx] pxor xmm1, xmm0 pxor xmm0, xmm0 movd eax, xmm1 psrldq xmm1, 4 movzx edi, al add rdi, rdi pxor xmm0, [rsi + 32 + (0*4+0)*256*16 + rdi*8] movzx edi, ah add rdi, rdi pxor xmm0, [rsi + 32 + (0*4+1)*256*16 + rdi*8] shr eax, 16 movzx edi, al add rdi, rdi pxor xmm0, [rsi + 32 + (0*4+2)*256*16 + rdi*8] movzx edi, ah add rdi, rdi pxor xmm0, [rsi + 32 + (0*4+3)*256*16 + rdi*8] movd eax, xmm1 psrldq xmm1, 4 movzx edi, al add rdi, rdi pxor xmm0, [rsi + 32 + (1*4+0)*256*16 + rdi*8] movzx edi, ah add rdi, rdi pxor xmm0, [rsi + 32 + (1*4+1)*256*16 + rdi*8] shr eax, 16 movzx edi, al add rdi, rdi pxor xmm0, [rsi + 32 + (1*4+2)*256*16 + rdi*8] movzx edi, ah add rdi, rdi pxor xmm0, [rsi + 32 + (1*4+3)*256*16 + rdi*8] movd eax, xmm1 psrldq xmm1, 4 movzx edi, al add rdi, rdi pxor xmm0, [rsi + 32 + (2*4+0)*256*16 + rdi*8] movzx edi, ah add rdi, rdi pxor xmm0, [rsi + 32 + (2*4+1)*256*16 + rdi*8] shr eax, 16 movzx edi, al add rdi, rdi pxor xmm0, [rsi + 32 + (2*4+2)*256*16 + rdi*8] movzx edi, ah add rdi, rdi pxor xmm0, [rsi + 32 + (2*4+3)*256*16 + rdi*8] movd eax, xmm1 psrldq xmm1, 4 movzx edi, al add rdi, rdi pxor xmm0, [rsi + 32 + (3*4+0)*256*16 + rdi*8] movzx edi, ah add rdi, rdi pxor xmm0, [rsi + 32 + (3*4+1)*256*16 + rdi*8] shr eax, 16 movzx edi, al add rdi, rdi pxor xmm0, [rsi + 32 + (3*4+2)*256*16 + rdi*8] movzx edi, ah add rdi, rdi pxor xmm0, [rsi + 32 + (3*4+3)*256*16 + rdi*8] add rcx, 16 sub rdx, 1 jnz label1 movdqa [rsi], xmm0 pop rdi pop rsi ret GCM_AuthenticateBlocks_64K ENDP ALIGN 8 X86_SHA256_HashBlocks PROC FRAME rex_push_reg rsi push_reg rdi push_reg rbx push_reg rbp alloc_stack(8*4 + 16*4 + 4*8 + 8) .endprolog mov rdi, r8 lea rsi, [?SHA256_K@CryptoPP@@3QBIB + 48*4] mov [rsp+8*4+16*4+1*8], rcx mov [rsp+8*4+16*4+2*8], rdx add rdi, rdx mov [rsp+8*4+16*4+3*8], rdi movdqa xmm0, XMMWORD PTR [rcx+0*16] movdqa xmm1, XMMWORD PTR [rcx+1*16] mov [rsp+8*4+16*4+0*8], rsi label0: sub rsi, 48*4 movdqa [rsp+((1024+7-(0+3)) MOD (8))*4], xmm1 movdqa [rsp+((1024+7-(0+7)) MOD (8))*4], xmm0 mov rbx, [rdx+0*8] bswap rbx mov [rsp+8*4+((1024+15-(0*(1+1)+1)) MOD (16))*4], rbx mov rbx, [rdx+1*8] bswap rbx mov [rsp+8*4+((1024+15-(1*(1+1)+1)) MOD (16))*4], rbx mov rbx, [rdx+2*8] bswap rbx mov [rsp+8*4+((1024+15-(2*(1+1)+1)) MOD (16))*4], rbx mov rbx, [rdx+3*8] bswap rbx mov [rsp+8*4+((1024+15-(3*(1+1)+1)) MOD (16))*4], rbx mov rbx, [rdx+4*8] bswap rbx mov [rsp+8*4+((1024+15-(4*(1+1)+1)) MOD (16))*4], rbx mov rbx, [rdx+5*8] bswap rbx mov [rsp+8*4+((1024+15-(5*(1+1)+1)) MOD (16))*4], rbx mov rbx, [rdx+6*8] bswap rbx mov [rsp+8*4+((1024+15-(6*(1+1)+1)) MOD (16))*4], rbx mov rbx, [rdx+7*8] bswap rbx mov [rsp+8*4+((1024+15-(7*(1+1)+1)) MOD (16))*4], rbx mov edi, [rsp+((1024+7-(0+3)) MOD (8))*4] mov eax, [rsp+((1024+7-(0+6)) MOD (8))*4] xor eax, [rsp+((1024+7-(0+5)) MOD (8))*4] mov ecx, [rsp+((1024+7-(0+7)) MOD (8))*4] mov edx, [rsp+((1024+7-(0+2)) MOD (8))*4] xor edx, [rsp+((1024+7-(0+1)) MOD (8))*4] and edx, edi xor edx, [rsp+((1024+7-(0+1)) MOD (8))*4] mov ebp, edi ror edi, 6 ror ebp, 25 add edx, [rsi+(0)*4] add edx, [rsp+8*4+((1024+15-(0)) MOD (16))*4] add edx, [rsp+((1024+7-(0)) MOD (8))*4] xor ebp, edi ror edi, 5 xor ebp, edi add edx, ebp mov ebx, ecx xor ecx, [rsp+((1024+7-(0+6)) MOD (8))*4] and eax, ecx xor eax, [rsp+((1024+7-(0+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add eax, edx add edx, [rsp+((1024+7-(0+4)) MOD (8))*4] mov [rsp+((1024+7-(0+4)) MOD (8))*4], edx ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add eax, ebp mov [rsp+((1024+7-(0)) MOD (8))*4], eax mov edi, [rsp+((1024+7-(1+2)) MOD (8))*4] xor edi, [rsp+((1024+7-(1+1)) MOD (8))*4] and edi, edx xor edi, [rsp+((1024+7-(1+1)) MOD (8))*4] mov ebp, edx ror edx, 6 ror ebp, 25 add edi, [rsi+(1)*4] add edi, [rsp+8*4+((1024+15-(1)) MOD (16))*4] add edi, [rsp+((1024+7-(1)) MOD (8))*4] xor ebp, edx ror edx, 5 xor ebp, edx add edi, ebp mov ebx, eax xor eax, [rsp+((1024+7-(1+6)) MOD (8))*4] and ecx, eax xor ecx, [rsp+((1024+7-(1+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add ecx, edi add edi, [rsp+((1024+7-(1+4)) MOD (8))*4] mov [rsp+((1024+7-(1+4)) MOD (8))*4], edi ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add ecx, ebp mov [rsp+((1024+7-(1)) MOD (8))*4], ecx mov edx, [rsp+((1024+7-(2+2)) MOD (8))*4] xor edx, [rsp+((1024+7-(2+1)) MOD (8))*4] and edx, edi xor edx, [rsp+((1024+7-(2+1)) MOD (8))*4] mov ebp, edi ror edi, 6 ror ebp, 25 add edx, [rsi+(2)*4] add edx, [rsp+8*4+((1024+15-(2)) MOD (16))*4] add edx, [rsp+((1024+7-(2)) MOD (8))*4] xor ebp, edi ror edi, 5 xor ebp, edi add edx, ebp mov ebx, ecx xor ecx, [rsp+((1024+7-(2+6)) MOD (8))*4] and eax, ecx xor eax, [rsp+((1024+7-(2+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add eax, edx add edx, [rsp+((1024+7-(2+4)) MOD (8))*4] mov [rsp+((1024+7-(2+4)) MOD (8))*4], edx ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add eax, ebp mov [rsp+((1024+7-(2)) MOD (8))*4], eax mov edi, [rsp+((1024+7-(3+2)) MOD (8))*4] xor edi, [rsp+((1024+7-(3+1)) MOD (8))*4] and edi, edx xor edi, [rsp+((1024+7-(3+1)) MOD (8))*4] mov ebp, edx ror edx, 6 ror ebp, 25 add edi, [rsi+(3)*4] add edi, [rsp+8*4+((1024+15-(3)) MOD (16))*4] add edi, [rsp+((1024+7-(3)) MOD (8))*4] xor ebp, edx ror edx, 5 xor ebp, edx add edi, ebp mov ebx, eax xor eax, [rsp+((1024+7-(3+6)) MOD (8))*4] and ecx, eax xor ecx, [rsp+((1024+7-(3+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add ecx, edi add edi, [rsp+((1024+7-(3+4)) MOD (8))*4] mov [rsp+((1024+7-(3+4)) MOD (8))*4], edi ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add ecx, ebp mov [rsp+((1024+7-(3)) MOD (8))*4], ecx mov edx, [rsp+((1024+7-(4+2)) MOD (8))*4] xor edx, [rsp+((1024+7-(4+1)) MOD (8))*4] and edx, edi xor edx, [rsp+((1024+7-(4+1)) MOD (8))*4] mov ebp, edi ror edi, 6 ror ebp, 25 add edx, [rsi+(4)*4] add edx, [rsp+8*4+((1024+15-(4)) MOD (16))*4] add edx, [rsp+((1024+7-(4)) MOD (8))*4] xor ebp, edi ror edi, 5 xor ebp, edi add edx, ebp mov ebx, ecx xor ecx, [rsp+((1024+7-(4+6)) MOD (8))*4] and eax, ecx xor eax, [rsp+((1024+7-(4+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add eax, edx add edx, [rsp+((1024+7-(4+4)) MOD (8))*4] mov [rsp+((1024+7-(4+4)) MOD (8))*4], edx ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add eax, ebp mov [rsp+((1024+7-(4)) MOD (8))*4], eax mov edi, [rsp+((1024+7-(5+2)) MOD (8))*4] xor edi, [rsp+((1024+7-(5+1)) MOD (8))*4] and edi, edx xor edi, [rsp+((1024+7-(5+1)) MOD (8))*4] mov ebp, edx ror edx, 6 ror ebp, 25 add edi, [rsi+(5)*4] add edi, [rsp+8*4+((1024+15-(5)) MOD (16))*4] add edi, [rsp+((1024+7-(5)) MOD (8))*4] xor ebp, edx ror edx, 5 xor ebp, edx add edi, ebp mov ebx, eax xor eax, [rsp+((1024+7-(5+6)) MOD (8))*4] and ecx, eax xor ecx, [rsp+((1024+7-(5+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add ecx, edi add edi, [rsp+((1024+7-(5+4)) MOD (8))*4] mov [rsp+((1024+7-(5+4)) MOD (8))*4], edi ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add ecx, ebp mov [rsp+((1024+7-(5)) MOD (8))*4], ecx mov edx, [rsp+((1024+7-(6+2)) MOD (8))*4] xor edx, [rsp+((1024+7-(6+1)) MOD (8))*4] and edx, edi xor edx, [rsp+((1024+7-(6+1)) MOD (8))*4] mov ebp, edi ror edi, 6 ror ebp, 25 add edx, [rsi+(6)*4] add edx, [rsp+8*4+((1024+15-(6)) MOD (16))*4] add edx, [rsp+((1024+7-(6)) MOD (8))*4] xor ebp, edi ror edi, 5 xor ebp, edi add edx, ebp mov ebx, ecx xor ecx, [rsp+((1024+7-(6+6)) MOD (8))*4] and eax, ecx xor eax, [rsp+((1024+7-(6+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add eax, edx add edx, [rsp+((1024+7-(6+4)) MOD (8))*4] mov [rsp+((1024+7-(6+4)) MOD (8))*4], edx ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add eax, ebp mov [rsp+((1024+7-(6)) MOD (8))*4], eax mov edi, [rsp+((1024+7-(7+2)) MOD (8))*4] xor edi, [rsp+((1024+7-(7+1)) MOD (8))*4] and edi, edx xor edi, [rsp+((1024+7-(7+1)) MOD (8))*4] mov ebp, edx ror edx, 6 ror ebp, 25 add edi, [rsi+(7)*4] add edi, [rsp+8*4+((1024+15-(7)) MOD (16))*4] add edi, [rsp+((1024+7-(7)) MOD (8))*4] xor ebp, edx ror edx, 5 xor ebp, edx add edi, ebp mov ebx, eax xor eax, [rsp+((1024+7-(7+6)) MOD (8))*4] and ecx, eax xor ecx, [rsp+((1024+7-(7+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add ecx, edi add edi, [rsp+((1024+7-(7+4)) MOD (8))*4] mov [rsp+((1024+7-(7+4)) MOD (8))*4], edi ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add ecx, ebp mov [rsp+((1024+7-(7)) MOD (8))*4], ecx mov edx, [rsp+((1024+7-(8+2)) MOD (8))*4] xor edx, [rsp+((1024+7-(8+1)) MOD (8))*4] and edx, edi xor edx, [rsp+((1024+7-(8+1)) MOD (8))*4] mov ebp, edi ror edi, 6 ror ebp, 25 add edx, [rsi+(8)*4] add edx, [rsp+8*4+((1024+15-(8)) MOD (16))*4] add edx, [rsp+((1024+7-(8)) MOD (8))*4] xor ebp, edi ror edi, 5 xor ebp, edi add edx, ebp mov ebx, ecx xor ecx, [rsp+((1024+7-(8+6)) MOD (8))*4] and eax, ecx xor eax, [rsp+((1024+7-(8+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add eax, edx add edx, [rsp+((1024+7-(8+4)) MOD (8))*4] mov [rsp+((1024+7-(8+4)) MOD (8))*4], edx ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add eax, ebp mov [rsp+((1024+7-(8)) MOD (8))*4], eax mov edi, [rsp+((1024+7-(9+2)) MOD (8))*4] xor edi, [rsp+((1024+7-(9+1)) MOD (8))*4] and edi, edx xor edi, [rsp+((1024+7-(9+1)) MOD (8))*4] mov ebp, edx ror edx, 6 ror ebp, 25 add edi, [rsi+(9)*4] add edi, [rsp+8*4+((1024+15-(9)) MOD (16))*4] add edi, [rsp+((1024+7-(9)) MOD (8))*4] xor ebp, edx ror edx, 5 xor ebp, edx add edi, ebp mov ebx, eax xor eax, [rsp+((1024+7-(9+6)) MOD (8))*4] and ecx, eax xor ecx, [rsp+((1024+7-(9+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add ecx, edi add edi, [rsp+((1024+7-(9+4)) MOD (8))*4] mov [rsp+((1024+7-(9+4)) MOD (8))*4], edi ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add ecx, ebp mov [rsp+((1024+7-(9)) MOD (8))*4], ecx mov edx, [rsp+((1024+7-(10+2)) MOD (8))*4] xor edx, [rsp+((1024+7-(10+1)) MOD (8))*4] and edx, edi xor edx, [rsp+((1024+7-(10+1)) MOD (8))*4] mov ebp, edi ror edi, 6 ror ebp, 25 add edx, [rsi+(10)*4] add edx, [rsp+8*4+((1024+15-(10)) MOD (16))*4] add edx, [rsp+((1024+7-(10)) MOD (8))*4] xor ebp, edi ror edi, 5 xor ebp, edi add edx, ebp mov ebx, ecx xor ecx, [rsp+((1024+7-(10+6)) MOD (8))*4] and eax, ecx xor eax, [rsp+((1024+7-(10+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add eax, edx add edx, [rsp+((1024+7-(10+4)) MOD (8))*4] mov [rsp+((1024+7-(10+4)) MOD (8))*4], edx ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add eax, ebp mov [rsp+((1024+7-(10)) MOD (8))*4], eax mov edi, [rsp+((1024+7-(11+2)) MOD (8))*4] xor edi, [rsp+((1024+7-(11+1)) MOD (8))*4] and edi, edx xor edi, [rsp+((1024+7-(11+1)) MOD (8))*4] mov ebp, edx ror edx, 6 ror ebp, 25 add edi, [rsi+(11)*4] add edi, [rsp+8*4+((1024+15-(11)) MOD (16))*4] add edi, [rsp+((1024+7-(11)) MOD (8))*4] xor ebp, edx ror edx, 5 xor ebp, edx add edi, ebp mov ebx, eax xor eax, [rsp+((1024+7-(11+6)) MOD (8))*4] and ecx, eax xor ecx, [rsp+((1024+7-(11+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add ecx, edi add edi, [rsp+((1024+7-(11+4)) MOD (8))*4] mov [rsp+((1024+7-(11+4)) MOD (8))*4], edi ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add ecx, ebp mov [rsp+((1024+7-(11)) MOD (8))*4], ecx mov edx, [rsp+((1024+7-(12+2)) MOD (8))*4] xor edx, [rsp+((1024+7-(12+1)) MOD (8))*4] and edx, edi xor edx, [rsp+((1024+7-(12+1)) MOD (8))*4] mov ebp, edi ror edi, 6 ror ebp, 25 add edx, [rsi+(12)*4] add edx, [rsp+8*4+((1024+15-(12)) MOD (16))*4] add edx, [rsp+((1024+7-(12)) MOD (8))*4] xor ebp, edi ror edi, 5 xor ebp, edi add edx, ebp mov ebx, ecx xor ecx, [rsp+((1024+7-(12+6)) MOD (8))*4] and eax, ecx xor eax, [rsp+((1024+7-(12+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add eax, edx add edx, [rsp+((1024+7-(12+4)) MOD (8))*4] mov [rsp+((1024+7-(12+4)) MOD (8))*4], edx ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add eax, ebp mov [rsp+((1024+7-(12)) MOD (8))*4], eax mov edi, [rsp+((1024+7-(13+2)) MOD (8))*4] xor edi, [rsp+((1024+7-(13+1)) MOD (8))*4] and edi, edx xor edi, [rsp+((1024+7-(13+1)) MOD (8))*4] mov ebp, edx ror edx, 6 ror ebp, 25 add edi, [rsi+(13)*4] add edi, [rsp+8*4+((1024+15-(13)) MOD (16))*4] add edi, [rsp+((1024+7-(13)) MOD (8))*4] xor ebp, edx ror edx, 5 xor ebp, edx add edi, ebp mov ebx, eax xor eax, [rsp+((1024+7-(13+6)) MOD (8))*4] and ecx, eax xor ecx, [rsp+((1024+7-(13+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add ecx, edi add edi, [rsp+((1024+7-(13+4)) MOD (8))*4] mov [rsp+((1024+7-(13+4)) MOD (8))*4], edi ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add ecx, ebp mov [rsp+((1024+7-(13)) MOD (8))*4], ecx mov edx, [rsp+((1024+7-(14+2)) MOD (8))*4] xor edx, [rsp+((1024+7-(14+1)) MOD (8))*4] and edx, edi xor edx, [rsp+((1024+7-(14+1)) MOD (8))*4] mov ebp, edi ror edi, 6 ror ebp, 25 add edx, [rsi+(14)*4] add edx, [rsp+8*4+((1024+15-(14)) MOD (16))*4] add edx, [rsp+((1024+7-(14)) MOD (8))*4] xor ebp, edi ror edi, 5 xor ebp, edi add edx, ebp mov ebx, ecx xor ecx, [rsp+((1024+7-(14+6)) MOD (8))*4] and eax, ecx xor eax, [rsp+((1024+7-(14+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add eax, edx add edx, [rsp+((1024+7-(14+4)) MOD (8))*4] mov [rsp+((1024+7-(14+4)) MOD (8))*4], edx ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add eax, ebp mov [rsp+((1024+7-(14)) MOD (8))*4], eax mov edi, [rsp+((1024+7-(15+2)) MOD (8))*4] xor edi, [rsp+((1024+7-(15+1)) MOD (8))*4] and edi, edx xor edi, [rsp+((1024+7-(15+1)) MOD (8))*4] mov ebp, edx ror edx, 6 ror ebp, 25 add edi, [rsi+(15)*4] add edi, [rsp+8*4+((1024+15-(15)) MOD (16))*4] add edi, [rsp+((1024+7-(15)) MOD (8))*4] xor ebp, edx ror edx, 5 xor ebp, edx add edi, ebp mov ebx, eax xor eax, [rsp+((1024+7-(15+6)) MOD (8))*4] and ecx, eax xor ecx, [rsp+((1024+7-(15+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add ecx, edi add edi, [rsp+((1024+7-(15+4)) MOD (8))*4] mov [rsp+((1024+7-(15+4)) MOD (8))*4], edi ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add ecx, ebp mov [rsp+((1024+7-(15)) MOD (8))*4], ecx label1: add rsi, 4*16 mov edx, [rsp+((1024+7-(0+2)) MOD (8))*4] xor edx, [rsp+((1024+7-(0+1)) MOD (8))*4] and edx, edi xor edx, [rsp+((1024+7-(0+1)) MOD (8))*4] mov ebp, edi ror edi, 6 ror ebp, 25 xor ebp, edi ror edi, 5 xor ebp, edi add edx, ebp mov ebp, [rsp+8*4+((1024+15-((0)-2)) MOD (16))*4] mov edi, [rsp+8*4+((1024+15-((0)-15)) MOD (16))*4] mov ebx, ebp shr ebp, 10 ror ebx, 17 xor ebp, ebx ror ebx, 2 xor ebx, ebp add ebx, [rsp+8*4+((1024+15-((0)-7)) MOD (16))*4] mov ebp, edi shr ebp, 3 ror edi, 7 add ebx, [rsp+8*4+((1024+15-(0)) MOD (16))*4] xor ebp, edi add edx, [rsi+(0)*4] ror edi, 11 add edx, [rsp+((1024+7-(0)) MOD (8))*4] xor ebp, edi add ebp, ebx mov [rsp+8*4+((1024+15-(0)) MOD (16))*4], ebp add edx, ebp mov ebx, ecx xor ecx, [rsp+((1024+7-(0+6)) MOD (8))*4] and eax, ecx xor eax, [rsp+((1024+7-(0+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add eax, edx add edx, [rsp+((1024+7-(0+4)) MOD (8))*4] mov [rsp+((1024+7-(0+4)) MOD (8))*4], edx ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add eax, ebp mov [rsp+((1024+7-(0)) MOD (8))*4], eax mov edi, [rsp+((1024+7-(1+2)) MOD (8))*4] xor edi, [rsp+((1024+7-(1+1)) MOD (8))*4] and edi, edx xor edi, [rsp+((1024+7-(1+1)) MOD (8))*4] mov ebp, edx ror edx, 6 ror ebp, 25 xor ebp, edx ror edx, 5 xor ebp, edx add edi, ebp mov ebp, [rsp+8*4+((1024+15-((1)-2)) MOD (16))*4] mov edx, [rsp+8*4+((1024+15-((1)-15)) MOD (16))*4] mov ebx, ebp shr ebp, 10 ror ebx, 17 xor ebp, ebx ror ebx, 2 xor ebx, ebp add ebx, [rsp+8*4+((1024+15-((1)-7)) MOD (16))*4] mov ebp, edx shr ebp, 3 ror edx, 7 add ebx, [rsp+8*4+((1024+15-(1)) MOD (16))*4] xor ebp, edx add edi, [rsi+(1)*4] ror edx, 11 add edi, [rsp+((1024+7-(1)) MOD (8))*4] xor ebp, edx add ebp, ebx mov [rsp+8*4+((1024+15-(1)) MOD (16))*4], ebp add edi, ebp mov ebx, eax xor eax, [rsp+((1024+7-(1+6)) MOD (8))*4] and ecx, eax xor ecx, [rsp+((1024+7-(1+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add ecx, edi add edi, [rsp+((1024+7-(1+4)) MOD (8))*4] mov [rsp+((1024+7-(1+4)) MOD (8))*4], edi ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add ecx, ebp mov [rsp+((1024+7-(1)) MOD (8))*4], ecx mov edx, [rsp+((1024+7-(2+2)) MOD (8))*4] xor edx, [rsp+((1024+7-(2+1)) MOD (8))*4] and edx, edi xor edx, [rsp+((1024+7-(2+1)) MOD (8))*4] mov ebp, edi ror edi, 6 ror ebp, 25 xor ebp, edi ror edi, 5 xor ebp, edi add edx, ebp mov ebp, [rsp+8*4+((1024+15-((2)-2)) MOD (16))*4] mov edi, [rsp+8*4+((1024+15-((2)-15)) MOD (16))*4] mov ebx, ebp shr ebp, 10 ror ebx, 17 xor ebp, ebx ror ebx, 2 xor ebx, ebp add ebx, [rsp+8*4+((1024+15-((2)-7)) MOD (16))*4] mov ebp, edi shr ebp, 3 ror edi, 7 add ebx, [rsp+8*4+((1024+15-(2)) MOD (16))*4] xor ebp, edi add edx, [rsi+(2)*4] ror edi, 11 add edx, [rsp+((1024+7-(2)) MOD (8))*4] xor ebp, edi add ebp, ebx mov [rsp+8*4+((1024+15-(2)) MOD (16))*4], ebp add edx, ebp mov ebx, ecx xor ecx, [rsp+((1024+7-(2+6)) MOD (8))*4] and eax, ecx xor eax, [rsp+((1024+7-(2+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add eax, edx add edx, [rsp+((1024+7-(2+4)) MOD (8))*4] mov [rsp+((1024+7-(2+4)) MOD (8))*4], edx ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add eax, ebp mov [rsp+((1024+7-(2)) MOD (8))*4], eax mov edi, [rsp+((1024+7-(3+2)) MOD (8))*4] xor edi, [rsp+((1024+7-(3+1)) MOD (8))*4] and edi, edx xor edi, [rsp+((1024+7-(3+1)) MOD (8))*4] mov ebp, edx ror edx, 6 ror ebp, 25 xor ebp, edx ror edx, 5 xor ebp, edx add edi, ebp mov ebp, [rsp+8*4+((1024+15-((3)-2)) MOD (16))*4] mov edx, [rsp+8*4+((1024+15-((3)-15)) MOD (16))*4] mov ebx, ebp shr ebp, 10 ror ebx, 17 xor ebp, ebx ror ebx, 2 xor ebx, ebp add ebx, [rsp+8*4+((1024+15-((3)-7)) MOD (16))*4] mov ebp, edx shr ebp, 3 ror edx, 7 add ebx, [rsp+8*4+((1024+15-(3)) MOD (16))*4] xor ebp, edx add edi, [rsi+(3)*4] ror edx, 11 add edi, [rsp+((1024+7-(3)) MOD (8))*4] xor ebp, edx add ebp, ebx mov [rsp+8*4+((1024+15-(3)) MOD (16))*4], ebp add edi, ebp mov ebx, eax xor eax, [rsp+((1024+7-(3+6)) MOD (8))*4] and ecx, eax xor ecx, [rsp+((1024+7-(3+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add ecx, edi add edi, [rsp+((1024+7-(3+4)) MOD (8))*4] mov [rsp+((1024+7-(3+4)) MOD (8))*4], edi ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add ecx, ebp mov [rsp+((1024+7-(3)) MOD (8))*4], ecx mov edx, [rsp+((1024+7-(4+2)) MOD (8))*4] xor edx, [rsp+((1024+7-(4+1)) MOD (8))*4] and edx, edi xor edx, [rsp+((1024+7-(4+1)) MOD (8))*4] mov ebp, edi ror edi, 6 ror ebp, 25 xor ebp, edi ror edi, 5 xor ebp, edi add edx, ebp mov ebp, [rsp+8*4+((1024+15-((4)-2)) MOD (16))*4] mov edi, [rsp+8*4+((1024+15-((4)-15)) MOD (16))*4] mov ebx, ebp shr ebp, 10 ror ebx, 17 xor ebp, ebx ror ebx, 2 xor ebx, ebp add ebx, [rsp+8*4+((1024+15-((4)-7)) MOD (16))*4] mov ebp, edi shr ebp, 3 ror edi, 7 add ebx, [rsp+8*4+((1024+15-(4)) MOD (16))*4] xor ebp, edi add edx, [rsi+(4)*4] ror edi, 11 add edx, [rsp+((1024+7-(4)) MOD (8))*4] xor ebp, edi add ebp, ebx mov [rsp+8*4+((1024+15-(4)) MOD (16))*4], ebp add edx, ebp mov ebx, ecx xor ecx, [rsp+((1024+7-(4+6)) MOD (8))*4] and eax, ecx xor eax, [rsp+((1024+7-(4+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add eax, edx add edx, [rsp+((1024+7-(4+4)) MOD (8))*4] mov [rsp+((1024+7-(4+4)) MOD (8))*4], edx ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add eax, ebp mov [rsp+((1024+7-(4)) MOD (8))*4], eax mov edi, [rsp+((1024+7-(5+2)) MOD (8))*4] xor edi, [rsp+((1024+7-(5+1)) MOD (8))*4] and edi, edx xor edi, [rsp+((1024+7-(5+1)) MOD (8))*4] mov ebp, edx ror edx, 6 ror ebp, 25 xor ebp, edx ror edx, 5 xor ebp, edx add edi, ebp mov ebp, [rsp+8*4+((1024+15-((5)-2)) MOD (16))*4] mov edx, [rsp+8*4+((1024+15-((5)-15)) MOD (16))*4] mov ebx, ebp shr ebp, 10 ror ebx, 17 xor ebp, ebx ror ebx, 2 xor ebx, ebp add ebx, [rsp+8*4+((1024+15-((5)-7)) MOD (16))*4] mov ebp, edx shr ebp, 3 ror edx, 7 add ebx, [rsp+8*4+((1024+15-(5)) MOD (16))*4] xor ebp, edx add edi, [rsi+(5)*4] ror edx, 11 add edi, [rsp+((1024+7-(5)) MOD (8))*4] xor ebp, edx add ebp, ebx mov [rsp+8*4+((1024+15-(5)) MOD (16))*4], ebp add edi, ebp mov ebx, eax xor eax, [rsp+((1024+7-(5+6)) MOD (8))*4] and ecx, eax xor ecx, [rsp+((1024+7-(5+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add ecx, edi add edi, [rsp+((1024+7-(5+4)) MOD (8))*4] mov [rsp+((1024+7-(5+4)) MOD (8))*4], edi ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add ecx, ebp mov [rsp+((1024+7-(5)) MOD (8))*4], ecx mov edx, [rsp+((1024+7-(6+2)) MOD (8))*4] xor edx, [rsp+((1024+7-(6+1)) MOD (8))*4] and edx, edi xor edx, [rsp+((1024+7-(6+1)) MOD (8))*4] mov ebp, edi ror edi, 6 ror ebp, 25 xor ebp, edi ror edi, 5 xor ebp, edi add edx, ebp mov ebp, [rsp+8*4+((1024+15-((6)-2)) MOD (16))*4] mov edi, [rsp+8*4+((1024+15-((6)-15)) MOD (16))*4] mov ebx, ebp shr ebp, 10 ror ebx, 17 xor ebp, ebx ror ebx, 2 xor ebx, ebp add ebx, [rsp+8*4+((1024+15-((6)-7)) MOD (16))*4] mov ebp, edi shr ebp, 3 ror edi, 7 add ebx, [rsp+8*4+((1024+15-(6)) MOD (16))*4] xor ebp, edi add edx, [rsi+(6)*4] ror edi, 11 add edx, [rsp+((1024+7-(6)) MOD (8))*4] xor ebp, edi add ebp, ebx mov [rsp+8*4+((1024+15-(6)) MOD (16))*4], ebp add edx, ebp mov ebx, ecx xor ecx, [rsp+((1024+7-(6+6)) MOD (8))*4] and eax, ecx xor eax, [rsp+((1024+7-(6+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add eax, edx add edx, [rsp+((1024+7-(6+4)) MOD (8))*4] mov [rsp+((1024+7-(6+4)) MOD (8))*4], edx ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add eax, ebp mov [rsp+((1024+7-(6)) MOD (8))*4], eax mov edi, [rsp+((1024+7-(7+2)) MOD (8))*4] xor edi, [rsp+((1024+7-(7+1)) MOD (8))*4] and edi, edx xor edi, [rsp+((1024+7-(7+1)) MOD (8))*4] mov ebp, edx ror edx, 6 ror ebp, 25 xor ebp, edx ror edx, 5 xor ebp, edx add edi, ebp mov ebp, [rsp+8*4+((1024+15-((7)-2)) MOD (16))*4] mov edx, [rsp+8*4+((1024+15-((7)-15)) MOD (16))*4] mov ebx, ebp shr ebp, 10 ror ebx, 17 xor ebp, ebx ror ebx, 2 xor ebx, ebp add ebx, [rsp+8*4+((1024+15-((7)-7)) MOD (16))*4] mov ebp, edx shr ebp, 3 ror edx, 7 add ebx, [rsp+8*4+((1024+15-(7)) MOD (16))*4] xor ebp, edx add edi, [rsi+(7)*4] ror edx, 11 add edi, [rsp+((1024+7-(7)) MOD (8))*4] xor ebp, edx add ebp, ebx mov [rsp+8*4+((1024+15-(7)) MOD (16))*4], ebp add edi, ebp mov ebx, eax xor eax, [rsp+((1024+7-(7+6)) MOD (8))*4] and ecx, eax xor ecx, [rsp+((1024+7-(7+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add ecx, edi add edi, [rsp+((1024+7-(7+4)) MOD (8))*4] mov [rsp+((1024+7-(7+4)) MOD (8))*4], edi ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add ecx, ebp mov [rsp+((1024+7-(7)) MOD (8))*4], ecx mov edx, [rsp+((1024+7-(8+2)) MOD (8))*4] xor edx, [rsp+((1024+7-(8+1)) MOD (8))*4] and edx, edi xor edx, [rsp+((1024+7-(8+1)) MOD (8))*4] mov ebp, edi ror edi, 6 ror ebp, 25 xor ebp, edi ror edi, 5 xor ebp, edi add edx, ebp mov ebp, [rsp+8*4+((1024+15-((8)-2)) MOD (16))*4] mov edi, [rsp+8*4+((1024+15-((8)-15)) MOD (16))*4] mov ebx, ebp shr ebp, 10 ror ebx, 17 xor ebp, ebx ror ebx, 2 xor ebx, ebp add ebx, [rsp+8*4+((1024+15-((8)-7)) MOD (16))*4] mov ebp, edi shr ebp, 3 ror edi, 7 add ebx, [rsp+8*4+((1024+15-(8)) MOD (16))*4] xor ebp, edi add edx, [rsi+(8)*4] ror edi, 11 add edx, [rsp+((1024+7-(8)) MOD (8))*4] xor ebp, edi add ebp, ebx mov [rsp+8*4+((1024+15-(8)) MOD (16))*4], ebp add edx, ebp mov ebx, ecx xor ecx, [rsp+((1024+7-(8+6)) MOD (8))*4] and eax, ecx xor eax, [rsp+((1024+7-(8+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add eax, edx add edx, [rsp+((1024+7-(8+4)) MOD (8))*4] mov [rsp+((1024+7-(8+4)) MOD (8))*4], edx ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add eax, ebp mov [rsp+((1024+7-(8)) MOD (8))*4], eax mov edi, [rsp+((1024+7-(9+2)) MOD (8))*4] xor edi, [rsp+((1024+7-(9+1)) MOD (8))*4] and edi, edx xor edi, [rsp+((1024+7-(9+1)) MOD (8))*4] mov ebp, edx ror edx, 6 ror ebp, 25 xor ebp, edx ror edx, 5 xor ebp, edx add edi, ebp mov ebp, [rsp+8*4+((1024+15-((9)-2)) MOD (16))*4] mov edx, [rsp+8*4+((1024+15-((9)-15)) MOD (16))*4] mov ebx, ebp shr ebp, 10 ror ebx, 17 xor ebp, ebx ror ebx, 2 xor ebx, ebp add ebx, [rsp+8*4+((1024+15-((9)-7)) MOD (16))*4] mov ebp, edx shr ebp, 3 ror edx, 7 add ebx, [rsp+8*4+((1024+15-(9)) MOD (16))*4] xor ebp, edx add edi, [rsi+(9)*4] ror edx, 11 add edi, [rsp+((1024+7-(9)) MOD (8))*4] xor ebp, edx add ebp, ebx mov [rsp+8*4+((1024+15-(9)) MOD (16))*4], ebp add edi, ebp mov ebx, eax xor eax, [rsp+((1024+7-(9+6)) MOD (8))*4] and ecx, eax xor ecx, [rsp+((1024+7-(9+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add ecx, edi add edi, [rsp+((1024+7-(9+4)) MOD (8))*4] mov [rsp+((1024+7-(9+4)) MOD (8))*4], edi ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add ecx, ebp mov [rsp+((1024+7-(9)) MOD (8))*4], ecx mov edx, [rsp+((1024+7-(10+2)) MOD (8))*4] xor edx, [rsp+((1024+7-(10+1)) MOD (8))*4] and edx, edi xor edx, [rsp+((1024+7-(10+1)) MOD (8))*4] mov ebp, edi ror edi, 6 ror ebp, 25 xor ebp, edi ror edi, 5 xor ebp, edi add edx, ebp mov ebp, [rsp+8*4+((1024+15-((10)-2)) MOD (16))*4] mov edi, [rsp+8*4+((1024+15-((10)-15)) MOD (16))*4] mov ebx, ebp shr ebp, 10 ror ebx, 17 xor ebp, ebx ror ebx, 2 xor ebx, ebp add ebx, [rsp+8*4+((1024+15-((10)-7)) MOD (16))*4] mov ebp, edi shr ebp, 3 ror edi, 7 add ebx, [rsp+8*4+((1024+15-(10)) MOD (16))*4] xor ebp, edi add edx, [rsi+(10)*4] ror edi, 11 add edx, [rsp+((1024+7-(10)) MOD (8))*4] xor ebp, edi add ebp, ebx mov [rsp+8*4+((1024+15-(10)) MOD (16))*4], ebp add edx, ebp mov ebx, ecx xor ecx, [rsp+((1024+7-(10+6)) MOD (8))*4] and eax, ecx xor eax, [rsp+((1024+7-(10+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add eax, edx add edx, [rsp+((1024+7-(10+4)) MOD (8))*4] mov [rsp+((1024+7-(10+4)) MOD (8))*4], edx ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add eax, ebp mov [rsp+((1024+7-(10)) MOD (8))*4], eax mov edi, [rsp+((1024+7-(11+2)) MOD (8))*4] xor edi, [rsp+((1024+7-(11+1)) MOD (8))*4] and edi, edx xor edi, [rsp+((1024+7-(11+1)) MOD (8))*4] mov ebp, edx ror edx, 6 ror ebp, 25 xor ebp, edx ror edx, 5 xor ebp, edx add edi, ebp mov ebp, [rsp+8*4+((1024+15-((11)-2)) MOD (16))*4] mov edx, [rsp+8*4+((1024+15-((11)-15)) MOD (16))*4] mov ebx, ebp shr ebp, 10 ror ebx, 17 xor ebp, ebx ror ebx, 2 xor ebx, ebp add ebx, [rsp+8*4+((1024+15-((11)-7)) MOD (16))*4] mov ebp, edx shr ebp, 3 ror edx, 7 add ebx, [rsp+8*4+((1024+15-(11)) MOD (16))*4] xor ebp, edx add edi, [rsi+(11)*4] ror edx, 11 add edi, [rsp+((1024+7-(11)) MOD (8))*4] xor ebp, edx add ebp, ebx mov [rsp+8*4+((1024+15-(11)) MOD (16))*4], ebp add edi, ebp mov ebx, eax xor eax, [rsp+((1024+7-(11+6)) MOD (8))*4] and ecx, eax xor ecx, [rsp+((1024+7-(11+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add ecx, edi add edi, [rsp+((1024+7-(11+4)) MOD (8))*4] mov [rsp+((1024+7-(11+4)) MOD (8))*4], edi ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add ecx, ebp mov [rsp+((1024+7-(11)) MOD (8))*4], ecx mov edx, [rsp+((1024+7-(12+2)) MOD (8))*4] xor edx, [rsp+((1024+7-(12+1)) MOD (8))*4] and edx, edi xor edx, [rsp+((1024+7-(12+1)) MOD (8))*4] mov ebp, edi ror edi, 6 ror ebp, 25 xor ebp, edi ror edi, 5 xor ebp, edi add edx, ebp mov ebp, [rsp+8*4+((1024+15-((12)-2)) MOD (16))*4] mov edi, [rsp+8*4+((1024+15-((12)-15)) MOD (16))*4] mov ebx, ebp shr ebp, 10 ror ebx, 17 xor ebp, ebx ror ebx, 2 xor ebx, ebp add ebx, [rsp+8*4+((1024+15-((12)-7)) MOD (16))*4] mov ebp, edi shr ebp, 3 ror edi, 7 add ebx, [rsp+8*4+((1024+15-(12)) MOD (16))*4] xor ebp, edi add edx, [rsi+(12)*4] ror edi, 11 add edx, [rsp+((1024+7-(12)) MOD (8))*4] xor ebp, edi add ebp, ebx mov [rsp+8*4+((1024+15-(12)) MOD (16))*4], ebp add edx, ebp mov ebx, ecx xor ecx, [rsp+((1024+7-(12+6)) MOD (8))*4] and eax, ecx xor eax, [rsp+((1024+7-(12+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add eax, edx add edx, [rsp+((1024+7-(12+4)) MOD (8))*4] mov [rsp+((1024+7-(12+4)) MOD (8))*4], edx ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add eax, ebp mov [rsp+((1024+7-(12)) MOD (8))*4], eax mov edi, [rsp+((1024+7-(13+2)) MOD (8))*4] xor edi, [rsp+((1024+7-(13+1)) MOD (8))*4] and edi, edx xor edi, [rsp+((1024+7-(13+1)) MOD (8))*4] mov ebp, edx ror edx, 6 ror ebp, 25 xor ebp, edx ror edx, 5 xor ebp, edx add edi, ebp mov ebp, [rsp+8*4+((1024+15-((13)-2)) MOD (16))*4] mov edx, [rsp+8*4+((1024+15-((13)-15)) MOD (16))*4] mov ebx, ebp shr ebp, 10 ror ebx, 17 xor ebp, ebx ror ebx, 2 xor ebx, ebp add ebx, [rsp+8*4+((1024+15-((13)-7)) MOD (16))*4] mov ebp, edx shr ebp, 3 ror edx, 7 add ebx, [rsp+8*4+((1024+15-(13)) MOD (16))*4] xor ebp, edx add edi, [rsi+(13)*4] ror edx, 11 add edi, [rsp+((1024+7-(13)) MOD (8))*4] xor ebp, edx add ebp, ebx mov [rsp+8*4+((1024+15-(13)) MOD (16))*4], ebp add edi, ebp mov ebx, eax xor eax, [rsp+((1024+7-(13+6)) MOD (8))*4] and ecx, eax xor ecx, [rsp+((1024+7-(13+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add ecx, edi add edi, [rsp+((1024+7-(13+4)) MOD (8))*4] mov [rsp+((1024+7-(13+4)) MOD (8))*4], edi ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add ecx, ebp mov [rsp+((1024+7-(13)) MOD (8))*4], ecx mov edx, [rsp+((1024+7-(14+2)) MOD (8))*4] xor edx, [rsp+((1024+7-(14+1)) MOD (8))*4] and edx, edi xor edx, [rsp+((1024+7-(14+1)) MOD (8))*4] mov ebp, edi ror edi, 6 ror ebp, 25 xor ebp, edi ror edi, 5 xor ebp, edi add edx, ebp mov ebp, [rsp+8*4+((1024+15-((14)-2)) MOD (16))*4] mov edi, [rsp+8*4+((1024+15-((14)-15)) MOD (16))*4] mov ebx, ebp shr ebp, 10 ror ebx, 17 xor ebp, ebx ror ebx, 2 xor ebx, ebp add ebx, [rsp+8*4+((1024+15-((14)-7)) MOD (16))*4] mov ebp, edi shr ebp, 3 ror edi, 7 add ebx, [rsp+8*4+((1024+15-(14)) MOD (16))*4] xor ebp, edi add edx, [rsi+(14)*4] ror edi, 11 add edx, [rsp+((1024+7-(14)) MOD (8))*4] xor ebp, edi add ebp, ebx mov [rsp+8*4+((1024+15-(14)) MOD (16))*4], ebp add edx, ebp mov ebx, ecx xor ecx, [rsp+((1024+7-(14+6)) MOD (8))*4] and eax, ecx xor eax, [rsp+((1024+7-(14+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add eax, edx add edx, [rsp+((1024+7-(14+4)) MOD (8))*4] mov [rsp+((1024+7-(14+4)) MOD (8))*4], edx ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add eax, ebp mov [rsp+((1024+7-(14)) MOD (8))*4], eax mov edi, [rsp+((1024+7-(15+2)) MOD (8))*4] xor edi, [rsp+((1024+7-(15+1)) MOD (8))*4] and edi, edx xor edi, [rsp+((1024+7-(15+1)) MOD (8))*4] mov ebp, edx ror edx, 6 ror ebp, 25 xor ebp, edx ror edx, 5 xor ebp, edx add edi, ebp mov ebp, [rsp+8*4+((1024+15-((15)-2)) MOD (16))*4] mov edx, [rsp+8*4+((1024+15-((15)-15)) MOD (16))*4] mov ebx, ebp shr ebp, 10 ror ebx, 17 xor ebp, ebx ror ebx, 2 xor ebx, ebp add ebx, [rsp+8*4+((1024+15-((15)-7)) MOD (16))*4] mov ebp, edx shr ebp, 3 ror edx, 7 add ebx, [rsp+8*4+((1024+15-(15)) MOD (16))*4] xor ebp, edx add edi, [rsi+(15)*4] ror edx, 11 add edi, [rsp+((1024+7-(15)) MOD (8))*4] xor ebp, edx add ebp, ebx mov [rsp+8*4+((1024+15-(15)) MOD (16))*4], ebp add edi, ebp mov ebx, eax xor eax, [rsp+((1024+7-(15+6)) MOD (8))*4] and ecx, eax xor ecx, [rsp+((1024+7-(15+6)) MOD (8))*4] mov ebp, ebx ror ebx, 2 add ecx, edi add edi, [rsp+((1024+7-(15+4)) MOD (8))*4] mov [rsp+((1024+7-(15+4)) MOD (8))*4], edi ror ebp, 22 xor ebp, ebx ror ebx, 11 xor ebp, ebx add ecx, ebp mov [rsp+((1024+7-(15)) MOD (8))*4], ecx cmp rsi, [rsp+8*4+16*4+0*8] jne label1 mov rcx, [rsp+8*4+16*4+1*8] movdqa xmm1, XMMWORD PTR [rcx+1*16] movdqa xmm0, XMMWORD PTR [rcx+0*16] paddd xmm1, [rsp+((1024+7-(0+3)) MOD (8))*4] paddd xmm0, [rsp+((1024+7-(0+7)) MOD (8))*4] movdqa [rcx+1*16], xmm1 movdqa [rcx+0*16], xmm0 mov rdx, [rsp+8*4+16*4+2*8] add rdx, 64 mov [rsp+8*4+16*4+2*8], rdx cmp rdx, [rsp+8*4+16*4+3*8] jne label0 add rsp, 8*4 + 16*4 + 4*8 + 8 pop rbp pop rbx pop rdi pop rsi ret X86_SHA256_HashBlocks ENDP _TEXT ENDS END
; BSD 3-Clause License ; Copyright (c) 2021, AtieP ; All rights reserved. ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions are met: ; 1. Redistributions of source code must retain the above copyright notice, this ; list of conditions and the following disclaimer. ; 2. Redistributions in binary form must reproduce the above copyright notice, ; this list of conditions and the following disclaimer in the documentation ; and/or other materials provided with the distribution. ; 3. Neither the name of the copyright holder nor the names of its ; contributors may be used to endorse or promote products derived from ; this software without specific prior written permission. ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" ; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE ; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE ; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ; TODO: 64 bit ; Verifies if the ELF header is correct ; IN: EBX = Pointer to ELF header ; Panics if it isn't elf_verify_header: pushf cmp [ebx], dword 0x464c457f ; ELF jne .invalid_magic_number cmp [ebx+5], byte 1 ; Little endian jne .invalid_endianness cmp [ebx+16], byte 2 ; Executable jne .invalid_file_format jmp .return .invalid_magic_number: panic "elf", "Invalid magic number" .invalid_endianness: panic "elf", "Invalid endianness" .invalid_file_format: panic "elf", "Invalid file format" .return: popf ret ; Returns bitness of ELF file ; IN: EBX = ELF Header ; OUT: Bitness in EAX (If it is an invalid one, it panics) elf_get_bitness: pushf cmp [ebx+18], byte 0x03 ; x86_32 je .32_bit cmp [ebx+18], byte 0x32 ; x86_64 je .64_bit panic "elf", "File is not 32 nor 64 bit" .32_bit: mov eax, 32 jmp .return .64_bit: mov eax, 64 .return: popf ret ; Loads en ELF section into memory ; IN: EBX = Pointer to full ELF file, ECX = Section name (must start with a dot (.)), EDX = Section length (0: doesn't matter) ; OUT: EAX = Pointer to section contents (0 if not found, 1 if section is too small, 2 if section is too big, else it's a pointer) ; NOTE: If there were any errors, this subroutine will panic elf_load_section: push ebx push ecx push edx push esi push edi pushf call elf_verify_header call elf_get_bitness mov [.section_name], ecx mov [.section_length], edx cmp eax, 32 je .32_bit panic "elf", "64 bit ELF files are not supported for now." .32_bit: mov ax, [ebx+0x2e] mov [.section_header_entry_size], ax ; eax = pointer in the shstrtab section ; try and find it ; shstrndx * shdrsize + offset + elf base movzx eax, word [ebx+0x32] mul word [.section_header_entry_size] add eax, [ebx+0x20] add eax, ebx mov eax, [eax+0x10] add eax, ebx ; ebx = start of elf file ; ecx = number of section header entries movzx ecx, word [ebx+0x30] inc ecx ; edx = pointer to section header entries mov edx, ebx add edx, [ebx+0x20] .32_bit.load_section: ; compare type cmp [edx+0x04], dword 1 jne .32_bit.next_header ; compare name push eax push ebx push ecx add eax, [edx] mov ebx, eax mov ecx, [.section_name] call strcmp pop ecx pop ebx test eax, eax pop eax jnz .32_bit.next_header ; check size mov eax, [.section_length] test eax, eax ; caller doesn't care about the size jz .32_bit.load cmp eax, [edx+0x14] jz .32_bit.load ja .too_big jb .too_small .32_bit.load: add ebx, [edx+0x10] memcpy [edx+0x0c], ebx, [edx+0x14] jmp .32_bit.found .32_bit.next_header: add edx, [.section_header_entry_size] loop .32_bit.load_section .not_found: xor eax, eax jmp .return .too_small: mov eax, 1 jmp .return .too_big: mov eax, 2 jmp .return .32_bit.found: mov eax, [edx+0x0c] .return: popf pop edi pop esi pop edx pop ecx pop ebx ret .section_name: dd 0 .section_length: dd 0 .section_header_entry_size: dd 0 ; Loads an ELF file into memory ; IN: EBX = Pointer to full ELF file ; OUT: EAX = Entry point ; NOTE: If there were any errors, this subroutine will panic elf_load_program: push ecx push edx push esi push edi pushf call elf_verify_header call elf_get_bitness cmp eax, 32 je .32_bit panic "elf", "64 bit ELF files are not allowed for now" .32_bit: ; get size of program header entry mov ax, [ebx+0x2a] mov [.program_header_entry_size], ax ; now, place the entry point in eax (eax gets unmodified for the rest of the program) mov eax, [ebx+0x18] ; get number of program header entries movzx ecx, word [ebx+0x2c] inc ecx ; point inside the program headers array mov edx, ebx add edx, [ebx+0x1c] .32_bit.load_program_headers: cmp [edx], dword 1 ; LOAD jne .32_bit.next_header push ebx push ecx add ebx, [edx+0x04] memcpy [edx+0x0c], ebx, [edx+0x10] pop ecx pop ebx ; now, check if there is some bss or something ; esi and edi are not used anyways except in memcpy and memset mov esi, [edx+0x10] ; file size mov edi, [edx+0x14] ; memory size sub edi, esi jz .32_bit.next_header ; zero it out add esi, [edx+0x0c] ; physical address push ax push ecx memset esi, 0, edi pop ecx pop ax .32_bit.next_header: add edx, [.program_header_entry_size] loop .32_bit.load_program_headers popf pop edi pop esi pop edx pop ecx ret .program_header_entry_size: dd 0
// Copyright (C) 2018 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <builders/ie_layer_fragment.hpp> #include <ie_inetwork.hpp> #include <string> #include <vector> namespace InferenceEngine { namespace Builder { /** * @brief The class represents a builder for Eltwise layer */ class INFERENCE_ENGINE_API_CLASS(EltwiseLayer): public LayerFragment { public: /** * @brief The enum defines all Eltwise types */ enum EltwiseType { SUM = 1, MAX, MUL }; /** * @brief The constructor creates a builder with the name * @param name Layer name */ explicit EltwiseLayer(const std::string& name = ""); /** * @brief The constructor creates a builder from generic builder * @param genLayer generic builder */ explicit EltwiseLayer(Layer& genLayer); /** * @brief Sets the name for the layer * @param name Layer name * @return reference to layer builder */ EltwiseLayer& setName(const std::string& name); /** * @brief Returns input ports * @return Vector of input ports */ const std::vector<Port>& getInputPorts() const; /** * @brief Sets input ports * @param ports Vector of input ports * @return reference to layer builder */ EltwiseLayer& setInputPorts(const std::vector<Port>& ports); /** * @brief Returns output port * @return Output port */ const Port& getOutputPort() const; /** * @brief Sets output port * @param port Output port * @return reference to layer builder */ EltwiseLayer& setOutputPort(const Port& port); /** * @brief Returns eltwise type * @return Eltwise type */ EltwiseType getEltwiseType() const; /** * @brief Sets eltwise type * @param type Eltwise type * @return reference to layer builder */ EltwiseLayer& setEltwiseType(EltwiseType type); /** * @brief Returns eltwise scales * @return Vector of scales */ const std::vector<float> getScales() const; /** * @brief Sets eltwise scales * @param scales Vector of scales * @return reference to layer builder */ EltwiseLayer& setScales(const std::vector<float>& scales); private: EltwiseType type; }; } // namespace Builder } // namespace InferenceEngine
//@HEADER // ************************************************************************ // // Kokkos v. 2.0 // Copyright (2014) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact H. Carter Edwards (hcedwar@sandia.gov) // // ************************************************************************ //@HEADER #include <iostream> #include <stdexcept> #include <limits> #include <utility> #include <BoxMeshPartition.hpp> //---------------------------------------------------------------------------- void test_box_partition( bool print ) { const size_t np_max = 10000 ; const BoxBoundsLinear use_box ; BoxType root_box ; root_box[0][0] = 0 ; root_box[0][1] = 100 ; root_box[1][0] = 0 ; root_box[1][1] = 200 ; root_box[2][0] = 0 ; root_box[2][1] = 300 ; const size_t cell_total = ( root_box[0][1] - root_box[0][0] ) * ( root_box[1][1] - root_box[1][0] ) * ( root_box[2][1] - root_box[2][0] ); for ( size_t np = 2 ; np < np_max ; np = 2 * ( np + 1 ) ) { std::vector<BoxType> part_boxes( np ); box_partition_rcb( root_box , part_boxes ); size_t cell_goal = ( cell_total + np - 1 ) / np ; size_t cell_max = 0 ; for ( size_t i = 0 ; i < np ; ++i ) { cell_max = std::max( cell_max , count( part_boxes[i] ) ); } if ( print ) { std::cout << std::endl << "box_part( " << np << " ) max( " << cell_max << " ) goal( " << cell_goal << " ) ratio( " << double(cell_max) / double(cell_goal) << " )" << std::endl ; } const size_t nsample = std::min(np,(size_t)4); const size_t stride = ( np + nsample - 1 ) / nsample ; for ( size_t my_part = 0 ; my_part < np ; my_part += stride ) { BoxType my_use_box ; std::vector<size_t> my_use_id_map ; size_t my_count_interior ; size_t my_count_owned ; size_t my_count_uses ; std::vector<size_t> my_recv_counts ; std::vector<std::vector<size_t> > my_send_map ; size_t count_verify = 0 ; box_partition_maps( root_box , part_boxes , use_box , my_part , my_use_box , my_use_id_map , my_count_interior , my_count_owned , my_count_uses , my_recv_counts , my_send_map ); count_verify = my_count_owned ; if ( print ) { std::cout << " my_part(" << my_part << ") layout { " << "P" << my_part << "(" << my_count_interior << "," << ( my_count_owned - my_count_interior ) << ")" ; } for ( size_t i = 1 ; i < np ; ++i ) { if ( my_recv_counts[i] ) { count_verify += my_recv_counts[i] ; const size_t ip = ( my_part + i ) % np ; if ( print ) { std::cout << " P" << ip << "(" << my_recv_counts[i] << ")" ; } // Compare recv & send lists BoxType ip_use_box ; std::vector<size_t> ip_use_id_map ; size_t ip_count_interior ; size_t ip_count_owned ; size_t ip_count_uses ; std::vector<size_t> ip_recv_counts ; std::vector<std::vector<size_t> > ip_send_map ; box_partition_maps( root_box , part_boxes , use_box , ip , ip_use_box , ip_use_id_map , ip_count_interior , ip_count_owned , ip_count_uses , ip_recv_counts , ip_send_map ); // Sent by ip, received by my_part: const BoxType recv_send = intersect( part_boxes[ip] , my_use_box ); const size_t recv_send_count = count( recv_send ); const size_t j = ( my_part + np - ip ) % np ; if ( recv_send_count != my_recv_counts[i] || recv_send_count != ip_send_map[j].size() ) { throw std::runtime_error( std::string("bad recv/send map") ); } } } if ( print ) { std::cout << " }" << std::endl ; } if ( count_verify != my_count_uses ) { throw std::runtime_error( std::string("bad partition map") ); } } } }
#include <ctime> #include <string> #include <iostream> std::string get_greet(const std::string& who) { return "Hello " + who; } void print_localtime() { std::time_t result = std::time(nullptr); std::cout << std::asctime(std::localtime(&result)); } int main(int argc, char** argv) { std::string who = "world"; if (argc > 1) { who = argv[1]; } std::cout << get_greet(who) << std::endl; print_localtime(); return 0; }
; ; PC-8801 specific routines ; ; int set_psg(int reg, int val); ; ; Play a sound by PSG ; ; ; $Id: set_psg.asm $ ; SECTION code_clib PUBLIC set_psg PUBLIC _set_psg EXTERN asm_set_psg set_psg: _set_psg: pop bc pop de pop hl push hl push de push bc jp asm_set_psg
; A030640: Discriminant of lattice A_n of determinant n+1. ; 1,1,-3,-2,5,3,-7,-4,9,5,-11,-6,13,7,-15,-8,17,9,-19,-10,21,11,-23,-12,25,13,-27,-14,29,15,-31,-16,33,17,-35,-18,37,19,-39,-20,41,21,-43,-22,45,23,-47,-24,49,25,-51,-26,53,27,-55,-28,57,29,-59 mov $1,$0 add $0,1 dif $0,2 div $1,2 mov $2,-1 pow $2,$1 mul $0,$2
; ; This file is part of QBDI. ; ; Copyright 2017 - 2021 Quarkslab ; ; 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. ; .386 .model flat, C _TEXT segment PUBLIC runRealExec .CODE runRealExec PROC push ebp; mov ebp, esp; pushad; mov eax, [ebp+8]; mov edi, [ebp+12]; call eax; popad; mov esp, ebp; pop ebp; ret; runRealExec ENDP END