text
stringlengths
1
1.05M
; A204708: Number of (n+1) X 4 0..1 arrays with the permanents of all 2 X 2 subblocks equal and nonzero. ; 25,81,257,833,2689,8705,28161,91137,294913,954369,3088385,9994241,32342017,104660993,338690049,1096024065,3546808321,11477712897,37142659073,120196169729,388962975745,1258710630401,4073273163777,13181388849153,42655870353409,138037296103425,446698073620481,1445545331654657,4677882957791233 add $0,1 mov $2,4 lpb $0,1 sub $0,1 mov $4,$2 add $4,$1 mov $1,$2 mul $1,2 mov $2,$4 add $2,5 mul $2,2 mov $3,$1 lpe add $1,4 sub $3,4 add $1,$3 add $1,9
; =============================================================== ; Mar 2014 ; =============================================================== ; ; int ba_priority_queue_empty(ba_priority_queue_t *q) ; ; Return non-zero if the queue is empty. ; ; =============================================================== SECTION code_clib SECTION code_adt_ba_priority_queue PUBLIC asm_ba_priority_queue_empty EXTERN l_testword_hl defc asm_ba_priority_queue_empty = l_testword_hl - 4 ; enter : hl = priority_queue * ; ; exit : if queue is empty ; ; hl = 1 ; z flag set ; ; if queue is not empty ; ; hl = 0 ; nz flag set ; ; uses : af, hl
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Microsoft Research Singularity ;;; ;;; Copyright (c) Microsoft Corporation. All rights reserved. ;;; ;;; This file contains ARM-specific assembly code. ;;; GBLL leq_s GET basic_d.asm END
scene_var: MACRO ; map, variable map_id \1 dw \2 ENDM MapScenes:: scene_var POKECENTER_2F, wPokecenter2FSceneID scene_var TRADE_CENTER, wTradeCenterSceneID scene_var COLOSSEUM, wColosseumSceneID scene_var TIME_CAPSULE, wTimeCapsuleSceneID ;scene_var REDS_HOUSE_2F, wRedsHouse2FSceneID scene_var SHIZUOKA, wShizuokaSceneID scene_var STUMPSLAB, wStumpsLabSceneID ;scene_var CERULEAN_GYM, wCeruleanGymSceneID ;scene_var ROUTE_25, wRoute25SceneID ;scene_var TRAINER_HOUSE_B1F, wTrainerHouseB1FSceneID ;scene_var VICTORY_ROAD_GATE, wVictoryRoadGateSceneID ;scene_var SAFFRON_MAGNET_TRAIN_STATION, wSaffronMagnetTrainStationSceneID ;scene_var ROUTE_16_GATE, wRoute16GateSceneID ;scene_var ROUTE_17_ROUTE_18_GATE, wRoute17Route18GateSceneID scene_var INDIGO_PLATEAU_POKECENTER_1F, wIndigoPlateauPokecenter1FSceneID scene_var WILLS_ROOM, wWillsRoomSceneID scene_var KOGAS_ROOM, wKogasRoomSceneID scene_var BRUNOS_ROOM, wBrunosRoomSceneID scene_var KARENS_ROOM, wKarensRoomSceneID scene_var LANCES_ROOM, wLancesRoomSceneID scene_var HALL_OF_FAME, wHallOfFameSceneID ;scene_var ROUTE_27, wRoute27SceneID ;scene_var PALLET_TOWN, wPalletTownSceneID ;scene_var ELMS_LAB, wElmsLabSceneID ;scene_var PLAYERS_HOUSE_1F, wPlayersHouse1FSceneID ;scene_var ROUTE_29, wRoute29SceneID ;scene_var CHERRYGROVE_CITY, wCherrygroveCitySceneID ;scene_var MR_POKEMONS_HOUSE, wMrPokemonsHouseSceneID ;scene_var ROUTE_32, wRoute32SceneID ;scene_var ROUTE_35_NATIONAL_PARK_GATE, wRoute35NationalParkGateSceneID ;scene_var ROUTE_36, wRoute36SceneID ;scene_var ROUTE_36_NATIONAL_PARK_GATE, wRoute36NationalParkGateSceneID ;scene_var AZALEA_TOWN, wAzaleaTownSceneID ;scene_var GOLDENROD_GYM, wGoldenrodGymSceneID ;scene_var GOLDENROD_MAGNET_TRAIN_STATION, wGoldenrodMagnetTrainStationSceneID ;scene_var GOLDENROD_POKECENTER_1F, wGoldenrodPokecenter1FSceneID ;scene_var OLIVINE_CITY, wOlivineCitySceneID ;scene_var ROUTE_34, wRoute34SceneID ; unused ;scene_var ROUTE_34_ILEX_FOREST_GATE, wRoute34IlexForestGateSceneID ; unused ;scene_var ECRUTEAK_TIN_TOWER_ENTRANCE, wEcruteakTinTowerEntranceSceneID ;scene_var WISE_TRIOS_ROOM, wWiseTriosRoomSceneID ;scene_var ECRUTEAK_POKECENTER_1F, wEcruteakPokecenter1FSceneID ;scene_var ECRUTEAK_GYM, wEcruteakGymSceneID ;scene_var MAHOGANY_TOWN, wMahoganyTownSceneID ;scene_var ROUTE_42, wRoute42SceneID ;scene_var CIANWOOD_CITY, wCianwoodCitySceneID ;scene_var BATTLE_TOWER_1F, wBattleTower1FSceneID ;scene_var BATTLE_TOWER_BATTLE_ROOM, wBattleTowerBattleRoomSceneID ;scene_var BATTLE_TOWER_ELEVATOR, wBattleTowerElevatorSceneID ;scene_var BATTLE_TOWER_HALLWAY, wBattleTowerHallwaySceneID ;scene_var BATTLE_TOWER_OUTSIDE, wBattleTowerOutsideSceneID ; unused ;scene_var ROUTE_43_GATE, wRoute43GateSceneID scene_var MOUNT_MOON, wMountMoonSceneID ;scene_var SPROUT_TOWER_3F, wSproutTower3FSceneID ;scene_var TIN_TOWER_1F, wTinTower1FSceneID ;scene_var BURNED_TOWER_1F, wBurnedTower1FSceneID ;scene_var BURNED_TOWER_B1F, wBurnedTowerB1FSceneID ;scene_var RADIO_TOWER_5F, wRadioTower5FSceneID ;scene_var RUINS_OF_ALPH_OUTSIDE, wRuinsOfAlphOutsideSceneID ;scene_var RUINS_OF_ALPH_RESEARCH_CENTER, wRuinsOfAlphResearchCenterSceneID ;scene_var RUINS_OF_ALPH_HO_OH_CHAMBER, wRuinsOfAlphHoOhChamberSceneID ;scene_var RUINS_OF_ALPH_KABUTO_CHAMBER, wRuinsOfAlphKabutoChamberSceneID ;scene_var RUINS_OF_ALPH_OMANYTE_CHAMBER, wRuinsOfAlphOmanyteChamberSceneID ;scene_var RUINS_OF_ALPH_AERODACTYL_CHAMBER, wRuinsOfAlphAerodactylChamberSceneID ;scene_var RUINS_OF_ALPH_INNER_CHAMBER, wRuinsOfAlphInnerChamberSceneID ;scene_var MAHOGANY_MART_1F, wMahoganyMart1FSceneID ;scene_var TEAM_ROCKET_BASE_B1F, wTeamRocketBaseB1FSceneID ;scene_var TEAM_ROCKET_BASE_B2F, wTeamRocketBaseB2FSceneID ;scene_var TEAM_ROCKET_BASE_B3F, wTeamRocketBaseB3FSceneID ;scene_var GOLDENROD_UNDERGROUND_SWITCH_ROOM_ENTRANCES, wGoldenrodUndergroundSwitchRoomEntrancesSceneID ;scene_var SILVER_CAVE_ROOM_3, wSilverCaveRoom3SceneID ; unused ;scene_var VICTORY_ROAD, wVictoryRoadSceneID ;scene_var DRAGONS_DEN_B1F, wDragonsDenB1FSceneID ;scene_var DRAGON_SHRINE, wDragonShrineSceneID ;scene_var OLIVINE_PORT, wOlivinePortSceneID ;scene_var VERMILION_PORT, wVermilionPortSceneID scene_var FAST_SHIP_1F, wFastShip1FSceneID scene_var FAST_SHIP_B1F, wFastShipB1FSceneID scene_var MOUNT_MOON_SQUARE, wMountMoonSquareSceneID scene_var MOBILE_TRADE_ROOM, wMobileTradeRoomSceneID scene_var MOBILE_BATTLE_ROOM, wMobileBattleRoomSceneID ;scene_var OAKS_LAB, wOaksLabSceneID ;scene_var VIRIDIAN_CITY, wViridianSceneID db -1 ; end
[BITS 32] GLOBAL _main EXTERN _ExitProcess@4 EXTERN _GetCommandLineA@0 EXTERN _GetStdHandle@4 EXTERN _WriteFile@20 SECTION .text _main: ;;; GetCommandLineA retrieves the cmdline as it was called. It ;;; includes the program name as it was called (e.g. quotes, ;;; relative/absolute path). 2 spaces (ASCII code 20h) ;;; follow the program name. The cmdline is NULL terminated. call _GetCommandLineA@0 mov esi, eax mov edi, eax call strlen_v3 push -0Bh ;STD_OUTPUT_HANDLE call _GetStdHandle@4 push 0 push 0 push ecx push esi push eax call _WriteFile@20 push 0 call _ExitProcess@4 xor eax, eax ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; strlen_v1 ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Description: ; ; Works like the C library function it's named ; ; after. Finds the length of a NULL terminated ; ; string. Version 1 (v1): This function is very ; ; inefficient by reading a single byte of the ; ; input string at a time rather than reading a ; ; DWORD at a time. ; ; ; ; DANGER: This function doesn't place a limit on ; ; the size of the string. If the string is not ; ; NULL terminated, this function will continue ; ; reading bytes of memory until an exception is ; ; thrown. ; ; ; ; Usage and Effects: ; ; ECX: Length of string upon return. ; ; EDI: Pointer to the input string on function ; ; call. Points to input string's NULL ; ; terminator upon return. ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; strlen_v1: xor ecx, ecx .loop: cmp byte [edi], 0 jz .end inc ecx inc edi jmp .loop .end: ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; strlen_v2 ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Description: ; ; Works like the C library function it's named ; ; after. Finds the length of a NULL terminated ; ; string. Version 2 (v2): This function is more ; ; efficient than v1 by reading a DWORD at a time ; ; from the input string. ; ; ; ; DANGER: This function doesn't place a limit on ; ; the size of the string. If the string is not ; ; NULL terminated, this function will continue ; ; reading bytes of memory until an exception is ; ; thrown. ; ; ; ; Usage and Effects: ; ; ECX: Length of string upon return. ; ; EDI: Pointer to the input string on function ; ; call. Points to input string's NULL ; ; terminator upon return. ; ; EDX: DESTROYED upon return. ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; strlen_v2: xor ecx, ecx .loop: mov edx, dword [edi] cmp dl, 0 jz .end shr edx, 8 inc ecx inc edi cmp dl, 0 jz .end shr edx, 8 inc ecx inc edi cmp dl, 0 jz .end shr edx, 8 inc ecx inc edi cmp dl, 0 jz .end inc ecx inc edi jmp .loop .end: ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; strlen_v3 ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Description: ; ; Works like the C library function it's named ; ; after. Finds the length of a NULL terminated ; ; string. Version 3 (v3): This function is the ; ; same as v2 but makes use of the processor's ; ; REP prefix. ; ; ; ; DANGER: This function doesn't place a limit on ; ; the size of the string. If the string is not ; ; NULL terminated, this function will continue ; ; reading bytes of memory until an exception is ; ; thrown. ; ; ; ; Usage and Effects: ; ; EAX: 0 upon return. ; ; ECX: Length of string upon return. ; ; EDI: Pointer to the input string on function ; ; call. Points to input string's NULL ; ; terminator upon return. ; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; strlen_v3: xor eax, eax mov ecx, -1 cld repne scasb inc ecx inc ecx dec edi neg ecx ret
; A045326: Primes congruent to {2, 3} mod 4. ; 2,3,7,11,19,23,31,43,47,59,67,71,79,83,103,107,127,131,139,151,163,167,179,191,199,211,223,227,239,251,263,271,283,307,311,331,347,359,367,379,383,419,431,439,443,463,467,479,487,491,499,503,523,547,563,571,587,599,607,619,631,643,647,659,683,691,719,727,739,743,751,787,811,823,827,839,859,863,883,887,907,911,919,947,967,971,983,991,1019,1031,1039,1051,1063,1087,1091,1103,1123,1151,1163,1171 lpb $0 add $2,1 sub $0,$2 mov $1,$0 max $1,0 seq $1,97538 ; Subtract 2 from primes == 3 (mod 4). add $2,$1 lpe add $1,2 mov $0,$1
; A058038: a(n) = Fibonacci(2*n)*Fibonacci(2*n+2). ; 0,3,24,168,1155,7920,54288,372099,2550408,17480760,119814915,821223648,5628750624,38580030723,264431464440,1812440220360,12422650078083,85146110326224,583600122205488,4000054745112195,27416783093579880 lpb $0 sub $0,1 add $2,1 add $1,$2 add $2,$1 add $1,$2 add $2,$1 lpe
* Network physical layer - QXL (20 MHz)  1984 & 1993 Tony Tebby * section nd * xdef nd_qxlc network access code xdef nd_qxle xdef nd_send send a packet xdef nd_send0 send a packet (server protocol) xdef nd_read read a packet xdef nd_read0 read a packet (server protocol) xdef nd_bcast read a broadcast * xref nd_break read break keys * include dev8_dd_nd_keys include dev8_mac_assert include dev8_smsq_qxl_keys include dev8_smsq_smsq_base_keys include dev8_keys_sys ; The lines ;----------- in this code represent line (16 byte) boundaries ; The code is copied to address qxl_netc ($1f000) to ensure line alignment ; The first two enties are to enable the scout and send byte timing to be ; adjusted. ; The timer constants are in the linkage block (a3) nd_qxlc bra.s ndi_sscout ; remember to set d1,d3,a3,a4,a5 bra.s ndi_sbytes ; remember to set d2,a1,a3,a4,a5 nop nop nop nop *********************************** * wait for active / inactive timers - 28.2 cycles / 1.41 us * ndt_wact equ *-nd_qxlc+qxl_netc move.w (a3,d0.w),d0 ; set up timer ;------------------------------------------- ndt_walp tst.b (a2) ; wait for active dbne d0,ndt_walp rts dc.w 0,0 ndt_wina equ *-nd_qxlc+qxl_netc move.w (a3,d0.w),d0 ;------------------------------------------- ndt_wilp tst.b (a2) ; wait for inactive dbeq d0,ndt_wilp rts dc.w 0,0 ndt_wait equ *-nd_qxlc+qxl_netc move.w (a3,d0.w),d0 ;------------------------------------------- ndt_wtlp tst.b (a2) ; wait, ignoring active/inactive dbra d0,ndt_wtlp rts ****************************************** * Send Scout: d1 bits in d3 msbytes * nd_sscout equ *-nd_qxlc+qxl_netc ndi_sscout move.w ndt_tsct(a3),d2 timer constant lsl.l #8,d3 next bit is lsb not.l d3 nds_sscbit ;----------------------------------------- move.w d2,d0 clr.w d3 lsr.l #1,d3 dc.w $50f5,$3200 ; st (a5,d3.w*2) nop tst.w d3 bpl.s nds_sact ... net is active ;----------------------------------------- nds_tact tst.b (a2) dbne d0,nds_tact 31us in loop bra.s nds_nxts dc.w 0,0,0,0 ;----------------------------------------- nds_sact tst.b (a2) dbra d0,nds_sact 31us in loop moveq #0,d0 * nds_nxts dbne d1,nds_sscbit 32us loop gives scout 480 us + rts dc.w 0 ;---------------------------------------- dc.w 0,0,0 ******************************** * Send d2 bytes (a1) * nd_sbytes equ *-nd_qxlc+qxl_netc ndi_sbytes moveq #ndt_paus,d0 pause 140 us jsr ndt_wait moveq #0,d3 preset send byte to 1s ;---------------------------------------- nds_byloop move.b (a1)+,d3 get byte not.b d3 add.w d3,d3 shift left addq.b #1,d3 lsl.w #2,d3 preceded by two stop bits swap d3 in msword moveq #12,d1 send 13 bits altogether * nds_bit_loop asr.l #1,d3 get next bit ;---------------------------------------- dc.w $50f5,$3200 ; st (a5,d3.w*2) nop move.w ndt_send(a3),d0 subq.w #4,d0 ; go down in counts of 4 bge.s *-2 roxr.w #2,d0 ; v clear ls bits in carry and sign ;---------------------------------------- bcs.s nds_eb23 bpl.s nds_eb0 dc.w $59fc ; trapvs bra.s nds_eb1 nds_eb23 bpl.s nds_eb2 bra.s nds_eb3 moveq #0,d0 moveq #0,d0 ;---------------------------------------- nds_eb3 bra.s nds_ebit dc.w $59fc ; trapvs nds_eb0 dc.w $59fc ; trapvs nds_eb1 nds_eb2 dc.w $59fc ; trapvs nds_ebit clr.w d3 dbra d1,nds_bit_loop hopefully about 224 cycles subq.w #1,d2 next byte ;---------------------------------------- bne.s nds_byloop * st (a4) inactive rts ****************************************************** * Read bytes (byte count d2, checksum d4, address a1) * nd_rbytes equ *-nd_qxlc+qxl_netc move.l nd_rpnt(a0),a1 read multiple bytes into data buffer nd_r1byte equ *-nd_qxlc+qxl_netc moveq #0,d4 checksum moveq #ndt_rtmo,d0 initial timeout ndr_byloop moveq #8,d1 eight bits per byte (plus start bit) ;---------------------------------------- jsr ndt_wact wait for net to go active beq.s ndr_nc ... oops, loss of comms * ndr_start tst.b (a2) wait for start bit dbeq d0,ndr_start bne.s ndr_nc ... oops, loss of comms ;---------------------------------------- move.w ndt_rdly(a3),d0 set up start bit timer bra.s ndr_bwait ndr_bit_loop move.w ndt_rbit(a3),d0 ndr_bwait subq.w #4,d0 ; go down in counts of 4 bge.s *-2 roxr.w #2,d0 ; v clear ls bits in carry and sign ;---------------------------------------- bcs.s ndr_eb23 bpl.s ndr_eb0 dc.w $59fc ; trapvs bra.s ndr_eb1 ndr_eb23 bpl.s ndr_eb2 bra.s ndr_eb3 moveq #0,d0 moveq #0,d0 ;---------------------------------------- ndr_eb3 bra.s ndr_rbit dc.w $59fc ; trapvs ndr_eb0 dc.w $59fc ; trapvs ndr_eb1 ndr_eb2 dc.w $59fc ; trapvs ;---------------------------------------- ndr_rbit move.b (a2),d3 next data bit ror.w #1,d3 dbra d1,ndr_bit_loop lsr.w #8,d3 get byte into low end move.b d3,(a1)+ put into buffer add.w d3,d4 and add to checksum moveq #ndt_rbto,d0 subsequent byte timeout = about 7 bits subq.w #1,d2 next byte bne.s ndr_byloop rts ndr_nc moveq #err.nc,d0 rts nd_qxle *%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ******************************************* * Set Buffer Pointers * nd_sbuf bsr.s nd_srpnt get pointer to data block move.l a1,nd_epnt(a0) set end pointer rts nd_srpnt lea nd_data(a0),a1 get pointer to data block move.l a1,nd_rpnt(a0) set running pointer rts page ******************************************* * Network read packet * nd_read0 clr.w nd_blkl(a0) clear block number nd_read bsr.l nd_setup setup registers etc. bsr.s nd_sbuf set buffer pointers * * check there's a gap at least 200us long * moveq #ndt_wgap,d0 test 200us jsr ndt_wact bne.s nd_e2_nc * * Gap found, look for scout for 20ms (50us active), * and.w #$f8ff,sr reenable interrupts moveq #ndt_lsct,d0 wait 20ms jsr ndt_wact beq.s nd_e3_nc ... no or.w #$0700,sr disable interrupts moveq #ndt_csct,d0 test 40us jsr ndt_wina nd_e3_nc beq.s nd_e1_nc not a scout * moveq #ndt_esct,d0 jsr ndt_wait wait 490us until end of scout * * Scout found and skipped, read header * bsr.l ndr_headr read header nd_e2_nc bne.s nd_e1_nc ... oops move.b (a1)+,d0 get destination from packet header cmp.b nd_self(a0),d0 is it for me? bne.s nd_e1_nc ... no move.b (a1)+,d1 get source from packet header cmp.b nd_dest(a0),d1 is from my preferred source? beq.s ndr_for_me ... yes cmp.b nd_dest(a0),d0 will I accept an offer from anybody? bne.s nd_e1_nc ... no move.b d1,nd_dest(a0) ... yes, from now on I talk to you only!! * ndr_for_me move.w (a1)+,d5 get block/byte (or checksum) sub.w nd_blkl(a0),d5 and compare against required * move.l (a1),nd_type(a0) set type, number of bytes and checksum moveq #0,d4 set number of bytes to read move.b nd_nbyt(a0),d4 addq.b #-nf.sblk,(a1) is it send large block? bne.s ndr_ackh ... no lsl.w #2,d4 ... yes, get 4* as many * ndr_ackh bsr.l nds_ack acknowledge header move.w d4,d2 and set number of bytes to read jsr nd_rbytes bne.s nd_bad_block ... oops cmp.b nd_dchk(a0),d4 was checksum ok? bne.s nd_bad_block tst.b nd_dest(a0) was it file server transaction? blt.s ndr_wchk ... yes tst.b nd_self(a0) bge.s ndr_ack ... no, acknowledge ndr_wchk cmp.w d5,d4 ... yes, check whole checksum bne.s nd_bad_block ... ... oops clr.w d5 ndr_ack bsr.l nds_ack send acknowledge * tst.w d5 was this the right block? bne.s nd_e1_nc ... no, leave eof flag move.l a1,nd_epnt(a0) ... yes, set end pointer bsr.s nd_nextb move to next block bra.l nd_ex_ok done * nd_bad_block sf nd_type(a0) clear type nd_e1_nc bra.l nd_ex_nc not complete * * move to next block * nd_nextb addq.b #1,nd_blkl(a0) move block low on one bcc.s nd_nx_rts addq.b #1,nd_blkh(a0) carry, so move block high on nd_nx_rts rts page ****************************************************** * Network send packet * * Create checksum * nd_csum moveq #0,d4 clear checksum moveq #0,d2 nd_csloop move.b (a1)+,d2 get byte add.w d2,d4 add byte subq.w #1,d1 next byte bne.s nd_csloop rts * * Send a packet - if net busy, give up * nd_send0 nd_send bsr.l nd_setup set net mode and registers * * Now do all the checksum rubbish so we can go straight on from the scout * moveq #0,d5 length of data block move.b nd_nbyt(a0),d5 cmp.b #nf.sblk,nd_type(a0) is it remote file block? bne.s nds_cdata ... no, create data checksum lsl.w #2,d5 ... yes, 4* as many bytes nds_cdata move.w d5,d1 create checksum lea nd_data(a0),a1 of data bsr.s nd_csum move.b d4,nd_dchk(a0) in data checksum loc tst.b nd_self(a0) is it server blt.s nds_wchk ... yes tst.b nd_dest(a0) bge.s nds_chead ... no, just create header checksum nds_wchk move.w d4,nd_blkl(a0) ... yes, set word checksum in block number nds_chead moveq #7,d1 create checksum lea nd_hedr(a0),a1 of header bsr.s nd_csum move.b d4,(a1) in header checksum loc at end of header * subq.l #7,a1 backspace to start of header * * Now send a scout, checking if anyone else is * moveq #-1,d3 preset 1s move.w nd_dest(a0),d3 get destination and self lsl.b #3,d3 11111111.11111111.000ddddd.sssss000 addq.b #3,d3 11111111.11111111.000ddddd.sssss011 lsl.w #2,d3 11111111.11111111.0dddddss.sss01100 lsl.l #6,d3 11111111.110ddddd.sssss011.00000000 moveq #14,d1 send 15 bits 110xxxxxxxxxxxx01 * * Wait at least 3 ms for any other scout * moveq #ndt_wsct,d0 3ms jsr ndt_wact ... wait for active bne.s nd_unset ... net active return +ve * jsr nd_sscout bne.s nd_ex_nc ; busy tst.b nd_dest(a0) was it broadcast? bne.s nds_header ... no, send header moveq #ndt_xsct,d0 ... yes, wait = 5ms jsr ndt_wait with net active * nds_header moveq #8,d2 send eight bytes from header bsr.l nds_half (half a packets worth) bne.s nd_ex_nc ... oops * move.w d5,d2 length of data block bsr.s nds_half (the other half of the packet) bne.s nd_ex_nc ... oops * tst.b nd_dest(a0) was it broadcast? bne.s nds_done ... no, done * moveq #ndt_back,d0 wait 500us jsr ndt_wact looking for active beq.s nd_ex_nc ... no acknowledge moveq #ndt_bace,d0 for 20ms jsr ndt_wina look for inactive * moveq #ndt_back,d0 wait 500us jsr ndt_wact looking for active bne.s nd_ex_nc ... nack nds_done bsr.l nd_nextb page * * Exits * nd_ex_ok moveq #0,d0 OK bra.s nd_unset nd_ex_nc moveq #err.nc,d0 not complete - quite normal nd_unset nd_exit move.l d0,d1 move.w (sp)+,sys_castt(a6) bne.s ndex_rest ; no cache or suppressed jsr sms.cenab ; enable both bra.s ndex_rest ndex_ninst jsr sms.cenab ; enable both jsr sms.cdisi ; disable instruction ndex_rest move.l d1,d0 movem.l (sp)+,d1-d7/a1/a2/a4/a5 pop regs and.w #$f8ff,sr reenable interrupts rts * * setup network, save regs, set cache etc * * a2 r neti * a4 r netl * a5 r neth * nd_setup move.l (sp)+,d0 pop return address movem.l d1-d7/a1/a2/a4/a5,-(sp) save regs move.l d0,a1 ... return is jmp (a1) lea qxl_neti,a2 lea qxl_netl,a4 lea qxl_neth,a5 net low is a5 -$8000-$8000 or.w #$0700,sr no interrupts move.w sys_castt(a6),-(sp) save cache status st sys_castt(a6) kill cache jsr sms.cdisb disable both caches jmp (a1) page * * Send procedures * * Send half a packet (byte count d2, address a1) * nds_half jsr nd_sbytes send bytes tst.b nd_dest(a0) is it b/cast? beq.s nds_rts ... yes, done moveq #1,d2 receive one byte reply lea nd_data-1(a0),a1 put into header checksum jsr nd_r1byte subq.b #1,d4 result should be 1 nds_rts rts * * Send acknowledge * nds_ack moveq #1,d2 send one byte move.l a1,-(sp) move.b d2,-(sp) move.l sp,a1 jsr nd_sbytes addq.w #2,sp move.l (sp)+,a1 rts page * * Read procedures * * Read header * ndr_headr moveq #8,d2 read eight bytes jsr nd_rbytes bne.s ndrh_rts ... oops sub.b -(a1),d4 take last byte away from checksum sub.b (a1),d4 is it ok? subq.l #7,a1 and backspace pointer ndrh_rts rts * d6 c p size of buffer extension * d7 p direct input bit number * a0 c p channel definition / $20(a0) header / $28(a0) data block * * Network Broadcast * nd_bcast bsr.l nd_sbuf set buffer pointers add.l d6,nd_epnt(a0) and extend the buffer bsr.s nd_setup setup registers etc. ndb_check move.l nd_rpnt(a0),a1 get running pointer cmp.l nd_epnt(a0),a1 check for end of buffer bgt.s ndb_abort * * Wait for continuous activity for minimum 500 us * ndb_start bsr.l nd_break check for break beq.s ndb_wscout not pressed, look for scout * ndb_abort move.b #1,nd_type(a0) ... set eof bra.s ndb_eof * ndb_wscout moveq #ndt_bsct,d0 500 us of continuous activity jsr ndt_wina wait for inactive beq.s ndb_start ... yes, restart * bsr.s ndr_headr read bytes bne.s ndb_nack ... oops tst.b (a1) was it broadcast? bne.s ndb_nack ... it must have been!!! * addq.l #2,a1 look at block/byte move.b (a1)+,d5 lsl.w #8,d5 move.b (a1)+,d5 sub.w nd_blkl(a0),d5 and compare against required * move.b (a1)+,nd_type(a0) set type move.b (a1)+,d2 number of bytes move.b (a1)+,nd_dchk(a0) ... and checksum * jsr nd_rbytes bne.s ndb_nack ... oops cmp.b nd_dchk(a0),d4 was checksum OK? bne.s ndb_nack * bsr.s ndb_active send acknowledgement * tst.w d5 was it the correct block? bne.s ndb_eof bsr.l nd_nextb move to next block move.l a1,nd_rpnt(a0) ndb_eof tst.b nd_type(a0) was it eof? beq.s ndb_check ... no, check if buffer full and continue * move.l a1,nd_epnt(a0) ... yes, set end pointer bsr.l nd_srpnt ... and reset running pointer bra.l nd_ex_ok * ndb_nack moveq #ndt_wgap,d0 wait for 200us inactive jsr ndt_wact beq.s ndb_start network is idle - restart * ndb_nact moveq #ndt_back,d0 check for 500us active jsr ndt_wina beq.s ndb_nack not BACK, try again move.w ndt_bnak(a3),d0 wait 200 us jsr ndt_wait * bsr.s ndb_active bra.l ndb_start and restart * ndb_active st (a5) set active moveq #ndt_xack,d0 5000us active jsr ndt_wait st (a4) set inactive rts end
// Copyright 2015-2020 Tier IV, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <quaternion_operation/quaternion_operation.h> #include <ament_index_cpp/get_package_share_directory.hpp> #include <cpp_mock_scenarios/catalogs.hpp> #include <cpp_mock_scenarios/cpp_scenario_node.hpp> #include <rclcpp/rclcpp.hpp> #include <traffic_simulator/api/api.hpp> #include <traffic_simulator_msgs/msg/driver_model.hpp> // headers in STL #include <memory> #include <string> #include <vector> class AccelerateAndFollowScenario : public cpp_mock_scenarios::CppScenarioNode { public: explicit AccelerateAndFollowScenario(const rclcpp::NodeOptions & option) : cpp_mock_scenarios::CppScenarioNode( "accelerate_and_follow", ament_index_cpp::get_package_share_directory("kashiwanoha_map") + "/map", "private_road_and_walkway_ele_fix/lanelet2_map.osm", __FILE__, false, option) { start(); } private: void onUpdate() override { double ego_accel = api_.getEntityStatus("ego").action_status.accel.linear.x; double ego_twist = api_.getEntityStatus("ego").action_status.twist.linear.x; // double npc_accel = api_.getEntityStatus("npc").action_status.accel.linear.x; double npc_twist = api_.getEntityStatus("npc").action_status.twist.linear.x; // LCOV_EXCL_START if (npc_twist > (ego_twist + 1) && ego_accel < 0) { stop(cpp_mock_scenarios::Result::FAILURE); } if (api_.checkCollision("ego", "npc")) { stop(cpp_mock_scenarios::Result::FAILURE); } // LCOV_EXCL_STOP if (api_.getCurrentTime() >= 10) { stop(cpp_mock_scenarios::Result::SUCCESS); } } void onInitialize() override { api_.spawn("ego", getVehicleParameters()); api_.setEntityStatus( "ego", traffic_simulator::helper::constructLaneletPose(34741, 0, 0), traffic_simulator::helper::constructActionStatus(3)); api_.spawn("npc", getVehicleParameters()); api_.setEntityStatus( "npc", traffic_simulator::helper::constructLaneletPose(34741, 10, 0), traffic_simulator::helper::constructActionStatus(10)); api_.requestSpeedChange("npc", 10, true); } }; int main(int argc, char * argv[]) { rclcpp::init(argc, argv); rclcpp::NodeOptions options; auto component = std::make_shared<AccelerateAndFollowScenario>(options); rclcpp::spin(component); rclcpp::shutdown(); return 0; }
.size 8000 .text@48 jp lstatint .text@100 jp lbegin .data@143 80 .text@150 lbegin: ld a, ff ldff(45), a ld b, 96 call lwaitly_b ld a, 80 ldff(68), a ld a, ff ld c, 69 ldff(c), a ldff(c), a ldff(c), a ldff(c), a ldff(c), a ldff(c), a xor a, a ldff(c), a ldff(c), a ld a, 40 ldff(41), a ld a, 02 ldff(ff), a xor a, a ldff(0f), a ei ld a, b inc a inc a ldff(45), a ld c, 0f .text@1000 lstatint: ld a, 10 ldff(41), a ld a, 99 ldff(45), a xor a, a ldff(c), a .text@1062 ld a, 40 ldff(41), a nop nop nop nop nop nop nop nop nop nop ldff a, (c) jp lprint_a .text@7000 lprint_a: push af ld b, 91 call lwaitly_b xor a, a ldff(40), a ld bc, 7a00 ld hl, 8000 ld d, 00 lprint_copytiles: ld a, (bc) inc bc ld(hl++), a dec d jrnz lprint_copytiles pop af ld b, a srl a srl a srl a srl a ld(9800), a ld a, b and a, 0f ld(9801), a ld a, c0 ldff(47), a ld a, 80 ldff(68), a ld a, ff ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a ldff(69), a xor a, a ldff(69), a ldff(69), a ldff(43), a ld a, 91 ldff(40), a lprint_limbo: jr lprint_limbo .text@7400 lwaitly_b: ld c, 44 lwaitly_b_loop: ldff a, (c) cmp a, b jrnz lwaitly_b_loop ret .data@7a00 00 00 7f 7f 41 41 41 41 41 41 41 41 41 41 7f 7f 00 00 08 08 08 08 08 08 08 08 08 08 08 08 08 08 00 00 7f 7f 01 01 01 01 7f 7f 40 40 40 40 7f 7f 00 00 7f 7f 01 01 01 01 3f 3f 01 01 01 01 7f 7f 00 00 41 41 41 41 41 41 7f 7f 01 01 01 01 01 01 00 00 7f 7f 40 40 40 40 7e 7e 01 01 01 01 7e 7e 00 00 7f 7f 40 40 40 40 7f 7f 41 41 41 41 7f 7f 00 00 7f 7f 01 01 02 02 04 04 08 08 10 10 10 10 00 00 3e 3e 41 41 41 41 3e 3e 41 41 41 41 3e 3e 00 00 7f 7f 41 41 41 41 7f 7f 01 01 01 01 7f 7f 00 00 08 08 22 22 41 41 7f 7f 41 41 41 41 41 41 00 00 7e 7e 41 41 41 41 7e 7e 41 41 41 41 7e 7e 00 00 3e 3e 41 41 40 40 40 40 40 40 41 41 3e 3e 00 00 7e 7e 41 41 41 41 41 41 41 41 41 41 7e 7e 00 00 7f 7f 40 40 40 40 7f 7f 40 40 40 40 7f 7f 00 00 7f 7f 40 40 40 40 7f 7f 40 40 40 40 40 40
/* ============================================================================ Name : Coordinate.cpp Author : Sun Jinbo Version : 1.0 Copyright : Your copyright notice Description : CCoordinate implementation ============================================================================ */ #include <eikenv.h> #include <fbs.h> #include <bitstd.h> #include <coecntrl.h> #include "Coordinate.h" #include "EllipseEnv.h" // CONSTANTS _LIT( KOriginText, "0" ); const TInt KOriginTextOffset = 4; _LIT( KXAxisText, "X" ); const TInt KXAxisTextOffset = 4; _LIT( KYAxisText, "Y" ); const TInt KYAxisTextOffset = 4; const TInt KScaleGap = 10; const TInt KScaleLen = 5; const TRgb KLineColor = KRgbBlack; CCoordinate::CCoordinate( MEllipseEnv& aEnv, const TRect& aRect ) : iGc( aEnv.Gc() ), iEnv( aEnv.EikonEnv() ), iCoordinateRect( aRect ) { // No implementation required } CCoordinate::~CCoordinate() { iEnv->ScreenDevice()->ReleaseFont( iFont ); } CCoordinate* CCoordinate::NewLC( MEllipseEnv& aEnv, const TRect& aRect ) { CCoordinate* self = new (ELeave) CCoordinate( aEnv, aRect ); CleanupStack::PushL(self); self->ConstructL(); return self; } CCoordinate* CCoordinate::NewL( MEllipseEnv& aEnv, const TRect& aRect ) { CCoordinate* self = CCoordinate::NewLC( aEnv, aRect ); CleanupStack::Pop(); // self; return self; } void CCoordinate::ConstructL() { TFontSpec fontSpec = iEnv->AnnotationFont()->FontSpecInTwips(); fontSpec.iHeight -= fontSpec.iHeight / 3; fontSpec.iFontStyle.SetBitmapType( EMonochromeGlyphBitmap ); iEnv->ScreenDevice()->GetNearestFontInTwips( iFont, fontSpec ); } void CCoordinate::Draw() { // Draws background iGc->SetPenStyle( CGraphicsContext::ESolidPen ); iGc->SetBrushStyle( CGraphicsContext::ENullBrush ); // Draws X-Axis TPoint start, end; start.iX = iCoordinateRect.iTl.iX; start.iY = iCoordinateRect.iBr.iY - iCoordinateRect.Height() / 2; end.iX = iCoordinateRect.iBr.iX; end.iY = iCoordinateRect.iBr.iY - iCoordinateRect.Height() / 2; iGc->SetPenColor( KLineColor ); iGc->DrawLine( start, end ); TInt x = 0; TInt y = iCoordinateRect.Center().iY; for ( x = iCoordinateRect.Center().iX + KScaleGap; x < iCoordinateRect.iBr.iX; x += KScaleGap ) { iGc->DrawLine( TPoint( x, y ), TPoint( x, y - KScaleLen ) ); } for ( x = iCoordinateRect.Center().iX - KScaleGap; x > iCoordinateRect.iTl.iX; x -= KScaleGap ) { iGc->DrawLine( TPoint( x, y ), TPoint( x, y - KScaleLen ) ); } // Draws Y-Axis start.iX = iCoordinateRect.iBr.iX - iCoordinateRect.Width() / 2; start.iY = iCoordinateRect.iTl.iY; end.iX = iCoordinateRect.iBr.iX - iCoordinateRect.Width() / 2; end.iY = iCoordinateRect.iBr.iY; iGc->SetPenColor( KLineColor ); iGc->DrawLine( start, end ); x = iCoordinateRect.Center().iX; for ( y = iCoordinateRect.Center().iY + KScaleGap; y < iCoordinateRect.iBr.iY; y += KScaleGap ) { iGc->DrawLine( TPoint( x, y ), TPoint( x - KScaleLen, y ) ); } for ( y = iCoordinateRect.Center().iY + KScaleGap; y > iCoordinateRect.iTl.iY; y -= KScaleGap ) { iGc->DrawLine( TPoint( x, y ), TPoint( x - KScaleLen, y ) ); } // Draws original point TRect textRect; TPoint tl; tl.iX = iCoordinateRect.Center().iX + KOriginTextOffset; tl.iY = iCoordinateRect.Center().iY + KOriginTextOffset; TInt w = iFont->TextWidthInPixels( KOriginText ); TInt h = iFont->HeightInPixels(); textRect.SetRect( tl, TSize( w, h ) ); TInt baseline = ( textRect.Height() + iFont->HeightInPixels() ) / 2; iGc->SetPenColor( KRgbBlack ); iGc->UseFont( iFont ); iGc->DrawText( KOriginText, textRect, baseline, CGraphicsContext::ECenter, 0 ); // Draws X-Axis text w = iFont->TextWidthInPixels( KXAxisText ); h = iFont->HeightInPixels(); tl.iX = iCoordinateRect.iBr.iX - w - KXAxisTextOffset; tl.iY = iCoordinateRect.iBr.iY - iCoordinateRect.Height() / 2 + KXAxisTextOffset; textRect.SetRect( tl, TSize( w, h ) ); iGc->SetPenColor( KRgbBlack ); iGc->DrawText( KXAxisText, textRect, baseline, CGraphicsContext::ECenter, 0 ); // Draws Y-Axis text w = iFont->TextWidthInPixels( KYAxisText ); h = iFont->HeightInPixels(); tl.iX = iCoordinateRect.iBr.iX - iCoordinateRect.Width() / 2 + KYAxisTextOffset; tl.iY = iCoordinateRect.iTl.iY; textRect.SetRect( tl, TSize( w, h ) ); iGc->SetPenColor( KRgbBlack ); iGc->DrawText( KYAxisText, textRect, baseline, CGraphicsContext::ECenter, 0 ); // Discards font iGc->DiscardFont(); } void CCoordinate::SetRect( const TRect& aRect ) { iCoordinateRect = aRect; }
/*------------------------------------------------------------------------ * Vulkan Conformance Tests * ------------------------ * * Copyright (c) 2015 The Khronos Group Inc. * Copyright (c) 2015 ARM Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *//*! * \file * \brief Pipeline Cache Tests *//*--------------------------------------------------------------------*/ #include "vktPipelineCacheTests.hpp" #include "vktPipelineClearUtil.hpp" #include "vktPipelineImageUtil.hpp" #include "vktPipelineVertexUtil.hpp" #include "vktTestCase.hpp" #include "vktTestCaseUtil.hpp" #include "vkImageUtil.hpp" #include "vkMemUtil.hpp" #include "vkPrograms.hpp" #include "vkBuilderUtil.hpp" #include "vkQueryUtil.hpp" #include "vkRef.hpp" #include "vkRefUtil.hpp" #include "vkTypeUtil.hpp" #include "vkCmdUtil.hpp" #include "vkObjUtil.hpp" #include "tcuImageCompare.hpp" #include "deUniquePtr.hpp" #include "deMemory.h" #include "tcuTestLog.hpp" #include <sstream> #include <vector> namespace vkt { namespace pipeline { using namespace vk; namespace { enum { VK_MAX_SHADER_STAGES = 6, }; // helper functions std::string getShaderFlagStr (const VkShaderStageFlagBits shader, bool isDescription) { std::ostringstream desc; switch(shader) { case VK_SHADER_STAGE_VERTEX_BIT: { desc << ((isDescription) ? "vertex stage" : "vertex_stage"); break; } case VK_SHADER_STAGE_FRAGMENT_BIT: { desc << ((isDescription) ? "fragment stage" : "fragment_stage"); break; } case VK_SHADER_STAGE_GEOMETRY_BIT: { desc << ((isDescription) ? "geometry stage" : "geometry_stage"); break; } case VK_SHADER_STAGE_COMPUTE_BIT: { desc << ((isDescription) ? "compute stage" : "compute_stage"); break; } case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT: { desc << ((isDescription) ? "tessellation control stage" : "tessellation_control_stage"); break; } case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT: { desc << ((isDescription) ? "tessellation evaluation stage" : "tessellation_evaluation_stage"); break; } default: desc << "unknown shader stage!"; DE_FATAL("Unknown shader Stage!"); break; }; return desc.str(); } // helper classes class CacheTestParam { public: CacheTestParam (const VkShaderStageFlagBits* shaders, deUint32 count); virtual ~CacheTestParam (void); virtual const std::string generateTestName (void) const; virtual const std::string generateTestDescription (void) const; VkShaderStageFlagBits getShaderFlag (deUint32 ndx) const { return m_shaders[ndx]; } deUint32 getShaderCount (void) const { return (deUint32)m_shaderCount; } protected: VkShaderStageFlagBits m_shaders[VK_MAX_SHADER_STAGES]; size_t m_shaderCount; }; CacheTestParam::CacheTestParam (const VkShaderStageFlagBits* shaders, deUint32 count) { DE_ASSERT(count <= VK_MAX_SHADER_STAGES); for (deUint32 ndx = 0; ndx < count; ndx++) m_shaders[ndx] = shaders[ndx]; m_shaderCount = count; } CacheTestParam::~CacheTestParam (void) { } const std::string CacheTestParam::generateTestName (void) const { std::string result(getShaderFlagStr(m_shaders[0], false)); for(deUint32 ndx = 1; ndx < m_shaderCount; ndx++) result += '_' + getShaderFlagStr(m_shaders[ndx], false) ; return result; } const std::string CacheTestParam::generateTestDescription (void) const { std::string result("Create pipeline cache with " + getShaderFlagStr(m_shaders[0], true)); for(deUint32 ndx = 1; ndx < m_shaderCount; ndx++) result += ' ' + getShaderFlagStr(m_shaders[ndx], true); return result; } class SimpleGraphicsPipelineBuilder { public: SimpleGraphicsPipelineBuilder (Context& context); ~SimpleGraphicsPipelineBuilder (void) { } void bindShaderStage (VkShaderStageFlagBits stage, const char* sourceName, const char* entryName); void enableTessellationStage (deUint32 patchControlPoints); Move<VkPipeline> buildPipeline (tcu::UVec2 renderSize, VkRenderPass renderPass, VkPipelineCache cache, VkPipelineLayout pipelineLayout); protected: Context& m_context; Move<VkShaderModule> m_shaderModules[VK_MAX_SHADER_STAGES]; deUint32 m_shaderStageCount; VkPipelineShaderStageCreateInfo m_shaderStageInfo[VK_MAX_SHADER_STAGES]; deUint32 m_patchControlPoints; }; SimpleGraphicsPipelineBuilder::SimpleGraphicsPipelineBuilder (Context& context) : m_context(context) { m_patchControlPoints = 0; m_shaderStageCount = 0; } void SimpleGraphicsPipelineBuilder::bindShaderStage (VkShaderStageFlagBits stage, const char* sourceName, const char* entryName) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); // Create shader module deUint32* code = (deUint32*)m_context.getBinaryCollection().get(sourceName).getBinary(); deUint32 codeSize = (deUint32)m_context.getBinaryCollection().get(sourceName).getSize(); const VkShaderModuleCreateInfo moduleCreateInfo = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkShaderModuleCreateFlags flags; codeSize, // deUintptr codeSize; code, // const deUint32* pCode; }; m_shaderModules[m_shaderStageCount] = createShaderModule(vk, vkDevice, &moduleCreateInfo); // Prepare shader stage info m_shaderStageInfo[m_shaderStageCount].sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; m_shaderStageInfo[m_shaderStageCount].pNext = DE_NULL; m_shaderStageInfo[m_shaderStageCount].flags = 0u; m_shaderStageInfo[m_shaderStageCount].stage = stage; m_shaderStageInfo[m_shaderStageCount].module = *m_shaderModules[m_shaderStageCount]; m_shaderStageInfo[m_shaderStageCount].pName = entryName; m_shaderStageInfo[m_shaderStageCount].pSpecializationInfo = DE_NULL; m_shaderStageCount++; } Move<VkPipeline> SimpleGraphicsPipelineBuilder::buildPipeline (tcu::UVec2 renderSize, VkRenderPass renderPass, VkPipelineCache cache, VkPipelineLayout pipelineLayout) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); // Create pipeline const VkVertexInputBindingDescription vertexInputBindingDescription = { 0u, // deUint32 binding; sizeof(Vertex4RGBA), // deUint32 strideInBytes; VK_VERTEX_INPUT_RATE_VERTEX, // VkVertexInputRate inputRate; }; const VkVertexInputAttributeDescription vertexInputAttributeDescriptions[2] = { { 0u, // deUint32 location; 0u, // deUint32 binding; VK_FORMAT_R32G32B32A32_SFLOAT, // VkFormat format; 0u // deUint32 offsetInBytes; }, { 1u, // deUint32 location; 0u, // deUint32 binding; VK_FORMAT_R32G32B32A32_SFLOAT, // VkFormat format; DE_OFFSET_OF(Vertex4RGBA, color), // deUint32 offsetInBytes; } }; const VkPipelineVertexInputStateCreateInfo vertexInputStateParams = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineVertexInputStateCreateFlags flags; 1u, // deUint32 vertexBindingDescriptionCount; &vertexInputBindingDescription, // const VkVertexInputBindingDescription* pVertexBindingDescriptions; 2u, // deUint32 vertexAttributeDescriptionCount; vertexInputAttributeDescriptions, // const VkVertexInputAttributeDescription* pVertexAttributeDescriptions; }; const VkPipelineInputAssemblyStateCreateInfo inputAssemblyStateParams = { VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineInputAssemblyStateCreateFlags flags; (m_patchControlPoints == 0 ? VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST : VK_PRIMITIVE_TOPOLOGY_PATCH_LIST), // VkPrimitiveTopology topology; VK_FALSE, // VkBool32 primitiveRestartEnable; }; const VkViewport viewport = makeViewport(renderSize); const VkRect2D scissor = makeRect2D(renderSize); const VkPipelineViewportStateCreateInfo viewportStateParams = { VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineViewportStateCreateFlags flags; 1u, // deUint32 viewportCount; &viewport, // const VkViewport* pViewports; 1u, // deUint32 scissorCount; &scissor // const VkRect2D* pScissors; }; const VkPipelineRasterizationStateCreateInfo rasterStateParams = { VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineRasterizationStateCreateFlags flags; VK_FALSE, // VkBool32 depthClampEnable; VK_FALSE, // VkBool32 rasterizerDiscardEnable; VK_POLYGON_MODE_FILL, // VkPolygonMode polygonMode; VK_CULL_MODE_NONE, // VkCullModeFlags cullMode; VK_FRONT_FACE_COUNTER_CLOCKWISE, // VkFrontFace frontFace; VK_FALSE, // VkBool32 depthBiasEnable; 0.0f, // float depthBiasConstantFactor; 0.0f, // float depthBiasClamp; 0.0f, // float depthBiasSlopeFactor; 1.0f, // float lineWidth; }; const VkPipelineColorBlendAttachmentState colorBlendAttachmentState = { VK_FALSE, // VkBool32 blendEnable; VK_BLEND_FACTOR_ONE, // VkBlendFactor srcColorBlendFactor; VK_BLEND_FACTOR_ZERO, // VkBlendFactor dstColorBlendFactor; VK_BLEND_OP_ADD, // VkBlendOp colorBlendOp; VK_BLEND_FACTOR_ONE, // VkBlendFactor srcAlphaBlendFactor; VK_BLEND_FACTOR_ZERO, // VkBlendFactor dstAlphaBlendFactor; VK_BLEND_OP_ADD, // VkBlendOp alphaBlendOp; VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT // VkColorComponentFlags colorWriteMask; }; const VkPipelineColorBlendStateCreateInfo colorBlendStateParams = { VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineColorBlendStateCreateFlags flags; VK_FALSE, // VkBool32 logicOpEnable; VK_LOGIC_OP_COPY, // VkLogicOp logicOp; 1u, // deUint32 attachmentCount; &colorBlendAttachmentState, // const VkPipelineColorBlendAttachmentState* pAttachments; { 0.0f, 0.0f, 0.0f, 0.0f }, // float blendConst[4]; }; const VkPipelineMultisampleStateCreateInfo multisampleStateParams = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineMultisampleStateCreateFlags flags; VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits rasterizationSamples; VK_FALSE, // VkBool32 sampleShadingEnable; 0.0f, // float minSampleShading; DE_NULL, // const VkSampleMask* pSampleMask; VK_FALSE, // VkBool32 alphaToCoverageEnable; VK_FALSE, // VkBool32 alphaToOneEnable; }; VkPipelineDepthStencilStateCreateInfo depthStencilStateParams = { VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineDepthStencilStateCreateFlags flags; VK_TRUE, // VkBool32 depthTestEnable; VK_TRUE, // VkBool32 depthWriteEnable; VK_COMPARE_OP_LESS_OR_EQUAL, // VkCompareOp depthCompareOp; VK_FALSE, // VkBool32 depthBoundsTestEnable; VK_FALSE, // VkBool32 stencilTestEnable; // VkStencilOpState front; { VK_STENCIL_OP_KEEP, // VkStencilOp failOp; VK_STENCIL_OP_KEEP, // VkStencilOp passOp; VK_STENCIL_OP_KEEP, // VkStencilOp depthFailOp; VK_COMPARE_OP_NEVER, // VkCompareOp compareOp; 0u, // deUint32 compareMask; 0u, // deUint32 writeMask; 0u, // deUint32 reference; }, // VkStencilOpState back; { VK_STENCIL_OP_KEEP, // VkStencilOp failOp; VK_STENCIL_OP_KEEP, // VkStencilOp passOp; VK_STENCIL_OP_KEEP, // VkStencilOp depthFailOp; VK_COMPARE_OP_NEVER, // VkCompareOp compareOp; 0u, // deUint32 compareMask; 0u, // deUint32 writeMask; 0u, // deUint32 reference; }, 0.0f, // float minDepthBounds; 1.0f, // float maxDepthBounds; }; const VkPipelineTessellationStateCreateInfo tessStateCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_TESSELLATION_STATE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineTesselationStateCreateFlags flags; m_patchControlPoints, // deUint32 patchControlPoints; }; const VkPipelineTessellationStateCreateInfo* pTessCreateInfo = (m_patchControlPoints > 0) ? &tessStateCreateInfo : DE_NULL; const VkGraphicsPipelineCreateInfo graphicsPipelineParams = { VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineCreateFlags flags; m_shaderStageCount, // deUint32 stageCount; m_shaderStageInfo, // const VkPipelineShaderStageCreateInfo* pStages; &vertexInputStateParams, // const VkPipelineVertexInputStateCreateInfo* pVertexInputState; &inputAssemblyStateParams, // const VkPipelineInputAssemblyStateCreateInfo* pInputAssemblyState; pTessCreateInfo, // const VkPipelineTessellationStateCreateInfo* pTessellationState; &viewportStateParams, // const VkPipelineViewportStateCreateInfo* pViewportState; &rasterStateParams, // const VkPipelineRasterizationStateCreateInfo* pRasterState; &multisampleStateParams, // const VkPipelineMultisampleStateCreateInfo* pMultisampleState; &depthStencilStateParams, // const VkPipelineDepthStencilStateCreateInfo* pDepthStencilState; &colorBlendStateParams, // const VkPipelineColorBlendStateCreateInfo* pColorBlendState; (const VkPipelineDynamicStateCreateInfo*)DE_NULL, // const VkPipelineDynamicStateCreateInfo* pDynamicState; pipelineLayout, // VkPipelineLayout layout; renderPass, // VkRenderPass renderPass; 0u, // deUint32 subpass; 0u, // VkPipeline basePipelineHandle; 0, // deInt32 basePipelineIndex; }; return createGraphicsPipeline(vk, vkDevice, cache, &graphicsPipelineParams); } void SimpleGraphicsPipelineBuilder::enableTessellationStage (deUint32 patchControlPoints) { m_patchControlPoints = patchControlPoints; } template <class Test> vkt::TestCase* newTestCase (tcu::TestContext& testContext, const CacheTestParam* testParam) { return new Test(testContext, testParam->generateTestName().c_str(), testParam->generateTestDescription().c_str(), testParam); } Move<VkBuffer> createBufferAndBindMemory (Context& context, VkDeviceSize size, VkBufferUsageFlags usage, de::MovePtr<Allocation>* pAlloc) { const DeviceInterface& vk = context.getDeviceInterface(); const VkDevice vkDevice = context.getDevice(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkBufferCreateInfo vertexBufferParams = { VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkBufferCreateFlags flags; size, // VkDeviceSize size; usage, // VkBufferUsageFlags usage; VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode; 1u, // deUint32 queueFamilyCount; &queueFamilyIndex // const deUint32* pQueueFamilyIndices; }; Move<VkBuffer> vertexBuffer = createBuffer(vk, vkDevice, &vertexBufferParams); *pAlloc = context.getDefaultAllocator().allocate(getBufferMemoryRequirements(vk, vkDevice, *vertexBuffer), MemoryRequirement::HostVisible); VK_CHECK(vk.bindBufferMemory(vkDevice, *vertexBuffer, (*pAlloc)->getMemory(), (*pAlloc)->getOffset())); return vertexBuffer; } Move<VkImage> createImage2DAndBindMemory (Context& context, VkFormat format, deUint32 width, deUint32 height, VkImageUsageFlags usage, VkSampleCountFlagBits sampleCount, de::details::MovePtr<Allocation>* pAlloc) { const DeviceInterface& vk = context.getDeviceInterface(); const VkDevice vkDevice = context.getDevice(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); const VkImageCreateInfo colorImageParams = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkImageCreateFlags flags; VK_IMAGE_TYPE_2D, // VkImageType imageType; format, // VkFormat format; { width, height, 1u }, // VkExtent3D extent; 1u, // deUint32 mipLevels; 1u, // deUint32 arraySize; sampleCount, // deUint32 samples; VK_IMAGE_TILING_OPTIMAL, // VkImageTiling tiling; usage, // VkImageUsageFlags usage; VK_SHARING_MODE_EXCLUSIVE, // VkSharingMode sharingMode; 1u, // deUint32 queueFamilyCount; &queueFamilyIndex, // const deUint32* pQueueFamilyIndices; VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout; }; Move<VkImage> image = createImage(vk, vkDevice, &colorImageParams); *pAlloc = context.getDefaultAllocator().allocate(getImageMemoryRequirements(vk, vkDevice, *image), MemoryRequirement::Any); VK_CHECK(vk.bindImageMemory(vkDevice, *image, (*pAlloc)->getMemory(), (*pAlloc)->getOffset())); return image; } // Test Classes class CacheTest : public vkt::TestCase { public: CacheTest(tcu::TestContext& testContext, const std::string& name, const std::string& description, const CacheTestParam* param) : vkt::TestCase (testContext, name, description) , m_param (*param) { } virtual ~CacheTest (void) { } protected: const CacheTestParam m_param; }; class CacheTestInstance : public vkt::TestInstance { public: enum { PIPELINE_CACHE_NDX_NO_CACHE, PIPELINE_CACHE_NDX_CACHED, PIPELINE_CACHE_NDX_COUNT, }; CacheTestInstance (Context& context, const CacheTestParam* param); virtual ~CacheTestInstance (void); virtual tcu::TestStatus iterate (void); protected: virtual tcu::TestStatus verifyTestResult (void) = 0; virtual void prepareCommandBuffer (void) = 0; protected: const CacheTestParam* m_param; Move<VkCommandPool> m_cmdPool; Move<VkCommandBuffer> m_cmdBuffer; Move<VkPipelineCache> m_cache; }; CacheTestInstance::CacheTestInstance (Context& context, const CacheTestParam* param) : TestInstance (context) , m_param (param) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); const deUint32 queueFamilyIndex = context.getUniversalQueueFamilyIndex(); // Create command pool m_cmdPool = createCommandPool(vk, vkDevice, VK_COMMAND_POOL_CREATE_TRANSIENT_BIT, queueFamilyIndex); // Create command buffer m_cmdBuffer = allocateCommandBuffer(vk, vkDevice, *m_cmdPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY); // Create the Pipeline Cache { const VkPipelineCacheCreateInfo pipelineCacheCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineCacheCreateFlags flags; 0u, // deUintptr initialDataSize; DE_NULL, // const void* pInitialData; }; m_cache = createPipelineCache(vk, vkDevice, &pipelineCacheCreateInfo); } } CacheTestInstance::~CacheTestInstance (void) { } tcu::TestStatus CacheTestInstance::iterate (void) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); const VkQueue queue = m_context.getUniversalQueue(); prepareCommandBuffer(); submitCommandsAndWait(vk, vkDevice, queue, m_cmdBuffer.get()); return verifyTestResult(); } class GraphicsCacheTest : public CacheTest { public: GraphicsCacheTest (tcu::TestContext& testContext, const std::string& name, const std::string& description, const CacheTestParam* param) : CacheTest (testContext, name, description, param) { } virtual ~GraphicsCacheTest (void) { } virtual void initPrograms (SourceCollections& programCollection) const; virtual TestInstance* createInstance (Context& context) const; }; class GraphicsCacheTestInstance : public CacheTestInstance { public: GraphicsCacheTestInstance (Context& context, const CacheTestParam* param); virtual ~GraphicsCacheTestInstance (void); protected: void prepareRenderPass (VkFramebuffer framebuffer, VkPipeline pipeline); virtual void prepareCommandBuffer (void); virtual tcu::TestStatus verifyTestResult (void); protected: const tcu::UVec2 m_renderSize; const VkFormat m_colorFormat; const VkFormat m_depthFormat; Move<VkPipelineLayout> m_pipelineLayout; Move<VkImage> m_depthImage; de::MovePtr<Allocation> m_depthImageAlloc; de::MovePtr<Allocation> m_colorImageAlloc[PIPELINE_CACHE_NDX_COUNT]; Move<VkImageView> m_depthAttachmentView; VkImageMemoryBarrier m_imageLayoutBarriers[3]; Move<VkBuffer> m_vertexBuffer; de::MovePtr<Allocation> m_vertexBufferMemory; std::vector<Vertex4RGBA> m_vertices; SimpleGraphicsPipelineBuilder m_pipelineBuilder; Move<VkRenderPass> m_renderPass; Move<VkImage> m_colorImage[PIPELINE_CACHE_NDX_COUNT]; Move<VkImageView> m_colorAttachmentView[PIPELINE_CACHE_NDX_COUNT]; Move<VkFramebuffer> m_framebuffer[PIPELINE_CACHE_NDX_COUNT]; Move<VkPipeline> m_pipeline[PIPELINE_CACHE_NDX_COUNT]; }; void GraphicsCacheTest::initPrograms (SourceCollections& programCollection) const { for (deUint32 shaderNdx = 0; shaderNdx < m_param.getShaderCount(); shaderNdx++) { switch(m_param.getShaderFlag(shaderNdx)) { case VK_SHADER_STAGE_VERTEX_BIT: programCollection.glslSources.add("color_vert") << glu::VertexSource( "#version 310 es\n" "layout(location = 0) in vec4 position;\n" "layout(location = 1) in vec4 color;\n" "layout(location = 0) out highp vec4 vtxColor;\n" "void main (void)\n" "{\n" " gl_Position = position;\n" " vtxColor = color;\n" "}\n"); break; case VK_SHADER_STAGE_FRAGMENT_BIT: programCollection.glslSources.add("color_frag") << glu::FragmentSource( "#version 310 es\n" "layout(location = 0) in highp vec4 vtxColor;\n" "layout(location = 0) out highp vec4 fragColor;\n" "void main (void)\n" "{\n" " fragColor = vtxColor;\n" "}\n"); break; case VK_SHADER_STAGE_GEOMETRY_BIT: programCollection.glslSources.add("dummy_geo") << glu::GeometrySource( "#version 450 \n" "layout(triangles) in;\n" "layout(triangle_strip, max_vertices = 3) out;\n" "layout(location = 0) in highp vec4 in_vtxColor[];\n" "layout(location = 0) out highp vec4 vtxColor;\n" "out gl_PerVertex { vec4 gl_Position; };\n" "in gl_PerVertex { vec4 gl_Position; } gl_in[];\n" "void main (void)\n" "{\n" " for(int ndx=0; ndx<3; ndx++)\n" " {\n" " gl_Position = gl_in[ndx].gl_Position;\n" " vtxColor = in_vtxColor[ndx];\n" " EmitVertex();\n" " }\n" " EndPrimitive();\n" "}\n"); break; case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT: programCollection.glslSources.add("basic_tcs") << glu::TessellationControlSource( "#version 450 \n" "layout(vertices = 3) out;\n" "layout(location = 0) in highp vec4 color[];\n" "layout(location = 0) out highp vec4 vtxColor[];\n" "out gl_PerVertex { vec4 gl_Position; } gl_out[3];\n" "in gl_PerVertex { vec4 gl_Position; } gl_in[gl_MaxPatchVertices];\n" "void main()\n" "{\n" " gl_TessLevelOuter[0] = 4.0;\n" " gl_TessLevelOuter[1] = 4.0;\n" " gl_TessLevelOuter[2] = 4.0;\n" " gl_TessLevelInner[0] = 4.0;\n" " gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;\n" " vtxColor[gl_InvocationID] = color[gl_InvocationID];\n" "}\n"); break; case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT: programCollection.glslSources.add("basic_tes") << glu::TessellationEvaluationSource( "#version 450 \n" "layout(triangles, fractional_even_spacing, ccw) in;\n" "layout(location = 0) in highp vec4 colors[];\n" "layout(location = 0) out highp vec4 vtxColor;\n" "out gl_PerVertex { vec4 gl_Position; };\n" "in gl_PerVertex { vec4 gl_Position; } gl_in[gl_MaxPatchVertices];\n" "void main() \n" "{\n" " float u = gl_TessCoord.x;\n" " float v = gl_TessCoord.y;\n" " float w = gl_TessCoord.z;\n" " vec4 pos = vec4(0);\n" " vec4 color = vec4(0);\n" " pos.xyz += u * gl_in[0].gl_Position.xyz;\n" " color.xyz += u * colors[0].xyz;\n" " pos.xyz += v * gl_in[1].gl_Position.xyz;\n" " color.xyz += v * colors[1].xyz;\n" " pos.xyz += w * gl_in[2].gl_Position.xyz;\n" " color.xyz += w * colors[2].xyz;\n" " pos.w = 1.0;\n" " color.w = 1.0;\n" " gl_Position = pos;\n" " vtxColor = color;\n" "}\n"); break; default: DE_FATAL("Unknown Shader Stage!"); break; }; } } TestInstance* GraphicsCacheTest::createInstance (Context& context) const { return new GraphicsCacheTestInstance(context, &m_param); } GraphicsCacheTestInstance::GraphicsCacheTestInstance (Context& context, const CacheTestParam* param) : CacheTestInstance (context,param) , m_renderSize (32u, 32u) , m_colorFormat (VK_FORMAT_R8G8B8A8_UNORM) , m_depthFormat (VK_FORMAT_D16_UNORM) , m_pipelineBuilder (context) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); // Create vertex buffer { m_vertexBuffer = createBufferAndBindMemory(m_context, 1024u, VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, &m_vertexBufferMemory); m_vertices = createOverlappingQuads(); // Load vertices into vertex buffer deMemcpy(m_vertexBufferMemory->getHostPtr(), m_vertices.data(), m_vertices.size() * sizeof(Vertex4RGBA)); flushMappedMemoryRange(vk, vkDevice, m_vertexBufferMemory->getMemory(), m_vertexBufferMemory->getOffset(), 1024u); } // Create render pass m_renderPass = makeRenderPass(vk, vkDevice, m_colorFormat, m_depthFormat); const VkComponentMapping ComponentMappingRGBA = { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A}; // Create color image { m_colorImage[PIPELINE_CACHE_NDX_NO_CACHE] = createImage2DAndBindMemory(m_context, m_colorFormat, m_renderSize.x(), m_renderSize.y(), VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_SAMPLE_COUNT_1_BIT, &m_colorImageAlloc[PIPELINE_CACHE_NDX_NO_CACHE]); m_colorImage[PIPELINE_CACHE_NDX_CACHED] = createImage2DAndBindMemory(m_context, m_colorFormat, m_renderSize.x(), m_renderSize.y(), VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT, VK_SAMPLE_COUNT_1_BIT, &m_colorImageAlloc[PIPELINE_CACHE_NDX_CACHED]); } // Create depth image { m_depthImage = createImage2DAndBindMemory(m_context, m_depthFormat, m_renderSize.x(), m_renderSize.y(), VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_SAMPLE_COUNT_1_BIT, &m_depthImageAlloc); } // Set up image layout transition barriers { VkImageMemoryBarrier colorImageBarrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkAccessFlags srcAccessMask; VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags dstAccessMask; VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout oldLayout; VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout newLayout; VK_QUEUE_FAMILY_IGNORED, // deUint32 srcQueueFamilyIndex; VK_QUEUE_FAMILY_IGNORED, // deUint32 dstQueueFamilyIndex; *m_colorImage[PIPELINE_CACHE_NDX_NO_CACHE], // VkImage image; { VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u }, // VkImageSubresourceRange subresourceRange; }; m_imageLayoutBarriers[0] = colorImageBarrier; colorImageBarrier.image = *m_colorImage[PIPELINE_CACHE_NDX_CACHED]; m_imageLayoutBarriers[1] = colorImageBarrier; const VkImageMemoryBarrier depthImageBarrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkAccessFlags srcAccessMask; VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, // VkAccessFlags dstAccessMask; VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout oldLayout; VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, // VkImageLayout newLayout; VK_QUEUE_FAMILY_IGNORED, // deUint32 srcQueueFamilyIndex; VK_QUEUE_FAMILY_IGNORED, // deUint32 dstQueueFamilyIndex; *m_depthImage, // VkImage image; { VK_IMAGE_ASPECT_DEPTH_BIT, 0u, 1u, 0u, 1u }, // VkImageSubresourceRange subresourceRange; }; m_imageLayoutBarriers[2] = depthImageBarrier; } // Create color attachment view { VkImageViewCreateInfo colorAttachmentViewParams = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkImageViewCreateFlags flags; *m_colorImage[PIPELINE_CACHE_NDX_NO_CACHE], // VkImage image; VK_IMAGE_VIEW_TYPE_2D, // VkImageViewType viewType; m_colorFormat, // VkFormat format; ComponentMappingRGBA, // VkComponentMapping components; { VK_IMAGE_ASPECT_COLOR_BIT, 0u, 1u, 0u, 1u }, // VkImageSubresourceRange subresourceRange; }; m_colorAttachmentView[PIPELINE_CACHE_NDX_NO_CACHE] = createImageView(vk, vkDevice, &colorAttachmentViewParams); colorAttachmentViewParams.image = *m_colorImage[PIPELINE_CACHE_NDX_CACHED]; m_colorAttachmentView[PIPELINE_CACHE_NDX_CACHED] = createImageView(vk, vkDevice, &colorAttachmentViewParams); } // Create depth attachment view { const VkImageViewCreateInfo depthAttachmentViewParams = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkImageViewCreateFlags flags; *m_depthImage, // VkImage image; VK_IMAGE_VIEW_TYPE_2D, // VkImageViewType viewType; m_depthFormat, // VkFormat format; ComponentMappingRGBA, // VkComponentMapping components; { VK_IMAGE_ASPECT_DEPTH_BIT, 0u, 1u, 0u, 1u }, // VkImageSubresourceRange subresourceRange; }; m_depthAttachmentView = createImageView(vk, vkDevice, &depthAttachmentViewParams); } // Create framebuffer { VkImageView attachmentBindInfos[2] = { *m_colorAttachmentView[PIPELINE_CACHE_NDX_NO_CACHE], *m_depthAttachmentView, }; const VkFramebufferCreateInfo framebufferParams = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkFramebufferCreateFlags flags; *m_renderPass, // VkRenderPass renderPass; 2u, // deUint32 attachmentCount; attachmentBindInfos, // const VkImageView* pAttachments; (deUint32)m_renderSize.x(), // deUint32 width; (deUint32)m_renderSize.y(), // deUint32 height; 1u, // deUint32 layers; }; m_framebuffer[PIPELINE_CACHE_NDX_NO_CACHE] = createFramebuffer(vk, vkDevice, &framebufferParams); attachmentBindInfos[0] = *m_colorAttachmentView[PIPELINE_CACHE_NDX_CACHED]; m_framebuffer[PIPELINE_CACHE_NDX_CACHED] = createFramebuffer(vk, vkDevice, &framebufferParams); } // Bind shader stages VkPhysicalDeviceFeatures features = m_context.getDeviceFeatures(); for (deUint32 shaderNdx = 0; shaderNdx < m_param->getShaderCount(); shaderNdx++) { switch(m_param->getShaderFlag(shaderNdx)) { case VK_SHADER_STAGE_VERTEX_BIT: m_pipelineBuilder.bindShaderStage(VK_SHADER_STAGE_VERTEX_BIT, "color_vert", "main"); break; case VK_SHADER_STAGE_FRAGMENT_BIT: m_pipelineBuilder.bindShaderStage(VK_SHADER_STAGE_FRAGMENT_BIT, "color_frag", "main"); break; case VK_SHADER_STAGE_GEOMETRY_BIT: if (features.geometryShader == VK_FALSE) { TCU_THROW(NotSupportedError, "Geometry Shader Not Supported"); } else { m_pipelineBuilder.bindShaderStage(VK_SHADER_STAGE_GEOMETRY_BIT, "dummy_geo", "main"); } break; case VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT: if (features.tessellationShader == VK_FALSE) { TCU_THROW(NotSupportedError, "Tessellation Not Supported"); } else { m_pipelineBuilder.bindShaderStage(VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, "basic_tcs", "main"); m_pipelineBuilder.enableTessellationStage(3); } break; case VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT: if (features.tessellationShader == VK_FALSE) { TCU_THROW(NotSupportedError, "Tessellation Not Supported"); } else { m_pipelineBuilder.bindShaderStage(VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, "basic_tes", "main"); m_pipelineBuilder.enableTessellationStage(3); } break; default: DE_FATAL("Unknown Shader Stage!"); break; }; } // Create pipeline layout { const VkPipelineLayoutCreateInfo pipelineLayoutParams = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineLayoutCreateFlags flags; 0u, // deUint32 setLayoutCount; DE_NULL, // const VkDescriptorSetLayout* pSetLayouts; 0u, // deUint32 pushConstantRangeCount; DE_NULL // const VkPushConstantRange* pPushConstantRanges; }; m_pipelineLayout = createPipelineLayout(vk, vkDevice, &pipelineLayoutParams); } m_pipeline[PIPELINE_CACHE_NDX_NO_CACHE] = m_pipelineBuilder.buildPipeline(m_renderSize, *m_renderPass, *m_cache, *m_pipelineLayout); m_pipeline[PIPELINE_CACHE_NDX_CACHED] = m_pipelineBuilder.buildPipeline(m_renderSize, *m_renderPass, *m_cache, *m_pipelineLayout); } GraphicsCacheTestInstance::~GraphicsCacheTestInstance (void) { } void GraphicsCacheTestInstance::prepareRenderPass (VkFramebuffer framebuffer, VkPipeline pipeline) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkClearValue attachmentClearValues[2] = { defaultClearValue(m_colorFormat), defaultClearValue(m_depthFormat), }; beginRenderPass(vk, *m_cmdBuffer, *m_renderPass, framebuffer, makeRect2D(0, 0, m_renderSize.x(), m_renderSize.y()), 2u, attachmentClearValues); vk.cmdBindPipeline(*m_cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline); VkDeviceSize offsets = 0u; vk.cmdBindVertexBuffers(*m_cmdBuffer, 0u, 1u, &m_vertexBuffer.get(), &offsets); vk.cmdDraw(*m_cmdBuffer, (deUint32)m_vertices.size(), 1u, 0u, 0u); endRenderPass(vk, *m_cmdBuffer); } void GraphicsCacheTestInstance::prepareCommandBuffer (void) { const DeviceInterface& vk = m_context.getDeviceInterface(); beginCommandBuffer(vk, *m_cmdBuffer, 0u); vk.cmdPipelineBarrier(*m_cmdBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT | VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT, (VkDependencyFlags)0, 0u, DE_NULL, 0u, DE_NULL, DE_LENGTH_OF_ARRAY(m_imageLayoutBarriers), m_imageLayoutBarriers); prepareRenderPass(*m_framebuffer[PIPELINE_CACHE_NDX_NO_CACHE], *m_pipeline[PIPELINE_CACHE_NDX_NO_CACHE]); // After the first render pass, the images are in correct layouts prepareRenderPass(*m_framebuffer[PIPELINE_CACHE_NDX_CACHED], *m_pipeline[PIPELINE_CACHE_NDX_CACHED]); endCommandBuffer(vk, *m_cmdBuffer); } tcu::TestStatus GraphicsCacheTestInstance::verifyTestResult (void) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); const deUint32 queueFamilyIndex = m_context.getUniversalQueueFamilyIndex(); const VkQueue queue = m_context.getUniversalQueue(); de::MovePtr<tcu::TextureLevel> resultNoCache = readColorAttachment(vk, vkDevice, queue, queueFamilyIndex, m_context.getDefaultAllocator(), *m_colorImage[PIPELINE_CACHE_NDX_NO_CACHE], m_colorFormat, m_renderSize); de::MovePtr<tcu::TextureLevel> resultCache = readColorAttachment(vk, vkDevice, queue, queueFamilyIndex, m_context.getDefaultAllocator(), *m_colorImage[PIPELINE_CACHE_NDX_CACHED], m_colorFormat, m_renderSize); bool compareOk = tcu::intThresholdCompare(m_context.getTestContext().getLog(), "IntImageCompare", "Image comparison", resultNoCache->getAccess(), resultCache->getAccess(), tcu::UVec4(1, 1, 1, 1), tcu::COMPARE_LOG_RESULT); if (compareOk) return tcu::TestStatus::pass("Render images w/o cached pipeline match."); else return tcu::TestStatus::fail("Render Images mismatch."); } class ComputeCacheTest : public CacheTest { public: ComputeCacheTest (tcu::TestContext& testContext, const std::string& name, const std::string& description, const CacheTestParam* param) : CacheTest (testContext, name, description, param) { } virtual ~ComputeCacheTest (void) { } virtual void initPrograms (SourceCollections& programCollection) const; virtual TestInstance* createInstance (Context& context) const; }; class ComputeCacheTestInstance : public CacheTestInstance { public: ComputeCacheTestInstance (Context& context, const CacheTestParam* param); virtual ~ComputeCacheTestInstance (void); virtual void prepareCommandBuffer (void); protected: virtual tcu::TestStatus verifyTestResult (void); void buildBuffers (void); void buildDescriptorSets (deUint32 ndx); void buildShader (void); void buildPipeline (deUint32 ndx); protected: Move<VkBuffer> m_inputBuf; de::MovePtr<Allocation> m_inputBufferAlloc; Move<VkShaderModule> m_computeShaderModule; Move<VkBuffer> m_outputBuf[PIPELINE_CACHE_NDX_COUNT]; de::MovePtr<Allocation> m_outputBufferAlloc[PIPELINE_CACHE_NDX_COUNT]; Move<VkDescriptorPool> m_descriptorPool[PIPELINE_CACHE_NDX_COUNT]; Move<VkDescriptorSetLayout> m_descriptorSetLayout[PIPELINE_CACHE_NDX_COUNT]; Move<VkDescriptorSet> m_descriptorSet[PIPELINE_CACHE_NDX_COUNT]; Move<VkPipelineLayout> m_pipelineLayout[PIPELINE_CACHE_NDX_COUNT]; Move<VkPipeline> m_pipeline[PIPELINE_CACHE_NDX_COUNT]; }; void ComputeCacheTest::initPrograms (SourceCollections& programCollection) const { programCollection.glslSources.add("basic_compute") << glu::ComputeSource( "#version 310 es\n" "layout(local_size_x = 1) in;\n" "layout(std430) buffer;\n" "layout(binding = 0) readonly buffer Input0\n" "{\n" " vec4 elements[];\n" "} input_data0;\n" "layout(binding = 1) writeonly buffer Output\n" "{\n" " vec4 elements[];\n" "} output_data;\n" "void main()\n" "{\n" " uint ident = gl_GlobalInvocationID.x;\n" " output_data.elements[ident] = input_data0.elements[ident] * input_data0.elements[ident];\n" "}"); } TestInstance* ComputeCacheTest::createInstance (Context& context) const { return new ComputeCacheTestInstance(context, &m_param); } void ComputeCacheTestInstance::buildBuffers (void) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); // Create buffer object, allocate storage, and generate input data const VkDeviceSize size = sizeof(tcu::Vec4) * 128u; m_inputBuf = createBufferAndBindMemory(m_context, size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &m_inputBufferAlloc); // Initialize input buffer tcu::Vec4* pVec = reinterpret_cast<tcu::Vec4*>(m_inputBufferAlloc->getHostPtr()); for (deUint32 ndx = 0u; ndx < 128u; ndx++) { for (deUint32 component = 0u; component < 4u; component++) pVec[ndx][component]= (float)(ndx * (component + 1u)); } flushMappedMemoryRange(vk, vkDevice, m_inputBufferAlloc->getMemory(), m_inputBufferAlloc->getOffset(), size); // Clear the output buffer for (deUint32 ndx = 0; ndx < PIPELINE_CACHE_NDX_COUNT; ndx++) { m_outputBuf[ndx] = createBufferAndBindMemory(m_context, size, VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, &m_outputBufferAlloc[ndx]); pVec = reinterpret_cast<tcu::Vec4*>(m_outputBufferAlloc[ndx]->getHostPtr()); for (deUint32 i = 0; i < (size / sizeof(tcu::Vec4)); i++) pVec[i] = tcu::Vec4(0.0f); flushMappedMemoryRange(vk, vkDevice, m_outputBufferAlloc[ndx]->getMemory(), m_outputBufferAlloc[ndx]->getOffset(), size); } } void ComputeCacheTestInstance::buildDescriptorSets (deUint32 ndx) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); // Create descriptor set layout DescriptorSetLayoutBuilder descLayoutBuilder; for (deUint32 bindingNdx = 0u; bindingNdx < 2u; bindingNdx++) descLayoutBuilder.addSingleBinding(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT); m_descriptorSetLayout[ndx] = descLayoutBuilder.build(vk, vkDevice); std::vector<VkDescriptorBufferInfo> descriptorInfos; descriptorInfos.push_back(makeDescriptorBufferInfo(*m_inputBuf, 0u, sizeof(tcu::Vec4) * 128u)); descriptorInfos.push_back(makeDescriptorBufferInfo(*m_outputBuf[ndx], 0u, sizeof(tcu::Vec4) * 128u)); // Create descriptor pool m_descriptorPool[ndx] = DescriptorPoolBuilder().addType(VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, 2u).build(vk, vkDevice, VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, 1u); // Create descriptor set const VkDescriptorSetAllocateInfo descriptorSetAllocInfo = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; *m_descriptorPool[ndx], // VkDescriptorPool descriptorPool; 1u, // deUint32 setLayoutCount; &m_descriptorSetLayout[ndx].get(), // const VkDescriptorSetLayout* pSetLayouts; }; m_descriptorSet[ndx] = allocateDescriptorSet(vk, vkDevice, &descriptorSetAllocInfo); DescriptorSetUpdateBuilder builder; for (deUint32 descriptorNdx = 0u; descriptorNdx < 2u; descriptorNdx++) { builder.writeSingle(*m_descriptorSet[ndx], DescriptorSetUpdateBuilder::Location::binding(descriptorNdx), VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, &descriptorInfos[descriptorNdx]); } builder.update(vk, vkDevice); } void ComputeCacheTestInstance::buildShader (void) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); // Create compute shader VkShaderModuleCreateInfo shaderModuleCreateInfo = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkShaderModuleCreateFlags flags; m_context.getBinaryCollection().get("basic_compute").getSize(), // deUintptr codeSize; (deUint32*)m_context.getBinaryCollection().get("basic_compute").getBinary(), // const deUint32* pCode; }; m_computeShaderModule = createShaderModule(vk, vkDevice, &shaderModuleCreateInfo); } void ComputeCacheTestInstance::buildPipeline (deUint32 ndx) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); // Create compute pipeline layout const VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineLayoutCreateFlags flags; 1u, // deUint32 setLayoutCount; &m_descriptorSetLayout[ndx].get(), // const VkDescriptorSetLayout* pSetLayouts; 0u, // deUint32 pushConstantRangeCount; DE_NULL, // const VkPushConstantRange* pPushConstantRanges; }; m_pipelineLayout[ndx] = createPipelineLayout(vk, vkDevice, &pipelineLayoutCreateInfo); const VkPipelineShaderStageCreateInfo stageCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineShaderStageCreateFlags flags; VK_SHADER_STAGE_COMPUTE_BIT, // VkShaderStageFlagBits stage; *m_computeShaderModule, // VkShaderModule module; "main", // const char* pName; DE_NULL, // const VkSpecializationInfo* pSpecializationInfo; }; const VkComputePipelineCreateInfo pipelineCreateInfo = { VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineCreateFlags flags; stageCreateInfo, // VkPipelineShaderStageCreateInfo stage; *m_pipelineLayout[ndx], // VkPipelineLayout layout; (VkPipeline)0, // VkPipeline basePipelineHandle; 0u, // deInt32 basePipelineIndex; }; m_pipeline[ndx] = createComputePipeline(vk, vkDevice, *m_cache, &pipelineCreateInfo); } ComputeCacheTestInstance::ComputeCacheTestInstance (Context& context, const CacheTestParam* param) : CacheTestInstance (context, param) { buildBuffers(); buildDescriptorSets(PIPELINE_CACHE_NDX_NO_CACHE); buildDescriptorSets(PIPELINE_CACHE_NDX_CACHED); buildShader(); buildPipeline(PIPELINE_CACHE_NDX_NO_CACHE); buildPipeline(PIPELINE_CACHE_NDX_CACHED); } ComputeCacheTestInstance::~ComputeCacheTestInstance (void) { } void ComputeCacheTestInstance::prepareCommandBuffer (void) { const DeviceInterface& vk = m_context.getDeviceInterface(); beginCommandBuffer(vk, *m_cmdBuffer, 0u); for (deUint32 ndx = 0; ndx < PIPELINE_CACHE_NDX_COUNT; ndx++) { vk.cmdBindPipeline(*m_cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *m_pipeline[ndx]); vk.cmdBindDescriptorSets(*m_cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, *m_pipelineLayout[ndx], 0u, 1u, &m_descriptorSet[ndx].get(), 0u, DE_NULL); vk.cmdDispatch(*m_cmdBuffer, 128u, 1u, 1u); } endCommandBuffer(vk, *m_cmdBuffer); } tcu::TestStatus ComputeCacheTestInstance::verifyTestResult (void) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); // Read the content of output buffers invalidateMappedMemoryRange(vk, vkDevice, m_outputBufferAlloc[PIPELINE_CACHE_NDX_NO_CACHE]->getMemory(), m_outputBufferAlloc[PIPELINE_CACHE_NDX_NO_CACHE]->getOffset(), sizeof(tcu::Vec4) * 128u); invalidateMappedMemoryRange(vk, vkDevice, m_outputBufferAlloc[PIPELINE_CACHE_NDX_CACHED]->getMemory(), m_outputBufferAlloc[PIPELINE_CACHE_NDX_CACHED]->getOffset(), sizeof(tcu::Vec4) * 128u); // Compare the content deUint8* bufNoCache = reinterpret_cast<deUint8*>(m_outputBufferAlloc[PIPELINE_CACHE_NDX_NO_CACHE]->getHostPtr()); deUint8* bufCached = reinterpret_cast<deUint8*>(m_outputBufferAlloc[PIPELINE_CACHE_NDX_CACHED]->getHostPtr()); for (deUint32 ndx = 0u; ndx < sizeof(tcu::Vec4) * 128u; ndx++) { if (bufNoCache[ndx] != bufCached[ndx]) { return tcu::TestStatus::fail("Output buffers w/o cached pipeline mismatch."); } } return tcu::TestStatus::pass("Output buffers w/o cached pipeline match."); } class PipelineFromCacheTest : public GraphicsCacheTest { public: PipelineFromCacheTest (tcu::TestContext& testContext, const std::string& name, const std::string& description, const CacheTestParam* param); virtual ~PipelineFromCacheTest (void) { } virtual TestInstance* createInstance (Context& context) const; }; PipelineFromCacheTest::PipelineFromCacheTest (tcu::TestContext& testContext, const std::string& name, const std::string& description, const CacheTestParam* param) : GraphicsCacheTest(testContext, name, description, param) { } class PipelineFromCacheTestInstance : public GraphicsCacheTestInstance { public: PipelineFromCacheTestInstance (Context& context, const CacheTestParam* param); virtual ~PipelineFromCacheTestInstance (void); protected: Move<VkPipelineCache> m_newCache; deUint8* m_data; }; TestInstance* PipelineFromCacheTest::createInstance (Context& context) const { return new PipelineFromCacheTestInstance(context, &m_param); } PipelineFromCacheTestInstance::PipelineFromCacheTestInstance (Context& context, const CacheTestParam* param) : GraphicsCacheTestInstance (context, param) , m_data (DE_NULL) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); // Create more pipeline caches { size_t dataSize = 0u; VK_CHECK(vk.getPipelineCacheData(vkDevice, *m_cache, (deUintptr*)&dataSize, DE_NULL)); m_data = new deUint8[dataSize]; DE_ASSERT(m_data); VK_CHECK(vk.getPipelineCacheData(vkDevice, *m_cache, (deUintptr*)&dataSize, (void*)m_data)); const VkPipelineCacheCreateInfo pipelineCacheCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineCacheCreateFlags flags; dataSize, // deUintptr initialDataSize; m_data, // const void* pInitialData; }; m_newCache = createPipelineCache(vk, vkDevice, &pipelineCacheCreateInfo); } m_pipeline[PIPELINE_CACHE_NDX_CACHED] = m_pipelineBuilder.buildPipeline(m_renderSize, *m_renderPass, *m_newCache, *m_pipelineLayout); } PipelineFromCacheTestInstance::~PipelineFromCacheTestInstance (void) { delete[] m_data; } class PipelineFromIncompleteCacheTest : public GraphicsCacheTest { public: PipelineFromIncompleteCacheTest (tcu::TestContext& testContext, const std::string& name, const std::string& description, const CacheTestParam* param); virtual ~PipelineFromIncompleteCacheTest (void) {} virtual TestInstance* createInstance (Context& context) const; }; PipelineFromIncompleteCacheTest::PipelineFromIncompleteCacheTest (tcu::TestContext& testContext, const std::string& name, const std::string& description, const CacheTestParam* param) : GraphicsCacheTest(testContext, name, description, param) { } class PipelineFromIncompleteCacheTestInstance : public GraphicsCacheTestInstance { public: PipelineFromIncompleteCacheTestInstance(Context& context, const CacheTestParam* param); virtual ~PipelineFromIncompleteCacheTestInstance(void); protected: protected: Move<VkPipelineCache> m_newCache; deUint8* m_data; }; TestInstance* PipelineFromIncompleteCacheTest::createInstance (Context& context) const { return new PipelineFromIncompleteCacheTestInstance(context, &m_param); } PipelineFromIncompleteCacheTestInstance::PipelineFromIncompleteCacheTestInstance (Context& context, const CacheTestParam* param) : GraphicsCacheTestInstance (context, param) , m_data (DE_NULL) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); // Create more pipeline caches { size_t dataSize = 0u; VK_CHECK(vk.getPipelineCacheData(vkDevice, *m_cache, (deUintptr*)&dataSize, DE_NULL)); if (dataSize == 0) TCU_THROW(NotSupportedError, "Empty pipeline cache - unable to test"); dataSize--; m_data = new deUint8[dataSize]; DE_ASSERT(m_data); if (vk.getPipelineCacheData(vkDevice, *m_cache, (deUintptr*)&dataSize, (void*)m_data) != VK_INCOMPLETE) TCU_THROW(TestError, "GetPipelineCacheData should return VK_INCOMPLETE state!"); const VkPipelineCacheCreateInfo pipelineCacheCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineCacheCreateFlags flags; dataSize, // deUintptr initialDataSize; m_data, // const void* pInitialData; }; m_newCache = createPipelineCache(vk, vkDevice, &pipelineCacheCreateInfo); } m_pipeline[PIPELINE_CACHE_NDX_CACHED] = m_pipelineBuilder.buildPipeline(m_renderSize, *m_renderPass, *m_newCache, *m_pipelineLayout); } PipelineFromIncompleteCacheTestInstance::~PipelineFromIncompleteCacheTestInstance (void) { delete[] m_data; } class MergeCacheTest : public GraphicsCacheTest { public: MergeCacheTest (tcu::TestContext& testContext, const std::string& name, const std::string& description, const CacheTestParam* param) : GraphicsCacheTest (testContext, name, description, param) { } virtual ~MergeCacheTest (void) { } virtual TestInstance* createInstance (Context& context) const; }; class MergeCacheTestInstance : public GraphicsCacheTestInstance { public: MergeCacheTestInstance (Context& context, const CacheTestParam* param); virtual ~MergeCacheTestInstance (void); protected: Move<VkPipelineCache> m_cacheGetData; Move<VkPipelineCache> m_cacheEmpty; Move<VkPipelineCache> m_cacheMerged; deUint8* m_data; }; TestInstance* MergeCacheTest::createInstance (Context& context) const { return new MergeCacheTestInstance(context, &m_param); } MergeCacheTestInstance::MergeCacheTestInstance (Context& context, const CacheTestParam* param) : GraphicsCacheTestInstance (context, param) , m_data (DE_NULL) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); // Create more pipeline caches { // Create a empty cache as one of source cache VkPipelineCacheCreateInfo pipelineCacheCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineCacheCreateFlags flags; 0u, // deUintptr initialDataSize; DE_NULL, // const void* pInitialData; }; m_cacheEmpty = createPipelineCache(vk, vkDevice, &pipelineCacheCreateInfo); // Create a empty cache for merge destination cache m_cacheMerged = createPipelineCache(vk, vkDevice, &pipelineCacheCreateInfo); // Create a cache with init data from m_cache size_t dataSize = 0u; VK_CHECK(vk.getPipelineCacheData(vkDevice, *m_cache, (deUintptr*)&dataSize, DE_NULL)); m_data = new deUint8[dataSize]; DE_ASSERT(m_data); VK_CHECK(vk.getPipelineCacheData(vkDevice, *m_cache, (deUintptr*)&dataSize, (void*)m_data)); pipelineCacheCreateInfo.initialDataSize = dataSize; pipelineCacheCreateInfo.pInitialData = m_data; m_cacheGetData = createPipelineCache(vk, vkDevice, &pipelineCacheCreateInfo); } // Merge the caches const VkPipelineCache sourceCaches[] = { *m_cacheEmpty, *m_cacheGetData, }; VK_CHECK(vk.mergePipelineCaches(vkDevice, *m_cacheMerged, 2u, sourceCaches)); // Create pipeline from merged cache m_pipeline[PIPELINE_CACHE_NDX_CACHED] = m_pipelineBuilder.buildPipeline(m_renderSize, *m_renderPass, *m_cacheMerged, *m_pipelineLayout); } MergeCacheTestInstance::~MergeCacheTestInstance (void) { delete[] m_data; } class CacheHeaderTest : public GraphicsCacheTest { public: CacheHeaderTest(tcu::TestContext& testContext, const std::string& name, const std::string& description, const CacheTestParam* param) : GraphicsCacheTest(testContext, name, description, param) { } virtual ~CacheHeaderTest(void) { } virtual TestInstance* createInstance(Context& context) const; }; class CacheHeaderTestInstance : public GraphicsCacheTestInstance { public: CacheHeaderTestInstance (Context& context, const CacheTestParam* param); virtual ~CacheHeaderTestInstance (void); protected: deUint8* m_data; struct CacheHeader { deUint32 HeaderLength; deUint32 HeaderVersion; deUint32 VendorID; deUint32 DeviceID; deUint8 PipelineCacheUUID[VK_UUID_SIZE]; } m_header; }; TestInstance* CacheHeaderTest::createInstance (Context& context) const { return new CacheHeaderTestInstance(context, &m_param); } CacheHeaderTestInstance::CacheHeaderTestInstance (Context& context, const CacheTestParam* param) : GraphicsCacheTestInstance (context, param) , m_data (DE_NULL) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); // Create more pipeline caches { // Create a cache with init data from m_cache size_t dataSize = 0u; VK_CHECK(vk.getPipelineCacheData(vkDevice, *m_cache, (deUintptr*)&dataSize, DE_NULL)); if (dataSize < sizeof(m_header)) TCU_THROW(TestError, "Pipeline cache size is smaller than header size"); m_data = new deUint8[dataSize]; DE_ASSERT(m_data); VK_CHECK(vk.getPipelineCacheData(vkDevice, *m_cache, (deUintptr*)&dataSize, (void*)m_data)); deMemcpy(&m_header, m_data, sizeof(m_header)); if (m_header.HeaderLength - VK_UUID_SIZE != 16) TCU_THROW(TestError, "Invalid header size!"); if (m_header.HeaderVersion != 1) TCU_THROW(TestError, "Invalid header version!"); if (m_header.VendorID != m_context.getDeviceProperties().vendorID) TCU_THROW(TestError, "Invalid header vendor ID!"); if (m_header.DeviceID != m_context.getDeviceProperties().deviceID) TCU_THROW(TestError, "Invalid header device ID!"); if (deMemCmp(&m_header.PipelineCacheUUID, &m_context.getDeviceProperties().pipelineCacheUUID, VK_UUID_SIZE) != 0) TCU_THROW(TestError, "Invalid header pipeline cache UUID!"); } } CacheHeaderTestInstance::~CacheHeaderTestInstance (void) { delete[] m_data; } class InvalidSizeTest : public GraphicsCacheTest { public: InvalidSizeTest (tcu::TestContext& testContext, const std::string& name, const std::string& description, const CacheTestParam* param); virtual ~InvalidSizeTest (void) {} virtual TestInstance* createInstance (Context& context) const; }; InvalidSizeTest::InvalidSizeTest (tcu::TestContext& testContext, const std::string& name, const std::string& description, const CacheTestParam* param) : GraphicsCacheTest(testContext, name, description, param) { } class InvalidSizeTestInstance : public GraphicsCacheTestInstance { public: InvalidSizeTestInstance (Context& context, const CacheTestParam* param); virtual ~InvalidSizeTestInstance (void); protected: deUint8* m_data; deUint8* m_zeroBlock; }; TestInstance* InvalidSizeTest::createInstance (Context& context) const { return new InvalidSizeTestInstance(context, &m_param); } InvalidSizeTestInstance::InvalidSizeTestInstance (Context& context, const CacheTestParam* param) : GraphicsCacheTestInstance (context, param) , m_data (DE_NULL) , m_zeroBlock (DE_NULL) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); // Create more pipeline caches try { // Create a cache with init data from m_cache size_t dataSize = 0u; size_t savedDataSize = 0u; VK_CHECK(vk.getPipelineCacheData(vkDevice, *m_cache, (deUintptr*)&dataSize, DE_NULL)); savedDataSize = dataSize; // If the value of dataSize is less than the maximum size that can be retrieved by the pipeline cache, // at most pDataSize bytes will be written to pData, and vkGetPipelineCacheData will return VK_INCOMPLETE. dataSize--; m_data = new deUint8[savedDataSize]; deMemset(m_data, 0, savedDataSize); DE_ASSERT(m_data); if (vk.getPipelineCacheData(vkDevice, *m_cache, (deUintptr*)&dataSize, (void*)m_data) != VK_INCOMPLETE) TCU_THROW(TestError, "GetPipelineCacheData should return VK_INCOMPLETE state!"); delete[] m_data; m_data = DE_NULL; // If the value of dataSize is less than what is necessary to store the header, // nothing will be written to pData and zero will be written to dataSize. dataSize = 16 + VK_UUID_SIZE - 1; m_data = new deUint8[savedDataSize]; deMemset(m_data, 0, savedDataSize); DE_ASSERT(m_data); if (vk.getPipelineCacheData(vkDevice, *m_cache, (deUintptr*)&dataSize, (void*)m_data) != VK_INCOMPLETE) TCU_THROW(TestError, "GetPipelineCacheData should return VK_INCOMPLETE state!"); m_zeroBlock = new deUint8[savedDataSize]; deMemset(m_zeroBlock, 0, savedDataSize); if (deMemCmp(m_data, m_zeroBlock, savedDataSize) != 0 || dataSize != 0) TCU_THROW(TestError, "Data needs to be empty and data size should be 0 when invalid size is passed to GetPipelineCacheData!"); } catch (...) { delete[] m_data; delete[] m_zeroBlock; throw; } } InvalidSizeTestInstance::~InvalidSizeTestInstance (void) { delete[] m_data; delete[] m_zeroBlock; } class ZeroSizeTest : public GraphicsCacheTest { public: ZeroSizeTest (tcu::TestContext& testContext, const std::string& name, const std::string& description, const CacheTestParam* param); virtual ~ZeroSizeTest (void) {} virtual TestInstance* createInstance (Context& context) const; }; ZeroSizeTest::ZeroSizeTest (tcu::TestContext& testContext, const std::string& name, const std::string& description, const CacheTestParam* param) : GraphicsCacheTest(testContext, name, description, param) { } class ZeroSizeTestInstance : public GraphicsCacheTestInstance { public: ZeroSizeTestInstance (Context& context, const CacheTestParam* param); virtual ~ZeroSizeTestInstance (void); protected: deUint8* m_data; deUint8* m_zeroBlock; }; TestInstance* ZeroSizeTest::createInstance (Context& context) const { return new ZeroSizeTestInstance(context, &m_param); } ZeroSizeTestInstance::ZeroSizeTestInstance (Context& context, const CacheTestParam* param) : GraphicsCacheTestInstance (context, param) , m_data (DE_NULL) , m_zeroBlock (DE_NULL) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); // Create more pipeline caches try { // Create a cache with init data from m_cache size_t dataSize = 0u; VK_CHECK(vk.getPipelineCacheData(vkDevice, *m_cache, (deUintptr*)&dataSize, DE_NULL)); m_data = new deUint8[dataSize]; deMemset(m_data, 0, dataSize); DE_ASSERT(m_data); VK_CHECK(vk.getPipelineCacheData(vkDevice, *m_cache, (deUintptr*)&dataSize, (void*)m_data)); { // Create a cache with initialDataSize = 0 & pInitialData != NULL const VkPipelineCacheCreateInfo pipelineCacheCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineCacheCreateFlags flags; 0u, // deUintptr initialDataSize; m_data, // const void* pInitialData; }; const Unique<VkPipelineCache> pipelineCache (createPipelineCache(vk, vkDevice, &pipelineCacheCreateInfo)); } } catch (...) { delete[] m_data; delete[] m_zeroBlock; throw; } } ZeroSizeTestInstance::~ZeroSizeTestInstance (void) { delete[] m_data; delete[] m_zeroBlock; } class InvalidBlobTest : public GraphicsCacheTest { public: InvalidBlobTest (tcu::TestContext& testContext, const std::string& name, const std::string& description, const CacheTestParam* param); virtual ~InvalidBlobTest (void) {} virtual TestInstance* createInstance (Context& context) const; }; InvalidBlobTest::InvalidBlobTest (tcu::TestContext& testContext, const std::string& name, const std::string& description, const CacheTestParam* param) : GraphicsCacheTest(testContext, name, description, param) { } class InvalidBlobTestInstance : public GraphicsCacheTestInstance { public: InvalidBlobTestInstance (Context& context, const CacheTestParam* param); virtual ~InvalidBlobTestInstance (void); protected: deUint8* m_data; deUint8* m_zeroBlock; }; TestInstance* InvalidBlobTest::createInstance (Context& context) const { return new InvalidBlobTestInstance(context, &m_param); } InvalidBlobTestInstance::InvalidBlobTestInstance (Context& context, const CacheTestParam* param) : GraphicsCacheTestInstance (context, param) , m_data (DE_NULL) , m_zeroBlock (DE_NULL) { const DeviceInterface& vk = m_context.getDeviceInterface(); const VkDevice vkDevice = m_context.getDevice(); // Create more pipeline caches try { // Create a cache with init data from m_cache size_t dataSize = 0u; VK_CHECK(vk.getPipelineCacheData(vkDevice, *m_cache, (deUintptr*)&dataSize, DE_NULL)); m_data = new deUint8[dataSize]; deMemset(m_data, 0, dataSize); DE_ASSERT(m_data); VK_CHECK(vk.getPipelineCacheData(vkDevice, *m_cache, (deUintptr*)&dataSize, (void*)m_data)); const struct { deUint32 offset; std::string name; } headerLayout[] = { { 4u, "pipeline cache header version" }, { 8u, "vendor ID" }, { 12u, "device ID" }, { 16u, "pipeline cache ID" } }; for (deUint32 i = 0u; i < DE_LENGTH_OF_ARRAY(headerLayout); i++) { m_context.getTestContext().getLog() << tcu::TestLog::Message << "Creating pipeline cache using previously retrieved data with invalid " << headerLayout[i].name << tcu::TestLog::EndMessage; m_data[headerLayout[i].offset] = (deUint8)(m_data[headerLayout[i].offset] + 13u); // Add arbitrary number to create an invalid value const VkPipelineCacheCreateInfo pipelineCacheCreateInfo = { VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, // VkStructureType sType; DE_NULL, // const void* pNext; 0u, // VkPipelineCacheCreateFlags flags; dataSize, // deUintptr initialDataSize; m_data, // const void* pInitialData; }; const Unique<VkPipelineCache> pipelineCache (createPipelineCache(vk, vkDevice, &pipelineCacheCreateInfo)); m_data[headerLayout[i].offset] = (deUint8)(m_data[headerLayout[i].offset] - 13u); // Return to original value } } catch (...) { delete[] m_data; delete[] m_zeroBlock; throw; } } InvalidBlobTestInstance::~InvalidBlobTestInstance (void) { delete[] m_data; delete[] m_zeroBlock; } } // anonymous tcu::TestCaseGroup* createCacheTests (tcu::TestContext& testCtx) { de::MovePtr<tcu::TestCaseGroup> cacheTests (new tcu::TestCaseGroup(testCtx, "cache", "pipeline cache tests")); // Graphics Pipeline Tests { de::MovePtr<tcu::TestCaseGroup> graphicsTests (new tcu::TestCaseGroup(testCtx, "graphics_tests", "Test pipeline cache with graphics pipeline.")); const VkShaderStageFlagBits testParamShaders0[] = { VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, }; const VkShaderStageFlagBits testParamShaders1[] = { VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_GEOMETRY_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, }; const VkShaderStageFlagBits testParamShaders2[] = { VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, }; const CacheTestParam testParams[] = { CacheTestParam(testParamShaders0, DE_LENGTH_OF_ARRAY(testParamShaders0)), CacheTestParam(testParamShaders1, DE_LENGTH_OF_ARRAY(testParamShaders1)), CacheTestParam(testParamShaders2, DE_LENGTH_OF_ARRAY(testParamShaders2)), }; for (deUint32 i = 0; i < DE_LENGTH_OF_ARRAY(testParams); i++) graphicsTests->addChild(newTestCase<GraphicsCacheTest>(testCtx, &testParams[i])); cacheTests->addChild(graphicsTests.release()); } // Graphics Pipeline Tests { de::MovePtr<tcu::TestCaseGroup> graphicsTests(new tcu::TestCaseGroup(testCtx, "pipeline_from_get_data", "Test pipeline cache with graphics pipeline.")); const VkShaderStageFlagBits testParamShaders0[] = { VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, }; const VkShaderStageFlagBits testParamShaders1[] = { VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_GEOMETRY_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, }; const VkShaderStageFlagBits testParamShaders2[] = { VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, }; const CacheTestParam testParams[] = { CacheTestParam(testParamShaders0, DE_LENGTH_OF_ARRAY(testParamShaders0)), CacheTestParam(testParamShaders1, DE_LENGTH_OF_ARRAY(testParamShaders1)), CacheTestParam(testParamShaders2, DE_LENGTH_OF_ARRAY(testParamShaders2)), }; for (deUint32 i = 0; i < DE_LENGTH_OF_ARRAY(testParams); i++) graphicsTests->addChild(newTestCase<PipelineFromCacheTest>(testCtx, &testParams[i])); cacheTests->addChild(graphicsTests.release()); } // Graphics Pipeline Tests { de::MovePtr<tcu::TestCaseGroup> graphicsTests(new tcu::TestCaseGroup(testCtx, "pipeline_from_incomplete_get_data", "Test pipeline cache with graphics pipeline.")); const VkShaderStageFlagBits testParamShaders0[] = { VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, }; const VkShaderStageFlagBits testParamShaders1[] = { VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_GEOMETRY_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, }; const VkShaderStageFlagBits testParamShaders2[] = { VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, }; const CacheTestParam testParams[] = { CacheTestParam(testParamShaders0, DE_LENGTH_OF_ARRAY(testParamShaders0)), CacheTestParam(testParamShaders1, DE_LENGTH_OF_ARRAY(testParamShaders1)), CacheTestParam(testParamShaders2, DE_LENGTH_OF_ARRAY(testParamShaders2)), }; for (deUint32 i = 0; i < DE_LENGTH_OF_ARRAY(testParams); i++) graphicsTests->addChild(newTestCase<PipelineFromIncompleteCacheTest>(testCtx, &testParams[i])); cacheTests->addChild(graphicsTests.release()); } // Compute Pipeline Tests { de::MovePtr<tcu::TestCaseGroup> computeTests (new tcu::TestCaseGroup(testCtx, "compute_tests", "Test pipeline cache with compute pipeline.")); const VkShaderStageFlagBits testParamShaders0[] = { VK_SHADER_STAGE_COMPUTE_BIT, }; const CacheTestParam testParams[] = { CacheTestParam(testParamShaders0, DE_LENGTH_OF_ARRAY(testParamShaders0)), }; for (deUint32 i = 0; i < DE_LENGTH_OF_ARRAY(testParams); i++) computeTests->addChild(newTestCase<ComputeCacheTest>(testCtx, &testParams[i])); cacheTests->addChild(computeTests.release()); } // Misc Tests { de::MovePtr<tcu::TestCaseGroup> miscTests (new tcu::TestCaseGroup(testCtx, "misc_tests", "Misc tests that can not be categorized to other group.")); const VkShaderStageFlagBits testParamShaders[] = { VK_SHADER_STAGE_VERTEX_BIT, VK_SHADER_STAGE_FRAGMENT_BIT, }; const CacheTestParam testParam(testParamShaders, DE_LENGTH_OF_ARRAY(testParamShaders)); miscTests->addChild(new MergeCacheTest(testCtx, "merge_cache_test", "Merge the caches test.", &testParam)); miscTests->addChild(new CacheHeaderTest(testCtx, "cache_header_test", "Cache header test.", &testParam)); miscTests->addChild(new InvalidSizeTest(testCtx, "invalid_size_test", "Invalid size test.", &testParam)); miscTests->addChild(new ZeroSizeTest(testCtx, "zero_size_test", "Zero size test.", &testParam)); miscTests->addChild(new InvalidBlobTest(testCtx, "invalid_blob_test", "Invalid cache blob test.", &testParam)); cacheTests->addChild(miscTests.release()); } return cacheTests.release(); } } // pipeline } // vkt
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2012, John Haddon. All rights reserved. // Copyright (c) 2013, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of John Haddon nor the names of // any other contributors to this software 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 OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "GafferUI/ViewportGadget.h" #include "GafferUI/Style.h" #include "GafferUI/Pointer.h" #include "IECoreGL/PerspectiveCamera.h" #include "IECoreGL/Selector.h" #include "IECoreGL/State.h" #include "IECoreGL/ToGLCameraConverter.h" #include "IECoreScene/Transform.h" #include "IECore/AngleConversion.h" #include "IECore/MessageHandler.h" #include "IECore/NullObject.h" #include "IECore/SimpleTypedData.h" #include "OpenEXR/ImathBoxAlgo.h" #include "OpenEXR/ImathMatrixAlgo.h" #include "boost/bind.hpp" #include "boost/bind/placeholders.hpp" #include <chrono> #include <cmath> using namespace Imath; using namespace IECore; using namespace IECoreScene; using namespace IECoreGL; using namespace GafferUI; ////////////////////////////////////////////////////////////////////////// // Internal utilities ////////////////////////////////////////////////////////////////////////// namespace { float ceilSignificantDigits( float x, int significantDigits ) { const int ceilLog10 = ceil( log10( x ) ); const float magnitude = pow( 10, ceilLog10 - significantDigits ); return ceil( x / magnitude ) * magnitude; } float floorSignificantDigits( float x, int significantDigits ) { const int ceilLog10 = ceil( log10( x ) ); const float magnitude = pow( 10, ceilLog10 - significantDigits ); return floor( x / magnitude ) * magnitude; } // This horrible function is just because theoretically someone could call // setCamera while in planarMovement mode, requiring us to reverse engineer // a planarScale based on the current resolution. This is pretty useless, // setting planarScale directly would be far more useful - but since the // interface exists, we have to deal with someone potentially calling it. V2f planarScaleFromCameraAndRes( const IECoreScene::Camera *cam, const V2i &res ) { if( cam->getProjection() != "orthographic" ) { return V2f( 1.0f ); } return V2f( cam->getAperture()[0] / ((float)res[0] ), cam->getAperture()[1] / ((float)res[1] ) ); } } // namespace ////////////////////////////////////////////////////////////////////////// // CameraController ////////////////////////////////////////////////////////////////////////// class ViewportGadget::CameraController : public boost::noncopyable { public : CameraController() : m_planarMovement( true ), m_sourceCamera( new IECoreScene::Camera() ), m_viewportResolution( 640, 480 ), m_planarScale( 1.0f ), m_clippingPlanes( 0.01f, 100000.0f ), m_centerOfInterest( 1.0f ) { } void setCamera( IECoreScene::CameraPtr camera ) { if( m_planarMovement ) { m_planarScale = planarScaleFromCameraAndRes( camera.get(), m_viewportResolution ); } m_clippingPlanes = camera->getClippingPlanes(); m_sourceCamera = camera; } IECoreScene::ConstCameraPtr getCamera() const { IECoreScene::CameraPtr viewportCamera = m_sourceCamera->copy(); if( m_planarMovement ) { viewportCamera->setProjection( "orthographic" ); viewportCamera->setAperture( m_planarScale * V2f( m_viewportResolution[0], m_viewportResolution[1] ) ); } viewportCamera->setResolution( m_viewportResolution ); viewportCamera->setClippingPlanes( m_clippingPlanes ); return viewportCamera; } void setPlanarMovement( bool planarMovement ) { if( planarMovement && !m_planarMovement ) { m_planarScale = planarScaleFromCameraAndRes( m_sourceCamera.get(), m_viewportResolution ); } m_planarMovement = planarMovement; } bool getPlanarMovement() const { return m_planarMovement; } void setTransform( const M44f &transform ) { m_transform = transform; } const M44f &getTransform() const { return m_transform; } /// Positive. void setCenterOfInterest( float centerOfInterest ) { m_centerOfInterest = centerOfInterest; } float getCenterOfInterest() { return m_centerOfInterest; } /// Set the resolution of the viewport we are working in void setViewportResolution( const Imath::V2i &viewportResolution ) { m_viewportResolution = viewportResolution; } const Imath::V2i &getViewportResolution() const { return m_viewportResolution; } void setClippingPlanes( const Imath::V2f &clippingPlanes ) { m_clippingPlanes = clippingPlanes; } const Imath::V2f &getClippingPlanes() const { return m_clippingPlanes; } /// Moves the camera to frame the specified box, keeping the /// current viewing direction unchanged. void frame( const Imath::Box3f &box, bool variableAspectZoom = false ) { V3f z( 0, 0, -1 ); V3f y( 0, 1, 0 ); M44f t = m_transform; t.multDirMatrix( z, z ); t.multDirMatrix( y, y ); frame( box, z, y, variableAspectZoom ); } /// Moves the camera to frame the specified box, viewing it from the /// specified direction, and with the specified up vector. void frame( const Imath::Box3f &box, const Imath::V3f &viewDirection, const Imath::V3f &upVector = Imath::V3f( 0, 1, 0 ), bool variableAspectZoom = false ) { // Make a matrix to center the camera on the box, with the appropriate view direction. M44f cameraMatrix = rotationMatrixWithUpDir( V3f( 0, 0, -1 ), viewDirection, upVector ); M44f translationMatrix; translationMatrix.translate( box.center() ); cameraMatrix *= translationMatrix; // Now translate the camera back until the box is completely visible. How // we do this exactly depends on the camera projection. M44f inverseCameraMatrix = cameraMatrix.inverse(); Box3f cBox = transform( box, inverseCameraMatrix ); if( m_planarMovement ) { // Orthographic. Translate to front of box. // The 0.1 is just a fudge factor to ensure we don't accidentally clip // the front of the box. m_centerOfInterest = cBox.max.z + m_clippingPlanes[0] + 0.1; // Adjust the planar scale so the entire bound can be seen. V2f ratio( cBox.size().x / m_viewportResolution[0], cBox.size().y / m_viewportResolution[1] ); if( variableAspectZoom ) { m_planarScale = ratio; } else { m_planarScale = V2f( std::max( ratio.x, ratio.y ) ); } } else { if( m_sourceCamera->getProjection()=="perspective" ) { // Perspective. leave the field of view and screen window as is and translate // back till the box is wholly visible. this currently assumes the screen window // is centered about the camera axis. const Box2f &normalizedScreenWindow = m_sourceCamera->frustum( m_sourceCamera->getFilmFit(), ( (float)m_viewportResolution.x ) / m_viewportResolution.y ); // Compute a distance to push back in z in order to see the whole width and height of cBox float z0 = cBox.size().x / normalizedScreenWindow.size().x; float z1 = cBox.size().y / normalizedScreenWindow.size().y; m_centerOfInterest = std::max( z0, z1 ) + cBox.max.z + m_clippingPlanes[0]; } else { // Orthographic. Note that we are not altering the projection, so we may still not // be able to see the entire bound, if the ortho camera has too small an aperture to // see the whole bound at once. // Translate to front of box. // We need to clamp the near clipping plane to >= 0.0f because // the LightToCamera node creates hugely negative near clipping // planes that would otherwise send us way out into space. The // 0.1 is just a fudge factor to ensure we don't accidentally clip // the front of the box. m_centerOfInterest = cBox.max.z + std::max( m_clippingPlanes[0], 0.0f ) + 0.1; // The user might want to tumble around the thing // they framed. Translate back some more to make // room to tumble around the entire bound. m_centerOfInterest += cBox.size().length(); } } cameraMatrix.translate( V3f( 0.0f, 0.0f, m_centerOfInterest ) ); m_transform = cameraMatrix; } /// Computes the points on the near and far clipping planes that correspond /// with the specified raster position. Points are computed in world space. void unproject( const Imath::V2f rasterPosition, Imath::V3f &near, Imath::V3f &far ) const { if( m_planarMovement ) { V2f rasterCenter = 0.5f * V2f( m_viewportResolution ); V2f unscaled = ( rasterPosition - rasterCenter ) * m_planarScale; near = V3f( unscaled.x, -unscaled.y, -m_clippingPlanes[0] ); far = V3f( unscaled.x, -unscaled.y, -m_clippingPlanes[1] ); } else { V2f ndc = V2f( rasterPosition ) / m_viewportResolution; const Box2f &normalizedScreenWindow = m_sourceCamera->frustum( m_sourceCamera->getFilmFit(), ( (float)m_viewportResolution.x ) / m_viewportResolution.y ); V2f screen( lerp( normalizedScreenWindow.min.x, normalizedScreenWindow.max.x, ndc.x ), lerp( normalizedScreenWindow.max.y, normalizedScreenWindow.min.y, ndc.y ) ); if( m_sourceCamera->getProjection()=="perspective" ) { V3f camera( screen.x, screen.y, -1.0f ); near = camera * m_clippingPlanes[0]; far = camera * m_clippingPlanes[1]; } else { near = V3f( screen.x, screen.y, -m_clippingPlanes[0] ); far = V3f( screen.x, screen.y, -m_clippingPlanes[1] ); } } near = near * m_transform; far = far * m_transform; } /// Projects the point in world space into a raster space position. Imath::V2f project( const Imath::V3f &worldPosition ) const { M44f inverseCameraMatrix = m_transform.inverse(); V3f cameraPosition = worldPosition * inverseCameraMatrix; if( m_planarMovement ) { V2f rasterCenter = 0.5f * V2f( m_viewportResolution ); return rasterCenter + V2f( cameraPosition.x, -cameraPosition.y ) / m_planarScale; } else { const V2i &resolution = m_viewportResolution; const Box2f &normalizedScreenWindow = m_sourceCamera->frustum( m_sourceCamera->getFilmFit(), ( (float)m_viewportResolution.x ) / m_viewportResolution.y ); if( m_sourceCamera->getProjection() == "perspective" ) { cameraPosition = cameraPosition / -cameraPosition.z; } V2f ndcPosition( lerpfactor( cameraPosition.x, normalizedScreenWindow.min.x, normalizedScreenWindow.max.x ), lerpfactor( cameraPosition.y, normalizedScreenWindow.max.y, normalizedScreenWindow.min.y ) ); return V2f( ndcPosition.x * resolution.x, ndcPosition.y * resolution.y ); } } /// Motion /// ====== /// /// These functions facilitate the implementation of maya style /// camera movement controls within a UI. All coordinates passed /// are mouse coordinates in raster space (0,0 at top left). enum MotionType { None, Track, Tumble, Dolly, }; enum class ZoomAxis { Undefined, X, Y }; /// Starts a motion of the specified type. void motionStart( MotionType motion, const Imath::V2f &startPosition ) { if( motion == Tumble && m_planarMovement ) { motion = Track; } m_motionType = motion; m_motionStart = startPosition; m_motionMatrix = m_transform; m_motionPlanarScale = m_planarScale; m_motionCenterOfInterest = m_centerOfInterest; } /// Updates the camera position based on a changed mouse position. Can only /// be called after motionStart() and before motionEnd(). void motionUpdate( const Imath::V2f &newPosition, bool variableAspect = false ) { switch( m_motionType ) { case Track : track( newPosition ); break; case Tumble : tumble( newPosition ); break; case Dolly : dolly( newPosition, variableAspect ); break; default : throw Exception( "CameraController not in motion." ); } } /// End the current motion, ready to call motionStart() again if required. void motionEnd( const Imath::V2f &endPosition, bool variableAspect = false ) { switch( m_motionType ) { case Track : track( endPosition ); break; case Tumble : tumble( endPosition ); break; case Dolly : dolly( endPosition, variableAspect ); break; default : break; } m_motionType = None; m_zoomAxis = ZoomAxis::Undefined; Pointer::setCurrent( "" ); } /// Determine the type of motion based on current events /// \todo: The original separation of responsibilities was that /// CameraController knew how to perform camera movement, and /// ViewportGadgets knew how to handle events, and decided how to map /// those to camera movement requests. This breaks that original /// separation. Full separation would mean that the CameraController /// made its own connections to buttonPressSignal/dragBeginSignal etc, /// "stealing" any events it wanted before they were processed by the /// ViewportGadget. There are a few complications regarding drag /// tracking and unmodified MMB drags, though. MotionType cameraMotionType( const ButtonEvent &event, bool variableAspectZoom ) { if( ( event.modifiers == ModifiableEvent::Alt ) || ( event.buttons == ButtonEvent::Middle && event.modifiers == ModifiableEvent::None ) || ( variableAspectZoom && event.modifiers & ModifiableEvent::Shift && event.modifiers & ModifiableEvent::Alt && event.buttons == ButtonEvent::Right ) ) { switch( event.buttons ) { case ButtonEvent::Left : return ViewportGadget::CameraController::Tumble; case ButtonEvent::Middle : return CameraController::Track; case ButtonEvent::Right : return CameraController::Dolly; default : return CameraController::None; } } return CameraController::None; } private: void track( const Imath::V2f &p ) { V2f d = p - m_motionStart; V3f translate( 0.0f ); if( m_planarMovement ) { translate = V3f( -d[0] * m_planarScale[0], d[1] * m_planarScale[1], 0.0f ); } else { const Box2f &normalizedScreenWindow = m_sourceCamera->frustum( m_sourceCamera->getFilmFit(), ( (float)m_viewportResolution.x ) / m_viewportResolution.y ); translate.x = -normalizedScreenWindow.size().x * d.x/(float)m_viewportResolution.x; translate.y = normalizedScreenWindow.size().y * d.y/(float)m_viewportResolution.y; if( m_sourceCamera->getProjection()=="perspective" ) { translate *= m_centerOfInterest; } } M44f t = m_motionMatrix; t.translate( translate ); m_transform = t; } void tumble( const Imath::V2f &p ) { V2f d = p - m_motionStart; V3f centerOfInterestInWorld = V3f( 0, 0, -m_centerOfInterest ) * m_motionMatrix; V3f xAxisInWorld = V3f( 1, 0, 0 ); m_motionMatrix.multDirMatrix( xAxisInWorld, xAxisInWorld ); xAxisInWorld.normalize(); M44f t; t.translate( centerOfInterestInWorld ); t.rotate( V3f( 0, -d.x / 100.0f, 0 ) ); M44f xRotate; xRotate.setAxisAngle( xAxisInWorld, -d.y / 100.0f ); t = xRotate * t; t.translate( -centerOfInterestInWorld ); m_transform = m_motionMatrix * t; } void dolly( const Imath::V2f &p, bool variableAspect ) { V2i resolution = m_viewportResolution; V2f dv = V2f( (p - m_motionStart) ) / resolution; float d = dv.x - dv.y; if( m_planarMovement ) { V2f mult; if( !variableAspect ) { mult = V2f( expf( -1.9f * d ) ); Pointer::setCurrent( "" ); } else { if( abs( dv.x ) >= abs( dv.y ) ) { m_zoomAxis = ZoomAxis::X; Pointer::setCurrent( "moveHorizontally" ); mult = V2f( expf( -1.9f * dv.x ), 1.0f ); } else { m_zoomAxis = ZoomAxis::Y; Pointer::setCurrent( "moveVertically" ); mult = V2f( 1.0f, expf( 1.9f * dv.y ) ); } } m_planarScale = m_motionPlanarScale * mult; // Also apply a transform to keep the origin of the scale centered on the // starting cursor position V2f offset = V2f( -1, 1 ) * ( m_planarScale - m_motionPlanarScale ) * ( m_motionStart - V2f( 0.5 ) * resolution ); M44f t = m_motionMatrix; t.translate( V3f( offset.x, offset.y, 0 ) ); m_transform = t; } else { m_centerOfInterest = m_motionCenterOfInterest * expf( -1.9f * d ); M44f t = m_motionMatrix; t.translate( V3f( 0, 0, m_centerOfInterest - m_motionCenterOfInterest ) ); m_transform = t; } } // If m_planarMovement is true, we are doing a 2D view with a fixed scaling // between world units and pixels, independ of viewport resolution // ( and m_sourceCamera will be null ). bool m_planarMovement; // m_sourceCamera provides the values for any camera properties // which we don't override IECoreScene::ConstCameraPtr m_sourceCamera; // Resolution of the viewport we are working in Imath::V2i m_viewportResolution; // Parts of the camera we manipulate Imath::V2f m_planarScale; Imath::V2f m_clippingPlanes; float m_centerOfInterest; M44f m_transform; // Motion state MotionType m_motionType; Imath::V2f m_motionStart; Imath::M44f m_motionMatrix; float m_motionCenterOfInterest; Imath::V2f m_motionPlanarScale; ZoomAxis m_zoomAxis; }; ////////////////////////////////////////////////////////////////////////// // ViewportGadget ////////////////////////////////////////////////////////////////////////// GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( ViewportGadget ); ViewportGadget::ViewportGadget( GadgetPtr primaryChild ) : Gadget(), m_cameraController( new CameraController() ), m_cameraInMotion( false ), m_cameraEditable( true ), m_dragTracking( DragTracking::NoDragTracking ), m_variableAspectZoom( false ) { // Viewport visibility is managed by GadgetWidgets, setVisible( false ); setPrimaryChild( primaryChild ); childRemovedSignal().connect( boost::bind( &ViewportGadget::childRemoved, this, ::_1, ::_2 ) ); buttonPressSignal().connect( boost::bind( &ViewportGadget::buttonPress, this, ::_1, ::_2 ) ); buttonReleaseSignal().connect( boost::bind( &ViewportGadget::buttonRelease, this, ::_1, ::_2 ) ); buttonDoubleClickSignal().connect( boost::bind( &ViewportGadget::buttonDoubleClick, this, ::_1, ::_2 ) ); enterSignal().connect( boost::bind( &ViewportGadget::enter, this, ::_2 ) ); leaveSignal().connect( boost::bind( &ViewportGadget::leave, this, ::_2 ) ); mouseMoveSignal().connect( boost::bind( &ViewportGadget::mouseMove, this, ::_1, ::_2 ) ); dragBeginSignal().connect( boost::bind( &ViewportGadget::dragBegin, this, ::_1, ::_2 ) ); dragEnterSignal().connect( boost::bind( &ViewportGadget::dragEnter, this, ::_1, ::_2 ) ); dragMoveSignal().connect( boost::bind( &ViewportGadget::dragMove, this, ::_1, ::_2 ) ); dragLeaveSignal().connect( boost::bind( &ViewportGadget::dragLeave, this, ::_1, ::_2 ) ); dropSignal().connect( boost::bind( &ViewportGadget::drop, this, ::_1, ::_2 ) ); dragEndSignal().connect( boost::bind( &ViewportGadget::dragEnd, this, ::_1, ::_2 ) ); wheelSignal().connect( boost::bind( &ViewportGadget::wheel, this, ::_1, ::_2 ) ); keyPressSignal().connect( boost::bind( &ViewportGadget::keyPress, this, ::_1, ::_2 ) ); keyReleaseSignal().connect( boost::bind( &ViewportGadget::keyRelease, this, ::_1, ::_2 ) ); } ViewportGadget::~ViewportGadget() { } bool ViewportGadget::acceptsParent( const Gaffer::GraphComponent *potentialParent ) const { return false; } std::string ViewportGadget::getToolTip( const IECore::LineSegment3f &line ) const { std::string result = Gadget::getToolTip( line ); if( result.size() ) { return result; } std::vector<GadgetPtr> gadgets; gadgetsAt( V2f( line.p0.x, line.p0.y ), gadgets ); for( std::vector<GadgetPtr>::const_iterator it = gadgets.begin(), eIt = gadgets.end(); it != eIt; it++ ) { Gadget *gadget = it->get(); while( gadget && gadget != this ) { IECore::LineSegment3f lineInGadgetSpace = rasterToGadgetSpace( V2f( line.p0.x, line.p0.y), gadget ); result = gadget->getToolTip( lineInGadgetSpace ); if( result.size() ) { return result; } gadget = gadget->parent<Gadget>(); } } return result; } void ViewportGadget::setPrimaryChild( GadgetPtr gadget ) { if( gadget ) { setChild( "__primary", gadget ); } else { if( Gadget *existingChild = getChild<Gadget>( "__primary" ) ) { removeChild( existingChild ); } } } Gadget *ViewportGadget::getPrimaryChild() { return getChild<Gadget>( "__primary" ); } const Gadget *ViewportGadget::getPrimaryChild() const { return getChild<Gadget>( "__primary" ); } const Imath::V2i &ViewportGadget::getViewport() const { return m_cameraController->getViewportResolution(); } void ViewportGadget::setViewport( const Imath::V2i &viewport ) { if( viewport == m_cameraController->getViewportResolution() ) { return; } m_cameraController->setViewportResolution( viewport ); m_viewportChangedSignal( this ); } ViewportGadget::UnarySignal &ViewportGadget::viewportChangedSignal() { return m_viewportChangedSignal; } bool ViewportGadget::getPlanarMovement() const { return m_cameraController->getPlanarMovement(); } void ViewportGadget::setPlanarMovement( bool planarMovement ) { m_cameraController->setPlanarMovement( planarMovement ); } IECoreScene::ConstCameraPtr ViewportGadget::getCamera() const { return m_cameraController->getCamera(); } void ViewportGadget::setCamera( IECoreScene::CameraPtr camera ) { if( !camera ) { throw Exception( "Cannot use null camera in ViewportGadget." ); } if( m_cameraController->getCamera()->isEqualTo( camera.get() ) ) { return; } m_cameraController->setCamera( camera->copy() ); m_cameraChangedSignal( this ); requestRender(); } const Imath::M44f &ViewportGadget::getCameraTransform() const { return m_cameraController->getTransform(); } void ViewportGadget::setCameraTransform( const Imath::M44f &transform ) { if( transform == getCameraTransform() ) { return; } m_cameraController->setTransform( transform ); m_cameraChangedSignal( this ); requestRender(); } ViewportGadget::UnarySignal &ViewportGadget::cameraChangedSignal() { return m_cameraChangedSignal; } bool ViewportGadget::getCameraEditable() const { return m_cameraEditable; } void ViewportGadget::setCameraEditable( bool editable ) { m_cameraEditable = editable; } void ViewportGadget::setCenterOfInterest( float centerOfInterest ) { m_cameraController->setCenterOfInterest( centerOfInterest ); } float ViewportGadget::getCenterOfInterest() { return m_cameraController->getCenterOfInterest(); } void ViewportGadget::frame( const Imath::Box3f &box ) { m_cameraController->frame( box, m_variableAspectZoom ); m_cameraChangedSignal( this ); requestRender(); } void ViewportGadget::frame( const Imath::Box3f &box, const Imath::V3f &viewDirection, const Imath::V3f &upVector ) { m_cameraController->frame( box, viewDirection, upVector ); m_cameraChangedSignal( this ); requestRender(); } void ViewportGadget::fitClippingPlanes( const Imath::Box3f &box ) { // Transform bound to camera space. Box3f b = transform( box, getCameraTransform().inverse() ); // Choose a far plane that should still be // sufficient no matter how we orbit about the // center of the bound. const float bRadius = b.size().length() / 2.0; float far = b.center().z - bRadius; if( far >= 0.0f ) { // Far plane behind the camera - not much we // can sensibly do. return; } else { // Far will be -ve because camera looks down -ve // Z, but clipping is specified as +ve. far *= -1; } // Round up to 2 significant digits, so we have a tiny // bit of padding and a neatish number. far = ceilSignificantDigits( far, 2 ); // Now choose a near plane. We don't want this to get // too small, to avoid losing precision. const float nearMin = far / 10000.0f; float near = b.center().z + bRadius; if( near >= 0.0f ) { // Behind camera. near = nearMin; } else { // Neaten near = floorSignificantDigits( -1 * near, 2 ); // Provide room for dollying in. near /= 100.0f; // But don't allow precision to be lost. near = std::max( near, nearMin ); } m_cameraController->setClippingPlanes( V2f( near, far ) ); m_cameraChangedSignal( this ); requestRender(); } void ViewportGadget::setDragTracking( unsigned dragTracking ) { m_dragTracking = dragTracking; } unsigned ViewportGadget::getDragTracking() const { return m_dragTracking; } void ViewportGadget::setVariableAspectZoom( bool variableAspectZoom ) { m_variableAspectZoom = variableAspectZoom; } bool ViewportGadget::getVariableAspectZoom() const { return m_variableAspectZoom; } void ViewportGadget::gadgetsAt( const Imath::V2f &rasterPosition, std::vector<GadgetPtr> &gadgets ) const { std::vector<HitRecord> selection; { SelectionScope selectionScope( this, rasterPosition, selection, IECoreGL::Selector::IDRender ); Gadget::render(); } for( std::vector<HitRecord>::const_iterator it = selection.begin(); it!= selection.end(); it++ ) { GadgetPtr gadget = Gadget::select( it->name ); if( gadget ) { gadgets.push_back( gadget ); } } if( !gadgets.size() ) { if( const Gadget *g = getPrimaryChild() ) { gadgets.push_back( const_cast<Gadget *>( g ) ); } } } IECore::LineSegment3f ViewportGadget::rasterToGadgetSpace( const Imath::V2f &position, const Gadget *gadget ) const { LineSegment3f result; m_cameraController->unproject( position, result.p0, result.p1 ); if( gadget ) { M44f m = gadget->fullTransform(); m.invert( true ); result = result * m; } return result; } Imath::V2f ViewportGadget::gadgetToRasterSpace( const Imath::V3f &gadgetPosition, const Gadget *gadget ) const { M44f gadgetTransform = gadget->fullTransform(); V3f worldSpacePosition = gadgetPosition * gadgetTransform; return m_cameraController->project( worldSpacePosition ); } IECore::LineSegment3f ViewportGadget::rasterToWorldSpace( const Imath::V2f &rasterPosition ) const { LineSegment3f result; m_cameraController->unproject( rasterPosition, result.p0, result.p1 ); return result; } Imath::V2f ViewportGadget::worldToRasterSpace( const Imath::V3f &worldPosition ) const { return m_cameraController->project( worldPosition ); } void ViewportGadget::render() const { const_cast<ViewportGadget *>( this )->preRenderSignal()( const_cast<ViewportGadget *>( this ) ); IECoreGL::ToGLConverterPtr converter = new IECoreGL::ToGLCameraConverter( m_cameraController->getCamera() ); IECoreGL::CameraPtr camera = boost::static_pointer_cast<IECoreGL::Camera>( converter->convert() ); camera->setTransform( getCameraTransform() ); camera->render( nullptr ); glClearColor( 0.26f, 0.26f, 0.26f, 0.0f ); glClearDepth( 1.0f ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); // Set up the camera to world matrix in gl_TextureMatrix[0] so that we can // reference world space positions in shaders // This should be more appropriately named in a uniform buffer, but the // easiest time to get this right is probably when we switch everything // away from using fixed function stuff glActiveTexture( GL_TEXTURE0 ); glMatrixMode( GL_TEXTURE ); glLoadIdentity(); glMultMatrixf( camera->getTransform().getValue() ); glMatrixMode( GL_MODELVIEW ); Gadget::render(); } ViewportGadget::UnarySignal &ViewportGadget::preRenderSignal() { return m_preRenderSignal; } void ViewportGadget::childRemoved( GraphComponent *parent, GraphComponent *child ) { const Gadget *childGadget = static_cast<const Gadget *>( child ); if( childGadget == m_lastButtonPressGadget || childGadget->isAncestorOf( m_lastButtonPressGadget.get() ) ) { m_lastButtonPressGadget = nullptr; } if( childGadget == m_gadgetUnderMouse || childGadget->isAncestorOf( m_gadgetUnderMouse.get() ) ) { m_gadgetUnderMouse = nullptr; } } bool ViewportGadget::buttonPress( GadgetPtr gadget, const ButtonEvent &event ) { // A child's interaction with an unmodifier MMB drag takes precedence over camera moves bool unmodifiedMiddleDrag = event.buttons == ButtonEvent::Middle && event.modifiers == ModifiableEvent::None; if( !unmodifiedMiddleDrag && m_cameraController->cameraMotionType( event, m_variableAspectZoom ) ) { // accept press so we get a dragBegin opportunity for camera movement return true; } std::vector<GadgetPtr> gadgets; gadgetsAt( V2f( event.line.p0.x, event.line.p0.y ), gadgets ); GadgetPtr handler; m_lastButtonPressGadget = nullptr; bool result = dispatchEvent( gadgets, &Gadget::buttonPressSignal, event, handler ); if( result ) { m_lastButtonPressGadget = handler; return true; } if( unmodifiedMiddleDrag ) { // accept press so we get a dragBegin opportunity for camera movement return true; } return false; } bool ViewportGadget::buttonRelease( GadgetPtr gadget, const ButtonEvent &event ) { bool result = false; if( m_lastButtonPressGadget ) { result = dispatchEvent( m_lastButtonPressGadget, &Gadget::buttonReleaseSignal, event ); } m_lastButtonPressGadget = nullptr; return result; } bool ViewportGadget::buttonDoubleClick( GadgetPtr gadget, const ButtonEvent &event ) { /// \todo Implement me. I'm not sure who this event should go to - probably /// the last button press gadget, but we erased that in buttonRelease. return false; } void ViewportGadget::updateGadgetUnderMouse( const ButtonEvent &event ) { std::vector<GadgetPtr> gadgets; gadgetsAt( V2f( event.line.p0.x, event.line.p0.y ), gadgets ); GadgetPtr newGadgetUnderMouse; if( gadgets.size() ) { newGadgetUnderMouse = gadgets[0]; } if( m_gadgetUnderMouse != newGadgetUnderMouse ) { emitEnterLeaveEvents( newGadgetUnderMouse, m_gadgetUnderMouse, event ); m_gadgetUnderMouse = newGadgetUnderMouse; } } void ViewportGadget::emitEnterLeaveEvents( GadgetPtr newGadgetUnderMouse, GadgetPtr oldGadgetUnderMouse, const ButtonEvent &event ) { // figure out the lowest point in the hierarchy where the entered status is unchanged. GadgetPtr lowestUnchanged = this; if( oldGadgetUnderMouse && newGadgetUnderMouse ) { if( oldGadgetUnderMouse->isAncestorOf( newGadgetUnderMouse.get() ) ) { lowestUnchanged = oldGadgetUnderMouse; } else if( newGadgetUnderMouse->isAncestorOf( oldGadgetUnderMouse.get() ) ) { lowestUnchanged = newGadgetUnderMouse; } else { if( Gadget *commonAncestor = oldGadgetUnderMouse->commonAncestor<Gadget>( newGadgetUnderMouse.get() ) ) { lowestUnchanged = commonAncestor; } } } // emit leave events, innermost first if( oldGadgetUnderMouse ) { GadgetPtr leaveTarget = oldGadgetUnderMouse; while( leaveTarget && leaveTarget != lowestUnchanged ) { dispatchEvent( leaveTarget.get(), &Gadget::leaveSignal, event ); leaveTarget = leaveTarget->parent<Gadget>(); } } // emit enter events, outermost first if( newGadgetUnderMouse ) { std::vector<GadgetPtr> enterTargets; GadgetPtr enterTarget = newGadgetUnderMouse; while( enterTarget && enterTarget != lowestUnchanged ) { enterTargets.push_back( enterTarget ); enterTarget = enterTarget->parent<Gadget>(); } for( std::vector<GadgetPtr>::const_reverse_iterator it = enterTargets.rbegin(); it!=enterTargets.rend(); it++ ) { dispatchEvent( *it, &Gadget::enterSignal, event ); } } }; void ViewportGadget::enter( const ButtonEvent &event ) { updateGadgetUnderMouse( event ); } void ViewportGadget::leave( const ButtonEvent &event ) { if( m_gadgetUnderMouse ) { emitEnterLeaveEvents( nullptr, m_gadgetUnderMouse, event ); m_gadgetUnderMouse = nullptr; } } bool ViewportGadget::mouseMove( GadgetPtr gadget, const ButtonEvent &event ) { // find the gadget under the mouse updateGadgetUnderMouse( event ); // pass the signal through if( m_gadgetUnderMouse ) { std::vector<GadgetPtr> gadgetUnderMouse( 1, m_gadgetUnderMouse ); GadgetPtr handler; return dispatchEvent( gadgetUnderMouse, &Gadget::mouseMoveSignal, event, handler ); } return false; } IECore::RunTimeTypedPtr ViewportGadget::dragBegin( GadgetPtr gadget, const DragDropEvent &event ) { m_dragTrackingThreshold = limits<float>::max(); CameraController::MotionType cameraMotionType = m_cameraController->cameraMotionType( event, m_variableAspectZoom ); bool unmodifiedMiddleDrag = event.buttons == ButtonEvent::Middle && event.modifiers == ModifiableEvent::None; if( ( !cameraMotionType || unmodifiedMiddleDrag ) && m_lastButtonPressGadget ) { // see if a child gadget would like to start a drag because the camera doesn't handle the event RunTimeTypedPtr data = dispatchEvent( m_lastButtonPressGadget, &Gadget::dragBeginSignal, event ); if( data ) { const_cast<DragDropEvent &>( event ).sourceGadget = m_lastButtonPressGadget; return data; } } if( cameraMotionType ) { m_cameraInMotion = true; // the const_cast is necessary because we don't want to give all the other // Gadget types non-const access to the event, but we do need the ViewportGadget // to assign destination and source gadgets. the alternative would be a different // set of non-const signals on the ViewportGadget, or maybe even having ViewportGadget // not derived from Gadget at all. this seems the lesser of two evils. const_cast<DragDropEvent &>( event ).sourceGadget = this; // we only actually update the camera if it's editable, but we still go through // the usual dragEnter/dragMove/dragEnd process so that we can swallow the events. // it would be confusing for users if they tried to edit a non-editable camera and // their gestures fell through and affected the viewport contents. if( getCameraEditable() ) { m_cameraController->motionStart( cameraMotionType, V2i( (int)event.line.p1.x, (int)event.line.p1.y ) ); } // we have to return something to start the drag, but we return something that // noone else will accept to make sure we keep the drag to ourself. return IECore::NullObject::defaultNullObject(); } else { return nullptr; } return nullptr; } bool ViewportGadget::dragEnter( GadgetPtr gadget, const DragDropEvent &event ) { if( m_cameraInMotion ) { // it's a drag for moving the camera return true; } else { std::vector<GadgetPtr> gadgets; gadgetsAt( V2f( event.line.p0.x, event.line.p0.y ), gadgets ); GadgetPtr dragDestination = updatedDragDestination( gadgets, event ); if( dragDestination ) { const_cast<DragDropEvent &>( event ).destinationGadget = dragDestination; return true; } } return false; } bool ViewportGadget::dragMove( GadgetPtr gadget, const DragDropEvent &event ) { if( m_cameraInMotion ) { if( getCameraEditable() ) { m_cameraController->motionUpdate( V2i( (int)event.line.p1.x, (int)event.line.p1.y ), m_variableAspectZoom && ( event.modifiers & ModifiableEvent::Shift ) != 0 ); m_cameraChangedSignal( this ); requestRender(); } return true; } else { // perform drag tracking if necessary trackDrag( event ); // update the destination gadget. if the drag data is a NullObject then we know // that it isn't intended for use outside of the source gadget, and can skip this // step as an optimisation. if( !event.destinationGadget || !event.data->isInstanceOf( IECore::NullObjectTypeId ) ) { std::vector<GadgetPtr> gadgets; gadgetsAt( V2f( event.line.p0.x, event.line.p0.y ), gadgets ); // update drag destination GadgetPtr updatedDestination = updatedDragDestination( gadgets, event ); if( updatedDestination != event.destinationGadget ) { GadgetPtr previousDestination = event.destinationGadget; const_cast<DragDropEvent &>( event ).destinationGadget = updatedDestination; if( previousDestination ) { dispatchEvent( previousDestination, &Gadget::dragLeaveSignal, event ); } } } // dispatch drag move to current destination if( event.destinationGadget ) { return dispatchEvent( event.destinationGadget, &Gadget::dragMoveSignal, event ); } } return false; } void ViewportGadget::trackDrag( const DragDropEvent &event ) { // early out if tracking is off for any reason, or // the drag didn't originate from within the viewport. if( getDragTracking() == DragTracking::NoDragTracking || !getCameraEditable() || !this->isAncestorOf( event.sourceGadget.get() ) ) { m_dragTrackingIdleConnection.disconnect(); return; } // we automatically scroll to track drags when the mouse is // near the edge of our viewport. figure out an inset box within // which we _don't_ perform tracking - if the mouse leaves this then // we'll track it. const V2i viewport = getViewport(); const float borderWidth = std::min( std::min( viewport.x, viewport.y ) / 8.0f, 60.0f ); const Box3f viewportBox( V3f( borderWidth, borderWidth, -1000.0f ), V3f( viewport.x - borderWidth, viewport.y - borderWidth, 1000.0f ) ); // figure out the offset, if any, of the mouse outside this central box. V2f offset( 0.0f ); if( !viewportBox.intersects( event.line.p0 ) ) { const V3f offset3 = event.line.p0 - closestPointOnBox( event.line.p0, viewportBox ); offset = V2f( getDragTracking() & DragTracking::XDragTracking ? offset3.x : 0, getDragTracking() & DragTracking::YDragTracking ? offset3.y : 0 ); } const float offsetLength = clamp( offset.length(), 0.0f, borderWidth ); // update our tracking threshold. the mouse has to go past this offset before // tracking starts. this allows us to avoid tracking too early when a drag is // started inside the tracking area, but the user is dragging back into the // center of frame. m_dragTrackingThreshold = std::min( offsetLength, m_dragTrackingThreshold ); // figure out our drag velocity. we ramp up the speed of the scrolling from 0 // to a maximum at the edge of the viewport, and clamp it so it doesn't get any // faster outside of the viewport. although getting even faster when the mouse // is outside the viewport might be nice, it results in an inconsistent // experience where a viewport edge is at the edge of the screen and the mouse // can't go any further. m_dragTrackingVelocity = -offset.normalized() * borderWidth * lerpfactor( offsetLength, m_dragTrackingThreshold, borderWidth ); // we don't actually do the scrolling in this function - instead we ensure that // trackDragIdle will be called to apply the scrolling on idle events. // this allows the scrolling to happen even when the mouse isn't moving. if( m_dragTrackingVelocity.length() > 0.0001 ) { m_dragTrackingEvent = event; if( !m_dragTrackingIdleConnection.connected() ) { m_dragTrackingTime = std::chrono::steady_clock::now(); m_dragTrackingIdleConnection = idleSignal().connect( boost::bind( &ViewportGadget::trackDragIdle, this ) ); } } else { m_dragTrackingIdleConnection.disconnect(); } } void ViewportGadget::trackDragIdle() { std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); std::chrono::duration<float> duration( now - m_dragTrackingTime ); // Avoid excessive movements if some other process causes a large delay // between idle events. duration = std::min( duration, std::chrono::duration<float>( 0.1 ) ); m_cameraController->motionStart( CameraController::Track, V2f( 0 ) ); m_cameraController->motionEnd( m_dragTrackingVelocity * duration.count() * 20.0f ); m_dragTrackingTime = now; // although the mouse hasn't moved, moving the camera will have moved it // relative to our child gadgets, so we fake a move event to update any // visual representation of the drag. dragMove( this, m_dragTrackingEvent ); m_cameraChangedSignal( this ); requestRender(); } GadgetPtr ViewportGadget::updatedDragDestination( std::vector<GadgetPtr> &gadgets, const DragDropEvent &event ) { for( std::vector<GadgetPtr>::const_iterator it = gadgets.begin(), eIt = gadgets.end(); it != eIt; it++ ) { GadgetPtr gadget = *it; while( gadget && gadget != this ) { if( gadget == event.destinationGadget ) { // no need to emit enter events when the current destination // hasn't changed. return gadget; } bool result = dispatchEvent( gadget, &Gadget::dragEnterSignal, event ); if( result ) { return gadget; } gadget = gadget->parent<Gadget>(); } } // there's nothing under the mouse that wants the drag. if the event source // is a gadget, and we're the owner of that gadget, then there's some more // things to try, but otherwise we should get out now. if( !event.sourceGadget || !this->isAncestorOf( event.sourceGadget.get() ) ) { return nullptr; } // keep the existing destination if it's also the source. if( event.destinationGadget && event.destinationGadget == event.sourceGadget ) { return event.destinationGadget; } // and if that's not the case then give the drag source another chance // to become the destination again. if( event.sourceGadget ) { if( dispatchEvent( event.sourceGadget, &Gadget::dragEnterSignal, event ) ) { return event.sourceGadget; } } // and if that failed, we have no current destination return nullptr; } bool ViewportGadget::dragLeave( GadgetPtr gadget, const DragDropEvent &event ) { if( event.destinationGadget ) { GadgetPtr previousDestination = event.destinationGadget; const_cast<DragDropEvent &>( event ).destinationGadget = nullptr; dispatchEvent( previousDestination, &Gadget::dragLeaveSignal, event ); } return true; } bool ViewportGadget::drop( GadgetPtr gadget, const DragDropEvent &event ) { if( m_cameraInMotion ) { return true; } else { if( event.destinationGadget ) { return dispatchEvent( event.destinationGadget, &Gadget::dropSignal, event ); } else { return false; } } } bool ViewportGadget::dragEnd( GadgetPtr gadget, const DragDropEvent &event ) { if( m_cameraInMotion ) { m_cameraInMotion = false; if( getCameraEditable() ) { m_cameraController->motionEnd( V2i( (int)event.line.p1.x, (int)event.line.p1.y ), m_variableAspectZoom && ( event.modifiers & ModifiableEvent::Shift ) != 0 ); m_cameraChangedSignal( this ); requestRender(); } return true; } else { m_dragTrackingIdleConnection.disconnect(); if( event.sourceGadget ) { return dispatchEvent( event.sourceGadget, &Gadget::dragEndSignal, event ); } } return false; } bool ViewportGadget::wheel( GadgetPtr gadget, const ButtonEvent &event ) { if( m_cameraInMotion ) { // we can't embed a dolly inside whatever other motion we already // started - we get here when the user accidentally rotates // the wheel while middle dragging, so it's fine to do nothing. return false; } if( !getCameraEditable() ) { return true; } V2f position( event.line.p0.x, event.line.p0.y ); m_cameraController->motionStart( CameraController::Dolly, position ); position.x += event.wheelRotation * getViewport().x / 140.0f; m_cameraController->motionUpdate( position ); m_cameraController->motionEnd( position ); m_cameraChangedSignal( this ); requestRender(); return true; } bool ViewportGadget::keyPress( GadgetPtr gadget, const KeyEvent &event ) { /// \todo We might want some sort of focus model to say who gets the keypress. if( Gadget *child = getPrimaryChild() ) { return child->keyPressSignal()( child, event ); } return false; } bool ViewportGadget::keyRelease( GadgetPtr gadget, const KeyEvent &event ) { if( Gadget *child = getPrimaryChild() ) { return child->keyReleaseSignal()( child, event ); } return false; } void ViewportGadget::eventToGadgetSpace( Event &event, Gadget *gadget ) { // no need to do anything } void ViewportGadget::eventToGadgetSpace( ButtonEvent &event, Gadget *gadget ) { event.line = rasterToGadgetSpace( V2f( event.line.p0.x, event.line.p0.y ), gadget ); } template<typename Event, typename Signal> typename Signal::result_type ViewportGadget::dispatchEvent( std::vector<GadgetPtr> &gadgets, Signal &(Gadget::*signalGetter)(), const Event &event, GadgetPtr &handler ) { for( std::vector<GadgetPtr>::const_iterator it = gadgets.begin(), eIt = gadgets.end(); it != eIt; it++ ) { GadgetPtr gadget = *it; if( !gadget->enabled() ) { continue; } while( gadget && gadget != this ) { typename Signal::result_type result = dispatchEvent( gadget, signalGetter, event ); if( result ) { handler = gadget; return result; } gadget = gadget->parent<Gadget>(); } } return typename Signal::result_type(); } template<typename Event, typename Signal> typename Signal::result_type ViewportGadget::dispatchEvent( GadgetPtr gadget, Signal &(Gadget::*signalGetter)(), const Event &event ) { Event transformedEvent( event ); eventToGadgetSpace( transformedEvent, gadget.get() ); Signal &s = (gadget.get()->*signalGetter)(); return s( gadget.get(), transformedEvent ); } ////////////////////////////////////////////////////////////////////////// // SelectionScope implementation ////////////////////////////////////////////////////////////////////////// ViewportGadget::SelectionScope::SelectionScope( const IECore::LineSegment3f &lineInGadgetSpace, const Gadget *gadget, std::vector<IECoreGL::HitRecord> &selection, IECoreGL::Selector::Mode mode ) : m_selection( selection ) { const ViewportGadget *viewportGadget = gadget->ancestor<ViewportGadget>(); V2f rasterPosition = viewportGadget->gadgetToRasterSpace( lineInGadgetSpace.p1, gadget ); begin( viewportGadget, rasterPosition, gadget->fullTransform(), mode ); } ViewportGadget::SelectionScope::SelectionScope( const Imath::V3f &corner0InGadgetSpace, const Imath::V3f &corner1InGadgetSpace, const Gadget *gadget, std::vector<IECoreGL::HitRecord> &selection, IECoreGL::Selector::Mode mode ) : m_selection( selection ) { const ViewportGadget *viewportGadget = gadget->ancestor<ViewportGadget>(); Box2f rasterRegion; rasterRegion.extendBy( viewportGadget->gadgetToRasterSpace( corner0InGadgetSpace, gadget ) ); rasterRegion.extendBy( viewportGadget->gadgetToRasterSpace( corner1InGadgetSpace, gadget ) ); begin( viewportGadget, rasterRegion, gadget->fullTransform(), mode ); } ViewportGadget::SelectionScope::SelectionScope( const ViewportGadget *viewportGadget, const Imath::V2f &rasterPosition, std::vector<IECoreGL::HitRecord> &selection, IECoreGL::Selector::Mode mode ) : m_selection( selection ) { begin( viewportGadget, rasterPosition, M44f(), mode ); } ViewportGadget::SelectionScope::~SelectionScope() { end(); } IECoreGL::State *ViewportGadget::SelectionScope::baseState() { return m_selector->baseState(); } void ViewportGadget::SelectionScope::begin( const ViewportGadget *viewportGadget, const Imath::V2f &rasterPosition, const Imath::M44f &transform, IECoreGL::Selector::Mode mode ) { begin( viewportGadget, Box2f( rasterPosition - V2f( 1 ), rasterPosition + V2f( 1 ) ), transform, mode ); } void ViewportGadget::SelectionScope::begin( const ViewportGadget *viewportGadget, const Imath::Box2f &rasterRegion, const Imath::M44f &transform, IECoreGL::Selector::Mode mode ) { glPushAttrib( GL_ALL_ATTRIB_BITS ); glPushClientAttrib( GL_CLIENT_ALL_ATTRIB_BITS ); V2f viewport = viewportGadget->getViewport(); Box2f ndcRegion( rasterRegion.min / viewport, rasterRegion.max / viewport ); IECoreGL::ToGLConverterPtr converter = new IECoreGL::ToGLCameraConverter( viewportGadget->m_cameraController->getCamera() ); IECoreGL::CameraPtr camera = boost::static_pointer_cast<IECoreGL::Camera>( converter->convert() ); camera->setTransform( viewportGadget->getCameraTransform() ); /// \todo It would be better to base this on whether we have a depth buffer or not, but /// we don't have access to that information right now. m_depthSort = camera->isInstanceOf( IECoreGL::PerspectiveCamera::staticTypeId() ); camera->render( nullptr ); glClearColor( 0.3f, 0.3f, 0.3f, 0.0f ); glClearDepth( 1.0f ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); m_selector = SelectorPtr( new IECoreGL::Selector( ndcRegion, mode, m_selection ) ); glPushMatrix(); glMultMatrixf( transform.getValue() ); } void ViewportGadget::SelectionScope::end() { glPopMatrix(); m_selector = SelectorPtr(); glPopClientAttrib(); glPopAttrib(); if( m_depthSort ) { std::sort( m_selection.begin(), m_selection.end() ); } else { std::reverse( m_selection.begin(), m_selection.end() ); } } ViewportGadget::RasterScope::RasterScope( const ViewportGadget *viewportGadget ) { V2f viewport = viewportGadget->getViewport(); glMatrixMode( GL_PROJECTION ); glPushMatrix(); glLoadIdentity(); if( IECoreGL::Selector *selector = IECoreGL::Selector::currentSelector() ) { glMultMatrixd( selector->postProjectionMatrix().getValue() ); } glOrtho( 0, viewport.x, viewport.y, 0, -1, 1 ); glMatrixMode( GL_MODELVIEW ); glPushMatrix(); glLoadIdentity(); glTranslatef( 0, 0, 1 ); } ViewportGadget::RasterScope::~RasterScope() { glPopMatrix(); glMatrixMode( GL_PROJECTION ); glPopMatrix(); glMatrixMode( GL_MODELVIEW ); }
; void __CALLEE__ sp1_IterateSprChar_callee(struct sp1_ss *s, void *hook1) ; 02.2006 aralbrec, Sprite Pack v3.0 ; sinclair spectrum version SECTION code_sprite_sp1 PUBLIC sp1_IterateSprChar_callee PUBLIC ASMDISP_SP1_ITERATESPRCHAR_CALLEE EXTERN l_jpix .sp1_IterateSprChar_callee pop hl pop ix ex (sp),hl .asmentry ; Iterate over all the struct sp1_cs contained in a sprite ; in row major order, calling the user function for each one. ; ; enter : hl = & struct sp1_ss ; ix = user function ; uses : af, bc, hl + whatever user function uses .SP1IterateSprChar ld bc,15 add hl,bc ; hl = & struct sp1_ss.first ld c,b ; bc = sprite char counter = 0 .iterloop ld a,(hl) or a ret z inc hl ld l,(hl) ld h,a ; hl = & next struct sp1_cs push bc push hl call l_jpix ; call userfunc(uint count, struct sp1_cs *c) pop hl pop bc inc bc jp iterloop DEFC ASMDISP_SP1_ITERATESPRCHAR_CALLEE = asmentry - sp1_IterateSprChar_callee
// Copyright 2010 Google Inc. All Rights Reserved. // Author: rays@google.com (Ray Smith) // // 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. // /////////////////////////////////////////////////////////////////////// #ifdef HAVE_TESSERACT_CONFIG_H # include "config_auto.h" #endif #include <algorithm> #include <allheaders.h> #include "boxread.h" #include "fontinfo.h" //#include "helpers.h" #include "indexmapbidi.h" #include "intfeaturedist.h" #include "intfeaturemap.h" #include "intfeaturespace.h" #include "shapetable.h" #include "trainingsample.h" #include "trainingsampleset.h" #include "unicity_table.h" namespace tesseract { const int kTestChar = -1; // 37; // Max number of distances to compute the squared way const int kSquareLimit = 25; // Prime numbers for subsampling distances. const int kPrime1 = 17; const int kPrime2 = 13; TrainingSampleSet::FontClassInfo::FontClassInfo() : num_raw_samples(0), canonical_sample(-1), canonical_dist(0.0f) {} // Writes to the given file. Returns false in case of error. bool TrainingSampleSet::FontClassInfo::Serialize(FILE *fp) const { if (fwrite(&num_raw_samples, sizeof(num_raw_samples), 1, fp) != 1) { return false; } if (fwrite(&canonical_sample, sizeof(canonical_sample), 1, fp) != 1) { return false; } if (fwrite(&canonical_dist, sizeof(canonical_dist), 1, fp) != 1) { return false; } if (!::tesseract::Serialize(fp, samples)) { return false; } return true; } // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool TrainingSampleSet::FontClassInfo::DeSerialize(bool swap, FILE *fp) { if (fread(&num_raw_samples, sizeof(num_raw_samples), 1, fp) != 1) { return false; } if (fread(&canonical_sample, sizeof(canonical_sample), 1, fp) != 1) { return false; } if (fread(&canonical_dist, sizeof(canonical_dist), 1, fp) != 1) { return false; } if (!::tesseract::DeSerialize(swap, fp, samples)) { return false; } if (swap) { ReverseN(&num_raw_samples, sizeof(num_raw_samples)); ReverseN(&canonical_sample, sizeof(canonical_sample)); ReverseN(&canonical_dist, sizeof(canonical_dist)); } return true; } TrainingSampleSet::TrainingSampleSet(const FontInfoTable &font_table) : num_raw_samples_(0) , unicharset_size_(0) , font_class_array_(nullptr) , fontinfo_table_(font_table) {} TrainingSampleSet::~TrainingSampleSet() { for (auto sample : samples_) { delete sample; } delete font_class_array_; } // Writes to the given file. Returns false in case of error. bool TrainingSampleSet::Serialize(FILE *fp) const { if (!tesseract::Serialize(fp, samples_)) { return false; } if (!unicharset_.save_to_file(fp)) { return false; } if (!font_id_map_.Serialize(fp)) { return false; } int8_t not_null = font_class_array_ != nullptr; if (fwrite(&not_null, sizeof(not_null), 1, fp) != 1) { return false; } if (not_null) { if (!font_class_array_->SerializeClasses(fp)) { return false; } } return true; } // Reads from the given file. Returns false in case of error. // If swap is true, assumes a big/little-endian swap is needed. bool TrainingSampleSet::DeSerialize(bool swap, FILE *fp) { if (!tesseract::DeSerialize(swap, fp, samples_)) { return false; } num_raw_samples_ = samples_.size(); if (!unicharset_.load_from_file(fp)) { return false; } if (!font_id_map_.DeSerialize(swap, fp)) { return false; } delete font_class_array_; font_class_array_ = nullptr; int8_t not_null; if (fread(&not_null, sizeof(not_null), 1, fp) != 1) { return false; } if (not_null) { FontClassInfo empty; font_class_array_ = new GENERIC_2D_ARRAY<FontClassInfo>(1, 1, empty); if (!font_class_array_->DeSerializeClasses(swap, fp)) { return false; } } unicharset_size_ = unicharset_.size(); return true; } // Load an initial unicharset, or set one up if the file cannot be read. void TrainingSampleSet::LoadUnicharset(const char *filename) { if (!unicharset_.load_from_file(filename)) { tprintf( "ERROR: Failed to load unicharset from file %s\n" "Building unicharset from scratch...\n", filename); unicharset_.clear(); // Add special characters as they were removed by the clear. UNICHARSET empty; unicharset_.AppendOtherUnicharset(empty); } unicharset_size_ = unicharset_.size(); } // Adds a character sample to this sample set. // If the unichar is not already in the local unicharset, it is added. // Returns the unichar_id of the added sample, from the local unicharset. int TrainingSampleSet::AddSample(const char *unichar, TrainingSample *sample) { if (!unicharset_.contains_unichar(unichar)) { unicharset_.unichar_insert(unichar); if (unicharset_.size() > MAX_NUM_CLASSES) { tprintf( "ERROR: Size of unicharset in TrainingSampleSet::AddSample is " "greater than MAX_NUM_CLASSES\n"); return -1; } } UNICHAR_ID char_id = unicharset_.unichar_to_id(unichar); AddSample(char_id, sample); return char_id; } // Adds a character sample to this sample set with the given unichar_id, // which must correspond to the local unicharset (in this). void TrainingSampleSet::AddSample(int unichar_id, TrainingSample *sample) { sample->set_class_id(unichar_id); samples_.push_back(sample); num_raw_samples_ = samples_.size(); unicharset_size_ = unicharset_.size(); } // Returns the number of samples for the given font,class pair. // If randomize is true, returns the number of samples accessible // with randomizing on. (Increases the number of samples if small.) // OrganizeByFontAndClass must have been already called. int TrainingSampleSet::NumClassSamples(int font_id, int class_id, bool randomize) const { ASSERT_HOST(font_class_array_ != nullptr); if (font_id < 0 || class_id < 0 || font_id >= font_id_map_.SparseSize() || class_id >= unicharset_size_) { // There are no samples because the font or class doesn't exist. return 0; } int font_index = font_id_map_.SparseToCompact(font_id); if (font_index < 0) { return 0; // The font has no samples. } if (randomize) { return (*font_class_array_)(font_index, class_id).samples.size(); } else { return (*font_class_array_)(font_index, class_id).num_raw_samples; } } // Gets a sample by its index. const TrainingSample *TrainingSampleSet::GetSample(int index) const { return samples_[index]; } // Gets a sample by its font, class, index. // OrganizeByFontAndClass must have been already called. const TrainingSample *TrainingSampleSet::GetSample(int font_id, int class_id, int index) const { ASSERT_HOST(font_class_array_ != nullptr); int font_index = font_id_map_.SparseToCompact(font_id); if (font_index < 0) { return nullptr; } int sample_index = (*font_class_array_)(font_index, class_id).samples[index]; return samples_[sample_index]; } // Get a sample by its font, class, index. Does not randomize. // OrganizeByFontAndClass must have been already called. TrainingSample *TrainingSampleSet::MutableSample(int font_id, int class_id, int index) { ASSERT_HOST(font_class_array_ != nullptr); int font_index = font_id_map_.SparseToCompact(font_id); if (font_index < 0) { return nullptr; } int sample_index = (*font_class_array_)(font_index, class_id).samples[index]; return samples_[sample_index]; } // Returns a string debug representation of the given sample: // font, unichar_str, bounding box, page. std::string TrainingSampleSet::SampleToString(const TrainingSample &sample) const { std::string boxfile_str; MakeBoxFileStr(unicharset_.id_to_unichar(sample.class_id()), sample.bounding_box(), sample.page_num(), boxfile_str); return std::string(fontinfo_table_.at(sample.font_id()).name) + " " + boxfile_str; } // Gets the combined set of features used by all the samples of the given // font/class combination. const BitVector &TrainingSampleSet::GetCloudFeatures(int font_id, int class_id) const { int font_index = font_id_map_.SparseToCompact(font_id); ASSERT_HOST(font_index >= 0); return (*font_class_array_)(font_index, class_id).cloud_features; } // Gets the indexed features of the canonical sample of the given // font/class combination. const std::vector<int> &TrainingSampleSet::GetCanonicalFeatures(int font_id, int class_id) const { int font_index = font_id_map_.SparseToCompact(font_id); ASSERT_HOST(font_index >= 0); return (*font_class_array_)(font_index, class_id).canonical_features; } // Returns the distance between the given UniCharAndFonts pair. // If matched_fonts, only matching fonts, are considered, unless that yields // the empty set. // OrganizeByFontAndClass must have been already called. float TrainingSampleSet::UnicharDistance(const UnicharAndFonts &uf1, const UnicharAndFonts &uf2, bool matched_fonts, const IntFeatureMap &feature_map) { int num_fonts1 = uf1.font_ids.size(); int c1 = uf1.unichar_id; int num_fonts2 = uf2.font_ids.size(); int c2 = uf2.unichar_id; double dist_sum = 0.0; int dist_count = 0; const bool debug = false; if (matched_fonts) { // Compute distances only where fonts match. for (int i = 0; i < num_fonts1; ++i) { int f1 = uf1.font_ids[i]; for (int j = 0; j < num_fonts2; ++j) { int f2 = uf2.font_ids[j]; if (f1 == f2) { dist_sum += ClusterDistance(f1, c1, f2, c2, feature_map); ++dist_count; } } } } else if (num_fonts1 * num_fonts2 <= kSquareLimit) { // Small enough sets to compute all the distances. for (int i = 0; i < num_fonts1; ++i) { int f1 = uf1.font_ids[i]; for (int j = 0; j < num_fonts2; ++j) { int f2 = uf2.font_ids[j]; dist_sum += ClusterDistance(f1, c1, f2, c2, feature_map); if (debug) { tprintf("Cluster dist %d %d %d %d = %g\n", f1, c1, f2, c2, ClusterDistance(f1, c1, f2, c2, feature_map)); } ++dist_count; } } } else { // Subsample distances, using the largest set once, and stepping through // the smaller set so as to ensure that all the pairs are different. int increment = kPrime1 != num_fonts2 ? kPrime1 : kPrime2; int index = 0; int num_samples = std::max(num_fonts1, num_fonts2); for (int i = 0; i < num_samples; ++i, index += increment) { int f1 = uf1.font_ids[i % num_fonts1]; int f2 = uf2.font_ids[index % num_fonts2]; if (debug) { tprintf("Cluster dist %d %d %d %d = %g\n", f1, c1, f2, c2, ClusterDistance(f1, c1, f2, c2, feature_map)); } dist_sum += ClusterDistance(f1, c1, f2, c2, feature_map); ++dist_count; } } if (dist_count == 0) { if (matched_fonts) { return UnicharDistance(uf1, uf2, false, feature_map); } return 0.0f; } return dist_sum / dist_count; } // Returns the distance between the given pair of font/class pairs. // Finds in cache or computes and caches. // OrganizeByFontAndClass must have been already called. float TrainingSampleSet::ClusterDistance(int font_id1, int class_id1, int font_id2, int class_id2, const IntFeatureMap &feature_map) { ASSERT_HOST(font_class_array_ != nullptr); int font_index1 = font_id_map_.SparseToCompact(font_id1); int font_index2 = font_id_map_.SparseToCompact(font_id2); if (font_index1 < 0 || font_index2 < 0) { return 0.0f; } FontClassInfo &fc_info = (*font_class_array_)(font_index1, class_id1); if (font_id1 == font_id2) { // Special case cache for speed. if (fc_info.unichar_distance_cache.empty()) { fc_info.unichar_distance_cache.resize(unicharset_size_, -1.0f); } if (fc_info.unichar_distance_cache[class_id2] < 0) { // Distance has to be calculated. float result = ComputeClusterDistance(font_id1, class_id1, font_id2, class_id2, feature_map); fc_info.unichar_distance_cache[class_id2] = result; // Copy to the symmetric cache entry. FontClassInfo &fc_info2 = (*font_class_array_)(font_index2, class_id2); if (fc_info2.unichar_distance_cache.empty()) { fc_info2.unichar_distance_cache.resize(unicharset_size_, -1.0f); } fc_info2.unichar_distance_cache[class_id1] = result; } return fc_info.unichar_distance_cache[class_id2]; } else if (class_id1 == class_id2) { // Another special-case cache for equal class-id. if (fc_info.font_distance_cache.empty()) { fc_info.font_distance_cache.resize(font_id_map_.CompactSize(), -1.0f); } if (fc_info.font_distance_cache[font_index2] < 0) { // Distance has to be calculated. float result = ComputeClusterDistance(font_id1, class_id1, font_id2, class_id2, feature_map); fc_info.font_distance_cache[font_index2] = result; // Copy to the symmetric cache entry. FontClassInfo &fc_info2 = (*font_class_array_)(font_index2, class_id2); if (fc_info2.font_distance_cache.empty()) { fc_info2.font_distance_cache.resize(font_id_map_.CompactSize(), -1.0f); } fc_info2.font_distance_cache[font_index1] = result; } return fc_info.font_distance_cache[font_index2]; } // Both font and class are different. Linear search for class_id2/font_id2 // in what is a hopefully short list of distances. size_t cache_index = 0; while (cache_index < fc_info.distance_cache.size() && (fc_info.distance_cache[cache_index].unichar_id != class_id2 || fc_info.distance_cache[cache_index].font_id != font_id2)) { ++cache_index; } if (cache_index == fc_info.distance_cache.size()) { // Distance has to be calculated. float result = ComputeClusterDistance(font_id1, class_id1, font_id2, class_id2, feature_map); FontClassDistance fc_dist = {class_id2, font_id2, result}; fc_info.distance_cache.push_back(fc_dist); // Copy to the symmetric cache entry. We know it isn't there already, as // we always copy to the symmetric entry. FontClassInfo &fc_info2 = (*font_class_array_)(font_index2, class_id2); fc_dist.unichar_id = class_id1; fc_dist.font_id = font_id1; fc_info2.distance_cache.push_back(fc_dist); } return fc_info.distance_cache[cache_index].distance; } // Computes the distance between the given pair of font/class pairs. float TrainingSampleSet::ComputeClusterDistance(int font_id1, int class_id1, int font_id2, int class_id2, const IntFeatureMap &feature_map) const { int dist = ReliablySeparable(font_id1, class_id1, font_id2, class_id2, feature_map, false); dist += ReliablySeparable(font_id2, class_id2, font_id1, class_id1, feature_map, false); int denominator = GetCanonicalFeatures(font_id1, class_id1).size(); denominator += GetCanonicalFeatures(font_id2, class_id2).size(); return static_cast<float>(dist) / denominator; } // Helper to add a feature and its near neighbors to the good_features. // levels indicates how many times to compute the offset features of what is // already there. This is done by iteration rather than recursion. static void AddNearFeatures(const IntFeatureMap &feature_map, int f, int levels, std::vector<int> *good_features) { int prev_num_features = 0; good_features->push_back(f); int num_features = 1; for (int level = 0; level < levels; ++level) { for (int i = prev_num_features; i < num_features; ++i) { int feature = (*good_features)[i]; for (int dir = -kNumOffsetMaps; dir <= kNumOffsetMaps; ++dir) { if (dir == 0) { continue; } int f1 = feature_map.OffsetFeature(feature, dir); if (f1 >= 0) { good_features->push_back(f1); } } } prev_num_features = num_features; num_features = good_features->size(); } } // Returns the number of canonical features of font/class 2 for which // neither the feature nor any of its near neighbors occurs in the cloud // of font/class 1. Each such feature is a reliable separation between // the classes, ASSUMING that the canonical sample is sufficiently // representative that every sample has a feature near that particular // feature. To check that this is so on the fly would be prohibitively // expensive, but it might be possible to pre-qualify the canonical features // to include only those for which this assumption is true. // ComputeCanonicalFeatures and ComputeCloudFeatures must have been called // first, or the results will be nonsense. int TrainingSampleSet::ReliablySeparable(int font_id1, int class_id1, int font_id2, int class_id2, const IntFeatureMap &feature_map, bool thorough) const { int result = 0; const TrainingSample *sample2 = GetCanonicalSample(font_id2, class_id2); if (sample2 == nullptr) { return 0; // There are no canonical features. } const std::vector<int> &canonical2 = GetCanonicalFeatures(font_id2, class_id2); const BitVector &cloud1 = GetCloudFeatures(font_id1, class_id1); if (cloud1.empty()) { return canonical2.size(); // There are no cloud features. } // Find a canonical2 feature that is not in cloud1. for (int feature : canonical2) { if (cloud1[feature]) { continue; } // Gather the near neighbours of f. std::vector<int> good_features; AddNearFeatures(feature_map, feature, 1, &good_features); // Check that none of the good_features are in the cloud. bool found = false; for (auto good_f : good_features) { if (cloud1[good_f]) { found = true; break; } } if (found) { continue; // Found one in the cloud. } ++result; } return result; } // Returns the total index of the requested sample. // OrganizeByFontAndClass must have been already called. int TrainingSampleSet::GlobalSampleIndex(int font_id, int class_id, int index) const { ASSERT_HOST(font_class_array_ != nullptr); int font_index = font_id_map_.SparseToCompact(font_id); if (font_index < 0) { return -1; } return (*font_class_array_)(font_index, class_id).samples[index]; } // Gets the canonical sample for the given font, class pair. // ComputeCanonicalSamples must have been called first. const TrainingSample *TrainingSampleSet::GetCanonicalSample(int font_id, int class_id) const { ASSERT_HOST(font_class_array_ != nullptr); int font_index = font_id_map_.SparseToCompact(font_id); if (font_index < 0) { return nullptr; } const int sample_index = (*font_class_array_)(font_index, class_id).canonical_sample; return sample_index >= 0 ? samples_[sample_index] : nullptr; } // Gets the max distance for the given canonical sample. // ComputeCanonicalSamples must have been called first. float TrainingSampleSet::GetCanonicalDist(int font_id, int class_id) const { ASSERT_HOST(font_class_array_ != nullptr); int font_index = font_id_map_.SparseToCompact(font_id); if (font_index < 0) { return 0.0f; } if ((*font_class_array_)(font_index, class_id).canonical_sample >= 0) { return (*font_class_array_)(font_index, class_id).canonical_dist; } else { return 0.0f; } } // Generates indexed features for all samples with the supplied feature_space. void TrainingSampleSet::IndexFeatures(const IntFeatureSpace &feature_space) { for (auto &sample : samples_) { sample->IndexFeatures(feature_space); } } // Marks the given sample index for deletion. // Deletion is actually completed by DeleteDeadSamples. void TrainingSampleSet::KillSample(TrainingSample *sample) { sample->set_sample_index(-1); } // Deletes all samples with zero features marked by KillSample. void TrainingSampleSet::DeleteDeadSamples() { using namespace std::placeholders; // for _1 auto old_it = samples_.begin(); for (; old_it < samples_.end(); ++old_it) { if (*old_it == nullptr || (*old_it)->class_id() < 0) { break; } } auto new_it = old_it; for (; old_it < samples_.end(); ++old_it) { if (*old_it == nullptr || (*old_it)->class_id() < 0) { delete *old_it; } else { *new_it = *old_it; ++new_it; } } samples_.resize(new_it - samples_.begin() + 1); num_raw_samples_ = samples_.size(); // Samples must be re-organized now we have deleted a few. } // Construct an array to access the samples by font,class pair. void TrainingSampleSet::OrganizeByFontAndClass() { // Font indexes are sparse, so we used a map to compact them, so we can // have an efficient 2-d array of fonts and character classes. SetupFontIdMap(); int compact_font_size = font_id_map_.CompactSize(); // Get a 2-d array of generic vectors. delete font_class_array_; FontClassInfo empty; font_class_array_ = new GENERIC_2D_ARRAY<FontClassInfo>(compact_font_size, unicharset_size_, empty); for (size_t s = 0; s < samples_.size(); ++s) { int font_id = samples_[s]->font_id(); int class_id = samples_[s]->class_id(); if (font_id < 0 || font_id >= font_id_map_.SparseSize()) { tprintf("Font id = %d/%d, class id = %d/%d on sample %zu\n", font_id, font_id_map_.SparseSize(), class_id, unicharset_size_, s); } ASSERT_HOST(font_id >= 0 && font_id < font_id_map_.SparseSize()); ASSERT_HOST(class_id >= 0 && class_id < unicharset_size_); int font_index = font_id_map_.SparseToCompact(font_id); (*font_class_array_)(font_index, class_id).samples.push_back(s); } // Set the num_raw_samples member of the FontClassInfo, to set the boundary // between the raw samples and the replicated ones. for (int f = 0; f < compact_font_size; ++f) { for (int c = 0; c < unicharset_size_; ++c) { (*font_class_array_)(f, c).num_raw_samples = (*font_class_array_)(f, c).samples.size(); } } // This is the global number of samples and also marks the boundary between // real and replicated samples. num_raw_samples_ = samples_.size(); } // Constructs the font_id_map_ which maps real font_ids (sparse) to a compact // index for the font_class_array_. void TrainingSampleSet::SetupFontIdMap() { // Number of samples for each font_id. std::vector<int> font_counts; for (auto &sample : samples_) { const int font_id = sample->font_id(); while (font_id >= font_counts.size()) { font_counts.push_back(0); } ++font_counts[font_id]; } font_id_map_.Init(font_counts.size(), false); for (size_t f = 0; f < font_counts.size(); ++f) { font_id_map_.SetMap(f, font_counts[f] > 0); } font_id_map_.Setup(); } // Finds the sample for each font, class pair that has least maximum // distance to all the other samples of the same font, class. // OrganizeByFontAndClass must have been already called. void TrainingSampleSet::ComputeCanonicalSamples(const IntFeatureMap &map, bool debug) { ASSERT_HOST(font_class_array_ != nullptr); IntFeatureDist f_table; if (debug) { tprintf("feature table size %d\n", map.sparse_size()); } f_table.Init(&map); int worst_s1 = 0; int worst_s2 = 0; double global_worst_dist = 0.0; // Compute distances independently for each font and char index. int font_size = font_id_map_.CompactSize(); for (int font_index = 0; font_index < font_size; ++font_index) { int font_id = font_id_map_.CompactToSparse(font_index); for (int c = 0; c < unicharset_size_; ++c) { int samples_found = 0; FontClassInfo &fcinfo = (*font_class_array_)(font_index, c); if (fcinfo.samples.empty() || (kTestChar >= 0 && c != kTestChar)) { fcinfo.canonical_sample = -1; fcinfo.canonical_dist = 0.0f; if (debug) { tprintf("Skipping class %d\n", c); } continue; } // The canonical sample will be the one with the min_max_dist, which // is the sample with the lowest maximum distance to all other samples. double min_max_dist = 2.0; // We keep track of the farthest apart pair (max_s1, max_s2) which // are max_max_dist apart, so we can see how bad the variability is. double max_max_dist = 0.0; int max_s1 = 0; int max_s2 = 0; fcinfo.canonical_sample = fcinfo.samples[0]; fcinfo.canonical_dist = 0.0f; for (auto s1 : fcinfo.samples) { const std::vector<int> &features1 = samples_[s1]->indexed_features(); f_table.Set(features1, features1.size(), true); double max_dist = 0.0; // Run the full squared-order search for similar samples. It is still // reasonably fast because f_table.FeatureDistance is fast, but we // may have to reconsider if we start playing with too many samples // of a single char/font. for (int s2 : fcinfo.samples) { if (samples_[s2]->class_id() != c || samples_[s2]->font_id() != font_id || s2 == s1) { continue; } std::vector<int> features2 = samples_[s2]->indexed_features(); double dist = f_table.FeatureDistance(features2); if (dist > max_dist) { max_dist = dist; if (dist > max_max_dist) { max_max_dist = dist; max_s1 = s1; max_s2 = s2; } } } // Using Set(..., false) is far faster than re initializing, due to // the sparseness of the feature space. f_table.Set(features1, features1.size(), false); samples_[s1]->set_max_dist(max_dist); ++samples_found; if (max_dist < min_max_dist) { fcinfo.canonical_sample = s1; fcinfo.canonical_dist = max_dist; } UpdateRange(max_dist, &min_max_dist, &max_max_dist); } if (max_max_dist > global_worst_dist) { // Keep a record of the worst pair over all characters/fonts too. global_worst_dist = max_max_dist; worst_s1 = max_s1; worst_s2 = max_s2; } if (debug) { tprintf( "Found %d samples of class %d=%s, font %d, " "dist range [%g, %g], worst pair= %s, %s\n", samples_found, c, unicharset_.debug_str(c).c_str(), font_index, min_max_dist, max_max_dist, SampleToString(*samples_[max_s1]).c_str(), SampleToString(*samples_[max_s2]).c_str()); } } } if (debug) { tprintf("Global worst dist = %g, between sample %d and %d\n", global_worst_dist, worst_s1, worst_s2); } } // Replicates the samples to a minimum frequency defined by // 2 * kSampleRandomSize, or for larger counts duplicates all samples. // After replication, the replicated samples are perturbed slightly, but // in a predictable and repeatable way. // Use after OrganizeByFontAndClass(). void TrainingSampleSet::ReplicateAndRandomizeSamples() { ASSERT_HOST(font_class_array_ != nullptr); int font_size = font_id_map_.CompactSize(); for (int font_index = 0; font_index < font_size; ++font_index) { for (int c = 0; c < unicharset_size_; ++c) { FontClassInfo &fcinfo = (*font_class_array_)(font_index, c); int sample_count = fcinfo.samples.size(); int min_samples = 2 * std::max(kSampleRandomSize, sample_count); if (sample_count > 0 && sample_count < min_samples) { int base_count = sample_count; for (int base_index = 0; sample_count < min_samples; ++sample_count) { int src_index = fcinfo.samples[base_index++]; if (base_index >= base_count) { base_index = 0; } TrainingSample *sample = samples_[src_index]->RandomizedCopy(sample_count % kSampleRandomSize); int sample_index = samples_.size(); sample->set_sample_index(sample_index); samples_.push_back(sample); fcinfo.samples.push_back(sample_index); } } } } } // Caches the indexed features of the canonical samples. // ComputeCanonicalSamples must have been already called. // TODO(rays) see note on ReliablySeparable and try restricting the // canonical features to those that truly represent all samples. void TrainingSampleSet::ComputeCanonicalFeatures() { ASSERT_HOST(font_class_array_ != nullptr); const int font_size = font_id_map_.CompactSize(); for (int font_index = 0; font_index < font_size; ++font_index) { const int font_id = font_id_map_.CompactToSparse(font_index); for (int c = 0; c < unicharset_size_; ++c) { int num_samples = NumClassSamples(font_id, c, false); if (num_samples == 0) { continue; } const TrainingSample *sample = GetCanonicalSample(font_id, c); FontClassInfo &fcinfo = (*font_class_array_)(font_index, c); fcinfo.canonical_features = sample->indexed_features(); } } } // Computes the combined set of features used by all the samples of each // font/class combination. Use after ReplicateAndRandomizeSamples. void TrainingSampleSet::ComputeCloudFeatures(int feature_space_size) { ASSERT_HOST(font_class_array_ != nullptr); int font_size = font_id_map_.CompactSize(); for (int font_index = 0; font_index < font_size; ++font_index) { int font_id = font_id_map_.CompactToSparse(font_index); for (int c = 0; c < unicharset_size_; ++c) { int num_samples = NumClassSamples(font_id, c, false); if (num_samples == 0) { continue; } FontClassInfo &fcinfo = (*font_class_array_)(font_index, c); fcinfo.cloud_features.Init(feature_space_size); for (int s = 0; s < num_samples; ++s) { const TrainingSample *sample = GetSample(font_id, c, s); const std::vector<int> &sample_features = sample->indexed_features(); for (int sample_feature : sample_features) { fcinfo.cloud_features.SetBit(sample_feature); } } } } } // Adds all fonts of the given class to the shape. void TrainingSampleSet::AddAllFontsForClass(int class_id, Shape *shape) const { for (int f = 0; f < font_id_map_.CompactSize(); ++f) { const int font_id = font_id_map_.CompactToSparse(f); shape->AddToShape(class_id, font_id); } } #ifndef GRAPHICS_DISABLED // Display the samples with the given indexed feature that also match // the given shape. void TrainingSampleSet::DisplaySamplesWithFeature(int f_index, const Shape &shape, const IntFeatureSpace &space, ScrollView::Color color, ScrollView *window) const { for (int s = 0; s < num_raw_samples(); ++s) { const TrainingSample *sample = GetSample(s); if (shape.ContainsUnichar(sample->class_id())) { std::vector<int> indexed_features; space.IndexAndSortFeatures(sample->features(), sample->num_features(), &indexed_features); for (int indexed_feature : indexed_features) { if (indexed_feature == f_index) { sample->DisplayFeatures(color, window); } } } } } #endif // !GRAPHICS_DISABLED } // namespace tesseract.
<% from pwnlib.shellcraft import arm, pretty, common %> <%page args="in_fd = 'r6', size = 0x800, allocate_stack = True"/> <%docstring> Reads to the stack from a directory. Args: in_fd (int/str): File descriptor to be read from. size (int): Buffer size. allocate_stack (bool): allocate 'size' bytes on the stack. You can optioanlly shave a few bytes not allocating the stack space. The size read is left in eax. </%docstring> <% getdents_loop = common.label('getdents_loop') %> %if allocate_stack: sub sp, sp, ${pretty(size)} %endif ${getdents_loop}: ${arm.linux.getdents(in_fd, 'sp', size)}
SECTION code_fp_math16 PUBLIC asinf16_fastcall EXTERN _m16_asinf defc asinf16_fastcall = _m16_asinf ; SDCC bridge for Classic IF __CLASSIC PUBLIC _asinf16_fastcall defc _asinf16_fastcall = _m16_asinf ENDIF
addi r28, r29, 16702650 # fedcba addi r28, r29, 16702650 # fedcba label0: addi r28, r29, 65535 # ffff addi r28, r29, $label4 # abcde subi r28, r29, 16702650 # fedcba subi r28, r29, 16702650 # fedcba label1: subi r28, r29, 65535 # ffff subi r28, r29, $label3 # abcde muli r28, r29, 16702650 # fedcba muli r28, r29, 16702650 # fedcba label2: muli r28, r29, 65535 # ffff muli r28, r29, $label2 # abcde divi r28, r29, 16702650 # fedcba divi r28, r29, 16702650 # fedcba label3: divi r28, r29, 65535 # ffff divi r28, r29, $label1 # abcde modi r28, r29, 16702650 # fedcba modi r28, r29, 16702650 # fedcba label4: modi r28, r29, 65535 # ffff modi r28, r29, $label0 # abcde
; ======================================================================== ; ; void *sms_memcpy_mem_to_vram_unsafe(void *dst, void *src, unsigned int n) ; ; memcpy from memory to vram; VRAM addresses are assumed to be stable. ; ; ======================================================================== SECTION code_clib SECTION code_crt_common PUBLIC asm_sms_memcpy_mem_to_vram_unsafe EXTERN asm_sms_vram_write_de EXTERN asm_sms_copy_mem_to_vram_unsafe asm_sms_memcpy_mem_to_vram_unsafe: ; memcpy from memory to vram ; ; enter : hl = void *src in memory ; de = void *dst in vram ; bc = unsigned int n > 0 ; ; exit : de = void *src, &byte after last read from memory ; hl = void *dst, &byte after last written in vram ; bc = 0 ; ; uses : af, bc, de, hl call asm_sms_vram_write_de ex de,hl add hl,bc ex de,hl ; hl = void *src in memory ; bc = unsigned int n > 0 ; VRAM has dst address set jp asm_sms_copy_mem_to_vram_unsafe
/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "../../StroikaPreComp.h" #include "IConsumer.h" using namespace Stroika::Foundation::DataExchange; using namespace Stroika::Foundation::DataExchange::StructuredStreamEvents; /* ******************************************************************************** ***************************** DataExchange::IConsumer ************************** ******************************************************************************** */ void IConsumer::StartDocument () { } void IConsumer::EndDocument () { } void IConsumer::StartElement ([[maybe_unused]] const Name& name) { } void IConsumer::EndElement ([[maybe_unused]] const Name& name) { } void IConsumer::TextInsideElement ([[maybe_unused]] const String& text) { }
dos_func macro val mov ah, val int 21h endm exit macro dos_func 4ch endm .model small .stack 64h .data array dw 4400h, 1100h, 9900h, 2200h, 3300h len equ ($ - array) / 2 .code mov ax, @data mov ds, ax mov cx, 2 outer: mov dx, cx dec dx mov si, dx add si, si mov ax, array[si] inner: cmp array[si - 2], ax jbe break mov di, array[si - 2] mov array[si], di dec si dec si dec dx jnz inner break: mov array[si], ax inc cx cmp cx, len jbe outer exit end
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r14 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_D_ht+0x116a0, %rsi lea addresses_D_ht+0xe7a0, %rdi and %r11, %r11 mov $8, %rcx rep movsw nop xor $43685, %rdi lea addresses_WC_ht+0x1aea0, %r11 nop nop nop nop nop xor $56837, %rbx mov (%r11), %rdi nop nop sub %r11, %r11 lea addresses_normal_ht+0x16ca0, %r14 nop nop nop nop add %r10, %r10 movw $0x6162, (%r14) nop add $31613, %rcx lea addresses_UC_ht+0x137a0, %rbx nop nop sub $42930, %rcx mov $0x6162636465666768, %r10 movq %r10, (%rbx) nop nop nop nop xor %r11, %r11 lea addresses_A_ht+0x7c42, %rcx xor $18536, %rbx movl $0x61626364, (%rcx) nop nop and %rcx, %rcx lea addresses_D_ht+0x59e4, %rsi lea addresses_D_ht+0x130f8, %rdi nop nop nop nop dec %r9 mov $108, %rcx rep movsl nop cmp $2652, %rbx lea addresses_WT_ht+0x15408, %r9 nop nop nop nop nop lfence movb (%r9), %r11b add %r10, %r10 lea addresses_WT_ht+0x10b20, %rsi lea addresses_WC_ht+0x1a8a0, %rdi nop cmp $43164, %r9 mov $101, %rcx rep movsb nop nop inc %r9 lea addresses_D_ht+0xaa80, %r10 clflush (%r10) nop nop nop cmp $19476, %rbx movl $0x61626364, (%r10) nop nop nop nop inc %rdi lea addresses_A_ht+0x124a0, %rbx nop nop nop nop nop sub $52529, %rsi mov (%rbx), %r10w nop nop nop nop add %rbx, %rbx lea addresses_WT_ht+0x1a1a0, %rdi nop cmp %rsi, %rsi movw $0x6162, (%rdi) nop nop cmp $37119, %rdi pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r14 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r9 push %rax push %rbp push %rbx push %rdi // Store mov $0x2a0, %rbx nop nop xor $59005, %r10 mov $0x5152535455565758, %rdi movq %rdi, %xmm5 movaps %xmm5, (%rbx) nop sub $51694, %rbx // Store lea addresses_UC+0x64a0, %r9 nop nop nop nop cmp $14020, %r11 mov $0x5152535455565758, %r10 movq %r10, %xmm5 movups %xmm5, (%r9) nop nop nop nop nop dec %r9 // Store lea addresses_normal+0x1dca0, %r9 xor $47434, %rax mov $0x5152535455565758, %rbp movq %rbp, %xmm0 vmovups %ymm0, (%r9) nop add $14214, %rdi // Store lea addresses_normal+0x78e0, %r9 nop nop add $42465, %rbx movw $0x5152, (%r9) nop nop sub %r11, %r11 // Store lea addresses_D+0x67a0, %r11 nop sub $62617, %r10 mov $0x5152535455565758, %rbp movq %rbp, %xmm7 vmovups %ymm7, (%r11) nop nop nop nop add $39246, %rax // Store lea addresses_D+0xcd20, %r10 nop inc %r9 mov $0x5152535455565758, %rdi movq %rdi, %xmm0 movups %xmm0, (%r10) nop nop nop nop cmp $35419, %r11 // Store lea addresses_PSE+0x15ca0, %rdi clflush (%rdi) nop nop cmp %rax, %rax movl $0x51525354, (%rdi) nop sub %rax, %rax // Store lea addresses_UC+0xe6a0, %r9 nop nop nop nop dec %rbp movb $0x51, (%r9) nop nop nop nop cmp $3808, %r11 // Load lea addresses_A+0x184a0, %rdi nop nop sub %r11, %r11 mov (%rdi), %rbp nop nop nop nop nop add %rax, %rax // Load lea addresses_PSE+0x162a0, %rax nop nop nop sub %r11, %r11 mov (%rax), %rbp nop nop nop nop and %r10, %r10 // Faulty Load lea addresses_UC+0x64a0, %r10 nop nop nop add %r9, %r9 mov (%r10), %bx lea oracles, %rax and $0xff, %rbx shlq $12, %rbx mov (%rax,%rbx,1), %rbx pop %rdi pop %rbx pop %rbp pop %rax pop %r9 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_UC'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 8, 'AVXalign': True, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_P'}} {'OP': 'STOR', 'dst': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 16, 'NT': False, 'type': 'addresses_UC'}} {'OP': 'STOR', 'dst': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_normal'}} {'OP': 'STOR', 'dst': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_normal'}} {'OP': 'STOR', 'dst': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_D'}} {'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_D'}} {'OP': 'STOR', 'dst': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_PSE'}} {'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_UC'}} {'src': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_A'}, 'OP': 'LOAD'} {'src': {'congruent': 8, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_PSE'}, 'OP': 'LOAD'} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 2, 'NT': False, 'type': 'addresses_UC'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 9, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_D_ht'}} {'src': {'congruent': 8, 'AVXalign': True, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 10, 'AVXalign': True, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_normal_ht'}} {'OP': 'STOR', 'dst': {'congruent': 5, 'AVXalign': False, 'same': False, 'size': 8, 'NT': False, 'type': 'addresses_UC_ht'}} {'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': False, 'same': False, 'size': 4, 'NT': True, 'type': 'addresses_A_ht'}} {'src': {'congruent': 1, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 1, 'same': False, 'type': 'addresses_D_ht'}} {'src': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 6, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 10, 'same': False, 'type': 'addresses_WC_ht'}} {'OP': 'STOR', 'dst': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 4, 'NT': True, 'type': 'addresses_D_ht'}} {'src': {'congruent': 11, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 8, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WT_ht'}} {'58': 15482} 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 */
// Example usages of conio for Atari XL target. // Atari XL/XE executable XEX file with a single segment // https://www.atarimax.com/jindroush.atari.org/afmtexe.html .plugin "dk.camelot64.kickass.xexplugin.AtariXex" .file [name="atarixl-conio.xex", type="bin", segments="XexFile"] .segmentdef XexFile [segments="Program", modify="XexFormat", _RunAddr=__start] .segmentdef Program [segments="Code, Data"] .segmentdef Code [start=$2000] .segmentdef Data [startAfter="Code"] .const DARK_ORANGE = $30 .const MEDIUM_BLUE = $80 .const WHITE = $fe .const OFFSET_STRUCT_PRINTF_BUFFER_NUMBER_DIGITS = 1 .const STACK_BASE = $103 .const SIZEOF_STRUCT_PRINTF_BUFFER_NUMBER = $c /// 2-byte saved memory scan counter .label SAVMSC = $58 /// data under cursor .label OLDCHR = $5d /// 2-byte saved cursor memory address .label OLDADR = $5e /// Shadow for 53271 ($D017). Text color in Gr.0 .label COLOR1 = $2c5 /// Shadow for 53272 ($D018). Background color in GR.0 .label COLOR2 = $2c6 /// Shadow for 53274 ($D01A). Border color in GR.0 .label COLOR4 = $2c8 /// Cursor inhibit flag, 0 turns on, any other number turns off. Cursor doesn't change until it moves next. .label CRSINH = $2f0 /// Internal hardware value for the last key pressed. Set to 0xFF to clear. .label CH = $2fc /// Atari ZP registers /// 1-byte cursor row .label ROWCRS = $54 /// 2-byte cursor column .label COLCRS = $55 // The screen width // The screen height // The current reverse value indicator. Values 0 or 0x80 for reverse text .label conio_reverse_value = $91 // The current cursor enable flag. 1 = on, 0 = off. .label conio_display_cursor = $8f // The current scroll enable flag. 1 = on, 0 = off. .label conio_scroll_enable = $92 .segment Code __start: { // __ma char conio_reverse_value = 0 lda #0 sta.z conio_reverse_value // __ma char conio_display_cursor = 1 lda #1 sta.z conio_display_cursor // __ma char conio_scroll_enable = 1 sta.z conio_scroll_enable jsr main rts } // Output one character at the current cursor position // Moves the cursor forward. Scrolls the entire screen if needed // void cputc(__zp($90) volatile char c) cputc: { .const OFFSET_STACK_C = 0 .label convertToScreenCode1_v = c .label c = $90 tsx lda STACK_BASE+OFFSET_STACK_C,x sta.z c // if (c == '\r') .encoding "ascii" lda #'\r' cmp.z c beq __b1 // if(c == '\n' || c == 0x9b) lda #'\$9b' cmp.z c beq __b2 lda #$9b cmp.z c beq __b2 // return rawmap[*v]; ldy.z convertToScreenCode1_v ldx rawmap,y // putchar(convertToScreenCode(&c)) jsr putchar // (*COLCRS)++; inc.z COLCRS bne !+ inc.z COLCRS+1 !: // if (*COLCRS == CONIO_WIDTH) lda.z COLCRS+1 bne !+ lda.z COLCRS cmp #$28 beq __b5 !: // setcursor() jsr setcursor // } rts __b5: // *COLCRS = 0 lda #<0 sta.z COLCRS sta.z COLCRS+1 // newline() jsr newline rts __b2: // *COLCRS = 0 // 0x0a LF, or atascii EOL lda #<0 sta.z COLCRS sta.z COLCRS+1 // newline() jsr newline rts __b1: // *COLCRS = 0 // 0x0d, CR = just set the cursor x value to 0 lda #<0 sta.z COLCRS sta.z COLCRS+1 // setcursor() jsr setcursor rts } main: { .label i = $93 .label i1 = $95 // cursor(0) // hide the cursor jsr cursor // bgcolor(DARK_ORANGE) // change colors jsr bgcolor // bordercolor(MEDIUM_BLUE) jsr bordercolor // textcolor(WHITE) jsr textcolor // cputsxy(0, 1, "Hello, World!\n") // print some text at a location jsr cputsxy // gotoxy(0, 3) // skip a line ldx #3 lda #0 jsr gotoxy // revers(1) // set inverse text and use printf to output a string lda #1 jsr revers // printf("Hello, %s - press a key!\n", name) lda #<cputc sta.z printf_str.putc lda #>cputc sta.z printf_str.putc+1 lda #<s1 sta.z printf_str.s lda #>s1 sta.z printf_str.s+1 jsr printf_str // printf("Hello, %s - press a key!\n", name) jsr printf_string // printf("Hello, %s - press a key!\n", name) lda #<cputc sta.z printf_str.putc lda #>cputc sta.z printf_str.putc+1 lda #<s2 sta.z printf_str.s lda #>s2 sta.z printf_str.s+1 jsr printf_str // waitkey() // wait for user keypress jsr waitkey // clrscr() // clear screen jsr clrscr // revers(0) // reset reverse and do some scrolling lines. lda #0 jsr revers lda #<0 sta.z i sta.z i+1 __b1: // printf("Scrolling lines ... %d\n", i) lda #<cputc sta.z printf_str.putc lda #>cputc sta.z printf_str.putc+1 lda #<s3 sta.z printf_str.s lda #>s3 sta.z printf_str.s+1 jsr printf_str // printf("Scrolling lines ... %d\n", i) lda.z i sta.z printf_sint.value lda.z i+1 sta.z printf_sint.value+1 jsr printf_sint // printf("Scrolling lines ... %d\n", i) lda #<cputc sta.z printf_str.putc lda #>cputc sta.z printf_str.putc+1 lda #<s4 sta.z printf_str.s lda #>s4 sta.z printf_str.s+1 jsr printf_str // for(int i: 0..50) inc.z i bne !+ inc.z i+1 !: lda.z i+1 cmp #>$33 bne __b1 lda.z i cmp #<$33 bne __b1 // waitkey() jsr waitkey // scroll(0) // turn scroll off and do more lines jsr scroll lda #<$33 sta.z i1 lda #>$33 sta.z i1+1 __b3: // printf("Some wrapping lines ... %d\n", i) lda #<cputc sta.z printf_str.putc lda #>cputc sta.z printf_str.putc+1 lda #<s5 sta.z printf_str.s lda #>s5 sta.z printf_str.s+1 jsr printf_str // printf("Some wrapping lines ... %d\n", i) lda.z i1 sta.z printf_sint.value lda.z i1+1 sta.z printf_sint.value+1 jsr printf_sint // printf("Some wrapping lines ... %d\n", i) lda #<cputc sta.z printf_str.putc lda #>cputc sta.z printf_str.putc+1 lda #<s4 sta.z printf_str.s lda #>s4 sta.z printf_str.s+1 jsr printf_str // for(int i: 51..200) inc.z i1 bne !+ inc.z i1+1 !: lda.z i1+1 cmp #>$c9 bne __b3 lda.z i1 cmp #<$c9 bne __b3 // waitkey() jsr waitkey // } rts .segment Data name: .text "Mark" .byte 0 s: .text @"Hello, World!\$9b" .byte 0 s1: .text "Hello, " .byte 0 s2: .text @" - press a key!\$9b" .byte 0 s3: .text "Scrolling lines ... " .byte 0 s4: .text @"\$9b" .byte 0 s5: .text "Some wrapping lines ... " .byte 0 } .segment Code // Puts a character to the screen a the current location. Uses internal screencode. Deals with storing the old cursor value // void putchar(char code) putchar: { .label loc = $82 // **OLDADR = *OLDCHR lda.z OLDCHR ldy.z OLDADR sty.z $fe ldy.z OLDADR+1 sty.z $ff ldy #0 sta ($fe),y // char * loc = cursorLocation() jsr cursorLocation // char newChar = code | conio_reverse_value txa ora.z conio_reverse_value // *loc = newChar ldy #0 sta (loc),y // *OLDCHR = newChar sta.z OLDCHR // setcursor() jsr setcursor // } rts } // Handles cursor movement, displaying it if required, and inverting character it is over if there is one (and enabled) setcursor: { .label loc = $82 // **OLDADR = *OLDCHR // save the current oldchr into oldadr lda.z OLDCHR ldy.z OLDADR sty.z $fe ldy.z OLDADR+1 sty.z $ff ldy #0 sta ($fe),y // char * loc = cursorLocation() // work out the new location for oldadr based on new column/row jsr cursorLocation // char c = *loc ldy #0 lda (loc),y tax // *OLDCHR = c stx.z OLDCHR // *OLDADR = loc lda.z loc sta.z OLDADR lda.z loc+1 sta.z OLDADR+1 // if (conio_display_cursor == 0) lda.z conio_display_cursor beq __b1 // *CRSINH = 0 // cursor is on, so invert the inverse bit and turn cursor on tya sta CRSINH // c = c ^ 0x80 txa eor #$80 tax __b2: // **OLDADR = c txa ldy.z OLDADR sty.z $fe ldy.z OLDADR+1 sty.z $ff ldy #0 sta ($fe),y // } rts __b1: // *CRSINH = 1 // cursor is off, don't affect the character at all, but do turn off cursor lda #1 sta CRSINH jmp __b2 } newline: { .label start = $84 // if ((*ROWCRS)++ == CONIO_HEIGHT) inc.z ROWCRS lda #$18 cmp.z ROWCRS bne __b1 // if (conio_scroll_enable == 1) lda #1 cmp.z conio_scroll_enable beq __b4 // gotoxy(0, 0) ldx #0 txa jsr gotoxy __b1: // setcursor() jsr setcursor // } rts __b4: // if (conio_display_cursor == 1) lda #1 cmp.z conio_display_cursor bne __b5 // **OLDADR ^= 0x80 ldy.z OLDADR sty.z $fe ldy.z OLDADR+1 sty.z $ff ldy #0 lda ($fe),y eor #$80 sta ($fe),y __b5: // char * start = *SAVMSC // move screen up 1 line lda.z SAVMSC sta.z start lda.z SAVMSC+1 sta.z start+1 // start + CONIO_WIDTH lda #$28 clc adc.z start sta.z memcpy.source lda #0 adc.z start+1 sta.z memcpy.source+1 // memcpy(start, start + CONIO_WIDTH, CONIO_WIDTH * 23) lda.z start sta.z memcpy.destination lda.z start+1 sta.z memcpy.destination+1 jsr memcpy // start + CONIO_WIDTH * 23 lda.z memset.str clc adc #<$28*$17 sta.z memset.str lda.z memset.str+1 adc #>$28*$17 sta.z memset.str+1 // memset(start + CONIO_WIDTH * 23, 0x00, CONIO_WIDTH) lda #<$28 sta.z memset.num lda #>$28 sta.z memset.num+1 jsr memset // *ROWCRS = CONIO_HEIGHT - 1 lda #$18-1 sta.z ROWCRS jmp __b1 } // If onoff is 1, a cursor is displayed when any text is output. // If onoff is 0, the cursor is hidden instead. // char cursor(char onoff) cursor: { .const onoff = 0 // conio_display_cursor = onoff lda #onoff sta.z conio_display_cursor // } rts } // Set the color for the background. The old color setting is returned. // char bgcolor(char color) bgcolor: { // *COLOR2 = color lda #DARK_ORANGE sta COLOR2 // } rts } // Set the color for the border. The old color setting is returned. // char bordercolor(char color) bordercolor: { // *COLOR4 = color lda #MEDIUM_BLUE sta COLOR4 // } rts } // Set the color for the text. The old color setting is returned. // char textcolor(char color) textcolor: { // *COLOR1 = color lda #WHITE sta COLOR1 // } rts } // Move cursor and output a NUL-terminated string // Same as "gotoxy (x, y); puts (s);" // void cputsxy(char x, char y, const char *s) cputsxy: { .const x = 0 .const y = 1 // gotoxy(x, y) ldx #y lda #x jsr gotoxy // cputs(s) jsr cputs // } rts } // Set the cursor to the specified position // void gotoxy(__register(A) char x, __register(X) char y) gotoxy: { // *COLCRS = x sta.z COLCRS lda #0 sta.z COLCRS+1 // *ROWCRS = y stx.z ROWCRS // setcursor() jsr setcursor // } rts } // Sets reverse mode for text. 1 enables reverse, 0 disables. Returns the old value. // char revers(__register(A) char onoff) revers: { // if (onoff == 0) cmp #0 beq __b1 // conio_reverse_value = 0x80 lda #$80 sta.z conio_reverse_value // } rts __b1: // conio_reverse_value = 0 lda #0 sta.z conio_reverse_value rts } /// Print a NUL-terminated string // void printf_str(__zp($80) void (*putc)(char), __zp($8c) const char *s) printf_str: { .label s = $8c .label putc = $80 __b1: // while(c=*s++) ldy #0 lda (s),y inc.z s bne !+ inc.z s+1 !: cmp #0 bne __b2 // } rts __b2: // putc(c) pha jsr icall1 pla jmp __b1 icall1: jmp (putc) } // Print a string value using a specific format // Handles justification and min length // void printf_string(void (*putc)(char), char *str, char format_min_length, char format_justify_left) printf_string: { .label putc = cputc // printf_str(putc, str) lda #<putc sta.z printf_str.putc lda #>putc sta.z printf_str.putc+1 lda #<main.name sta.z printf_str.s lda #>main.name sta.z printf_str.s+1 jsr printf_str // } rts } waitkey: { __b1: // kbhit() jsr kbhit // while(!kbhit()) cmp #0 beq __b1 // *CH = 0xff lda #$ff sta CH // } rts } // clears the screen and moves the cursor to the upper left-hand corner of the screen. clrscr: { lda.z SAVMSC sta.z memset.str lda.z SAVMSC+1 sta.z memset.str+1 // memset(*SAVMSC, 0x00, CONIO_WIDTH * CONIO_HEIGHT) // Fill entire screen with spaces lda #<$28*$18 sta.z memset.num lda #>$28*$18 sta.z memset.num+1 jsr memset // *OLDCHR = 0x00 // 0x00 is screencode for space character // set the old character to a space so the cursor doesn't reappear at the last position it was at lda #0 sta.z OLDCHR // gotoxy(0,0) tax txa jsr gotoxy // } rts } // Print a signed integer using a specific format // void printf_sint(void (*putc)(char), __zp($80) int value, char format_min_length, char format_justify_left, char format_sign_always, char format_zero_padding, char format_upper_case, char format_radix) printf_sint: { .label value = $80 // printf_buffer.sign = 0 // Handle any sign lda #0 sta printf_buffer // if(value<0) lda.z value+1 bmi __b1 jmp __b2 __b1: // value = -value lda #0 sec sbc.z value sta.z value lda #0 sbc.z value+1 sta.z value+1 // printf_buffer.sign = '-' lda #'-' sta printf_buffer __b2: // utoa(uvalue, printf_buffer.digits, format.radix) jsr utoa // printf_number_buffer(putc, printf_buffer, format) lda printf_buffer // Print using format jsr printf_number_buffer // } rts } // If onoff is 1, scrolling is enabled when outputting past the end of the screen // If onoff is 0, scrolling is disabled and the cursor instead moves to (0,0) // The function returns the old scroll setting. // char scroll(char onoff) scroll: { .const onoff = 0 // conio_scroll_enable = onoff lda #onoff sta.z conio_scroll_enable // } rts } // Return a pointer to the location of the cursor cursorLocation: { .label __0 = $82 .label __1 = $82 .label __3 = $82 .label return = $82 .label __4 = $8a .label __5 = $82 // (word)(*ROWCRS)*CONIO_WIDTH lda.z ROWCRS sta.z __3 lda #0 sta.z __3+1 lda.z __3 asl sta.z __4 lda.z __3+1 rol sta.z __4+1 asl.z __4 rol.z __4+1 clc lda.z __5 adc.z __4 sta.z __5 lda.z __5+1 adc.z __4+1 sta.z __5+1 asl.z __0 rol.z __0+1 asl.z __0 rol.z __0+1 asl.z __0 rol.z __0+1 // *SAVMSC + (word)(*ROWCRS)*CONIO_WIDTH clc lda.z __1 adc.z SAVMSC sta.z __1 lda.z __1+1 adc.z SAVMSC+1 sta.z __1+1 // *SAVMSC + (word)(*ROWCRS)*CONIO_WIDTH + *COLCRS clc lda.z return adc.z COLCRS sta.z return lda.z return+1 adc.z COLCRS+1 sta.z return+1 // } rts } // Copy block of memory (forwards) // Copies the values of num bytes from the location pointed to by source directly to the memory block pointed to by destination. // void * memcpy(__zp($82) void *destination, __zp($88) char *source, unsigned int num) memcpy: { .const num = $28*$17 .label src_end = $8a .label dst = $82 .label src = $88 .label destination = $82 .label source = $88 // char* src_end = (char*)source+num lda.z source clc adc #<num sta.z src_end lda.z source+1 adc #>num sta.z src_end+1 __b1: // while(src!=src_end) lda.z src+1 cmp.z src_end+1 bne __b2 lda.z src cmp.z src_end bne __b2 // } rts __b2: // *dst++ = *src++ ldy #0 lda (src),y sta (dst),y // *dst++ = *src++; inc.z dst bne !+ inc.z dst+1 !: inc.z src bne !+ inc.z src+1 !: jmp __b1 } // Copies the character c (an unsigned char) to the first num characters of the object pointed to by the argument str. // void * memset(__zp($84) char *str, char c, __zp($88) unsigned int num) memset: { .label end = $88 .label dst = $84 .label str = $84 .label num = $88 // if(num>0) lda.z num bne !+ lda.z num+1 beq __breturn !: // char* end = (char*)str + num clc lda.z end adc.z str sta.z end lda.z end+1 adc.z str+1 sta.z end+1 __b2: // for(char* dst = str; dst!=end; dst++) lda.z dst+1 cmp.z end+1 bne __b3 lda.z dst cmp.z end bne __b3 __breturn: // } rts __b3: // *dst = c lda #0 tay sta (dst),y // for(char* dst = str; dst!=end; dst++) inc.z dst bne !+ inc.z dst+1 !: jmp __b2 } // Output a NUL-terminated string at the current cursor position // void cputs(__zp($8c) const char *s) cputs: { .label s = $8c lda #<main.s sta.z s lda #>main.s sta.z s+1 __b1: // while (c = *s++) ldy #0 lda (s),y inc.z s bne !+ inc.z s+1 !: cmp #0 bne __b2 // } rts __b2: // cputc(c) pha jsr cputc pla jmp __b1 } // Return 1 if there's a key waiting, return 0 if not kbhit: { // if (*CH == 0xff) lda #$ff cmp CH beq __b1 lda #1 rts __b1: lda #0 // } rts } // Converts unsigned number value to a string representing it in RADIX format. // If the leading digits are zero they are not included in the string. // - value : The number to be converted to RADIX // - buffer : receives the string representing the number and zero-termination. // - radix : The radix to convert the number to (from the enum RADIX) // void utoa(__zp($80) unsigned int value, __zp($8c) char *buffer, char radix) utoa: { .label digit_value = $86 .label buffer = $8c .label digit = $8e .label value = $80 lda #<printf_buffer+OFFSET_STRUCT_PRINTF_BUFFER_NUMBER_DIGITS sta.z buffer lda #>printf_buffer+OFFSET_STRUCT_PRINTF_BUFFER_NUMBER_DIGITS sta.z buffer+1 ldx #0 txa sta.z digit __b1: // for( char digit=0; digit<max_digits-1; digit++ ) lda.z digit cmp #5-1 bcc __b2 // *buffer++ = DIGITS[(char)value] ldx.z value lda DIGITS,x ldy #0 sta (buffer),y // *buffer++ = DIGITS[(char)value]; inc.z buffer bne !+ inc.z buffer+1 !: // *buffer = 0 lda #0 tay sta (buffer),y // } rts __b2: // unsigned int digit_value = digit_values[digit] lda.z digit asl tay lda RADIX_DECIMAL_VALUES,y sta.z digit_value lda RADIX_DECIMAL_VALUES+1,y sta.z digit_value+1 // if (started || value >= digit_value) cpx #0 bne __b5 cmp.z value+1 bne !+ lda.z digit_value cmp.z value beq __b5 !: bcc __b5 __b4: // for( char digit=0; digit<max_digits-1; digit++ ) inc.z digit jmp __b1 __b5: // utoa_append(buffer++, value, digit_value) jsr utoa_append // utoa_append(buffer++, value, digit_value) // value = utoa_append(buffer++, value, digit_value) // value = utoa_append(buffer++, value, digit_value); inc.z buffer bne !+ inc.z buffer+1 !: ldx #1 jmp __b4 } // Print the contents of the number buffer using a specific format. // This handles minimum length, zero-filling, and left/right justification from the format // void printf_number_buffer(void (*putc)(char), __register(A) char buffer_sign, char *buffer_digits, char format_min_length, char format_justify_left, char format_sign_always, char format_zero_padding, char format_upper_case, char format_radix) printf_number_buffer: { .label buffer_digits = printf_buffer+OFFSET_STRUCT_PRINTF_BUFFER_NUMBER_DIGITS .label putc = cputc // if(buffer.sign) cmp #0 beq __b2 // putc(buffer.sign) pha jsr cputc pla __b2: // printf_str(putc, buffer.digits) lda #<putc sta.z printf_str.putc lda #>putc sta.z printf_str.putc+1 lda #<buffer_digits sta.z printf_str.s lda #>buffer_digits sta.z printf_str.s+1 jsr printf_str // } rts } // Used to convert a single digit of an unsigned number value to a string representation // Counts a single digit up from '0' as long as the value is larger than sub. // Each time the digit is increased sub is subtracted from value. // - buffer : pointer to the char that receives the digit // - value : The value where the digit will be derived from // - sub : the value of a '1' in the digit. Subtracted continually while the digit is increased. // (For decimal the subs used are 10000, 1000, 100, 10, 1) // returns : the value reduced by sub * digit so that it is less than sub. // __zp($80) unsigned int utoa_append(__zp($8c) char *buffer, __zp($80) unsigned int value, __zp($86) unsigned int sub) utoa_append: { .label buffer = $8c .label value = $80 .label sub = $86 .label return = $80 ldx #0 __b1: // while (value >= sub) lda.z sub+1 cmp.z value+1 bne !+ lda.z sub cmp.z value beq __b2 !: bcc __b2 // *buffer = DIGITS[digit] lda DIGITS,x ldy #0 sta (buffer),y // } rts __b2: // digit++; inx // value -= sub lda.z value sec sbc.z sub sta.z value lda.z value+1 sbc.z sub+1 sta.z value+1 jmp __b1 } .segment Data // The digits used for numbers DIGITS: .text "0123456789abcdef" // Values of decimal digits RADIX_DECIMAL_VALUES: .word $2710, $3e8, $64, $a // create a static table to map char value to screen value // use KickAsm functions to create a table of code -> screen code values, using cc65 algorithm rawmap: .var ht = Hashtable().put(0,64, 1,0, 2,32, 3,96) // the table for converting bit 6,7 into ora value .for(var i=0; i<256; i++) { .var idx = (i & $60) / 32 .var mask = i & $9f .byte mask | ht.get(idx) } // Buffer used for stringified number being printed printf_buffer: .fill SIZEOF_STRUCT_PRINTF_BUFFER_NUMBER, 0
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 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 <net_processing.h> #include <addrman.h> #include <arith_uint256.h> #include <blockencodings.h> #include <chainparams.h> #include <consensus/validation.h> #include <hash.h> #include <init.h> #include <merkleblock.h> #include <netmessagemaker.h> #include <netbase.h> #include <policy/fees.h> #include <policy/policy.h> #include <primitives/block.h> #include <primitives/transaction.h> #include <random.h> #include <reverse_iterator.h> #include <scheduler.h> #include <tinyformat.h> #include <txdb.h> #include <txmempool.h> #include <ui_interface.h> #include <util.h> #include <utilmoneystr.h> #include <utilstrencodings.h> #include <memory> #include <spork.h> #include <governance/governance.h> #include <masternode/masternode-payments.h> #include <masternode/masternode-sync.h> #include <masternode/masternode-meta.h> #ifdef ENABLE_WALLET #include <coinjoin/coinjoin-client.h> #endif // ENABLE_WALLET #include <coinjoin/coinjoin-server.h> #include <evo/deterministicmns.h> #include <evo/mnauth.h> #include <evo/simplifiedmns.h> #include <llmq/quorums_blockprocessor.h> #include <llmq/quorums_commitment.h> #include <llmq/quorums_chainlocks.h> #include <llmq/quorums_dkgsessionmgr.h> #include <llmq/quorums_instantsend.h> #include <llmq/quorums_signing.h> #include <llmq/quorums_signing_shares.h> #include <statsd_client.h> #if defined(NDEBUG) # error "LuckyCoinORO Core cannot be compiled without assertions." #endif /** Maximum number of in-flight objects from a peer */ static constexpr int32_t MAX_PEER_OBJECT_IN_FLIGHT = 100; /** Maximum number of announced objects from a peer */ static constexpr int32_t MAX_PEER_OBJECT_ANNOUNCEMENTS = 2 * MAX_INV_SZ; /** How many microseconds to delay requesting transactions from inbound peers */ static constexpr std::chrono::microseconds INBOUND_PEER_TX_DELAY{std::chrono::seconds{2}}; /** How long to wait (in microseconds) before downloading a transaction from an additional peer */ static constexpr std::chrono::microseconds GETDATA_TX_INTERVAL{std::chrono::seconds{60}}; /** Maximum delay (in microseconds) for transaction requests to avoid biasing some peers over others. */ static constexpr std::chrono::microseconds MAX_GETDATA_RANDOM_DELAY{std::chrono::seconds{2}}; /** How long to wait (expiry * factor microseconds) before expiring an in-flight getdata request to a peer */ static constexpr int64_t TX_EXPIRY_INTERVAL_FACTOR = 10; static_assert(INBOUND_PEER_TX_DELAY >= MAX_GETDATA_RANDOM_DELAY, "To preserve security, MAX_GETDATA_RANDOM_DELAY should not exceed INBOUND_PEER_DELAY"); /** Limit to avoid sending big packets. Not used in processing incoming GETDATA for compatibility */ static const unsigned int MAX_GETDATA_SZ = 1000; /** Expiration time for orphan transactions in seconds */ static constexpr int64_t ORPHAN_TX_EXPIRE_TIME = 20 * 60; /** Minimum time between orphan transactions expire time checks in seconds */ static constexpr int64_t ORPHAN_TX_EXPIRE_INTERVAL = 5 * 60; /** Headers download timeout expressed in microseconds * Timeout = base + per_header * (expected number of headers) */ static constexpr int64_t HEADERS_DOWNLOAD_TIMEOUT_BASE = 15 * 60 * 1000000; // 15 minutes static constexpr int64_t HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER = 1000; // 1ms/header /** Protect at least this many outbound peers from disconnection due to slow/ * behind headers chain. */ static constexpr int32_t MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT = 4; /** Timeout for (unprotected) outbound peers to sync to our chainwork, in seconds */ static constexpr int64_t CHAIN_SYNC_TIMEOUT = 20 * 60; // 20 minutes /** How frequently to check for stale tips, in seconds */ static constexpr int64_t STALE_CHECK_INTERVAL = 2.5 * 60; // 2.5 minutes (~block interval) /** How frequently to check for extra outbound peers and disconnect, in seconds */ static constexpr int64_t EXTRA_PEER_CHECK_INTERVAL = 45; /** Minimum time an outbound-peer-eviction candidate must be connected for, in order to evict, in seconds */ static constexpr int64_t MINIMUM_CONNECT_TIME = 30; /** SHA256("main address relay")[0:8] */ static constexpr uint64_t RANDOMIZER_ID_ADDRESS_RELAY = 0x3cac0035b5866b90ULL; /// Age after which a stale block will no longer be served if requested as /// protection against fingerprinting. Set to one month, denominated in seconds. static constexpr int STALE_RELAY_AGE_LIMIT = 30 * 24 * 60 * 60; /// Age after which a block is considered historical for purposes of rate /// limiting block relay. Set to one week, denominated in seconds. static constexpr int HISTORICAL_BLOCK_AGE = 7 * 24 * 60 * 60; struct COrphanTx { // When modifying, adapt the copy of this definition in tests/DoS_tests. CTransactionRef tx; NodeId fromPeer; int64_t nTimeExpire; size_t nTxSize; }; static CCriticalSection g_cs_orphans; std::map<uint256, COrphanTx> mapOrphanTransactions GUARDED_BY(g_cs_orphans); size_t nMapOrphanTransactionsSize = 0; void EraseOrphansFor(NodeId peer); /** Average delay between local address broadcasts in seconds. */ static constexpr unsigned int AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL = 24 * 60 * 60; /** Average delay between peer address broadcasts in seconds. */ static const unsigned int AVG_ADDRESS_BROADCAST_INTERVAL = 30; /** Average delay between trickled inventory transmissions in seconds. * Blocks and whitelisted receivers bypass this, regular outbound peers get half this delay, * Masternode outbound peers get quarter this delay. */ static const unsigned int INVENTORY_BROADCAST_INTERVAL = 5; /** Maximum number of inventory items to send per transmission. * Limits the impact of low-fee transaction floods. * We have 4 times smaller block times in LuckyCoinORO, so we need to push 4 times more invs per 1MB. */ static constexpr unsigned int INVENTORY_BROADCAST_MAX_PER_1MB_BLOCK = 4 * 7 * INVENTORY_BROADCAST_INTERVAL; // Internal stuff namespace { /** Number of nodes with fSyncStarted. */ int nSyncStarted GUARDED_BY(cs_main) = 0; /** * Sources of received blocks, saved to be able to send them reject * messages or ban them when processing happens afterwards. * Set mapBlockSource[hash].second to false if the node should not be * punished if the block is invalid. */ std::map<uint256, std::pair<NodeId, bool>> mapBlockSource GUARDED_BY(cs_main); /** * Filter for transactions that were recently rejected by * AcceptToMemoryPool. These are not rerequested until the chain tip * changes, at which point the entire filter is reset. * * Without this filter we'd be re-requesting txs from each of our peers, * increasing bandwidth consumption considerably. For instance, with 100 * peers, half of which relay a tx we don't accept, that might be a 50x * bandwidth increase. A flooding attacker attempting to roll-over the * filter using minimum-sized, 60byte, transactions might manage to send * 1000/sec if we have fast peers, so we pick 120,000 to give our peers a * two minute window to send invs to us. * * Decreasing the false positive rate is fairly cheap, so we pick one in a * million to make it highly unlikely for users to have issues with this * filter. * * Memory used: 1.3MB */ std::unique_ptr<CRollingBloomFilter> recentRejects GUARDED_BY(cs_main); uint256 hashRecentRejectsChainTip GUARDED_BY(cs_main); /** Blocks that are in flight, and that are in the queue to be downloaded. */ struct QueuedBlock { uint256 hash; const CBlockIndex* pindex; //!< Optional. bool fValidatedHeaders; //!< Whether this block has validated headers at the time of request. std::unique_ptr<PartiallyDownloadedBlock> partialBlock; //!< Optional, used for CMPCTBLOCK downloads }; std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> > mapBlocksInFlight GUARDED_BY(cs_main); /** Stack of nodes which we have set to announce using compact blocks */ std::list<NodeId> lNodesAnnouncingHeaderAndIDs GUARDED_BY(cs_main); /** Number of preferable block download peers. */ int nPreferredDownload GUARDED_BY(cs_main) = 0; /** Number of peers from which we're downloading blocks. */ int nPeersWithValidatedDownloads GUARDED_BY(cs_main) = 0; /** Number of outbound peers with m_chain_sync.m_protect. */ int g_outbound_peers_with_protect_from_disconnect GUARDED_BY(cs_main) = 0; /** When our tip was last updated. */ std::atomic<int64_t> g_last_tip_update(0); /** Relay map */ typedef std::map<uint256, CTransactionRef> MapRelay; MapRelay mapRelay GUARDED_BY(cs_main); /** Expiration-time ordered list of (expire time, relay map entry) pairs. */ std::deque<std::pair<int64_t, MapRelay::iterator>> vRelayExpiration GUARDED_BY(cs_main); std::atomic<int64_t> nTimeBestReceived(0); // Used only to inform the wallet of when we last received a block struct IteratorComparator { template<typename I> bool operator()(const I& a, const I& b) const { return &(*a) < &(*b); } }; std::map<COutPoint, std::set<std::map<uint256, COrphanTx>::iterator, IteratorComparator>> mapOrphanTransactionsByPrev GUARDED_BY(g_cs_orphans); static size_t vExtraTxnForCompactIt GUARDED_BY(g_cs_orphans) = 0; static std::vector<std::pair<uint256, CTransactionRef>> vExtraTxnForCompact GUARDED_BY(g_cs_orphans); } // namespace namespace { struct CBlockReject { unsigned char chRejectCode; std::string strRejectReason; uint256 hashBlock; }; /** * Maintain validation-specific state about nodes, protected by cs_main, instead * by CNode's own locks. This simplifies asynchronous operation, where * processing of incoming data is done after the ProcessMessage call returns, * and we're no longer holding the node's locks. */ struct CNodeState { //! The peer's address const CService address; //! Whether we have a fully established connection. bool fCurrentlyConnected; //! Accumulated misbehaviour score for this peer. int nMisbehavior; //! Whether this peer should be disconnected and banned (unless whitelisted). bool fShouldBan; //! String name of this peer (debugging/logging purposes). const std::string name; //! List of asynchronously-determined block rejections to notify this peer about. std::vector<CBlockReject> rejects; //! The best known block we know this peer has announced. const CBlockIndex *pindexBestKnownBlock; //! The hash of the last unknown block this peer has announced. uint256 hashLastUnknownBlock; //! The last full block we both have. const CBlockIndex *pindexLastCommonBlock; //! The best header we have sent our peer. const CBlockIndex *pindexBestHeaderSent; //! Length of current-streak of unconnecting headers announcements int nUnconnectingHeaders; //! Whether we've started headers synchronization with this peer. bool fSyncStarted; //! When to potentially disconnect peer for stalling headers download int64_t nHeadersSyncTimeout; //! Since when we're stalling block download progress (in microseconds), or 0. int64_t nStallingSince; std::list<QueuedBlock> vBlocksInFlight; //! When the first entry in vBlocksInFlight started downloading. Don't care when vBlocksInFlight is empty. int64_t nDownloadingSince; int nBlocksInFlight; int nBlocksInFlightValidHeaders; //! Whether we consider this a preferred download peer. bool fPreferredDownload; //! Whether this peer wants invs or headers (when possible) for block announcements. bool fPreferHeaders; //! Whether this peer wants invs or cmpctblocks (when possible) for block announcements. bool fPreferHeaderAndIDs; //! Whether this peer will send us cmpctblocks if we request them bool fProvidesHeaderAndIDs; /** * If we've announced last version to this peer: whether the peer sends last version in cmpctblocks/blocktxns, * otherwise: whether this peer sends non-last version in cmpctblocks/blocktxns. */ bool fSupportsDesiredCmpctVersion; /** State used to enforce CHAIN_SYNC_TIMEOUT * Only in effect for outbound, non-manual connections, with * m_protect == false * Algorithm: if a peer's best known block has less work than our tip, * set a timeout CHAIN_SYNC_TIMEOUT seconds in the future: * - If at timeout their best known block now has more work than our tip * when the timeout was set, then either reset the timeout or clear it * (after comparing against our current tip's work) * - If at timeout their best known block still has less work than our * tip did when the timeout was set, then send a getheaders message, * and set a shorter timeout, HEADERS_RESPONSE_TIME seconds in future. * If their best known block is still behind when that new timeout is * reached, disconnect. */ struct ChainSyncTimeoutState { //! A timeout used for checking whether our peer has sufficiently synced int64_t m_timeout; //! A header with the work we require on our peer's chain const CBlockIndex * m_work_header; //! After timeout is reached, set to true after sending getheaders bool m_sent_getheaders; //! Whether this peer is protected from disconnection due to a bad/slow chain bool m_protect; }; ChainSyncTimeoutState m_chain_sync; //! Time of last new block announcement int64_t m_last_block_announcement; /* * State associated with objects download. * * Tx download algorithm: * * When inv comes in, queue up (process_time, inv) inside the peer's * CNodeState (m_object_process_time) as long as m_object_announced for the peer * isn't too big (MAX_PEER_OBJECT_ANNOUNCEMENTS). * * The process_time for a objects is set to nNow for outbound peers, * nNow + 2 seconds for inbound peers. This is the time at which we'll * consider trying to request the objects from the peer in * SendMessages(). The delay for inbound peers is to allow outbound peers * a chance to announce before we request from inbound peers, to prevent * an adversary from using inbound connections to blind us to a * objects (InvBlock). * * When we call SendMessages() for a given peer, * we will loop over the objects in m_object_process_time, looking * at the objects whose process_time <= nNow. We'll request each * such objects that we don't have already and that hasn't been * requested from another peer recently, up until we hit the * MAX_PEER_OBJECT_IN_FLIGHT limit for the peer. Then we'll update * g_already_asked_for for each requested inv, storing the time of the * GETDATA request. We use g_already_asked_for to coordinate objects * requests amongst our peers. * * For objects that we still need but we have already recently * requested from some other peer, we'll reinsert (process_time, inv) * back into the peer's m_object_process_time at the point in the future at * which the most recent GETDATA request would time out (ie * GetObjectInterval + the request time stored in g_already_asked_for). * We add an additional delay for inbound peers, again to prefer * attempting download from outbound peers first. * We also add an extra small random delay up to 2 seconds * to avoid biasing some peers over others. (e.g., due to fixed ordering * of peer processing in ThreadMessageHandler). * * When we receive a objects from a peer, we remove the inv from the * peer's m_object_in_flight set and from their recently announced set * (m_object_announced). We also clear g_already_asked_for for that entry, so * that if somehow the objects is not accepted but also not added to * the reject filter, then we will eventually redownload from other * peers. */ struct ObjectDownloadState { /* Track when to attempt download of announced objects (process * time in micros -> inv) */ std::multimap<std::chrono::microseconds, CInv> m_object_process_time; //! Store all the objects a peer has recently announced std::set<CInv> m_object_announced; //! Store objects which were requested by us, with timestamp std::map<CInv, std::chrono::microseconds> m_object_in_flight; //! Periodically check for stuck getdata requests std::chrono::microseconds m_check_expiry_timer{0}; }; ObjectDownloadState m_object_download; CNodeState(CAddress addrIn, std::string addrNameIn) : address(addrIn), name(addrNameIn) { fCurrentlyConnected = false; nMisbehavior = 0; fShouldBan = false; pindexBestKnownBlock = nullptr; hashLastUnknownBlock.SetNull(); pindexLastCommonBlock = nullptr; pindexBestHeaderSent = nullptr; nUnconnectingHeaders = 0; fSyncStarted = false; nHeadersSyncTimeout = 0; nStallingSince = 0; nDownloadingSince = 0; nBlocksInFlight = 0; nBlocksInFlightValidHeaders = 0; fPreferredDownload = false; fPreferHeaders = false; fPreferHeaderAndIDs = false; fProvidesHeaderAndIDs = false; fSupportsDesiredCmpctVersion = false; m_chain_sync = { 0, nullptr, false, false }; m_last_block_announcement = 0; } }; // Keeps track of the time (in microseconds) when transactions were requested last time unordered_limitedmap<uint256, std::chrono::microseconds, StaticSaltedHasher> g_already_asked_for(MAX_INV_SZ, MAX_INV_SZ * 2); unordered_limitedmap<uint256, std::chrono::microseconds, StaticSaltedHasher> g_erased_object_requests(MAX_INV_SZ, MAX_INV_SZ * 2); /** Map maintaining per-node state. */ static std::map<NodeId, CNodeState> mapNodeState GUARDED_BY(cs_main); static CNodeState *State(NodeId pnode) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { std::map<NodeId, CNodeState>::iterator it = mapNodeState.find(pnode); if (it == mapNodeState.end()) return nullptr; return &it->second; } void UpdatePreferredDownload(CNode* node, CNodeState* state) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { nPreferredDownload -= state->fPreferredDownload; // Whether this node should be marked as a preferred download node. state->fPreferredDownload = (!node->fInbound || node->fWhitelisted) && !node->fOneShot && !node->fClient; nPreferredDownload += state->fPreferredDownload; } void PushNodeVersion(CNode *pnode, CConnman* connman, int64_t nTime) { const auto& params = Params(); ServiceFlags nLocalNodeServices = pnode->GetLocalServices(); uint64_t nonce = pnode->GetLocalNonce(); int nNodeStartingHeight = pnode->GetMyStartingHeight(); NodeId nodeid = pnode->GetId(); CAddress addr = pnode->addr; CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService(), addr.nServices)); CAddress addrMe = CAddress(CService(), nLocalNodeServices); uint256 mnauthChallenge; GetRandBytes(mnauthChallenge.begin(), mnauthChallenge.size()); { LOCK(pnode->cs_mnauth); pnode->sentMNAuthChallenge = mnauthChallenge; } int nProtocolVersion = PROTOCOL_VERSION; if (params.NetworkIDString() != CBaseChainParams::MAIN && gArgs.IsArgSet("-pushversion")) { nProtocolVersion = gArgs.GetArg("-pushversion", PROTOCOL_VERSION); } connman->PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERSION, nProtocolVersion, (uint64_t)nLocalNodeServices, nTime, addrYou, addrMe, nonce, strSubVersion, nNodeStartingHeight, ::fRelayTxes, mnauthChallenge, pnode->m_masternode_connection)); if (fLogIPs) { LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", nProtocolVersion, nNodeStartingHeight, addrMe.ToString(), addrYou.ToString(), nodeid); } else { LogPrint(BCLog::NET, "send version message: version %d, blocks=%d, us=%s, peer=%d\n", nProtocolVersion, nNodeStartingHeight, addrMe.ToString(), nodeid); } } // Returns a bool indicating whether we requested this block. // Also used if a block was /not/ received and timed out or started with another peer bool MarkBlockAsReceived(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash); if (itInFlight != mapBlocksInFlight.end()) { CNodeState *state = State(itInFlight->second.first); assert(state != nullptr); state->nBlocksInFlightValidHeaders -= itInFlight->second.second->fValidatedHeaders; if (state->nBlocksInFlightValidHeaders == 0 && itInFlight->second.second->fValidatedHeaders) { // Last validated block on the queue was received. nPeersWithValidatedDownloads--; } if (state->vBlocksInFlight.begin() == itInFlight->second.second) { // First block on the queue was received, update the start download time for the next one state->nDownloadingSince = std::max(state->nDownloadingSince, GetTimeMicros()); } state->vBlocksInFlight.erase(itInFlight->second.second); state->nBlocksInFlight--; state->nStallingSince = 0; mapBlocksInFlight.erase(itInFlight); return true; } return false; } // returns false, still setting pit, if the block was already in flight from the same peer // pit will only be valid as long as the same cs_main lock is being held bool MarkBlockAsInFlight(NodeId nodeid, const uint256& hash, const CBlockIndex *pindex = nullptr, std::list<QueuedBlock>::iterator **pit = nullptr) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { CNodeState *state = State(nodeid); assert(state != nullptr); // Short-circuit most stuff in case it is from the same node std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator itInFlight = mapBlocksInFlight.find(hash); if (itInFlight != mapBlocksInFlight.end() && itInFlight->second.first == nodeid) { if (pit) { *pit = &itInFlight->second.second; } return false; } // Make sure it's not listed somewhere already. MarkBlockAsReceived(hash); std::list<QueuedBlock>::iterator it = state->vBlocksInFlight.insert(state->vBlocksInFlight.end(), {hash, pindex, pindex != nullptr, std::unique_ptr<PartiallyDownloadedBlock>(pit ? new PartiallyDownloadedBlock(&mempool) : nullptr)}); state->nBlocksInFlight++; state->nBlocksInFlightValidHeaders += it->fValidatedHeaders; if (state->nBlocksInFlight == 1) { // We're starting a block download (batch) from this peer. state->nDownloadingSince = GetTimeMicros(); } if (state->nBlocksInFlightValidHeaders == 1 && pindex != nullptr) { nPeersWithValidatedDownloads++; } itInFlight = mapBlocksInFlight.insert(std::make_pair(hash, std::make_pair(nodeid, it))).first; if (pit) *pit = &itInFlight->second.second; return true; } /** Check whether the last unknown block a peer advertised is not yet known. */ void ProcessBlockAvailability(NodeId nodeid) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { CNodeState *state = State(nodeid); assert(state != nullptr); if (!state->hashLastUnknownBlock.IsNull()) { const CBlockIndex* pindex = LookupBlockIndex(state->hashLastUnknownBlock); if (pindex && pindex->nChainWork > 0) { if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) { state->pindexBestKnownBlock = pindex; } state->hashLastUnknownBlock.SetNull(); } } } /** Update tracking information about which blocks a peer is assumed to have. */ void UpdateBlockAvailability(NodeId nodeid, const uint256 &hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { CNodeState *state = State(nodeid); assert(state != nullptr); ProcessBlockAvailability(nodeid); const CBlockIndex* pindex = LookupBlockIndex(hash); if (pindex && pindex->nChainWork > 0) { // An actually better block was announced. if (state->pindexBestKnownBlock == nullptr || pindex->nChainWork >= state->pindexBestKnownBlock->nChainWork) { state->pindexBestKnownBlock = pindex; } } else { // An unknown block was announced; just assume that the latest one is the best one. state->hashLastUnknownBlock = hash; } } /** * When a peer sends us a valid block, instruct it to announce blocks to us * using CMPCTBLOCK if possible by adding its nodeid to the end of * lNodesAnnouncingHeaderAndIDs, and keeping that list under a certain size by * removing the first element if necessary. */ void MaybeSetPeerAsAnnouncingHeaderAndIDs(NodeId nodeid, CConnman* connman) { AssertLockHeld(cs_main); CNodeState* nodestate = State(nodeid); if (!nodestate || !nodestate->fSupportsDesiredCmpctVersion) { // Never ask from peers who can't provide desired version. return; } if (nodestate->fProvidesHeaderAndIDs) { for (std::list<NodeId>::iterator it = lNodesAnnouncingHeaderAndIDs.begin(); it != lNodesAnnouncingHeaderAndIDs.end(); it++) { if (*it == nodeid) { lNodesAnnouncingHeaderAndIDs.erase(it); lNodesAnnouncingHeaderAndIDs.push_back(nodeid); return; } } connman->ForNode(nodeid, [connman](CNode* pfrom){ AssertLockHeld(cs_main); uint64_t nCMPCTBLOCKVersion = 1; if (lNodesAnnouncingHeaderAndIDs.size() >= 3) { // As per BIP152, we only get 3 of our peers to announce // blocks using compact encodings. connman->ForNode(lNodesAnnouncingHeaderAndIDs.front(), [connman, nCMPCTBLOCKVersion](CNode* pnodeStop){ AssertLockHeld(cs_main); connman->PushMessage(pnodeStop, CNetMsgMaker(pnodeStop->GetSendVersion()).Make(NetMsgType::SENDCMPCT, /*fAnnounceUsingCMPCTBLOCK=*/false, nCMPCTBLOCKVersion)); return true; }); lNodesAnnouncingHeaderAndIDs.pop_front(); } connman->PushMessage(pfrom, CNetMsgMaker(pfrom->GetSendVersion()).Make(NetMsgType::SENDCMPCT, /*fAnnounceUsingCMPCTBLOCK=*/true, nCMPCTBLOCKVersion)); lNodesAnnouncingHeaderAndIDs.push_back(pfrom->GetId()); return true; }); } } bool TipMayBeStale(const Consensus::Params &consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { AssertLockHeld(cs_main); if (g_last_tip_update == 0) { g_last_tip_update = GetTime(); } return g_last_tip_update < GetTime() - consensusParams.nPowTargetSpacing * 3 && mapBlocksInFlight.empty(); } bool CanDirectFetch(const Consensus::Params &consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { return chainActive.Tip()->GetBlockTime() > GetAdjustedTime() - consensusParams.nPowTargetSpacing * 20; } bool PeerHasHeader(CNodeState *state, const CBlockIndex *pindex) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { if (state->pindexBestKnownBlock && pindex == state->pindexBestKnownBlock->GetAncestor(pindex->nHeight)) return true; if (state->pindexBestHeaderSent && pindex == state->pindexBestHeaderSent->GetAncestor(pindex->nHeight)) return true; return false; } /** Update pindexLastCommonBlock and add not-in-flight missing successors to vBlocks, until it has * at most count entries. */ void FindNextBlocksToDownload(NodeId nodeid, unsigned int count, std::vector<const CBlockIndex*>& vBlocks, NodeId& nodeStaller, const Consensus::Params& consensusParams) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { if (count == 0) return; vBlocks.reserve(vBlocks.size() + count); CNodeState *state = State(nodeid); assert(state != nullptr); // Make sure pindexBestKnownBlock is up to date, we'll need it. ProcessBlockAvailability(nodeid); if (state->pindexBestKnownBlock == nullptr || state->pindexBestKnownBlock->nChainWork < chainActive.Tip()->nChainWork || state->pindexBestKnownBlock->nChainWork < nMinimumChainWork) { // This peer has nothing interesting. return; } if (state->pindexLastCommonBlock == nullptr) { // Bootstrap quickly by guessing a parent of our best tip is the forking point. // Guessing wrong in either direction is not a problem. state->pindexLastCommonBlock = chainActive[std::min(state->pindexBestKnownBlock->nHeight, chainActive.Height())]; } // If the peer reorganized, our previous pindexLastCommonBlock may not be an ancestor // of its current tip anymore. Go back enough to fix that. state->pindexLastCommonBlock = LastCommonAncestor(state->pindexLastCommonBlock, state->pindexBestKnownBlock); if (state->pindexLastCommonBlock == state->pindexBestKnownBlock) return; std::vector<const CBlockIndex*> vToFetch; const CBlockIndex *pindexWalk = state->pindexLastCommonBlock; // Never fetch further than the best block we know the peer has, or more than BLOCK_DOWNLOAD_WINDOW + 1 beyond the last // linked block we have in common with this peer. The +1 is so we can detect stalling, namely if we would be able to // download that next block if the window were 1 larger. int nWindowEnd = state->pindexLastCommonBlock->nHeight + BLOCK_DOWNLOAD_WINDOW; int nMaxHeight = std::min<int>(state->pindexBestKnownBlock->nHeight, nWindowEnd + 1); NodeId waitingfor = -1; while (pindexWalk->nHeight < nMaxHeight) { // Read up to 128 (or more, if more blocks than that are needed) successors of pindexWalk (towards // pindexBestKnownBlock) into vToFetch. We fetch 128, because CBlockIndex::GetAncestor may be as expensive // as iterating over ~100 CBlockIndex* entries anyway. int nToFetch = std::min(nMaxHeight - pindexWalk->nHeight, std::max<int>(count - vBlocks.size(), 128)); vToFetch.resize(nToFetch); pindexWalk = state->pindexBestKnownBlock->GetAncestor(pindexWalk->nHeight + nToFetch); vToFetch[nToFetch - 1] = pindexWalk; for (unsigned int i = nToFetch - 1; i > 0; i--) { vToFetch[i - 1] = vToFetch[i]->pprev; } // Iterate over those blocks in vToFetch (in forward direction), adding the ones that // are not yet downloaded and not in flight to vBlocks. In the meantime, update // pindexLastCommonBlock as long as all ancestors are already downloaded, or if it's // already part of our chain (and therefore don't need it even if pruned). for (const CBlockIndex* pindex : vToFetch) { if (!pindex->IsValid(BLOCK_VALID_TREE)) { // We consider the chain that this peer is on invalid. return; } if (pindex->nStatus & BLOCK_HAVE_DATA || chainActive.Contains(pindex)) { if (pindex->nChainTx) state->pindexLastCommonBlock = pindex; } else if (mapBlocksInFlight.count(pindex->GetBlockHash()) == 0) { // The block is not already downloaded, and not yet in flight. if (pindex->nHeight > nWindowEnd) { // We reached the end of the window. if (vBlocks.size() == 0 && waitingfor != nodeid) { // We aren't able to fetch anything, but we would be if the download window was one larger. nodeStaller = waitingfor; } return; } vBlocks.push_back(pindex); if (vBlocks.size() == count) { return; } } else if (waitingfor == -1) { // This is the first already-in-flight block. waitingfor = mapBlocksInFlight[pindex->GetBlockHash()].first; } } } } } // namespace void EraseObjectRequest(CNodeState* nodestate, const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { AssertLockHeld(cs_main); LogPrint(BCLog::NET, "%s -- inv=(%s)\n", __func__, inv.ToString()); g_already_asked_for.erase(inv.hash); g_erased_object_requests.insert(std::make_pair(inv.hash, GetTime<std::chrono::microseconds>())); if (nodestate) { nodestate->m_object_download.m_object_announced.erase(inv); nodestate->m_object_download.m_object_in_flight.erase(inv); } } void EraseObjectRequest(NodeId nodeId, const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { AssertLockHeld(cs_main); auto* state = State(nodeId); if (!state) { return; } EraseObjectRequest(state, inv); } std::chrono::microseconds GetObjectRequestTime(const uint256& hash) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { AssertLockHeld(cs_main); auto it = g_already_asked_for.find(hash); if (it != g_already_asked_for.end()) { return it->second; } return {}; } void UpdateObjectRequestTime(const uint256& hash, std::chrono::microseconds request_time) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { AssertLockHeld(cs_main); auto it = g_already_asked_for.find(hash); if (it == g_already_asked_for.end()) { g_already_asked_for.insert(std::make_pair(hash, request_time)); } else { g_already_asked_for.update(it, request_time); } } std::chrono::microseconds GetObjectInterval(int invType) { // some messages need to be re-requested faster when the first announcing peer did not answer to GETDATA switch(invType) { case MSG_QUORUM_RECOVERED_SIG: return std::chrono::seconds{15}; case MSG_CLSIG: return std::chrono::seconds{5}; case MSG_ISLOCK: return std::chrono::seconds{10}; default: return GETDATA_TX_INTERVAL; } } std::chrono::microseconds GetObjectExpiryInterval(int invType) { return GetObjectInterval(invType) * TX_EXPIRY_INTERVAL_FACTOR; } std::chrono::microseconds GetObjectRandomDelay(int invType) { if (invType == MSG_TX) { return GetRandMicros(MAX_GETDATA_RANDOM_DELAY); } return {}; } std::chrono::microseconds CalculateObjectGetDataTime(const CInv& inv, std::chrono::microseconds current_time, bool use_inbound_delay) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { AssertLockHeld(cs_main); std::chrono::microseconds process_time; const auto last_request_time = GetObjectRequestTime(inv.hash); // First time requesting this tx if (last_request_time.count() == 0) { process_time = current_time; } else { // Randomize the delay to avoid biasing some peers over others (such as due to // fixed ordering of peer processing in ThreadMessageHandler) process_time = last_request_time + GetObjectInterval(inv.type) + GetObjectRandomDelay(inv.type); } // We delay processing announcements from inbound peers if (inv.type == MSG_TX && !fMasternodeMode && use_inbound_delay) process_time += INBOUND_PEER_TX_DELAY; return process_time; } void RequestObject(CNodeState* state, const CInv& inv, std::chrono::microseconds current_time, bool fForce = false) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { AssertLockHeld(cs_main); CNodeState::ObjectDownloadState& peer_download_state = state->m_object_download; if (peer_download_state.m_object_announced.size() >= MAX_PEER_OBJECT_ANNOUNCEMENTS || peer_download_state.m_object_process_time.size() >= MAX_PEER_OBJECT_ANNOUNCEMENTS || peer_download_state.m_object_announced.count(inv)) { // Too many queued announcements from this peer, or we already have // this announcement return; } peer_download_state.m_object_announced.insert(inv); // Calculate the time to try requesting this transaction. Use // fPreferredDownload as a proxy for outbound peers. std::chrono::microseconds process_time = CalculateObjectGetDataTime(inv, current_time, !state->fPreferredDownload); peer_download_state.m_object_process_time.emplace(process_time, inv); if (fForce) { // make sure this object is actually requested ASAP g_erased_object_requests.erase(inv.hash); g_already_asked_for.erase(inv.hash); } LogPrint(BCLog::NET, "%s -- inv=(%s), current_time=%d, process_time=%d, delta=%d\n", __func__, inv.ToString(), current_time.count(), process_time.count(), (process_time - current_time).count()); } void RequestObject(NodeId nodeId, const CInv& inv, std::chrono::microseconds current_time, bool fForce) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { AssertLockHeld(cs_main); auto* state = State(nodeId); if (!state) { return; } RequestObject(state, inv, current_time, fForce); } size_t GetRequestedObjectCount(NodeId nodeId) { AssertLockHeld(cs_main); auto* state = State(nodeId); if (!state) { return 0; } return state->m_object_download.m_object_process_time.size(); } // This function is used for testing the stale tip eviction logic, see // denialofservice_tests.cpp void UpdateLastBlockAnnounceTime(NodeId node, int64_t time_in_seconds) { LOCK(cs_main); CNodeState *state = State(node); if (state) state->m_last_block_announcement = time_in_seconds; } // Returns true for outbound peers, excluding manual connections, feelers, and // one-shots bool IsOutboundDisconnectionCandidate(const CNode *node) { return !(node->fInbound || node->m_manual_connection || node->fFeeler || node->fOneShot); } void PeerLogicValidation::InitializeNode(CNode *pnode) { CAddress addr = pnode->addr; std::string addrName = pnode->GetAddrName(); NodeId nodeid = pnode->GetId(); { LOCK(cs_main); mapNodeState.emplace_hint(mapNodeState.end(), std::piecewise_construct, std::forward_as_tuple(nodeid), std::forward_as_tuple(addr, std::move(addrName))); } if(!pnode->fInbound) PushNodeVersion(pnode, connman, GetTime()); } void PeerLogicValidation::FinalizeNode(NodeId nodeid, bool& fUpdateConnectionTime) { fUpdateConnectionTime = false; LOCK(cs_main); CNodeState *state = State(nodeid); assert(state != nullptr); if (state->fSyncStarted) nSyncStarted--; if (state->nMisbehavior == 0 && state->fCurrentlyConnected) { fUpdateConnectionTime = true; } for (const QueuedBlock& entry : state->vBlocksInFlight) { mapBlocksInFlight.erase(entry.hash); } EraseOrphansFor(nodeid); nPreferredDownload -= state->fPreferredDownload; nPeersWithValidatedDownloads -= (state->nBlocksInFlightValidHeaders != 0); assert(nPeersWithValidatedDownloads >= 0); g_outbound_peers_with_protect_from_disconnect -= state->m_chain_sync.m_protect; assert(g_outbound_peers_with_protect_from_disconnect >= 0); mapNodeState.erase(nodeid); if (mapNodeState.empty()) { // Do a consistency check after the last peer is removed. assert(mapBlocksInFlight.empty()); assert(nPreferredDownload == 0); assert(nPeersWithValidatedDownloads == 0); assert(g_outbound_peers_with_protect_from_disconnect == 0); } LogPrint(BCLog::NET, "Cleared nodestate for peer=%d\n", nodeid); } bool GetNodeStateStats(NodeId nodeid, CNodeStateStats &stats) { LOCK(cs_main); CNodeState *state = State(nodeid); if (state == nullptr) return false; stats.nMisbehavior = state->nMisbehavior; stats.nSyncHeight = state->pindexBestKnownBlock ? state->pindexBestKnownBlock->nHeight : -1; stats.nCommonHeight = state->pindexLastCommonBlock ? state->pindexLastCommonBlock->nHeight : -1; for (const QueuedBlock& queue : state->vBlocksInFlight) { if (queue.pindex) stats.vHeightInFlight.push_back(queue.pindex->nHeight); } return true; } ////////////////////////////////////////////////////////////////////////////// // // mapOrphanTransactions // void AddToCompactExtraTransactions(const CTransactionRef& tx) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans) { size_t max_extra_txn = gArgs.GetArg("-blockreconstructionextratxn", DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN); if (max_extra_txn <= 0) return; if (!vExtraTxnForCompact.size()) vExtraTxnForCompact.resize(max_extra_txn); vExtraTxnForCompact[vExtraTxnForCompactIt] = std::make_pair(tx->GetHash(), tx); vExtraTxnForCompactIt = (vExtraTxnForCompactIt + 1) % max_extra_txn; } bool AddOrphanTx(const CTransactionRef& tx, NodeId peer) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans) { const uint256& hash = tx->GetHash(); if (mapOrphanTransactions.count(hash)) return false; // Ignore big transactions, to avoid a // send-big-orphans memory exhaustion attack. If a peer has a legitimate // large transaction with a missing parent then we assume // it will rebroadcast it later, after the parent transaction(s) // have been mined or received. // 100 orphans, each of which is at most 99,999 bytes big is // at most 10 megabytes of orphans and somewhat more byprev index (in the worst case): unsigned int sz = GetSerializeSize(*tx, SER_NETWORK, CTransaction::CURRENT_VERSION); if (sz > MAX_STANDARD_TX_SIZE) { LogPrint(BCLog::MEMPOOL, "ignoring large orphan tx (size: %u, hash: %s)\n", sz, hash.ToString()); return false; } auto ret = mapOrphanTransactions.emplace(hash, COrphanTx{tx, peer, GetTime() + ORPHAN_TX_EXPIRE_TIME, sz}); assert(ret.second); for (const CTxIn& txin : tx->vin) { mapOrphanTransactionsByPrev[txin.prevout].insert(ret.first); } AddToCompactExtraTransactions(tx); nMapOrphanTransactionsSize += sz; LogPrint(BCLog::MEMPOOL, "stored orphan tx %s (mapsz %u outsz %u)\n", hash.ToString(), mapOrphanTransactions.size(), mapOrphanTransactionsByPrev.size()); statsClient.inc("transactions.orphans.add", 1.0f); statsClient.gauge("transactions.orphans", mapOrphanTransactions.size()); return true; } int static EraseOrphanTx(uint256 hash) EXCLUSIVE_LOCKS_REQUIRED(g_cs_orphans) { std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.find(hash); if (it == mapOrphanTransactions.end()) return 0; for (const CTxIn& txin : it->second.tx->vin) { auto itPrev = mapOrphanTransactionsByPrev.find(txin.prevout); if (itPrev == mapOrphanTransactionsByPrev.end()) continue; itPrev->second.erase(it); if (itPrev->second.empty()) mapOrphanTransactionsByPrev.erase(itPrev); } assert(nMapOrphanTransactionsSize >= it->second.nTxSize); nMapOrphanTransactionsSize -= it->second.nTxSize; mapOrphanTransactions.erase(it); statsClient.inc("transactions.orphans.remove", 1.0f); statsClient.gauge("transactions.orphans", mapOrphanTransactions.size()); return 1; } void EraseOrphansFor(NodeId peer) { LOCK(g_cs_orphans); int nErased = 0; std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin(); while (iter != mapOrphanTransactions.end()) { std::map<uint256, COrphanTx>::iterator maybeErase = iter++; // increment to avoid iterator becoming invalid if (maybeErase->second.fromPeer == peer) { nErased += EraseOrphanTx(maybeErase->second.tx->GetHash()); } } if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx from peer=%d\n", nErased, peer); } unsigned int LimitOrphanTxSize(unsigned int nMaxOrphansSize) { LOCK(g_cs_orphans); unsigned int nEvicted = 0; static int64_t nNextSweep; int64_t nNow = GetTime(); if (nNextSweep <= nNow) { // Sweep out expired orphan pool entries: int nErased = 0; int64_t nMinExpTime = nNow + ORPHAN_TX_EXPIRE_TIME - ORPHAN_TX_EXPIRE_INTERVAL; std::map<uint256, COrphanTx>::iterator iter = mapOrphanTransactions.begin(); while (iter != mapOrphanTransactions.end()) { std::map<uint256, COrphanTx>::iterator maybeErase = iter++; if (maybeErase->second.nTimeExpire <= nNow) { nErased += EraseOrphanTx(maybeErase->second.tx->GetHash()); } else { nMinExpTime = std::min(maybeErase->second.nTimeExpire, nMinExpTime); } } // Sweep again 5 minutes after the next entry that expires in order to batch the linear scan. nNextSweep = nMinExpTime + ORPHAN_TX_EXPIRE_INTERVAL; if (nErased > 0) LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx due to expiration\n", nErased); } while (!mapOrphanTransactions.empty() && nMapOrphanTransactionsSize > nMaxOrphansSize) { // Evict a random orphan: uint256 randomhash = GetRandHash(); std::map<uint256, COrphanTx>::iterator it = mapOrphanTransactions.lower_bound(randomhash); if (it == mapOrphanTransactions.end()) it = mapOrphanTransactions.begin(); EraseOrphanTx(it->first); ++nEvicted; } return nEvicted; } void static ProcessOrphanTx(CConnman* connman, std::set<uint256>& orphan_work_set) EXCLUSIVE_LOCKS_REQUIRED(cs_main, g_cs_orphans); /** * Mark a misbehaving peer to be banned depending upon the value of `-banscore`. */ void Misbehaving(NodeId pnode, int howmuch, const std::string& message) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { if (howmuch == 0) return; CNodeState *state = State(pnode); if (state == nullptr) return; state->nMisbehavior += howmuch; int banscore = gArgs.GetArg("-banscore", DEFAULT_BANSCORE_THRESHOLD); std::string message_prefixed = message.empty() ? "" : (": " + message); if (state->nMisbehavior >= banscore && state->nMisbehavior - howmuch < banscore) { LogPrint(BCLog::NET, "%s: %s peer=%d (%d -> %d) BAN THRESHOLD EXCEEDED%s\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior, message_prefixed); state->fShouldBan = true; statsClient.inc("misbehavior.banned", 1.0f); } else { LogPrint(BCLog::NET, "%s: %s peer=%d (%d -> %d)%s\n", __func__, state->name, pnode, state->nMisbehavior-howmuch, state->nMisbehavior, message_prefixed); statsClient.count("misbehavior.amount", howmuch, 1.0); } } // Requires cs_main. bool IsBanned(NodeId pnode) { CNodeState *state = State(pnode); if (state == nullptr) return false; if (state->fShouldBan) { return true; } return false; } ////////////////////////////////////////////////////////////////////////////// // // blockchain -> download logic notification // // To prevent fingerprinting attacks, only send blocks/headers outside of the // active chain if they are no more than a month older (both in time, and in // best equivalent proof of work) than the best header chain we know about and // we fully-validated them at some point. static bool BlockRequestAllowed(const CBlockIndex* pindex, const Consensus::Params& consensusParams) { AssertLockHeld(cs_main); if (chainActive.Contains(pindex)) return true; return pindex->IsValid(BLOCK_VALID_SCRIPTS) && (pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() < STALE_RELAY_AGE_LIMIT) && (GetBlockProofEquivalentTime(*pindexBestHeader, *pindex, *pindexBestHeader, consensusParams) < STALE_RELAY_AGE_LIMIT); } PeerLogicValidation::PeerLogicValidation(CConnman* connmanIn, CScheduler &scheduler, bool enable_bip61) : connman(connmanIn), m_stale_tip_check_time(0), m_enable_bip61(enable_bip61) { // Initialize global variables that cannot be constructed at startup. recentRejects.reset(new CRollingBloomFilter(120000, 0.000001)); const Consensus::Params& consensusParams = Params().GetConsensus(); // Stale tip checking and peer eviction are on two different timers, but we // don't want them to get out of sync due to drift in the scheduler, so we // combine them in one function and schedule at the quicker (peer-eviction) // timer. static_assert(EXTRA_PEER_CHECK_INTERVAL < STALE_CHECK_INTERVAL, "peer eviction timer should be less than stale tip check timer"); scheduler.scheduleEvery(std::bind(&PeerLogicValidation::CheckForStaleTipAndEvictPeers, this, consensusParams), EXTRA_PEER_CHECK_INTERVAL * 1000); } /** * Evict orphan txn pool entries (EraseOrphanTx) based on a newly connected * block. Also save the time of the last tip update. */ void PeerLogicValidation::BlockConnected(const std::shared_ptr<const CBlock>& pblock, const CBlockIndex* pindex, const std::vector<CTransactionRef>& vtxConflicted) { LOCK2(cs_main, g_cs_orphans); std::vector<uint256> vOrphanErase; std::set<uint256> orphanWorkSet; for (const CTransactionRef& ptx : pblock->vtx) { const CTransaction& tx = *ptx; // Which orphan pool entries we should reprocess and potentially try to accept into mempool again? for (size_t i = 0; i < tx.vin.size(); i++) { auto itByPrev = mapOrphanTransactionsByPrev.find(COutPoint(tx.GetHash(), (uint32_t)i)); if (itByPrev == mapOrphanTransactionsByPrev.end()) continue; for (const auto& elem : itByPrev->second) { orphanWorkSet.insert(elem->first); } } // Which orphan pool entries must we evict? for (const auto& txin : tx.vin) { auto itByPrev = mapOrphanTransactionsByPrev.find(txin.prevout); if (itByPrev == mapOrphanTransactionsByPrev.end()) continue; for (auto mi = itByPrev->second.begin(); mi != itByPrev->second.end(); ++mi) { const CTransaction& orphanTx = *(*mi)->second.tx; const uint256& orphanHash = orphanTx.GetHash(); vOrphanErase.push_back(orphanHash); } } } // Erase orphan transactions included or precluded by this block if (vOrphanErase.size()) { int nErased = 0; for (uint256 &orphanHash : vOrphanErase) { nErased += EraseOrphanTx(orphanHash); } LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx included or conflicted by block\n", nErased); } while (!orphanWorkSet.empty()) { LogPrint(BCLog::MEMPOOL, "Trying to process %d orphans\n", orphanWorkSet.size()); ProcessOrphanTx(g_connman.get(), orphanWorkSet); } g_last_tip_update = GetTime(); } // All of the following cache a recent block, and are protected by cs_most_recent_block static CCriticalSection cs_most_recent_block; static std::shared_ptr<const CBlock> most_recent_block GUARDED_BY(cs_most_recent_block); static std::shared_ptr<const CBlockHeaderAndShortTxIDs> most_recent_compact_block GUARDED_BY(cs_most_recent_block); static uint256 most_recent_block_hash GUARDED_BY(cs_most_recent_block); /** * Maintain state about the best-seen block and fast-announce a compact block * to compatible peers. */ void PeerLogicValidation::NewPoWValidBlock(const CBlockIndex *pindex, const std::shared_ptr<const CBlock>& pblock) { std::shared_ptr<const CBlockHeaderAndShortTxIDs> pcmpctblock = std::make_shared<const CBlockHeaderAndShortTxIDs> (*pblock); const CNetMsgMaker msgMaker(PROTOCOL_VERSION); LOCK(cs_main); static int nHighestFastAnnounce = 0; if (pindex->nHeight <= nHighestFastAnnounce) return; nHighestFastAnnounce = pindex->nHeight; uint256 hashBlock(pblock->GetHash()); { LOCK(cs_most_recent_block); most_recent_block_hash = hashBlock; most_recent_block = pblock; most_recent_compact_block = pcmpctblock; } connman->ForEachNode([this, &pcmpctblock, pindex, &msgMaker, &hashBlock](CNode* pnode) { AssertLockHeld(cs_main); // TODO: Avoid the repeated-serialization here if (pnode->fDisconnect) return; ProcessBlockAvailability(pnode->GetId()); CNodeState &state = *State(pnode->GetId()); // If the peer has, or we announced to them the previous block already, // but we don't think they have this one, go ahead and announce it if (state.fPreferHeaderAndIDs && !PeerHasHeader(&state, pindex) && PeerHasHeader(&state, pindex->pprev)) { LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", "PeerLogicValidation::NewPoWValidBlock", hashBlock.ToString(), pnode->GetId()); connman->PushMessage(pnode, msgMaker.Make(NetMsgType::CMPCTBLOCK, *pcmpctblock)); state.pindexBestHeaderSent = pindex; } }); } /** * Update our best height and announce any block hashes which weren't previously * in chainActive to our peers. */ void PeerLogicValidation::UpdatedBlockTip(const CBlockIndex *pindexNew, const CBlockIndex *pindexFork, bool fInitialDownload) { const int nNewHeight = pindexNew->nHeight; connman->SetBestHeight(nNewHeight); SetServiceFlagsIBDCache(!fInitialDownload); if (!fInitialDownload) { // Find the hashes of all blocks that weren't previously in the best chain. std::vector<uint256> vHashes; const CBlockIndex *pindexToAnnounce = pindexNew; while (pindexToAnnounce != pindexFork) { vHashes.push_back(pindexToAnnounce->GetBlockHash()); pindexToAnnounce = pindexToAnnounce->pprev; if (vHashes.size() == MAX_BLOCKS_TO_ANNOUNCE) { // Limit announcements in case of a huge reorganization. // Rely on the peer's synchronization mechanism in that case. break; } } // Relay inventory, but don't relay old inventory during initial block download. connman->ForEachNode([nNewHeight, &vHashes](CNode* pnode) { if (!pnode->CanRelay()) { return; } if (nNewHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : 0)) { for (const uint256& hash : reverse_iterate(vHashes)) { pnode->PushBlockHash(hash); } } }); connman->WakeMessageHandler(); } nTimeBestReceived = GetTime(); } /** * Handle invalid block rejection and consequent peer banning, maintain which * peers announce compact blocks. */ void PeerLogicValidation::BlockChecked(const CBlock& block, const CValidationState& state) { LOCK(cs_main); const uint256 hash(block.GetHash()); std::map<uint256, std::pair<NodeId, bool> >::iterator it = mapBlockSource.find(hash); int nDoS = 0; if (state.IsInvalid(nDoS)) { // Don't send reject message with code 0 or an internal reject code. if (it != mapBlockSource.end() && State(it->second.first) && state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) { CBlockReject reject = {(unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), hash}; State(it->second.first)->rejects.push_back(reject); if (nDoS > 0 && it->second.second) Misbehaving(it->second.first, nDoS); } } // Check that: // 1. The block is valid // 2. We're not in initial block download // 3. This is currently the best block we're aware of. We haven't updated // the tip yet so we have no way to check this directly here. Instead we // just check that there are currently no other blocks in flight. else if (state.IsValid() && !IsInitialBlockDownload() && mapBlocksInFlight.count(hash) == mapBlocksInFlight.size()) { if (it != mapBlockSource.end()) { MaybeSetPeerAsAnnouncingHeaderAndIDs(it->second.first, connman); } } if (it != mapBlockSource.end()) mapBlockSource.erase(it); } ////////////////////////////////////////////////////////////////////////////// // // Messages // bool static AlreadyHave(const CInv& inv) EXCLUSIVE_LOCKS_REQUIRED(cs_main) { switch (inv.type) { case MSG_TX: case MSG_DSTX: case MSG_LEGACY_TXLOCK_REQUEST: // we treat legacy IX messages as TX messages { assert(recentRejects); if (chainActive.Tip()->GetBlockHash() != hashRecentRejectsChainTip) { // If the chain tip has changed previously rejected transactions // might be now valid, e.g. due to a nLockTime'd tx becoming valid, // or a double-spend. Reset the rejects filter and give those // txs a second chance. hashRecentRejectsChainTip = chainActive.Tip()->GetBlockHash(); recentRejects->reset(); } { LOCK(g_cs_orphans); if (mapOrphanTransactions.count(inv.hash)) return true; } // When we receive an islock for a previously rejected transaction, we have to // drop the first-seen tx (which such a locked transaction was conflicting with) // and re-request the locked transaction (which did not make it into the mempool // previously due to txn-mempool-conflict rule). This means that we must ignore // recentRejects filter for such locked txes here. // We also ignore recentRejects filter for DSTX-es because a malicious peer might // relay a valid DSTX as a regular TX first which would skip all the specific checks // but would cause such tx to be rejected by ATMP due to 0 fee. Ignoring it here // should let DSTX to be propagated by honest peer later. Note, that a malicious // masternode would not be able to exploit this to spam the network with specially // crafted invalid DSTX-es and potentially cause high load cheaply, because // corresponding checks in ProcessMessage won't let it to send DSTX-es too often. bool fIgnoreRecentRejects = llmq::quorumInstantSendManager->IsLocked(inv.hash) || inv.type == MSG_DSTX; return (!fIgnoreRecentRejects && recentRejects->contains(inv.hash)) || (inv.type == MSG_DSTX && static_cast<bool>(CCoinJoin::GetDSTX(inv.hash))) || mempool.exists(inv.hash) || pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 0)) || // Best effort: only try output 0 and 1 pcoinsTip->HaveCoinInCache(COutPoint(inv.hash, 1)) || (fTxIndex && pblocktree->HasTxIndex(inv.hash)); } case MSG_BLOCK: return LookupBlockIndex(inv.hash) != nullptr; /* LuckyCoinORO Related Inventory Messages -- We shouldn't update the sync times for each of the messages when we already have it. We're going to be asking many nodes upfront for the full inventory list, so we'll get duplicates of these. We want to only update the time on new hits, so that we can time out appropriately if needed. */ case MSG_SPORK: { CSporkMessage spork; return sporkManager.GetSporkByHash(inv.hash, spork); } case MSG_GOVERNANCE_OBJECT: case MSG_GOVERNANCE_OBJECT_VOTE: return ! governance.ConfirmInventoryRequest(inv); case MSG_QUORUM_FINAL_COMMITMENT: return llmq::quorumBlockProcessor->HasMinableCommitment(inv.hash); case MSG_QUORUM_CONTRIB: case MSG_QUORUM_COMPLAINT: case MSG_QUORUM_JUSTIFICATION: case MSG_QUORUM_PREMATURE_COMMITMENT: return llmq::quorumDKGSessionManager->AlreadyHave(inv); case MSG_QUORUM_RECOVERED_SIG: return llmq::quorumSigningManager->AlreadyHave(inv); case MSG_CLSIG: return llmq::chainLocksHandler->AlreadyHave(inv); case MSG_ISLOCK: return llmq::quorumInstantSendManager->AlreadyHave(inv); } // Don't know what it is, just say we already got one return true; } static void RelayAddress(const CAddress& addr, bool fReachable, CConnman* connman) { unsigned int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s) // Relay to a limited number of other nodes // Use deterministic randomness to send to the same nodes for 24 hours // at a time so the addrKnowns of the chosen nodes prevent repeats uint64_t hashAddr = addr.GetHash(); const CSipHasher hasher = connman->GetDeterministicRandomizer(RANDOMIZER_ID_ADDRESS_RELAY).Write(hashAddr << 32).Write((GetTime() + hashAddr) / (24*60*60)); FastRandomContext insecure_rand; std::array<std::pair<uint64_t, CNode*>,2> best{{{0, nullptr}, {0, nullptr}}}; assert(nRelayNodes <= best.size()); auto sortfunc = [&best, &hasher, nRelayNodes](CNode* pnode) { if (pnode->nVersion >= CADDR_TIME_VERSION) { uint64_t hashKey = CSipHasher(hasher).Write(pnode->GetId()).Finalize(); for (unsigned int i = 0; i < nRelayNodes; i++) { if (hashKey > best[i].first) { std::copy(best.begin() + i, best.begin() + nRelayNodes - 1, best.begin() + i + 1); best[i] = std::make_pair(hashKey, pnode); break; } } } }; auto pushfunc = [&addr, &best, nRelayNodes, &insecure_rand] { for (unsigned int i = 0; i < nRelayNodes && best[i].first != 0; i++) { best[i].second->PushAddress(addr, insecure_rand); } }; connman->ForEachNodeThen(std::move(sortfunc), std::move(pushfunc)); } void static ProcessGetBlockData(CNode* pfrom, const CChainParams& chainparams, const CInv& inv, CConnman* connman) { bool send = false; std::shared_ptr<const CBlock> a_recent_block; std::shared_ptr<const CBlockHeaderAndShortTxIDs> a_recent_compact_block; const Consensus::Params& consensusParams = chainparams.GetConsensus(); { LOCK(cs_most_recent_block); a_recent_block = most_recent_block; a_recent_compact_block = most_recent_compact_block; } bool need_activate_chain = false; { LOCK(cs_main); const CBlockIndex* pindex = LookupBlockIndex(inv.hash); if (pindex) { if (pindex->nChainTx && !pindex->IsValid(BLOCK_VALID_SCRIPTS) && pindex->IsValid(BLOCK_VALID_TREE)) { // If we have the block and all of its parents, but have not yet validated it, // we might be in the middle of connecting it (ie in the unlock of cs_main // before ActivateBestChain but after AcceptBlock). // In this case, we need to run ActivateBestChain prior to checking the relay // conditions below. need_activate_chain = true; } } } // release cs_main before calling ActivateBestChain if (need_activate_chain) { CValidationState state; if (!ActivateBestChain(state, Params(), a_recent_block)) { LogPrint(BCLog::NET, "failed to activate chain (%s)\n", FormatStateMessage(state)); } } LOCK(cs_main); const CBlockIndex* pindex = LookupBlockIndex(inv.hash); if (pindex) { send = BlockRequestAllowed(pindex, consensusParams); if (!send) { LogPrint(BCLog::NET,"%s: ignoring request from peer=%i for old block that isn't in the main chain\n", __func__, pfrom->GetId()); } } const CNetMsgMaker msgMaker(pfrom->GetSendVersion()); // disconnect node in case we have reached the outbound limit for serving historical blocks // never disconnect whitelisted nodes if (send && connman->OutboundTargetReached(true) && ( ((pindexBestHeader != nullptr) && (pindexBestHeader->GetBlockTime() - pindex->GetBlockTime() > HISTORICAL_BLOCK_AGE)) || inv.type == MSG_FILTERED_BLOCK) && !pfrom->fWhitelisted) { LogPrint(BCLog::NET, "historical block serving limit reached, disconnect peer=%d\n", pfrom->GetId()); //disconnect node pfrom->fDisconnect = true; send = false; } // Avoid leaking prune-height by never sending blocks below the NODE_NETWORK_LIMITED threshold if (send && !pfrom->fWhitelisted && ( (((pfrom->GetLocalServices() & NODE_NETWORK_LIMITED) == NODE_NETWORK_LIMITED) && ((pfrom->GetLocalServices() & NODE_NETWORK) != NODE_NETWORK) && (chainActive.Tip()->nHeight - pindex->nHeight > (int)NODE_NETWORK_LIMITED_MIN_BLOCKS + 2 /* add two blocks buffer extension for possible races */) ) )) { LogPrint(BCLog::NET, "Ignore block request below NODE_NETWORK_LIMITED threshold from peer=%d\n", pfrom->GetId()); //disconnect node and prevent it from stalling (would otherwise wait for the missing block) pfrom->fDisconnect = true; send = false; } // Pruned nodes may have deleted the block, so check whether // it's available before trying to send. if (send && (pindex->nStatus & BLOCK_HAVE_DATA)) { std::shared_ptr<const CBlock> pblock; if (a_recent_block && a_recent_block->GetHash() == pindex->GetBlockHash()) { pblock = a_recent_block; } else { // Send block from disk std::shared_ptr<CBlock> pblockRead = std::make_shared<CBlock>(); if (!ReadBlockFromDisk(*pblockRead, pindex, consensusParams)) assert(!"cannot load block from disk"); pblock = pblockRead; } if (pblock) { if (inv.type == MSG_BLOCK) connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::BLOCK, *pblock)); else if (inv.type == MSG_FILTERED_BLOCK) { bool sendMerkleBlock = false; CMerkleBlock merkleBlock; { LOCK(pfrom->cs_filter); if (pfrom->pfilter) { sendMerkleBlock = true; merkleBlock = CMerkleBlock(*pblock, *pfrom->pfilter); } } if (sendMerkleBlock) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::MERKLEBLOCK, merkleBlock)); // CMerkleBlock just contains hashes, so also push any transactions in the block the client did not see // This avoids hurting performance by pointlessly requiring a round-trip // Note that there is currently no way for a node to request any single transactions we didn't send here - // they must either disconnect and retry or request the full block. // Thus, the protocol spec specified allows for us to provide duplicate txn here, // however we MUST always provide at least what the remote peer needs typedef std::pair<unsigned int, uint256> PairType; for (PairType &pair : merkleBlock.vMatchedTxn) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::TX, *pblock->vtx[pair.first])); } for (PairType &pair : merkleBlock.vMatchedTxn) { auto islock = llmq::quorumInstantSendManager->GetInstantSendLockByTxid(pair.second); if (islock != nullptr) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::ISLOCK, *islock)); } } } // else // no response } else if (inv.type == MSG_CMPCT_BLOCK) { // If a peer is asking for old blocks, we're almost guaranteed // they won't have a useful mempool to match against a compact block, // and we don't feel like constructing the object for them, so // instead we respond with the full, non-compact block. if (CanDirectFetch(consensusParams) && pindex->nHeight >= chainActive.Height() - MAX_CMPCTBLOCK_DEPTH) { if (a_recent_compact_block && a_recent_compact_block->header.GetHash() == pindex->GetBlockHash()) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::CMPCTBLOCK, *a_recent_compact_block)); } else { CBlockHeaderAndShortTxIDs cmpctblock(*pblock); connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::CMPCTBLOCK, cmpctblock)); } } else { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::BLOCK, *pblock)); } } } // Trigger the peer node to send a getblocks request for the next batch of inventory if (inv.hash == pfrom->hashContinue) { // Bypass PushInventory, this must send even if redundant, // and we want it right after the last block so they don't // wait for other stuff first. std::vector<CInv> vInv; vInv.push_back(CInv(MSG_BLOCK, chainActive.Tip()->GetBlockHash())); connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::INV, vInv)); pfrom->hashContinue.SetNull(); } } } void static ProcessGetData(CNode* pfrom, const CChainParams& chainparams, CConnman* connman, const std::atomic<bool>& interruptMsgProc) { AssertLockNotHeld(cs_main); std::deque<CInv>::iterator it = pfrom->vRecvGetData.begin(); std::vector<CInv> vNotFound; const CNetMsgMaker msgMaker(pfrom->GetSendVersion()); { LOCK(cs_main); while (it != pfrom->vRecvGetData.end() && it->IsKnownType()) { if (interruptMsgProc) return; // Don't bother if send buffer is too full to respond anyway if (pfrom->fPauseSend) break; const CInv &inv = *it; if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK) { break; } it++; // Send stream from relay memory bool push = false; if (inv.type == MSG_TX || inv.type == MSG_DSTX) { CCoinJoinBroadcastTx dstx; if (inv.type == MSG_DSTX) { dstx = CCoinJoin::GetDSTX(inv.hash); } auto mi = mapRelay.find(inv.hash); if (mi != mapRelay.end()) { if (dstx) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::DSTX, dstx)); } else { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::TX, *mi->second)); } push = true; } else if (pfrom->timeLastMempoolReq) { auto txinfo = mempool.info(inv.hash); // To protect privacy, do not answer getdata using the mempool when // that TX couldn't have been INVed in reply to a MEMPOOL request. if (txinfo.tx && txinfo.nTime <= pfrom->timeLastMempoolReq) { if (dstx) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::DSTX, dstx)); } else { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::TX, *txinfo.tx)); } push = true; } } } if (!push && inv.type == MSG_SPORK) { CSporkMessage spork; if(sporkManager.GetSporkByHash(inv.hash, spork)) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SPORK, spork)); push = true; } } if (!push && inv.type == MSG_GOVERNANCE_OBJECT) { LogPrint(BCLog::NET, "ProcessGetData -- MSG_GOVERNANCE_OBJECT: inv = %s\n", inv.ToString()); CDataStream ss(SER_NETWORK, pfrom->GetSendVersion()); bool topush = false; { if(governance.HaveObjectForHash(inv.hash)) { ss.reserve(1000); if(governance.SerializeObjectForHash(inv.hash, ss)) { topush = true; } } } LogPrint(BCLog::NET, "ProcessGetData -- MSG_GOVERNANCE_OBJECT: topush = %d, inv = %s\n", topush, inv.ToString()); if(topush) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::MNGOVERNANCEOBJECT, ss)); push = true; } } if (!push && inv.type == MSG_GOVERNANCE_OBJECT_VOTE) { CDataStream ss(SER_NETWORK, pfrom->GetSendVersion()); bool topush = false; { if(governance.HaveVoteForHash(inv.hash)) { ss.reserve(1000); if(governance.SerializeVoteForHash(inv.hash, ss)) { topush = true; } } } if(topush) { LogPrint(BCLog::NET, "ProcessGetData -- pushing: inv = %s\n", inv.ToString()); connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::MNGOVERNANCEOBJECTVOTE, ss)); push = true; } } if (!push && (inv.type == MSG_QUORUM_FINAL_COMMITMENT)) { llmq::CFinalCommitment o; if (llmq::quorumBlockProcessor->GetMinableCommitmentByHash(inv.hash, o)) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::QFCOMMITMENT, o)); push = true; } } if (!push && (inv.type == MSG_QUORUM_CONTRIB)) { llmq::CDKGContribution o; if (llmq::quorumDKGSessionManager->GetContribution(inv.hash, o)) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::QCONTRIB, o)); push = true; } } if (!push && (inv.type == MSG_QUORUM_COMPLAINT)) { llmq::CDKGComplaint o; if (llmq::quorumDKGSessionManager->GetComplaint(inv.hash, o)) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::QCOMPLAINT, o)); push = true; } } if (!push && (inv.type == MSG_QUORUM_JUSTIFICATION)) { llmq::CDKGJustification o; if (llmq::quorumDKGSessionManager->GetJustification(inv.hash, o)) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::QJUSTIFICATION, o)); push = true; } } if (!push && (inv.type == MSG_QUORUM_PREMATURE_COMMITMENT)) { llmq::CDKGPrematureCommitment o; if (llmq::quorumDKGSessionManager->GetPrematureCommitment(inv.hash, o)) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::QPCOMMITMENT, o)); push = true; } } if (!push && (inv.type == MSG_QUORUM_RECOVERED_SIG)) { llmq::CRecoveredSig o; if (llmq::quorumSigningManager->GetRecoveredSigForGetData(inv.hash, o)) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::QSIGREC, o)); push = true; } } if (!push && (inv.type == MSG_CLSIG)) { llmq::CChainLockSig o; if (llmq::chainLocksHandler->GetChainLockByHash(inv.hash, o)) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::CLSIG, o)); push = true; } } if (!push && (inv.type == MSG_ISLOCK)) { llmq::CInstantSendLock o; if (llmq::quorumInstantSendManager->GetInstantSendLockByHash(inv.hash, o)) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::ISLOCK, o)); push = true; } } if (!push) vNotFound.push_back(inv); } } // release cs_main if (it != pfrom->vRecvGetData.end() && !pfrom->fPauseSend) { const CInv &inv = *it; if (inv.type == MSG_BLOCK || inv.type == MSG_FILTERED_BLOCK || inv.type == MSG_CMPCT_BLOCK) { it++; ProcessGetBlockData(pfrom, chainparams, inv, connman); } } pfrom->vRecvGetData.erase(pfrom->vRecvGetData.begin(), it); if (!vNotFound.empty()) { // Let the peer know that we didn't find what it asked for, so it doesn't // have to wait around forever. // SPV clients care about this message: it's needed when they are // recursively walking the dependencies of relevant unconfirmed // transactions. SPV clients want to do that because they want to know // about (and store and rebroadcast and risk analyze) the dependencies // of transactions relevant to them, without having to download the // entire memory pool. // Also, other nodes can use these messages to automatically request a // transaction from some other peer that annnounced it, and stop // waiting for us to respond. // In normal operation, we often send NOTFOUND messages for parents of // transactions that we relay; if a peer is missing a parent, they may // assume we have them and request the parents from us. connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::NOTFOUND, vNotFound)); } } inline void static SendBlockTransactions(const CBlock& block, const BlockTransactionsRequest& req, CNode* pfrom, CConnman* connman) { BlockTransactions resp(req); for (size_t i = 0; i < req.indexes.size(); i++) { if (req.indexes[i] >= block.vtx.size()) { LOCK(cs_main); Misbehaving(pfrom->GetId(), 100, strprintf("Peer %d sent us a getblocktxn with out-of-bounds tx indices", pfrom->GetId())); return; } resp.txn[i] = block.vtx[req.indexes[i]]; } LOCK(cs_main); CNetMsgMaker msgMaker(pfrom->GetSendVersion()); connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::BLOCKTXN, resp)); } bool static ProcessHeadersMessage(CNode *pfrom, CConnman *connman, const std::vector<CBlockHeader>& headers, const CChainParams& chainparams, bool punish_duplicate_invalid) { const CNetMsgMaker msgMaker(pfrom->GetSendVersion()); size_t nCount = headers.size(); if (nCount == 0) { // Nothing interesting. Stop asking this peers for more headers. return true; } bool received_new_header = false; const CBlockIndex *pindexLast = nullptr; { LOCK(cs_main); CNodeState *nodestate = State(pfrom->GetId()); // If this looks like it could be a block announcement (nCount < // MAX_BLOCKS_TO_ANNOUNCE), use special logic for handling headers that // don't connect: // - Send a getheaders message in response to try to connect the chain. // - The peer can send up to MAX_UNCONNECTING_HEADERS in a row that // don't connect before giving DoS points // - Once a headers message is received that is valid and does connect, // nUnconnectingHeaders gets reset back to 0. if (!LookupBlockIndex(headers[0].hashPrevBlock) && nCount < MAX_BLOCKS_TO_ANNOUNCE) { nodestate->nUnconnectingHeaders++; connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256())); LogPrint(BCLog::NET, "received header %s: missing prev block %s, sending getheaders (%d) to end (peer=%d, nUnconnectingHeaders=%d)\n", headers[0].GetHash().ToString(), headers[0].hashPrevBlock.ToString(), pindexBestHeader->nHeight, pfrom->GetId(), nodestate->nUnconnectingHeaders); // Set hashLastUnknownBlock for this peer, so that if we // eventually get the headers - even from a different peer - // we can use this peer to download. UpdateBlockAvailability(pfrom->GetId(), headers.back().GetHash()); if (nodestate->nUnconnectingHeaders % MAX_UNCONNECTING_HEADERS == 0) { Misbehaving(pfrom->GetId(), 20); } return true; } uint256 hashLastBlock; for (const CBlockHeader& header : headers) { if (!hashLastBlock.IsNull() && header.hashPrevBlock != hashLastBlock) { Misbehaving(pfrom->GetId(), 20, "non-continuous headers sequence"); return false; } hashLastBlock = header.GetHash(); } // If we don't have the last header, then they'll have given us // something new (if these headers are valid). if (!LookupBlockIndex(hashLastBlock)) { received_new_header = true; } } CValidationState state; CBlockHeader first_invalid_header; if (!ProcessNewBlockHeaders(headers, state, chainparams, &pindexLast, &first_invalid_header)) { int nDoS; if (state.IsInvalid(nDoS)) { LOCK(cs_main); if (nDoS > 0) { Misbehaving(pfrom->GetId(), nDoS, "invalid header received"); } else { LogPrint(BCLog::NET, "peer=%d: invalid header received\n", pfrom->GetId()); } if (punish_duplicate_invalid && LookupBlockIndex(first_invalid_header.GetHash())) { // Goal: don't allow outbound peers to use up our outbound // connection slots if they are on incompatible chains. // // We ask the caller to set punish_invalid appropriately based // on the peer and the method of header delivery (compact // blocks are allowed to be invalid in some circumstances, // under BIP 152). // Here, we try to detect the narrow situation that we have a // valid block header (ie it was valid at the time the header // was received, and hence stored in mapBlockIndex) but know the // block is invalid, and that a peer has announced that same // block as being on its active chain. // Disconnect the peer in such a situation. // // Note: if the header that is invalid was not accepted to our // mapBlockIndex at all, that may also be grounds for // disconnecting the peer, as the chain they are on is likely // to be incompatible. However, there is a circumstance where // that does not hold: if the header's timestamp is more than // 2 hours ahead of our current time. In that case, the header // may become valid in the future, and we don't want to // disconnect a peer merely for serving us one too-far-ahead // block header, to prevent an attacker from splitting the // network by mining a block right at the 2 hour boundary. // // TODO: update the DoS logic (or, rather, rewrite the // DoS-interface between validation and net_processing) so that // the interface is cleaner, and so that we disconnect on all the // reasons that a peer's headers chain is incompatible // with ours (eg block->nVersion softforks, MTP violations, // etc), and not just the duplicate-invalid case. pfrom->fDisconnect = true; } return false; } } { LOCK(cs_main); CNodeState *nodestate = State(pfrom->GetId()); if (nodestate->nUnconnectingHeaders > 0) { LogPrint(BCLog::NET, "peer=%d: resetting nUnconnectingHeaders (%d -> 0)\n", pfrom->GetId(), nodestate->nUnconnectingHeaders); } nodestate->nUnconnectingHeaders = 0; assert(pindexLast); UpdateBlockAvailability(pfrom->GetId(), pindexLast->GetBlockHash()); // From here, pindexBestKnownBlock should be guaranteed to be non-null, // because it is set in UpdateBlockAvailability. Some nullptr checks // are still present, however, as belt-and-suspenders. if (received_new_header && pindexLast->nChainWork > chainActive.Tip()->nChainWork) { nodestate->m_last_block_announcement = GetTime(); } if (nCount == MAX_HEADERS_RESULTS) { // Headers message had its maximum size; the peer may have more headers. // TODO: optimize: if pindexLast is an ancestor of chainActive.Tip or pindexBestHeader, continue // from there instead. LogPrint(BCLog::NET, "more getheaders (%d) to end to peer=%d (startheight:%d)\n", pindexLast->nHeight, pfrom->GetId(), pfrom->nStartingHeight); connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexLast), uint256())); } bool fCanDirectFetch = CanDirectFetch(chainparams.GetConsensus()); // If this set of headers is valid and ends in a block with at least as // much work as our tip, download as much as possible. if (fCanDirectFetch && pindexLast->IsValid(BLOCK_VALID_TREE) && chainActive.Tip()->nChainWork <= pindexLast->nChainWork) { std::vector<const CBlockIndex*> vToFetch; const CBlockIndex *pindexWalk = pindexLast; // Calculate all the blocks we'd need to switch to pindexLast, up to a limit. while (pindexWalk && !chainActive.Contains(pindexWalk) && vToFetch.size() <= MAX_BLOCKS_IN_TRANSIT_PER_PEER) { if (!(pindexWalk->nStatus & BLOCK_HAVE_DATA) && !mapBlocksInFlight.count(pindexWalk->GetBlockHash())) { // We don't have this block, and it's not yet in flight. vToFetch.push_back(pindexWalk); } pindexWalk = pindexWalk->pprev; } // If pindexWalk still isn't on our main chain, we're looking at a // very large reorg at a time we think we're close to caught up to // the main chain -- this shouldn't really happen. Bail out on the // direct fetch and rely on parallel download instead. if (!chainActive.Contains(pindexWalk)) { LogPrint(BCLog::NET, "Large reorg, won't direct fetch to %s (%d)\n", pindexLast->GetBlockHash().ToString(), pindexLast->nHeight); } else { std::vector<CInv> vGetData; // Download as much as possible, from earliest to latest. for (const CBlockIndex *pindex : reverse_iterate(vToFetch)) { if (nodestate->nBlocksInFlight >= MAX_BLOCKS_IN_TRANSIT_PER_PEER) { // Can't download any more from this peer break; } vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash())); MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex); LogPrint(BCLog::NET, "Requesting block %s from peer=%d\n", pindex->GetBlockHash().ToString(), pfrom->GetId()); } if (vGetData.size() > 1) { LogPrint(BCLog::NET, "Downloading blocks toward %s (%d) via headers direct fetch\n", pindexLast->GetBlockHash().ToString(), pindexLast->nHeight); } if (vGetData.size() > 0) { if (nodestate->fSupportsDesiredCmpctVersion && vGetData.size() == 1 && mapBlocksInFlight.size() == 1 && pindexLast->pprev->IsValid(BLOCK_VALID_CHAIN)) { // In any case, we want to download using a compact block, not a regular one vGetData[0] = CInv(MSG_CMPCT_BLOCK, vGetData[0].hash); } connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vGetData)); } } } // If we're in IBD, we want outbound peers that will serve us a useful // chain. Disconnect peers that are on chains with insufficient work. if (IsInitialBlockDownload() && nCount != MAX_HEADERS_RESULTS) { // When nCount < MAX_HEADERS_RESULTS, we know we have no more // headers to fetch from this peer. if (nodestate->pindexBestKnownBlock && nodestate->pindexBestKnownBlock->nChainWork < nMinimumChainWork) { // This peer has too little work on their headers chain to help // us sync -- disconnect if using an outbound slot (unless // whitelisted or addnode). // Note: We compare their tip to nMinimumChainWork (rather than // chainActive.Tip()) because we won't start block download // until we have a headers chain that has at least // nMinimumChainWork, even if a peer has a chain past our tip, // as an anti-DoS measure. if (IsOutboundDisconnectionCandidate(pfrom)) { LogPrintf("Disconnecting outbound peer %d -- headers chain has insufficient work\n", pfrom->GetId()); pfrom->fDisconnect = true; } } } if (!pfrom->fDisconnect && IsOutboundDisconnectionCandidate(pfrom) && nodestate->pindexBestKnownBlock != nullptr) { // If this is an outbound peer, check to see if we should protect // it from the bad/lagging chain logic. if (g_outbound_peers_with_protect_from_disconnect < MAX_OUTBOUND_PEERS_TO_PROTECT_FROM_DISCONNECT && nodestate->pindexBestKnownBlock->nChainWork >= chainActive.Tip()->nChainWork && !nodestate->m_chain_sync.m_protect) { LogPrint(BCLog::NET, "Protecting outbound peer=%d from eviction\n", pfrom->GetId()); nodestate->m_chain_sync.m_protect = true; ++g_outbound_peers_with_protect_from_disconnect; } } } return true; } void static ProcessOrphanTx(CConnman* connman, std::set<uint256>& orphan_work_set) EXCLUSIVE_LOCKS_REQUIRED(cs_main, g_cs_orphans) { AssertLockHeld(cs_main); AssertLockHeld(g_cs_orphans); std::set<NodeId> setMisbehaving; bool done = false; while (!done && !orphan_work_set.empty()) { const uint256 orphanHash = *orphan_work_set.begin(); orphan_work_set.erase(orphan_work_set.begin()); auto orphan_it = mapOrphanTransactions.find(orphanHash); if (orphan_it == mapOrphanTransactions.end()) continue; const CTransactionRef porphanTx = orphan_it->second.tx; const CTransaction& orphanTx = *porphanTx; NodeId fromPeer = orphan_it->second.fromPeer; bool fMissingInputs2 = false; // Use a dummy CValidationState so someone can't setup nodes to counter-DoS based on orphan // resolution (that is, feeding people an invalid transaction based on LegitTxX in order to get // anyone relaying LegitTxX banned) CValidationState stateDummy; if (setMisbehaving.count(fromPeer)) continue; if (AcceptToMemoryPool(mempool, stateDummy, porphanTx, &fMissingInputs2 /* pfMissingInputs */, false /* bypass_limits */, 0 /* nAbsurdFee */)) { LogPrint(BCLog::MEMPOOL, " accepted orphan tx %s\n", orphanHash.ToString()); connman->RelayTransaction(orphanTx); for (unsigned int i = 0; i < orphanTx.vout.size(); i++) { auto it_by_prev = mapOrphanTransactionsByPrev.find(COutPoint(orphanHash, i)); if (it_by_prev != mapOrphanTransactionsByPrev.end()) { for (const auto& elem : it_by_prev->second) { orphan_work_set.insert(elem->first); } } } EraseOrphanTx(orphanHash); done = true; } else if (!fMissingInputs2) { int nDos = 0; if (stateDummy.IsInvalid(nDos) && nDos > 0) { // Punish peer that gave us an invalid orphan tx Misbehaving(fromPeer, nDos); setMisbehaving.insert(fromPeer); LogPrint(BCLog::MEMPOOL, " invalid orphan tx %s\n", orphanHash.ToString()); } // Has inputs but not accepted to mempool // Probably non-standard or insufficient fee LogPrint(BCLog::MEMPOOL, " removed orphan tx %s\n", orphanHash.ToString()); if (!stateDummy.CorruptionPossible()) { assert(recentRejects); recentRejects->insert(orphanHash); } EraseOrphanTx(orphanHash); done = true; } mempool.check(pcoinsTip.get()); } } std::string RejectCodeToString(const unsigned char code) { if (code == REJECT_MALFORMED) return "malformed"; if (code == REJECT_INVALID) return "invalid"; if (code == REJECT_OBSOLETE) return "obsolete"; if (code == REJECT_DUPLICATE) return "duplicate"; if (code == REJECT_NONSTANDARD) return "nonstandard"; if (code == REJECT_INSUFFICIENTFEE) return "insufficientfee"; if (code == REJECT_CHECKPOINT) return "checkpoint"; return ""; } bool static ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, int64_t nTimeReceived, const CChainParams& chainparams, CConnman* connman, const std::atomic<bool>& interruptMsgProc, bool enable_bip61) { LogPrint(BCLog::NET, "received: %s (%u bytes) peer=%d\n", SanitizeString(strCommand), vRecv.size(), pfrom->GetId()); statsClient.inc("message.received." + SanitizeString(strCommand), 1.0f); if (gArgs.IsArgSet("-dropmessagestest") && GetRand(gArgs.GetArg("-dropmessagestest", 0)) == 0) { LogPrintf("dropmessagestest DROPPING RECV MESSAGE\n"); return true; } if (!(pfrom->GetLocalServices() & NODE_BLOOM) && (strCommand == NetMsgType::FILTERLOAD || strCommand == NetMsgType::FILTERADD)) { LOCK(cs_main); Misbehaving(pfrom->GetId(), 100); return false; } if (strCommand == NetMsgType::REJECT) { std::string strMsg; unsigned char ccode; std::string strReason; uint256 hash; try { vRecv >> LIMITED_STRING(strMsg, CMessageHeader::COMMAND_SIZE) >> ccode >> LIMITED_STRING(strReason, MAX_REJECT_MESSAGE_LENGTH); if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX) { vRecv >> hash; } } catch (const std::ios_base::failure&) { // Avoid feedback loops by preventing reject messages from triggering a new reject message. LogPrint(BCLog::NET, "Unparseable reject message received\n"); } if (strMsg == NetMsgType::BLOCK) { // The node requested a block from us and then rejected it, which indicates that it's most likely running // on rules which are incompatible to ours. Better to ban him after some time as it might otherwise keep // asking for the same block (if -addnode/-connect was used on the other side). LOCK(cs_main); Misbehaving(pfrom->GetId(), 1); } if (LogAcceptCategory(BCLog::NET)) { std::ostringstream ss; ss << strMsg << " code " << itostr(ccode) << ": " << strReason; if (strMsg == NetMsgType::BLOCK || strMsg == NetMsgType::TX) { ss << ": hash " << hash.ToString(); } LogPrint(BCLog::NET, "Reject %s\n", SanitizeString(ss.str())); } statsClient.inc("message.sent.reject_" + strMsg + "_" + RejectCodeToString(ccode), 1.0f); return true; } if (strCommand == NetMsgType::VERSION) { // Each connection can only send one version message if (pfrom->nVersion != 0) { if (enable_bip61) { connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_DUPLICATE, std::string("Duplicate version message"))); } LOCK(cs_main); Misbehaving(pfrom->GetId(), 1); return false; } int64_t nTime; CAddress addrMe; CAddress addrFrom; uint64_t nNonce = 1; uint64_t nServiceInt; ServiceFlags nServices; int nVersion; int nSendVersion; std::string strSubVer; std::string cleanSubVer; int nStartingHeight = -1; bool fRelay = true; vRecv >> nVersion >> nServiceInt >> nTime >> addrMe; nSendVersion = std::min(nVersion, PROTOCOL_VERSION); nServices = ServiceFlags(nServiceInt); if (!pfrom->fInbound) { connman->SetServices(pfrom->addr, nServices); } if (!pfrom->fInbound && !pfrom->fFeeler && !pfrom->m_manual_connection && !HasAllDesirableServiceFlags(nServices)) { LogPrint(BCLog::NET, "peer=%d does not offer the expected services (%08x offered, %08x expected); disconnecting\n", pfrom->GetId(), nServices, GetDesirableServiceFlags(nServices)); if (enable_bip61) { connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_NONSTANDARD, strprintf("Expected to offer services %08x", GetDesirableServiceFlags(nServices)))); } pfrom->fDisconnect = true; return false; } if (nVersion < MIN_PEER_PROTO_VERSION) { // disconnect from peers older than this proto version LogPrint(BCLog::NET, "peer=%d using obsolete version %i; disconnecting\n", pfrom->GetId(), nVersion); if (enable_bip61) { connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", MIN_PEER_PROTO_VERSION))); } pfrom->fDisconnect = true; return false; } if (!vRecv.empty()) vRecv >> addrFrom >> nNonce; if (!vRecv.empty()) { vRecv >> LIMITED_STRING(strSubVer, MAX_SUBVERSION_LENGTH); cleanSubVer = SanitizeString(strSubVer); } if (!vRecv.empty()) { vRecv >> nStartingHeight; } if (!vRecv.empty()) vRecv >> fRelay; if (!vRecv.empty()) { LOCK(pfrom->cs_mnauth); vRecv >> pfrom->receivedMNAuthChallenge; } if (!vRecv.empty()) { bool fOtherMasternode = false; vRecv >> fOtherMasternode; if (pfrom->fInbound) { pfrom->m_masternode_connection = fOtherMasternode; if (fOtherMasternode) { LogPrint(BCLog::NET_NETCONN, "peer=%d is an inbound masternode connection, not relaying anything to it\n", pfrom->GetId()); if (!fMasternodeMode) { LogPrint(BCLog::NET_NETCONN, "but we're not a masternode, disconnecting\n"); pfrom->fDisconnect = true; return true; } } } } // Disconnect if we connected to ourself if (pfrom->fInbound && !connman->CheckIncomingNonce(nNonce)) { LogPrintf("connected to self at %s, disconnecting\n", pfrom->addr.ToString()); pfrom->fDisconnect = true; return true; } if (pfrom->fInbound && addrMe.IsRoutable()) { SeenLocal(addrMe); } // Be shy and don't send version until we hear if (pfrom->fInbound) PushNodeVersion(pfrom, connman, GetAdjustedTime()); if (Params().NetworkIDString() == CBaseChainParams::DEVNET) { if (strSubVer.find(strprintf("devnet=%s", gArgs.GetDevNetName())) == std::string::npos) { LOCK(cs_main); LogPrintf("connected to wrong devnet. Reported version is %s, expected devnet name is %s\n", strSubVer, gArgs.GetDevNetName()); if (!pfrom->fInbound) Misbehaving(pfrom->GetId(), 100); // don't try to connect again else Misbehaving(pfrom->GetId(), 1); // whover connected, might just have made a mistake, don't ban him immediately pfrom->fDisconnect = true; return true; } } connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::VERACK)); pfrom->nServices = nServices; pfrom->SetAddrLocal(addrMe); { LOCK(pfrom->cs_SubVer); pfrom->strSubVer = strSubVer; pfrom->cleanSubVer = cleanSubVer; } pfrom->nStartingHeight = nStartingHeight; // set nodes not relaying blocks and tx and not serving (parts) of the historical blockchain as "clients" pfrom->fClient = (!(nServices & NODE_NETWORK) && !(nServices & NODE_NETWORK_LIMITED)); // set nodes not capable of serving the complete blockchain history as "limited nodes" pfrom->m_limited_node = (!(nServices & NODE_NETWORK) && (nServices & NODE_NETWORK_LIMITED)); { LOCK(pfrom->cs_filter); pfrom->fRelayTxes = fRelay; // set to true after we get the first filter* message } // Change version pfrom->SetSendVersion(nSendVersion); pfrom->nVersion = nVersion; // Potentially mark this peer as a preferred download peer. { LOCK(cs_main); UpdatePreferredDownload(pfrom, State(pfrom->GetId())); } if (!pfrom->fInbound) { // Advertise our address if (fListen && !IsInitialBlockDownload()) { CAddress addr = GetLocalAddress(&pfrom->addr, pfrom->GetLocalServices()); FastRandomContext insecure_rand; if (addr.IsRoutable()) { LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString()); pfrom->PushAddress(addr, insecure_rand); } else if (IsPeerAddrLocalGood(pfrom)) { addr.SetIP(addrMe); LogPrint(BCLog::NET, "ProcessMessages: advertising address %s\n", addr.ToString()); pfrom->PushAddress(addr, insecure_rand); } } // Get recent addresses if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || connman->GetAddressCount() < 1000) { connman->PushMessage(pfrom, CNetMsgMaker(nSendVersion).Make(NetMsgType::GETADDR)); pfrom->fGetAddr = true; } connman->MarkAddressGood(pfrom->addr); } std::string remoteAddr; if (fLogIPs) remoteAddr = ", peeraddr=" + pfrom->addr.ToString(); LogPrint(BCLog::NET, "receive version message: %s: version %d, blocks=%d, us=%s, peer=%d%s\n", cleanSubVer, pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString(), pfrom->GetId(), remoteAddr); int64_t nTimeOffset = nTime - GetTime(); pfrom->nTimeOffset = nTimeOffset; AddTimeData(pfrom->addr, nTimeOffset); // Feeler connections exist only to verify if address is online. if (pfrom->fFeeler) { assert(pfrom->fInbound == false); pfrom->fDisconnect = true; } return true; } if (pfrom->nVersion == 0) { // Must have a version message before anything else LOCK(cs_main); Misbehaving(pfrom->GetId(), 1); return false; } // At this point, the outgoing message serialization version can't change. const CNetMsgMaker msgMaker(pfrom->GetSendVersion()); if (strCommand == NetMsgType::VERACK) { pfrom->SetRecvVersion(std::min(pfrom->nVersion.load(), PROTOCOL_VERSION)); if (!pfrom->fInbound) { // Mark this node as currently connected, so we update its timestamp later. LOCK(cs_main); State(pfrom->GetId())->fCurrentlyConnected = true; LogPrintf("New outbound peer connected: version: %d, blocks=%d, peer=%d%s\n", pfrom->nVersion.load(), pfrom->nStartingHeight, pfrom->GetId(), (fLogIPs ? strprintf(", peeraddr=%s", pfrom->addr.ToString()) : "")); } if (pfrom->nVersion >= LLMQS_PROTO_VERSION && !pfrom->m_masternode_probe_connection) { CMNAuth::PushMNAUTH(pfrom, *connman); } // Tell our peer we prefer to receive headers rather than inv's // We send this to non-NODE NETWORK peers as well, because even // non-NODE NETWORK peers can announce blocks (such as pruning // nodes) connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDHEADERS)); if (pfrom->CanRelay()) { // Tell our peer we are willing to provide version-1 cmpctblocks // However, we do not request new block announcements using // cmpctblock messages. // We send this to non-NODE NETWORK peers as well, because // they may wish to request compact blocks from us bool fAnnounceUsingCMPCTBLOCK = false; uint64_t nCMPCTBLOCKVersion = 1; connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDCMPCT, fAnnounceUsingCMPCTBLOCK, nCMPCTBLOCKVersion)); } if (pfrom->nVersion >= SENDDSQUEUE_PROTO_VERSION) { // Tell our peer that he should send us CoinJoin queue messages connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::SENDDSQUEUE, true)); } else { // older nodes do not support SENDDSQUEUE and expect us to always send CoinJoin queue messages // TODO we can remove this compatibility code in 0.15.0 pfrom->fSendDSQueue = true; } if (llmq::CLLMQUtils::IsWatchQuorumsEnabled() && !pfrom->m_masternode_connection) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::QWATCH)); } pfrom->fSuccessfullyConnected = true; return true; } if (!pfrom->fSuccessfullyConnected) { // Must have a verack message before anything else LOCK(cs_main); Misbehaving(pfrom->GetId(), 1); return false; } if (pfrom->nTimeFirstMessageReceived == 0) { // First message after VERSION/VERACK pfrom->nTimeFirstMessageReceived = GetTimeMicros(); pfrom->fFirstMessageIsMNAUTH = strCommand == NetMsgType::MNAUTH; // Note: do not break the flow here if (pfrom->m_masternode_probe_connection && !pfrom->fFirstMessageIsMNAUTH) { LogPrint(BCLog::NET, "connection is a masternode probe but first received message is not MNAUTH, peer=%d\n", pfrom->GetId()); pfrom->fDisconnect = true; return false; } } if (strCommand == NetMsgType::ADDR) { std::vector<CAddress> vAddr; vRecv >> vAddr; // Don't want addr from older versions unless seeding if (pfrom->nVersion < CADDR_TIME_VERSION && connman->GetAddressCount() > 1000) return true; if (vAddr.size() > 1000) { LOCK(cs_main); Misbehaving(pfrom->GetId(), 20, strprintf("message addr size() = %u", vAddr.size())); return false; } // Store the new addresses std::vector<CAddress> vAddrOk; int64_t nNow = GetAdjustedTime(); int64_t nSince = nNow - 10 * 60; for (CAddress& addr : vAddr) { if (interruptMsgProc) return true; // We only bother storing full nodes, though this may include // things which we would not make an outbound connection to, in // part because we may make feeler connections to them. if (!MayHaveUsefulAddressDB(addr.nServices) && !HasAllDesirableServiceFlags(addr.nServices)) continue; if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60) addr.nTime = nNow - 5 * 24 * 60 * 60; pfrom->AddAddressKnown(addr); bool fReachable = IsReachable(addr); if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable()) { RelayAddress(addr, fReachable, connman); } // Do not store addresses outside our network if (fReachable) vAddrOk.push_back(addr); } connman->AddNewAddresses(vAddrOk, pfrom->addr, 2 * 60 * 60); if (vAddr.size() < 1000) pfrom->fGetAddr = false; if (pfrom->fOneShot) pfrom->fDisconnect = true; statsClient.gauge("peers.knownAddresses", connman->GetAddressCount(), 1.0f); return true; } if (strCommand == NetMsgType::SENDHEADERS) { LOCK(cs_main); State(pfrom->GetId())->fPreferHeaders = true; return true; } if (strCommand == NetMsgType::SENDCMPCT) { bool fAnnounceUsingCMPCTBLOCK = false; uint64_t nCMPCTBLOCKVersion = 1; vRecv >> fAnnounceUsingCMPCTBLOCK >> nCMPCTBLOCKVersion; if (nCMPCTBLOCKVersion == 1) { LOCK(cs_main); State(pfrom->GetId())->fProvidesHeaderAndIDs = true; State(pfrom->GetId())->fPreferHeaderAndIDs = fAnnounceUsingCMPCTBLOCK; State(pfrom->GetId())->fSupportsDesiredCmpctVersion = true; } return true; } if (strCommand == NetMsgType::SENDDSQUEUE) { bool b; vRecv >> b; pfrom->fSendDSQueue = b; return true; } if (strCommand == NetMsgType::QSENDRECSIGS) { bool b; vRecv >> b; pfrom->fSendRecSigs = b; return true; } if (strCommand == NetMsgType::INV) { std::vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > MAX_INV_SZ) { LOCK(cs_main); Misbehaving(pfrom->GetId(), 20, strprintf("message inv size() = %u", vInv.size())); return false; } bool fBlocksOnly = !fRelayTxes; // Allow whitelisted peers to send data other than blocks in blocks only mode if whitelistrelay is true if (pfrom->fWhitelisted && gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY)) fBlocksOnly = false; LOCK(cs_main); const auto current_time = GetTime<std::chrono::microseconds>(); for (CInv &inv : vInv) { if(!inv.IsKnownType()) { LogPrint(BCLog::NET, "got inv of unknown type %d: %s peer=%d\n", inv.type, inv.hash.ToString(), pfrom->GetId()); continue; } if (interruptMsgProc) return true; bool fAlreadyHave = AlreadyHave(inv); LogPrint(BCLog::NET, "got inv: %s %s peer=%d\n", inv.ToString(), fAlreadyHave ? "have" : "new", pfrom->GetId()); statsClient.inc(strprintf("message.received.inv_%s", inv.GetCommand()), 1.0f); if (inv.type == MSG_BLOCK) { UpdateBlockAvailability(pfrom->GetId(), inv.hash); if (fAlreadyHave || fImporting || fReindex || mapBlocksInFlight.count(inv.hash)) { continue; } CNodeState *state = State(pfrom->GetId()); if (!state) { continue; } // Download if this is a nice peer, or we have no nice peers and this one might do. bool fFetch = state->fPreferredDownload || (nPreferredDownload == 0 && !pfrom->fOneShot); // Only actively request headers from a single peer, unless we're close to end of initial download. if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - nMaxTipAge) { // Make sure to mark this peer as the one we are currently syncing with etc. state->fSyncStarted = true; state->nHeadersSyncTimeout = GetTimeMicros() + HEADERS_DOWNLOAD_TIMEOUT_BASE + HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER * (GetAdjustedTime() - pindexBestHeader->GetBlockTime())/(chainparams.GetConsensus().nPowTargetSpacing); nSyncStarted++; // We used to request the full block here, but since headers-announcements are now the // primary method of announcement on the network, and since, in the case that a node // fell back to inv we probably have a reorg which we should get the headers for first, // we now only provide a getheaders response here. When we receive the headers, we will // then ask for the blocks we need. connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), inv.hash)); LogPrint(BCLog::NET, "getheaders (%d) %s to peer=%d\n", pindexBestHeader->nHeight, inv.hash.ToString(), pfrom->GetId()); } } else { static std::set<int> allowWhileInIBDObjs = { MSG_SPORK }; pfrom->AddInventoryKnown(inv); if (fBlocksOnly) { LogPrint(BCLog::NET, "transaction (%s) inv sent in violation of protocol peer=%d\n", inv.hash.ToString(), pfrom->GetId()); } else if (!fAlreadyHave) { bool allowWhileInIBD = allowWhileInIBDObjs.count(inv.type); if (allowWhileInIBD || (!fImporting && !fReindex && !IsInitialBlockDownload())) { RequestObject(State(pfrom->GetId()), inv, current_time); } } } } return true; } if (strCommand == NetMsgType::GETDATA) { std::vector<CInv> vInv; vRecv >> vInv; if (vInv.size() > MAX_INV_SZ) { LOCK(cs_main); Misbehaving(pfrom->GetId(), 20, strprintf("message getdata size() = %u", vInv.size())); return false; } LogPrint(BCLog::NET, "received getdata (%u invsz) peer=%d\n", vInv.size(), pfrom->GetId()); if (vInv.size() > 0) { LogPrint(BCLog::NET, "received getdata for: %s peer=%d\n", vInv[0].ToString(), pfrom->GetId()); } pfrom->vRecvGetData.insert(pfrom->vRecvGetData.end(), vInv.begin(), vInv.end()); ProcessGetData(pfrom, chainparams, connman, interruptMsgProc); return true; } if (strCommand == NetMsgType::GETBLOCKS) { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; if (locator.vHave.size() > MAX_LOCATOR_SZ) { LogPrint(BCLog::NET, "getblocks locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom->GetId()); pfrom->fDisconnect = true; return true; } // We might have announced the currently-being-connected tip using a // compact block, which resulted in the peer sending a getblocks // request, which we would otherwise respond to without the new block. // To avoid this situation we simply verify that we are on our best // known chain now. This is super overkill, but we handle it better // for getheaders requests, and there are no known nodes which support // compact blocks but still use getblocks to request blocks. { std::shared_ptr<const CBlock> a_recent_block; { LOCK(cs_most_recent_block); a_recent_block = most_recent_block; } CValidationState state; if (!ActivateBestChain(state, Params(), a_recent_block)) { LogPrint(BCLog::NET, "failed to activate chain (%s)\n", FormatStateMessage(state)); } } LOCK(cs_main); // Find the last block the caller has in the main chain const CBlockIndex* pindex = FindForkInGlobalIndex(chainActive, locator); // Send the rest of the chain if (pindex) pindex = chainActive.Next(pindex); int nLimit = 500; LogPrint(BCLog::NET, "getblocks %d to %s limit %d from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), nLimit, pfrom->GetId()); for (; pindex; pindex = chainActive.Next(pindex)) { if (pindex->GetBlockHash() == hashStop) { LogPrint(BCLog::NET, " getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); break; } // If pruning, don't inv blocks unless we have on disk and are likely to still have // for some reasonable time window (1 hour) that block relay might require. const int nPrunedBlocksLikelyToHave = MIN_BLOCKS_TO_KEEP - 3600 / chainparams.GetConsensus().nPowTargetSpacing; if (fPruneMode && (!(pindex->nStatus & BLOCK_HAVE_DATA) || pindex->nHeight <= chainActive.Tip()->nHeight - nPrunedBlocksLikelyToHave)) { LogPrint(BCLog::NET, " getblocks stopping, pruned or too old block at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); break; } if (pfrom->CanRelay()) { pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash())); } if (--nLimit <= 0) { // When this block is requested, we'll send an inv that'll // trigger the peer to getblocks the next batch of inventory. LogPrint(BCLog::NET, " getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString()); pfrom->hashContinue = pindex->GetBlockHash(); break; } } return true; } if (strCommand == NetMsgType::GETBLOCKTXN) { BlockTransactionsRequest req; vRecv >> req; std::shared_ptr<const CBlock> recent_block; { LOCK(cs_most_recent_block); if (most_recent_block_hash == req.blockhash) recent_block = most_recent_block; // Unlock cs_most_recent_block to avoid cs_main lock inversion } if (recent_block) { SendBlockTransactions(*recent_block, req, pfrom, connman); return true; } LOCK(cs_main); const CBlockIndex* pindex = LookupBlockIndex(req.blockhash); if (!pindex || !(pindex->nStatus & BLOCK_HAVE_DATA)) { LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block we don't have\n", pfrom->GetId()); return true; } if (pindex->nHeight < chainActive.Height() - MAX_BLOCKTXN_DEPTH) { // If an older block is requested (should never happen in practice, // but can happen in tests) send a block response instead of a // blocktxn response. Sending a full block response instead of a // small blocktxn response is preferable in the case where a peer // might maliciously send lots of getblocktxn requests to trigger // expensive disk reads, because it will require the peer to // actually receive all the data read from disk over the network. LogPrint(BCLog::NET, "Peer %d sent us a getblocktxn for a block > %i deep\n", pfrom->GetId(), MAX_BLOCKTXN_DEPTH); CInv inv; inv.type = MSG_BLOCK; inv.hash = req.blockhash; pfrom->vRecvGetData.push_back(inv); // The message processing loop will go around again (without pausing) and we'll respond then (without cs_main) return true; } CBlock block; bool ret = ReadBlockFromDisk(block, pindex, chainparams.GetConsensus()); assert(ret); SendBlockTransactions(block, req, pfrom, connman); return true; } if (strCommand == NetMsgType::GETHEADERS) { CBlockLocator locator; uint256 hashStop; vRecv >> locator >> hashStop; if (locator.vHave.size() > MAX_LOCATOR_SZ) { LogPrint(BCLog::NET, "getheaders locator size %lld > %d, disconnect peer=%d\n", locator.vHave.size(), MAX_LOCATOR_SZ, pfrom->GetId()); pfrom->fDisconnect = true; return true; } LOCK(cs_main); if (IsInitialBlockDownload() && !pfrom->fWhitelisted) { LogPrint(BCLog::NET, "Ignoring getheaders from peer=%d because node is in initial block download\n", pfrom->GetId()); return true; } CNodeState *nodestate = State(pfrom->GetId()); const CBlockIndex* pindex = nullptr; if (locator.IsNull()) { // If locator is null, return the hashStop block pindex = LookupBlockIndex(hashStop); if (!pindex) { return true; } if (!BlockRequestAllowed(pindex, chainparams.GetConsensus())) { LogPrint(BCLog::NET, "%s: ignoring request from peer=%i for old block header that isn't in the main chain\n", __func__, pfrom->GetId()); return true; } } else { // Find the last block the caller has in the main chain pindex = FindForkInGlobalIndex(chainActive, locator); if (pindex) pindex = chainActive.Next(pindex); } // we must use CBlocks, as CBlockHeaders won't include the 0x00 nTx count at the end std::vector<CBlock> vHeaders; int nLimit = MAX_HEADERS_RESULTS; LogPrint(BCLog::NET, "getheaders %d to %s from peer=%d\n", (pindex ? pindex->nHeight : -1), hashStop.IsNull() ? "end" : hashStop.ToString(), pfrom->GetId()); for (; pindex; pindex = chainActive.Next(pindex)) { vHeaders.push_back(pindex->GetBlockHeader()); if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop) break; } // pindex can be nullptr either if we sent chainActive.Tip() OR // if our peer has chainActive.Tip() (and thus we are sending an empty // headers message). In both cases it's safe to update // pindexBestHeaderSent to be our tip. // // It is important that we simply reset the BestHeaderSent value here, // and not max(BestHeaderSent, newHeaderSent). We might have announced // the currently-being-connected tip using a compact block, which // resulted in the peer sending a headers request, which we respond to // without the new block. By resetting the BestHeaderSent, we ensure we // will re-announce the new block via headers (or compact blocks again) // in the SendMessages logic. nodestate->pindexBestHeaderSent = pindex ? pindex : chainActive.Tip(); connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::HEADERS, vHeaders)); return true; } if (strCommand == NetMsgType::TX || strCommand == NetMsgType::DSTX || strCommand == NetMsgType::LEGACYTXLOCKREQUEST) { // Stop processing the transaction early if // We are in blocks only mode and peer is either not whitelisted or whitelistrelay is off if (!fRelayTxes && (!pfrom->fWhitelisted || !gArgs.GetBoolArg("-whitelistrelay", DEFAULT_WHITELISTRELAY))) { LogPrint(BCLog::NET, "transaction sent in violation of protocol peer=%d\n", pfrom->GetId()); return true; } CTransactionRef ptx; CCoinJoinBroadcastTx dstx; int nInvType = MSG_TX; // Read data and assign inv type if(strCommand == NetMsgType::TX) { vRecv >> ptx; } else if(strCommand == NetMsgType::LEGACYTXLOCKREQUEST) { // we keep processing the legacy IX message here but revert to handling it as a regular TX vRecv >> ptx; } else if (strCommand == NetMsgType::DSTX) { vRecv >> dstx; ptx = dstx.tx; nInvType = MSG_DSTX; } const CTransaction& tx = *ptx; CInv inv(nInvType, tx.GetHash()); pfrom->AddInventoryKnown(inv); { LOCK(cs_main); EraseObjectRequest(pfrom->GetId(), inv); } // Process custom logic, no matter if tx will be accepted to mempool later or not if (nInvType == MSG_DSTX) { uint256 hashTx = tx.GetHash(); if (!dstx.IsValidStructure()) { LogPrint(BCLog::COINJOIN, "DSTX -- Invalid DSTX structure: %s\n", hashTx.ToString()); return false; } if(CCoinJoin::GetDSTX(hashTx)) { LogPrint(BCLog::COINJOIN, "DSTX -- Already have %s, skipping...\n", hashTx.ToString()); return true; // not an error } const CBlockIndex* pindex{nullptr}; CDeterministicMNCPtr dmn{nullptr}; { LOCK(cs_main); pindex = chainActive.Tip(); } // It could be that a MN is no longer in the list but its DSTX is not yet mined. // Try to find a MN up to 24 blocks deep to make sure such dstx-es are relayed and processed correctly. for (int i = 0; i < 24 && pindex; ++i) { dmn = deterministicMNManager->GetListForBlock(pindex).GetMNByCollateral(dstx.masternodeOutpoint); if (dmn) break; pindex = pindex->pprev; } if(!dmn) { LogPrint(BCLog::COINJOIN, "DSTX -- Can't find masternode %s to verify %s\n", dstx.masternodeOutpoint.ToStringShort(), hashTx.ToString()); return false; } if (!mmetaman.GetMetaInfo(dmn->proTxHash)->IsValidForMixingTxes()) { LogPrint(BCLog::COINJOIN, "DSTX -- Masternode %s is sending too many transactions %s\n", dstx.masternodeOutpoint.ToStringShort(), hashTx.ToString()); return true; // TODO: Not an error? Could it be that someone is relaying old DSTXes // we have no idea about (e.g we were offline)? How to handle them? } if (!dstx.CheckSignature(dmn->pdmnState->pubKeyOperator.Get())) { LogPrint(BCLog::COINJOIN, "DSTX -- CheckSignature() failed for %s\n", hashTx.ToString()); return false; } LogPrint(BCLog::COINJOIN, "DSTX -- Got Masternode transaction %s\n", hashTx.ToString()); mempool.PrioritiseTransaction(hashTx, 0.1*COIN); mmetaman.DisallowMixing(dmn->proTxHash); } LOCK2(cs_main, g_cs_orphans); bool fMissingInputs = false; CValidationState state; if (!AlreadyHave(inv) && AcceptToMemoryPool(mempool, state, ptx, &fMissingInputs /* pfMissingInputs */, false /* bypass_limits */, 0 /* nAbsurdFee */)) { // Process custom txes, this changes AlreadyHave to "true" if (nInvType == MSG_DSTX) { LogPrint(BCLog::COINJOIN, "DSTX -- Masternode transaction accepted, txid=%s, peer=%d\n", tx.GetHash().ToString(), pfrom->GetId()); CCoinJoin::AddDSTX(dstx); } mempool.check(pcoinsTip.get()); connman->RelayTransaction(tx); for (unsigned int i = 0; i < tx.vout.size(); i++) { auto it_by_prev = mapOrphanTransactionsByPrev.find(COutPoint(inv.hash, i)); if (it_by_prev != mapOrphanTransactionsByPrev.end()) { for (const auto& elem : it_by_prev->second) { pfrom->orphan_work_set.insert(elem->first); } } } pfrom->nLastTXTime = GetTime(); LogPrint(BCLog::MEMPOOL, "AcceptToMemoryPool: peer=%d: accepted %s (poolsz %u txn, %u kB)\n", pfrom->GetId(), tx.GetHash().ToString(), mempool.size(), mempool.DynamicMemoryUsage() / 1000); // Recursively process any orphan transactions that depended on this one ProcessOrphanTx(connman, pfrom->orphan_work_set); } else if (fMissingInputs) { bool fRejectedParents = false; // It may be the case that the orphans parents have all been rejected for (const CTxIn& txin : tx.vin) { if (recentRejects->contains(txin.prevout.hash)) { fRejectedParents = true; break; } } if (!fRejectedParents) { const auto current_time = GetTime<std::chrono::microseconds>(); for (const CTxIn& txin : tx.vin) { CInv _inv(MSG_TX, txin.prevout.hash); pfrom->AddInventoryKnown(_inv); if (!AlreadyHave(_inv)) RequestObject(State(pfrom->GetId()), _inv, current_time); // We don't know if the previous tx was a regular or a mixing one, try both CInv _inv2(MSG_DSTX, txin.prevout.hash); pfrom->AddInventoryKnown(_inv2); if (!AlreadyHave(_inv2)) RequestObject(State(pfrom->GetId()), _inv2, current_time); } AddOrphanTx(ptx, pfrom->GetId()); // DoS prevention: do not allow mapOrphanTransactions to grow unbounded unsigned int nMaxOrphanTxSize = (unsigned int)std::max((int64_t)0, gArgs.GetArg("-maxorphantxsize", DEFAULT_MAX_ORPHAN_TRANSACTIONS_SIZE)) * 1000000; unsigned int nEvicted = LimitOrphanTxSize(nMaxOrphanTxSize); if (nEvicted > 0) { LogPrint(BCLog::MEMPOOL, "mapOrphan overflow, removed %u tx\n", nEvicted); } } else { LogPrint(BCLog::MEMPOOL, "not keeping orphan with rejected parents %s\n",tx.GetHash().ToString()); // We will continue to reject this tx since it has rejected // parents so avoid re-requesting it from other peers. recentRejects->insert(tx.GetHash()); llmq::quorumInstantSendManager->TransactionRemovedFromMempool(ptx); } } else { if (!state.CorruptionPossible()) { assert(recentRejects); recentRejects->insert(tx.GetHash()); if (RecursiveDynamicUsage(*ptx) < 100000) { AddToCompactExtraTransactions(ptx); } } if (pfrom->fWhitelisted && gArgs.GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) { // Always relay transactions received from whitelisted peers, even // if they were already in the mempool or rejected from it due // to policy, allowing the node to function as a gateway for // nodes hidden behind it. // // Never relay transactions that we would assign a non-zero DoS // score for, as we expect peers to do the same with us in that // case. int nDoS = 0; if (!state.IsInvalid(nDoS) || nDoS == 0) { LogPrintf("Force relaying tx %s from whitelisted peer=%d\n", tx.GetHash().ToString(), pfrom->GetId()); connman->RelayTransaction(tx); } else { LogPrintf("Not relaying invalid transaction %s from whitelisted peer=%d (%s)\n", tx.GetHash().ToString(), pfrom->GetId(), FormatStateMessage(state)); } } llmq::quorumInstantSendManager->TransactionRemovedFromMempool(ptx); } int nDoS = 0; if (state.IsInvalid(nDoS)) { LogPrint(BCLog::MEMPOOLREJ, "%s from peer=%d was not accepted: %s\n", tx.GetHash().ToString(), pfrom->GetId(), FormatStateMessage(state)); if (enable_bip61 && state.GetRejectCode() > 0 && state.GetRejectCode() < REJECT_INTERNAL) { // Never send AcceptToMemoryPool's internal codes over P2P connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::REJECT, strCommand, (unsigned char)state.GetRejectCode(), state.GetRejectReason().substr(0, MAX_REJECT_MESSAGE_LENGTH), inv.hash)); } if (nDoS > 0) { Misbehaving(pfrom->GetId(), nDoS); } } return true; } if (strCommand == NetMsgType::CMPCTBLOCK && !fImporting && !fReindex) // Ignore blocks received while importing { CBlockHeaderAndShortTxIDs cmpctblock; vRecv >> cmpctblock; bool received_new_header = false; { LOCK(cs_main); if (!LookupBlockIndex(cmpctblock.header.hashPrevBlock)) { // Doesn't connect (or is genesis), instead of DoSing in AcceptBlockHeader, request deeper headers if (!IsInitialBlockDownload()) connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexBestHeader), uint256())); return true; } if (!LookupBlockIndex(cmpctblock.header.GetHash())) { received_new_header = true; } } const CBlockIndex *pindex = nullptr; CValidationState state; if (!ProcessNewBlockHeaders({cmpctblock.header}, state, chainparams, &pindex)) { int nDoS; if (state.IsInvalid(nDoS)) { if (nDoS > 0) { LOCK(cs_main); Misbehaving(pfrom->GetId(), nDoS, strprintf("Peer %d sent us invalid header via cmpctblock", pfrom->GetId())); } else { LogPrint(BCLog::NET, "Peer %d sent us invalid header via cmpctblock\n", pfrom->GetId()); } return true; } } // When we succeed in decoding a block's txids from a cmpctblock // message we typically jump to the BLOCKTXN handling code, with a // dummy (empty) BLOCKTXN message, to re-use the logic there in // completing processing of the putative block (without cs_main). bool fProcessBLOCKTXN = false; CDataStream blockTxnMsg(SER_NETWORK, PROTOCOL_VERSION); // If we end up treating this as a plain headers message, call that as well // without cs_main. bool fRevertToHeaderProcessing = false; // Keep a CBlock for "optimistic" compactblock reconstructions (see // below) std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>(); bool fBlockReconstructed = false; { LOCK2(cs_main, g_cs_orphans); // If AcceptBlockHeader returned true, it set pindex assert(pindex); UpdateBlockAvailability(pfrom->GetId(), pindex->GetBlockHash()); CNodeState *nodestate = State(pfrom->GetId()); // If this was a new header with more work than our tip, update the // peer's last block announcement time if (received_new_header && pindex->nChainWork > chainActive.Tip()->nChainWork) { nodestate->m_last_block_announcement = GetTime(); } std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator blockInFlightIt = mapBlocksInFlight.find(pindex->GetBlockHash()); bool fAlreadyInFlight = blockInFlightIt != mapBlocksInFlight.end(); if (pindex->nStatus & BLOCK_HAVE_DATA) // Nothing to do here return true; if (pindex->nChainWork <= chainActive.Tip()->nChainWork || // We know something better pindex->nTx != 0) { // We had this block at some point, but pruned it if (fAlreadyInFlight) { // We requested this block for some reason, but our mempool will probably be useless // so we just grab the block via normal getdata std::vector<CInv> vInv(1); vInv[0] = CInv(MSG_BLOCK, cmpctblock.header.GetHash()); connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv)); } return true; } // If we're not close to tip yet, give up and let parallel block fetch work its magic if (!fAlreadyInFlight && !CanDirectFetch(chainparams.GetConsensus())) return true; // We want to be a bit conservative just to be extra careful about DoS // possibilities in compact block processing... if (pindex->nHeight <= chainActive.Height() + 2) { if ((!fAlreadyInFlight && nodestate->nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) || (fAlreadyInFlight && blockInFlightIt->second.first == pfrom->GetId())) { std::list<QueuedBlock>::iterator *queuedBlockIt = nullptr; if (!MarkBlockAsInFlight(pfrom->GetId(), pindex->GetBlockHash(), pindex, &queuedBlockIt)) { if (!(*queuedBlockIt)->partialBlock) (*queuedBlockIt)->partialBlock.reset(new PartiallyDownloadedBlock(&mempool)); else { // The block was already in flight using compact blocks from the same peer LogPrint(BCLog::NET, "Peer sent us compact block we were already syncing!\n"); return true; } } PartiallyDownloadedBlock& partialBlock = *(*queuedBlockIt)->partialBlock; ReadStatus status = partialBlock.InitData(cmpctblock, vExtraTxnForCompact); if (status == READ_STATUS_INVALID) { MarkBlockAsReceived(pindex->GetBlockHash()); // Reset in-flight state in case of whitelist Misbehaving(pfrom->GetId(), 100, strprintf("Peer %d sent us invalid compact block", pfrom->GetId())); return true; } else if (status == READ_STATUS_FAILED) { // Duplicate txindexes, the block is now in-flight, so just request it std::vector<CInv> vInv(1); vInv[0] = CInv(MSG_BLOCK, cmpctblock.header.GetHash()); connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv)); return true; } BlockTransactionsRequest req; for (size_t i = 0; i < cmpctblock.BlockTxCount(); i++) { if (!partialBlock.IsTxAvailable(i)) req.indexes.push_back(i); } if (req.indexes.empty()) { // Dirty hack to jump to BLOCKTXN code (TODO: move message handling into their own functions) BlockTransactions txn; txn.blockhash = cmpctblock.header.GetHash(); blockTxnMsg << txn; fProcessBLOCKTXN = true; } else { req.blockhash = pindex->GetBlockHash(); connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETBLOCKTXN, req)); } } else { // This block is either already in flight from a different // peer, or this peer has too many blocks outstanding to // download from. // Optimistically try to reconstruct anyway since we might be // able to without any round trips. PartiallyDownloadedBlock tempBlock(&mempool); ReadStatus status = tempBlock.InitData(cmpctblock, vExtraTxnForCompact); if (status != READ_STATUS_OK) { // TODO: don't ignore failures return true; } std::vector<CTransactionRef> dummy; status = tempBlock.FillBlock(*pblock, dummy); if (status == READ_STATUS_OK) { fBlockReconstructed = true; } } } else { if (fAlreadyInFlight) { // We requested this block, but its far into the future, so our // mempool will probably be useless - request the block normally std::vector<CInv> vInv(1); vInv[0] = CInv(MSG_BLOCK, cmpctblock.header.GetHash()); connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, vInv)); return true; } else { // If this was an announce-cmpctblock, we want the same treatment as a header message fRevertToHeaderProcessing = true; } } } // cs_main if (fProcessBLOCKTXN) return ProcessMessage(pfrom, NetMsgType::BLOCKTXN, blockTxnMsg, nTimeReceived, chainparams, connman, interruptMsgProc, enable_bip61); if (fRevertToHeaderProcessing) { // Headers received from HB compact block peers are permitted to be // relayed before full validation (see BIP 152), so we don't want to disconnect // the peer if the header turns out to be for an invalid block. // Note that if a peer tries to build on an invalid chain, that // will be detected and the peer will be banned. return ProcessHeadersMessage(pfrom, connman, {cmpctblock.header}, chainparams, /*punish_duplicate_invalid=*/false); } if (fBlockReconstructed) { // If we got here, we were able to optimistically reconstruct a // block that is in flight from some other peer. { LOCK(cs_main); mapBlockSource.emplace(pblock->GetHash(), std::make_pair(pfrom->GetId(), false)); } bool fNewBlock = false; // Setting fForceProcessing to true means that we bypass some of // our anti-DoS protections in AcceptBlock, which filters // unrequested blocks that might be trying to waste our resources // (eg disk space). Because we only try to reconstruct blocks when // we're close to caught up (via the CanDirectFetch() requirement // above, combined with the behavior of not requesting blocks until // we have a chain with at least nMinimumChainWork), and we ignore // compact blocks with less work than our tip, it is safe to treat // reconstructed compact blocks as having been requested. ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock); if (fNewBlock) { pfrom->nLastBlockTime = GetTime(); } else { LOCK(cs_main); mapBlockSource.erase(pblock->GetHash()); } LOCK(cs_main); // hold cs_main for CBlockIndex::IsValid() if (pindex->IsValid(BLOCK_VALID_TRANSACTIONS)) { // Clear download state for this block, which is in // process from some other peer. We do this after calling // ProcessNewBlock so that a malleated cmpctblock announcement // can't be used to interfere with block relay. MarkBlockAsReceived(pblock->GetHash()); } } return true; } if (strCommand == NetMsgType::BLOCKTXN && !fImporting && !fReindex) // Ignore blocks received while importing { BlockTransactions resp; vRecv >> resp; std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>(); bool fBlockRead = false; { LOCK(cs_main); std::map<uint256, std::pair<NodeId, std::list<QueuedBlock>::iterator> >::iterator it = mapBlocksInFlight.find(resp.blockhash); if (it == mapBlocksInFlight.end() || !it->second.second->partialBlock || it->second.first != pfrom->GetId()) { LogPrint(BCLog::NET, "Peer %d sent us block transactions for block we weren't expecting\n", pfrom->GetId()); return true; } PartiallyDownloadedBlock& partialBlock = *it->second.second->partialBlock; ReadStatus status = partialBlock.FillBlock(*pblock, resp.txn); if (status == READ_STATUS_INVALID) { MarkBlockAsReceived(resp.blockhash); // Reset in-flight state in case of whitelist Misbehaving(pfrom->GetId(), 100, strprintf("Peer %d sent us invalid compact block/non-matching block transactions", pfrom->GetId())); return true; } else if (status == READ_STATUS_FAILED) { // Might have collided, fall back to getdata now :( std::vector<CInv> invs; invs.push_back(CInv(MSG_BLOCK, resp.blockhash)); connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::GETDATA, invs)); } else { // Block is either okay, or possibly we received // READ_STATUS_CHECKBLOCK_FAILED. // Note that CheckBlock can only fail for one of a few reasons: // 1. bad-proof-of-work (impossible here, because we've already // accepted the header) // 2. merkleroot doesn't match the transactions given (already // caught in FillBlock with READ_STATUS_FAILED, so // impossible here) // 3. the block is otherwise invalid (eg invalid coinbase, // block is too big, too many legacy sigops, etc). // So if CheckBlock failed, #3 is the only possibility. // Under BIP 152, we don't DoS-ban unless proof of work is // invalid (we don't require all the stateless checks to have // been run). This is handled below, so just treat this as // though the block was successfully read, and rely on the // handling in ProcessNewBlock to ensure the block index is // updated, reject messages go out, etc. MarkBlockAsReceived(resp.blockhash); // it is now an empty pointer fBlockRead = true; // mapBlockSource is only used for sending reject messages and DoS scores, // so the race between here and cs_main in ProcessNewBlock is fine. // BIP 152 permits peers to relay compact blocks after validating // the header only; we should not punish peers if the block turns // out to be invalid. mapBlockSource.emplace(resp.blockhash, std::make_pair(pfrom->GetId(), false)); } } // Don't hold cs_main when we call into ProcessNewBlock if (fBlockRead) { bool fNewBlock = false; // Since we requested this block (it was in mapBlocksInFlight), force it to be processed, // even if it would not be a candidate for new tip (missing previous block, chain not long enough, etc) // This bypasses some anti-DoS logic in AcceptBlock (eg to prevent // disk-space attacks), but this should be safe due to the // protections in the compact block handler -- see related comment // in compact block optimistic reconstruction handling. ProcessNewBlock(chainparams, pblock, /*fForceProcessing=*/true, &fNewBlock); if (fNewBlock) { pfrom->nLastBlockTime = GetTime(); } else { LOCK(cs_main); mapBlockSource.erase(pblock->GetHash()); } } return true; } if (strCommand == NetMsgType::HEADERS && !fImporting && !fReindex) // Ignore headers received while importing { std::vector<CBlockHeader> headers; // Bypass the normal CBlock deserialization, as we don't want to risk deserializing 2000 full blocks. unsigned int nCount = ReadCompactSize(vRecv); if (nCount > MAX_HEADERS_RESULTS) { LOCK(cs_main); Misbehaving(pfrom->GetId(), 20, strprintf("headers message size = %u", nCount)); return false; } headers.resize(nCount); for (unsigned int n = 0; n < nCount; n++) { vRecv >> headers[n]; ReadCompactSize(vRecv); // ignore tx count; assume it is 0. } // Headers received via a HEADERS message should be valid, and reflect // the chain the peer is on. If we receive a known-invalid header, // disconnect the peer if it is using one of our outbound connection // slots. bool should_punish = !pfrom->fInbound && !pfrom->m_manual_connection; return ProcessHeadersMessage(pfrom, connman, headers, chainparams, should_punish); } if (strCommand == NetMsgType::BLOCK && !fImporting && !fReindex) // Ignore blocks received while importing { std::shared_ptr<CBlock> pblock = std::make_shared<CBlock>(); vRecv >> *pblock; LogPrint(BCLog::NET, "received block %s peer=%d\n", pblock->GetHash().ToString(), pfrom->GetId()); bool forceProcessing = false; const uint256 hash(pblock->GetHash()); { LOCK(cs_main); // Also always process if we requested the block explicitly, as we may // need it even though it is not a candidate for a new best tip. forceProcessing |= MarkBlockAsReceived(hash); // mapBlockSource is only used for sending reject messages and DoS scores, // so the race between here and cs_main in ProcessNewBlock is fine. mapBlockSource.emplace(hash, std::make_pair(pfrom->GetId(), true)); } bool fNewBlock = false; ProcessNewBlock(chainparams, pblock, forceProcessing, &fNewBlock); if (fNewBlock) { pfrom->nLastBlockTime = GetTime(); } else { LOCK(cs_main); mapBlockSource.erase(pblock->GetHash()); } return true; } if (strCommand == NetMsgType::GETADDR) { // This asymmetric behavior for inbound and outbound connections was introduced // to prevent a fingerprinting attack: an attacker can send specific fake addresses // to users' AddrMan and later request them by sending getaddr messages. // Making nodes which are behind NAT and can only make outgoing connections ignore // the getaddr message mitigates the attack. if (!pfrom->fInbound) { LogPrint(BCLog::NET, "Ignoring \"getaddr\" from outbound connection. peer=%d\n", pfrom->GetId()); return true; } // Only send one GetAddr response per connection to reduce resource waste // and discourage addr stamping of INV announcements. if (pfrom->fSentAddr) { LogPrint(BCLog::NET, "Ignoring repeated \"getaddr\". peer=%d\n", pfrom->GetId()); return true; } pfrom->fSentAddr = true; pfrom->vAddrToSend.clear(); std::vector<CAddress> vAddr = connman->GetAddresses(); FastRandomContext insecure_rand; for (const CAddress &addr : vAddr) pfrom->PushAddress(addr, insecure_rand); return true; } if (strCommand == NetMsgType::MEMPOOL) { if (!(pfrom->GetLocalServices() & NODE_BLOOM) && !pfrom->fWhitelisted) { LogPrint(BCLog::NET, "mempool request with bloom filters disabled, disconnect peer=%d\n", pfrom->GetId()); pfrom->fDisconnect = true; return true; } if (connman->OutboundTargetReached(false) && !pfrom->fWhitelisted) { LogPrint(BCLog::NET, "mempool request with bandwidth limit reached, disconnect peer=%d\n", pfrom->GetId()); pfrom->fDisconnect = true; return true; } LOCK(pfrom->cs_inventory); pfrom->fSendMempool = true; return true; } if (strCommand == NetMsgType::PING) { uint64_t nonce = 0; vRecv >> nonce; // Echo the message back with the nonce. This allows for two useful features: // // 1) A remote node can quickly check if the connection is operational // 2) Remote nodes can measure the latency of the network thread. If this node // is overloaded it won't respond to pings quickly and the remote node can // avoid sending us more work, like chain download requests. // // The nonce stops the remote getting confused between different pings: without // it, if the remote node sends a ping once per second and this node takes 5 // seconds to respond to each, the 5th ping the remote sends would appear to // return very quickly. connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::PONG, nonce)); return true; } if (strCommand == NetMsgType::PONG) { int64_t pingUsecEnd = nTimeReceived; uint64_t nonce = 0; size_t nAvail = vRecv.in_avail(); bool bPingFinished = false; std::string sProblem; if (nAvail >= sizeof(nonce)) { vRecv >> nonce; // Only process pong message if there is an outstanding ping (old ping without nonce should never pong) if (pfrom->nPingNonceSent != 0) { if (nonce == pfrom->nPingNonceSent) { // Matching pong received, this ping is no longer outstanding bPingFinished = true; int64_t pingUsecTime = pingUsecEnd - pfrom->nPingUsecStart; if (pingUsecTime > 0) { // Successful ping time measurement, replace previous pfrom->nPingUsecTime = pingUsecTime; pfrom->nMinPingUsecTime = std::min(pfrom->nMinPingUsecTime.load(), pingUsecTime); } else { // This should never happen sProblem = "Timing mishap"; } } else { // Nonce mismatches are normal when pings are overlapping sProblem = "Nonce mismatch"; if (nonce == 0) { // This is most likely a bug in another implementation somewhere; cancel this ping bPingFinished = true; sProblem = "Nonce zero"; } } } else { sProblem = "Unsolicited pong without ping"; } } else { // This is most likely a bug in another implementation somewhere; cancel this ping bPingFinished = true; sProblem = "Short payload"; } if (!(sProblem.empty())) { LogPrint(BCLog::NET, "pong peer=%d: %s, %x expected, %x received, %u bytes\n", pfrom->GetId(), sProblem, pfrom->nPingNonceSent, nonce, nAvail); } if (bPingFinished) { pfrom->nPingNonceSent = 0; } return true; } if (strCommand == NetMsgType::FILTERLOAD) { CBloomFilter filter; vRecv >> filter; if (!filter.IsWithinSizeConstraints()) { // There is no excuse for sending a too-large filter LOCK(cs_main); Misbehaving(pfrom->GetId(), 100); } else { LOCK(pfrom->cs_filter); pfrom->pfilter.reset(new CBloomFilter(filter)); pfrom->pfilter->UpdateEmptyFull(); pfrom->fRelayTxes = true; } return true; } if (strCommand == NetMsgType::FILTERADD) { std::vector<unsigned char> vData; vRecv >> vData; // Nodes must NEVER send a data item > 520 bytes (the max size for a script data object, // and thus, the maximum size any matched object can have) in a filteradd message bool bad = false; if (vData.size() > MAX_SCRIPT_ELEMENT_SIZE) { bad = true; } else { LOCK(pfrom->cs_filter); if (pfrom->pfilter) { pfrom->pfilter->insert(vData); } else { bad = true; } } if (bad) { LOCK(cs_main); Misbehaving(pfrom->GetId(), 100); } return true; } if (strCommand == NetMsgType::FILTERCLEAR) { LOCK(pfrom->cs_filter); if (pfrom->GetLocalServices() & NODE_BLOOM) { pfrom->pfilter = nullptr; } pfrom->fRelayTxes = true; return true; } if (strCommand == NetMsgType::GETMNLISTDIFF) { CGetSimplifiedMNListDiff cmd; vRecv >> cmd; LOCK(cs_main); CSimplifiedMNListDiff mnListDiff; std::string strError; if (BuildSimplifiedMNListDiff(cmd.baseBlockHash, cmd.blockHash, mnListDiff, strError)) { connman->PushMessage(pfrom, msgMaker.Make(NetMsgType::MNLISTDIFF, mnListDiff)); } else { strError = strprintf("getmnlistdiff failed for baseBlockHash=%s, blockHash=%s. error=%s", cmd.baseBlockHash.ToString(), cmd.blockHash.ToString(), strError); Misbehaving(pfrom->GetId(), 1, strError); } return true; } if (strCommand == NetMsgType::MNLISTDIFF) { // we have never requested this LOCK(cs_main); Misbehaving(pfrom->GetId(), 100, strprintf("received not-requested mnlistdiff. peer=%d", pfrom->GetId())); return true; } if (strCommand == NetMsgType::NOTFOUND) { // Remove the NOTFOUND transactions from the peer LOCK(cs_main); CNodeState *state = State(pfrom->GetId()); std::vector<CInv> vInv; vRecv >> vInv; if (vInv.size() <= MAX_PEER_OBJECT_IN_FLIGHT + MAX_BLOCKS_IN_TRANSIT_PER_PEER) { for (CInv &inv : vInv) { if (inv.IsKnownType()) { // If we receive a NOTFOUND message for a txid we requested, erase // it from our data structures for this peer. auto in_flight_it = state->m_object_download.m_object_in_flight.find(inv); if (in_flight_it == state->m_object_download.m_object_in_flight.end()) { // Skip any further work if this is a spurious NOTFOUND // message. continue; } state->m_object_download.m_object_in_flight.erase(in_flight_it); state->m_object_download.m_object_announced.erase(inv); } } } return true; } bool found = false; const std::vector<std::string> &allMessages = getAllNetMessageTypes(); for (const std::string msg : allMessages) { if(msg == strCommand) { found = true; break; } } if (found) { //probably one the extensions #ifdef ENABLE_WALLET coinJoinClientQueueManager.ProcessMessage(pfrom, strCommand, vRecv, *connman, enable_bip61); for (auto& pair : coinJoinClientManagers) { pair.second->ProcessMessage(pfrom, strCommand, vRecv, *connman, enable_bip61); } #endif // ENABLE_WALLET coinJoinServer.ProcessMessage(pfrom, strCommand, vRecv, *connman, enable_bip61); sporkManager.ProcessSpork(pfrom, strCommand, vRecv, *connman); masternodeSync.ProcessMessage(pfrom, strCommand, vRecv); governance.ProcessMessage(pfrom, strCommand, vRecv, *connman, enable_bip61); CMNAuth::ProcessMessage(pfrom, strCommand, vRecv, *connman); llmq::quorumBlockProcessor->ProcessMessage(pfrom, strCommand, vRecv); llmq::quorumDKGSessionManager->ProcessMessage(pfrom, strCommand, vRecv); llmq::quorumManager->ProcessMessage(pfrom, strCommand, vRecv); llmq::quorumSigSharesManager->ProcessMessage(pfrom, strCommand, vRecv); llmq::quorumSigningManager->ProcessMessage(pfrom, strCommand, vRecv); llmq::chainLocksHandler->ProcessMessage(pfrom, strCommand, vRecv); llmq::quorumInstantSendManager->ProcessMessage(pfrom, strCommand, vRecv); return true; } // Ignore unknown commands for extensibility LogPrint(BCLog::NET, "Unknown command \"%s\" from peer=%d\n", SanitizeString(strCommand), pfrom->GetId()); return true; } static bool SendRejectsAndCheckIfBanned(CNode* pnode, CConnman* connman, bool enable_bip61) { AssertLockHeld(cs_main); CNodeState &state = *State(pnode->GetId()); if (enable_bip61) { for (const CBlockReject& reject : state.rejects) { connman->PushMessage(pnode, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, std::string(NetMsgType::BLOCK), reject.chRejectCode, reject.strRejectReason, reject.hashBlock)); } } state.rejects.clear(); if (state.fShouldBan) { state.fShouldBan = false; if (pnode->fWhitelisted) LogPrintf("Warning: not punishing whitelisted peer %s!\n", pnode->GetLogString()); else if (pnode->m_manual_connection) LogPrintf("Warning: not punishing manually-connected peer %s!\n", pnode->GetLogString()); else { pnode->fDisconnect = true; if (pnode->addr.IsLocal()) LogPrintf("Warning: not banning local peer %s!\n", pnode->GetLogString()); else { connman->Ban(pnode->addr, BanReasonNodeMisbehaving); } } return true; } return false; } bool PeerLogicValidation::ProcessMessages(CNode* pfrom, std::atomic<bool>& interruptMsgProc) { const CChainParams& chainparams = Params(); // // Message format // (4) message start // (12) command // (4) size // (4) checksum // (x) data // bool fMoreWork = false; if (!pfrom->vRecvGetData.empty()) ProcessGetData(pfrom, chainparams, connman, interruptMsgProc); if (!pfrom->orphan_work_set.empty()) { LOCK2(cs_main, g_cs_orphans); ProcessOrphanTx(connman, pfrom->orphan_work_set); } if (pfrom->fDisconnect) return false; // this maintains the order of responses if (!pfrom->vRecvGetData.empty()) return true; if (!pfrom->orphan_work_set.empty()) return true; // Don't bother if send buffer is too full to respond anyway if (pfrom->fPauseSend) return false; std::list<CNetMessage> msgs; { LOCK(pfrom->cs_vProcessMsg); if (pfrom->vProcessMsg.empty()) return false; // Just take one message msgs.splice(msgs.begin(), pfrom->vProcessMsg, pfrom->vProcessMsg.begin()); pfrom->nProcessQueueSize -= msgs.front().vRecv.size() + CMessageHeader::HEADER_SIZE; pfrom->fPauseRecv = pfrom->nProcessQueueSize > connman->GetReceiveFloodSize(); fMoreWork = !pfrom->vProcessMsg.empty(); } CNetMessage& msg(msgs.front()); msg.SetVersion(pfrom->GetRecvVersion()); // Scan for message start if (memcmp(msg.hdr.pchMessageStart, chainparams.MessageStart(), CMessageHeader::MESSAGE_START_SIZE) != 0) { LogPrint(BCLog::NET, "PROCESSMESSAGE: INVALID MESSAGESTART %s peer=%d\n", SanitizeString(msg.hdr.GetCommand()), pfrom->GetId()); pfrom->fDisconnect = true; return false; } // Read header CMessageHeader& hdr = msg.hdr; if (!hdr.IsValid(chainparams.MessageStart())) { LogPrint(BCLog::NET, "PROCESSMESSAGE: ERRORS IN HEADER %s peer=%d\n", SanitizeString(hdr.GetCommand()), pfrom->GetId()); return fMoreWork; } std::string strCommand = hdr.GetCommand(); // Message size unsigned int nMessageSize = hdr.nMessageSize; // Checksum CDataStream& vRecv = msg.vRecv; const uint256& hash = msg.GetMessageHash(); if (memcmp(hash.begin(), hdr.pchChecksum, CMessageHeader::CHECKSUM_SIZE) != 0) { LogPrint(BCLog::NET, "%s(%s, %u bytes): CHECKSUM ERROR expected %s was %s\n", __func__, SanitizeString(strCommand), nMessageSize, HexStr(hash.begin(), hash.begin()+CMessageHeader::CHECKSUM_SIZE), HexStr(hdr.pchChecksum, hdr.pchChecksum+CMessageHeader::CHECKSUM_SIZE)); return fMoreWork; } // Process message bool fRet = false; try { fRet = ProcessMessage(pfrom, strCommand, vRecv, msg.nTime, chainparams, connman, interruptMsgProc, m_enable_bip61); if (interruptMsgProc) return false; if (!pfrom->vRecvGetData.empty()) fMoreWork = true; } catch (const std::ios_base::failure& e) { if (m_enable_bip61) { connman->PushMessage(pfrom, CNetMsgMaker(INIT_PROTO_VERSION).Make(NetMsgType::REJECT, strCommand, REJECT_MALFORMED, std::string("error parsing message"))); } if (strstr(e.what(), "end of data")) { // Allow exceptions from under-length message on vRecv LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' caught, normally caused by a message being shorter than its stated length\n", __func__, SanitizeString(strCommand), nMessageSize, e.what()); } else if (strstr(e.what(), "size too large")) { // Allow exceptions from over-long size LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what()); } else if (strstr(e.what(), "non-canonical ReadCompactSize()")) { // Allow exceptions from non-canonical encoding LogPrint(BCLog::NET, "%s(%s, %u bytes): Exception '%s' caught\n", __func__, SanitizeString(strCommand), nMessageSize, e.what()); } else { PrintExceptionContinue(std::current_exception(), "ProcessMessages()"); } } catch (...) { PrintExceptionContinue(std::current_exception(), "ProcessMessages()"); } if (!fRet) { LogPrint(BCLog::NET, "%s(%s, %u bytes) FAILED peer=%d\n", __func__, SanitizeString(strCommand), nMessageSize, pfrom->GetId()); } LOCK(cs_main); SendRejectsAndCheckIfBanned(pfrom, connman, m_enable_bip61); return fMoreWork; } void PeerLogicValidation::ConsiderEviction(CNode *pto, int64_t time_in_seconds) { AssertLockHeld(cs_main); CNodeState &state = *State(pto->GetId()); const CNetMsgMaker msgMaker(pto->GetSendVersion()); if (!state.m_chain_sync.m_protect && IsOutboundDisconnectionCandidate(pto) && state.fSyncStarted) { // This is an outbound peer subject to disconnection if they don't // announce a block with as much work as the current tip within // CHAIN_SYNC_TIMEOUT + HEADERS_RESPONSE_TIME seconds (note: if // their chain has more work than ours, we should sync to it, // unless it's invalid, in which case we should find that out and // disconnect from them elsewhere). if (state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= chainActive.Tip()->nChainWork) { if (state.m_chain_sync.m_timeout != 0) { state.m_chain_sync.m_timeout = 0; state.m_chain_sync.m_work_header = nullptr; state.m_chain_sync.m_sent_getheaders = false; } } else if (state.m_chain_sync.m_timeout == 0 || (state.m_chain_sync.m_work_header != nullptr && state.pindexBestKnownBlock != nullptr && state.pindexBestKnownBlock->nChainWork >= state.m_chain_sync.m_work_header->nChainWork)) { // Our best block known by this peer is behind our tip, and we're either noticing // that for the first time, OR this peer was able to catch up to some earlier point // where we checked against our tip. // Either way, set a new timeout based on current tip. state.m_chain_sync.m_timeout = time_in_seconds + CHAIN_SYNC_TIMEOUT; state.m_chain_sync.m_work_header = chainActive.Tip(); state.m_chain_sync.m_sent_getheaders = false; } else if (state.m_chain_sync.m_timeout > 0 && time_in_seconds > state.m_chain_sync.m_timeout) { // No evidence yet that our peer has synced to a chain with work equal to that // of our tip, when we first detected it was behind. Send a single getheaders // message to give the peer a chance to update us. if (state.m_chain_sync.m_sent_getheaders) { // They've run out of time to catch up! LogPrintf("Disconnecting outbound peer %d for old chain, best known block = %s\n", pto->GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>"); pto->fDisconnect = true; } else { assert(state.m_chain_sync.m_work_header); LogPrint(BCLog::NET, "sending getheaders to outbound peer=%d to verify chain work (current best known block:%s, benchmark blockhash: %s)\n", pto->GetId(), state.pindexBestKnownBlock != nullptr ? state.pindexBestKnownBlock->GetBlockHash().ToString() : "<none>", state.m_chain_sync.m_work_header->GetBlockHash().ToString()); connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(state.m_chain_sync.m_work_header->pprev), uint256())); state.m_chain_sync.m_sent_getheaders = true; constexpr int64_t HEADERS_RESPONSE_TIME = 120; // 2 minutes // Bump the timeout to allow a response, which could clear the timeout // (if the response shows the peer has synced), reset the timeout (if // the peer syncs to the required work but not to our tip), or result // in disconnect (if we advance to the timeout and pindexBestKnownBlock // has not sufficiently progressed) state.m_chain_sync.m_timeout = time_in_seconds + HEADERS_RESPONSE_TIME; } } } } void PeerLogicValidation::EvictExtraOutboundPeers(int64_t time_in_seconds) { // Check whether we have too many outbound peers int extra_peers = connman->GetExtraOutboundCount(); if (extra_peers > 0) { // If we have more outbound peers than we target, disconnect one. // Pick the outbound peer that least recently announced // us a new block, with ties broken by choosing the more recent // connection (higher node id) NodeId worst_peer = -1; int64_t oldest_block_announcement = std::numeric_limits<int64_t>::max(); connman->ForEachNode([&](CNode* pnode) { AssertLockHeld(cs_main); // Don't disconnect masternodes just because they were slow in block announcement if (pnode->m_masternode_connection) return; // Ignore non-outbound peers, or nodes marked for disconnect already if (!IsOutboundDisconnectionCandidate(pnode) || pnode->fDisconnect) return; CNodeState *state = State(pnode->GetId()); if (state == nullptr) return; // shouldn't be possible, but just in case // Don't evict our protected peers if (state->m_chain_sync.m_protect) return; if (state->m_last_block_announcement < oldest_block_announcement || (state->m_last_block_announcement == oldest_block_announcement && pnode->GetId() > worst_peer)) { worst_peer = pnode->GetId(); oldest_block_announcement = state->m_last_block_announcement; } }); if (worst_peer != -1) { bool disconnected = connman->ForNode(worst_peer, [&](CNode *pnode) { AssertLockHeld(cs_main); // Only disconnect a peer that has been connected to us for // some reasonable fraction of our check-frequency, to give // it time for new information to have arrived. // Also don't disconnect any peer we're trying to download a // block from. CNodeState &state = *State(pnode->GetId()); if (time_in_seconds - pnode->nTimeConnected > MINIMUM_CONNECT_TIME && state.nBlocksInFlight == 0) { LogPrint(BCLog::NET, "disconnecting extra outbound peer=%d (last block announcement received at time %d)\n", pnode->GetId(), oldest_block_announcement); pnode->fDisconnect = true; return true; } else { LogPrint(BCLog::NET, "keeping outbound peer=%d chosen for eviction (connect time: %d, blocks_in_flight: %d)\n", pnode->GetId(), pnode->nTimeConnected, state.nBlocksInFlight); return false; } }); if (disconnected) { // If we disconnected an extra peer, that means we successfully // connected to at least one peer after the last time we // detected a stale tip. Don't try any more extra peers until // we next detect a stale tip, to limit the load we put on the // network from these extra connections. connman->SetTryNewOutboundPeer(false); } } } } void PeerLogicValidation::CheckForStaleTipAndEvictPeers(const Consensus::Params &consensusParams) { LOCK(cs_main); if (connman == nullptr) return; int64_t time_in_seconds = GetTime(); EvictExtraOutboundPeers(time_in_seconds); if (time_in_seconds > m_stale_tip_check_time) { // Check whether our tip is stale, and if so, allow using an extra // outbound peer if (!fImporting && !fReindex && connman->GetNetworkActive() && connman->GetUseAddrmanOutgoing() && TipMayBeStale(consensusParams)) { LogPrintf("Potential stale tip detected, will try using extra outbound peer (last tip update: %d seconds ago)\n", time_in_seconds - g_last_tip_update); connman->SetTryNewOutboundPeer(true); } else if (connman->GetTryNewOutboundPeer()) { connman->SetTryNewOutboundPeer(false); } m_stale_tip_check_time = time_in_seconds + STALE_CHECK_INTERVAL; } } namespace { class CompareInvMempoolOrder { CTxMemPool *mp; public: explicit CompareInvMempoolOrder(CTxMemPool *_mempool) { mp = _mempool; } bool operator()(std::set<uint256>::iterator a, std::set<uint256>::iterator b) { /* As std::make_heap produces a max-heap, we want the entries with the * fewest ancestors/highest fee to sort later. */ return mp->CompareDepthAndScore(*b, *a); } }; } bool PeerLogicValidation::SendMessages(CNode* pto) { const Consensus::Params& consensusParams = Params().GetConsensus(); { // Don't send anything until the version handshake is complete if (!pto->fSuccessfullyConnected || pto->fDisconnect) return true; // If we get here, the outgoing message serialization version is set and can't change. const CNetMsgMaker msgMaker(pto->GetSendVersion()); // // Message: ping // bool pingSend = false; if (pto->fPingQueued) { // RPC ping request by user pingSend = true; } if (pto->nPingNonceSent == 0 && pto->nPingUsecStart + PING_INTERVAL * 1000000 < GetTimeMicros()) { // Ping automatically sent as a latency probe & keepalive. pingSend = true; } if (pingSend) { uint64_t nonce = 0; while (nonce == 0) { GetRandBytes((unsigned char*)&nonce, sizeof(nonce)); } pto->fPingQueued = false; pto->nPingUsecStart = GetTimeMicros(); pto->nPingNonceSent = nonce; connman->PushMessage(pto, msgMaker.Make(NetMsgType::PING, nonce)); } TRY_LOCK(cs_main, lockMain); // Acquire cs_main for IsInitialBlockDownload() and CNodeState() if (!lockMain) return true; if (SendRejectsAndCheckIfBanned(pto, connman, m_enable_bip61)) return true; CNodeState &state = *State(pto->GetId()); // Address refresh broadcast int64_t nNow = GetTimeMicros(); auto current_time = GetTime<std::chrono::microseconds>(); if (!IsInitialBlockDownload() && pto->nNextLocalAddrSend < nNow) { AdvertiseLocal(pto); pto->nNextLocalAddrSend = PoissonNextSend(nNow, AVG_LOCAL_ADDRESS_BROADCAST_INTERVAL); } // // Message: addr // if (pto->nNextAddrSend < nNow) { pto->nNextAddrSend = PoissonNextSend(nNow, AVG_ADDRESS_BROADCAST_INTERVAL); std::vector<CAddress> vAddr; vAddr.reserve(pto->vAddrToSend.size()); for (const CAddress& addr : pto->vAddrToSend) { if (!pto->addrKnown.contains(addr.GetKey())) { pto->addrKnown.insert(addr.GetKey()); vAddr.push_back(addr); // receiver rejects addr messages larger than 1000 if (vAddr.size() >= 1000) { connman->PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr)); vAddr.clear(); } } } pto->vAddrToSend.clear(); if (!vAddr.empty()) connman->PushMessage(pto, msgMaker.Make(NetMsgType::ADDR, vAddr)); // we only send the big addr message once if (pto->vAddrToSend.capacity() > 40) pto->vAddrToSend.shrink_to_fit(); } // Start block sync if (pindexBestHeader == nullptr) pindexBestHeader = chainActive.Tip(); bool fFetch = state.fPreferredDownload || (nPreferredDownload == 0 && !pto->fClient && !pto->fOneShot); // Download if this is a nice peer, or we have no nice peers and this one might do. if (!state.fSyncStarted && !pto->fClient && !fImporting && !fReindex && pto->CanRelay()) { // Only actively request headers from a single peer, unless we're close to end of initial download. if ((nSyncStarted == 0 && fFetch) || pindexBestHeader->GetBlockTime() > GetAdjustedTime() - nMaxTipAge) { state.fSyncStarted = true; state.nHeadersSyncTimeout = GetTimeMicros() + HEADERS_DOWNLOAD_TIMEOUT_BASE + HEADERS_DOWNLOAD_TIMEOUT_PER_HEADER * (GetAdjustedTime() - pindexBestHeader->GetBlockTime())/(consensusParams.nPowTargetSpacing); nSyncStarted++; const CBlockIndex *pindexStart = pindexBestHeader; /* If possible, start at the block preceding the currently best known header. This ensures that we always get a non-empty list of headers back as long as the peer is up-to-date. With a non-empty response, we can initialise the peer's known best block. This wouldn't be possible if we requested starting at pindexBestHeader and got back an empty response. */ if (pindexStart->pprev) pindexStart = pindexStart->pprev; LogPrint(BCLog::NET, "initial getheaders (%d) to peer=%d (startheight:%d)\n", pindexStart->nHeight, pto->GetId(), pto->nStartingHeight); connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETHEADERS, chainActive.GetLocator(pindexStart), uint256())); } } // Resend wallet transactions that haven't gotten in a block yet // Except during reindex, importing and IBD, when old wallet // transactions become unconfirmed and spams other nodes. if (!fReindex && !fImporting && !IsInitialBlockDownload()) { static int64_t nLastBroadcastTime = 0; // HACK: Call this only once every few seconds. SendMessages is called once per peer, which makes this signal very expensive // The proper solution would be to move this out of here, but this is not worth the effort right now as bitcoin#15632 will later do this. // Luckily, the Broadcast signal is not used for anything else then CWallet::ResendWalletTransactionsBefore. if (nNow - nLastBroadcastTime >= 5000000) { GetMainSignals().Broadcast(nTimeBestReceived, connman); nLastBroadcastTime = nNow; } } // // Try sending block announcements via headers // if (pto->CanRelay()) { // If we have less than MAX_BLOCKS_TO_ANNOUNCE in our // list of block hashes we're relaying, and our peer wants // headers announcements, then find the first header // not yet known to our peer but would connect, and send. // If no header would connect, or if we have too many // blocks, or if the peer doesn't want headers, just // add all to the inv queue. LOCK(pto->cs_inventory); std::vector<CBlock> vHeaders; bool fRevertToInv = ((!state.fPreferHeaders && (!state.fPreferHeaderAndIDs || pto->vBlockHashesToAnnounce.size() > 1)) || pto->vBlockHashesToAnnounce.size() > MAX_BLOCKS_TO_ANNOUNCE); const CBlockIndex *pBestIndex = nullptr; // last header queued for delivery ProcessBlockAvailability(pto->GetId()); // ensure pindexBestKnownBlock is up-to-date if (!fRevertToInv) { bool fFoundStartingHeader = false; // Try to find first header that our peer doesn't have, and // then send all headers past that one. If we come across any // headers that aren't on chainActive, give up. for (const uint256 &hash : pto->vBlockHashesToAnnounce) { const CBlockIndex* pindex = LookupBlockIndex(hash); assert(pindex); if (chainActive[pindex->nHeight] != pindex) { // Bail out if we reorged away from this block fRevertToInv = true; break; } if (pBestIndex != nullptr && pindex->pprev != pBestIndex) { // This means that the list of blocks to announce don't // connect to each other. // This shouldn't really be possible to hit during // regular operation (because reorgs should take us to // a chain that has some block not on the prior chain, // which should be caught by the prior check), but one // way this could happen is by using invalidateblock / // reconsiderblock repeatedly on the tip, causing it to // be added multiple times to vBlockHashesToAnnounce. // Robustly deal with this rare situation by reverting // to an inv. fRevertToInv = true; break; } pBestIndex = pindex; bool isPrevDevnetGenesisBlock = false; if (!consensusParams.hashDevnetGenesisBlock.IsNull() && pindex->pprev != nullptr && pindex->pprev->GetBlockHash() == consensusParams.hashDevnetGenesisBlock) { // even though the devnet genesis block was never transferred through the wire and thus not // appear anywhere in the node state where we track what other nodes have or not have, we can // assume that the other node already knows the devnet genesis block isPrevDevnetGenesisBlock = true; } if (fFoundStartingHeader) { // add this to the headers message vHeaders.push_back(pindex->GetBlockHeader()); } else if (PeerHasHeader(&state, pindex)) { continue; // keep looking for the first new block } else if (pindex->pprev == nullptr || PeerHasHeader(&state, pindex->pprev) || isPrevDevnetGenesisBlock) { // Peer doesn't have this header but they do have the prior one. // Start sending headers. fFoundStartingHeader = true; vHeaders.push_back(pindex->GetBlockHeader()); } else { // Peer doesn't have this header or the prior one -- nothing will // connect, so bail out. fRevertToInv = true; break; } } } if (!fRevertToInv && !vHeaders.empty()) { if (vHeaders.size() == 1 && state.fPreferHeaderAndIDs) { // We only send up to 1 block as header-and-ids, as otherwise // probably means we're doing an initial-ish-sync or they're slow LogPrint(BCLog::NET, "%s sending header-and-ids %s to peer=%d\n", __func__, vHeaders.front().GetHash().ToString(), pto->GetId()); bool fGotBlockFromCache = false; { LOCK(cs_most_recent_block); if (most_recent_block_hash == pBestIndex->GetBlockHash()) { connman->PushMessage(pto, msgMaker.Make(NetMsgType::CMPCTBLOCK, *most_recent_compact_block)); fGotBlockFromCache = true; } } if (!fGotBlockFromCache) { CBlock block; bool ret = ReadBlockFromDisk(block, pBestIndex, consensusParams); assert(ret); CBlockHeaderAndShortTxIDs cmpctblock(block); connman->PushMessage(pto, msgMaker.Make(NetMsgType::CMPCTBLOCK, cmpctblock)); } state.pindexBestHeaderSent = pBestIndex; } else if (state.fPreferHeaders) { if (vHeaders.size() > 1) { LogPrint(BCLog::NET, "%s: %u headers, range (%s, %s), to peer=%d\n", __func__, vHeaders.size(), vHeaders.front().GetHash().ToString(), vHeaders.back().GetHash().ToString(), pto->GetId()); } else { LogPrint(BCLog::NET, "%s: sending header %s to peer=%d\n", __func__, vHeaders.front().GetHash().ToString(), pto->GetId()); } connman->PushMessage(pto, msgMaker.Make(NetMsgType::HEADERS, vHeaders)); state.pindexBestHeaderSent = pBestIndex; } else fRevertToInv = true; } if (fRevertToInv) { // If falling back to using an inv, just try to inv the tip. // The last entry in vBlockHashesToAnnounce was our tip at some point // in the past. if (!pto->vBlockHashesToAnnounce.empty()) { const uint256 &hashToAnnounce = pto->vBlockHashesToAnnounce.back(); const CBlockIndex* pindex = LookupBlockIndex(hashToAnnounce); assert(pindex); // Warn if we're announcing a block that is not on the main chain. // This should be very rare and could be optimized out. // Just log for now. if (chainActive[pindex->nHeight] != pindex) { LogPrint(BCLog::NET, "Announcing block %s not on main chain (tip=%s)\n", hashToAnnounce.ToString(), chainActive.Tip()->GetBlockHash().ToString()); } // If the peer's chain has this block, don't inv it back. if (!PeerHasHeader(&state, pindex)) { pto->PushInventory(CInv(MSG_BLOCK, hashToAnnounce)); LogPrint(BCLog::NET, "%s: sending inv peer=%d hash=%s\n", __func__, pto->GetId(), hashToAnnounce.ToString()); } } } pto->vBlockHashesToAnnounce.clear(); } // // Message: inventory // std::vector<CInv> vInv; { size_t reserve = std::min<size_t>(pto->setInventoryTxToSend.size(), INVENTORY_BROADCAST_MAX_PER_1MB_BLOCK * MaxBlockSize() / 1000000); reserve = std::max<size_t>(reserve, pto->vInventoryBlockToSend.size()); reserve = std::min<size_t>(reserve, MAX_INV_SZ); vInv.reserve(reserve); LOCK2(mempool.cs, pto->cs_inventory); // Add blocks for (const uint256& hash : pto->vInventoryBlockToSend) { vInv.push_back(CInv(MSG_BLOCK, hash)); if (vInv.size() == MAX_INV_SZ) { connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv)); vInv.clear(); } } pto->vInventoryBlockToSend.clear(); // Check whether periodic sends should happen // Note: If this node is running in a Masternode mode, it makes no sense to delay outgoing txes // because we never produce any txes ourselves i.e. no privacy is lost in this case. bool fSendTrickle = pto->fWhitelisted || fMasternodeMode; if (pto->nNextInvSend < current_time) { fSendTrickle = true; if (pto->fInbound) { pto->nNextInvSend = std::chrono::microseconds{connman->PoissonNextSendInbound(current_time.count(), INVENTORY_BROADCAST_INTERVAL)}; } else { // Use half the delay for regular outbound peers, as there is less privacy concern for them. // and quarter the delay for Masternode outbound peers, as there is even less privacy concern in this case. pto->nNextInvSend = PoissonNextSend(current_time, std::chrono::seconds{INVENTORY_BROADCAST_INTERVAL >> 1 >> !pto->verifiedProRegTxHash.IsNull()}); } } // Time to send but the peer has requested we not relay transactions. if (fSendTrickle) { LOCK(pto->cs_filter); if (!pto->fRelayTxes) pto->setInventoryTxToSend.clear(); } auto queueAndMaybePushInv = [this, pto, &vInv, &msgMaker](const CInv& invIn) { AssertLockHeld(pto->cs_inventory); pto->filterInventoryKnown.insert(invIn.hash); LogPrint(BCLog::NET, "SendMessages -- queued inv: %s index=%d peer=%d\n", invIn.ToString(), vInv.size(), pto->GetId()); vInv.push_back(invIn); if (vInv.size() == MAX_INV_SZ) { LogPrint(BCLog::NET, "SendMessages -- pushing invs: count=%d peer=%d\n", vInv.size(), pto->GetId()); connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv)); vInv.clear(); } }; // Respond to BIP35 mempool requests if (fSendTrickle && pto->fSendMempool) { auto vtxinfo = mempool.infoAll(); pto->fSendMempool = false; LOCK(pto->cs_filter); // Send invs for txes and corresponding IS-locks for (const auto& txinfo : vtxinfo) { const uint256& hash = txinfo.tx->GetHash(); pto->setInventoryTxToSend.erase(hash); if (pto->pfilter && !pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue; int nInvType = CCoinJoin::GetDSTX(hash) ? MSG_DSTX : MSG_TX; queueAndMaybePushInv(CInv(nInvType, hash)); uint256 islockHash; if (!llmq::quorumInstantSendManager->GetInstantSendLockHashByTxid(hash, islockHash)) continue; queueAndMaybePushInv(CInv(MSG_ISLOCK, islockHash)); } // Send an inv for the best ChainLock we have const auto& clsig = llmq::chainLocksHandler->GetBestChainLock(); if (!clsig.IsNull()) { uint256 chainlockHash = ::SerializeHash(clsig); queueAndMaybePushInv(CInv(MSG_CLSIG, chainlockHash)); } pto->timeLastMempoolReq = GetTime(); } // Determine transactions to relay if (fSendTrickle) { // Produce a vector with all candidates for sending std::vector<std::set<uint256>::iterator> vInvTx; vInvTx.reserve(pto->setInventoryTxToSend.size()); for (std::set<uint256>::iterator it = pto->setInventoryTxToSend.begin(); it != pto->setInventoryTxToSend.end(); it++) { vInvTx.push_back(it); } // Topologically and fee-rate sort the inventory we send for privacy and priority reasons. // A heap is used so that not all items need sorting if only a few are being sent. CompareInvMempoolOrder compareInvMempoolOrder(&mempool); std::make_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder); // No reason to drain out at many times the network's capacity, // especially since we have many peers and some will draw much shorter delays. unsigned int nRelayedTransactions = 0; LOCK(pto->cs_filter); while (!vInvTx.empty() && nRelayedTransactions < INVENTORY_BROADCAST_MAX_PER_1MB_BLOCK * MaxBlockSize() / 1000000) { // Fetch the top element from the heap std::pop_heap(vInvTx.begin(), vInvTx.end(), compareInvMempoolOrder); std::set<uint256>::iterator it = vInvTx.back(); vInvTx.pop_back(); uint256 hash = *it; // Remove it from the to-be-sent set pto->setInventoryTxToSend.erase(it); // Check if not in the filter already if (pto->filterInventoryKnown.contains(hash)) { continue; } // Not in the mempool anymore? don't bother sending it. auto txinfo = mempool.info(hash); if (!txinfo.tx) { continue; } if (pto->pfilter && !pto->pfilter->IsRelevantAndUpdate(*txinfo.tx)) continue; // Send nRelayedTransactions++; { // Expire old relay messages while (!vRelayExpiration.empty() && vRelayExpiration.front().first < nNow) { mapRelay.erase(vRelayExpiration.front().second); vRelayExpiration.pop_front(); } auto ret = mapRelay.insert(std::make_pair(hash, std::move(txinfo.tx))); if (ret.second) { vRelayExpiration.push_back(std::make_pair(nNow + 15 * 60 * 1000000, ret.first)); } } int nInvType = CCoinJoin::GetDSTX(hash) ? MSG_DSTX : MSG_TX; queueAndMaybePushInv(CInv(nInvType, hash)); } } // Send non-tx/non-block inventory items for (const auto& inv : pto->vInventoryOtherToSend) { if (pto->filterInventoryKnown.contains(inv.hash)) { continue; } queueAndMaybePushInv(inv); } pto->vInventoryOtherToSend.clear(); } if (!vInv.empty()) connman->PushMessage(pto, msgMaker.Make(NetMsgType::INV, vInv)); // Detect whether we're stalling current_time = GetTime<std::chrono::microseconds>(); // nNow is the current system time (GetTimeMicros is not mockable) and // should be replaced by the mockable current_time eventually nNow = GetTimeMicros(); if (state.nStallingSince && state.nStallingSince < nNow - 1000000 * BLOCK_STALLING_TIMEOUT) { // Stalling only triggers when the block download window cannot move. During normal steady state, // the download window should be much larger than the to-be-downloaded set of blocks, so disconnection // should only happen during initial block download. LogPrintf("Peer=%d is stalling block download, disconnecting\n", pto->GetId()); pto->fDisconnect = true; return true; } // In case there is a block that has been in flight from this peer for 2 + 0.5 * N times the block interval // (with N the number of peers from which we're downloading validated blocks), disconnect due to timeout. // We compensate for other peers to prevent killing off peers due to our own downstream link // being saturated. We only count validated in-flight blocks so peers can't advertise non-existing block hashes // to unreasonably increase our timeout. if (state.vBlocksInFlight.size() > 0) { QueuedBlock &queuedBlock = state.vBlocksInFlight.front(); int nOtherPeersWithValidatedDownloads = nPeersWithValidatedDownloads - (state.nBlocksInFlightValidHeaders > 0); if (nNow > state.nDownloadingSince + consensusParams.nPowTargetSpacing * (BLOCK_DOWNLOAD_TIMEOUT_BASE + BLOCK_DOWNLOAD_TIMEOUT_PER_PEER * nOtherPeersWithValidatedDownloads)) { LogPrintf("Timeout downloading block %s from peer=%d, disconnecting\n", queuedBlock.hash.ToString(), pto->GetId()); pto->fDisconnect = true; return true; } } // Check for headers sync timeouts if (state.fSyncStarted && state.nHeadersSyncTimeout < std::numeric_limits<int64_t>::max()) { // Detect whether this is a stalling initial-headers-sync peer if (pindexBestHeader->GetBlockTime() <= GetAdjustedTime() - nMaxTipAge) { if (nNow > state.nHeadersSyncTimeout && nSyncStarted == 1 && (nPreferredDownload - state.fPreferredDownload >= 1)) { // Disconnect a (non-whitelisted) peer if it is our only sync peer, // and we have others we could be using instead. // Note: If all our peers are inbound, then we won't // disconnect our sync peer for stalling; we have bigger // problems if we can't get any outbound peers. if (!pto->fWhitelisted) { LogPrintf("Timeout downloading headers from peer=%d, disconnecting\n", pto->GetId()); pto->fDisconnect = true; return true; } else { LogPrintf("Timeout downloading headers from whitelisted peer=%d, not disconnecting\n", pto->GetId()); // Reset the headers sync state so that we have a // chance to try downloading from a different peer. // Note: this will also result in at least one more // getheaders message to be sent to // this peer (eventually). state.fSyncStarted = false; nSyncStarted--; state.nHeadersSyncTimeout = 0; } } } else { // After we've caught up once, reset the timeout so we can't trigger // disconnect later. state.nHeadersSyncTimeout = std::numeric_limits<int64_t>::max(); } } // Check that outbound peers have reasonable chains // GetTime() is used by this anti-DoS logic so we can test this using mocktime ConsiderEviction(pto, GetTime()); // // Message: getdata (blocks) // std::vector<CInv> vGetData; if (!pto->fClient && pto->CanRelay() && ((fFetch && !pto->m_limited_node) || !IsInitialBlockDownload()) && state.nBlocksInFlight < MAX_BLOCKS_IN_TRANSIT_PER_PEER) { std::vector<const CBlockIndex*> vToDownload; NodeId staller = -1; FindNextBlocksToDownload(pto->GetId(), MAX_BLOCKS_IN_TRANSIT_PER_PEER - state.nBlocksInFlight, vToDownload, staller, consensusParams); for (const CBlockIndex *pindex : vToDownload) { vGetData.push_back(CInv(MSG_BLOCK, pindex->GetBlockHash())); MarkBlockAsInFlight(pto->GetId(), pindex->GetBlockHash(), pindex); LogPrint(BCLog::NET, "Requesting block %s (%d) peer=%d\n", pindex->GetBlockHash().ToString(), pindex->nHeight, pto->GetId()); } if (state.nBlocksInFlight == 0 && staller != -1) { if (State(staller)->nStallingSince == 0) { State(staller)->nStallingSince = nNow; LogPrint(BCLog::NET, "Stall started peer=%d\n", staller); } } } // // Message: getdata (non-blocks) // // For robustness, expire old requests after a long timeout, so that // we can resume downloading objects from a peer even if they // were unresponsive in the past. // Eventually we should consider disconnecting peers, but this is // conservative. if (state.m_object_download.m_check_expiry_timer <= current_time) { for (auto it=state.m_object_download.m_object_in_flight.begin(); it != state.m_object_download.m_object_in_flight.end();) { if (it->second <= current_time - GetObjectExpiryInterval(it->first.type)) { LogPrint(BCLog::NET, "timeout of inflight object %s from peer=%d\n", it->first.ToString(), pto->GetId()); state.m_object_download.m_object_announced.erase(it->first); state.m_object_download.m_object_in_flight.erase(it++); } else { ++it; } } // On average, we do this check every GetObjectExpiryInterval. Randomize // so that we're not doing this for all peers at the same time. state.m_object_download.m_check_expiry_timer = current_time + GetObjectExpiryInterval(MSG_TX)/2 + GetRandMicros(GetObjectExpiryInterval(MSG_TX)); } // ORO this code also handles non-TXs (LuckyCoinORO specific messages) auto& object_process_time = state.m_object_download.m_object_process_time; while (!object_process_time.empty() && object_process_time.begin()->first <= current_time && state.m_object_download.m_object_in_flight.size() < MAX_PEER_OBJECT_IN_FLIGHT) { const CInv inv = object_process_time.begin()->second; // Erase this entry from object_process_time (it may be added back for // processing at a later time, see below) object_process_time.erase(object_process_time.begin()); if (g_erased_object_requests.count(inv.hash)) { LogPrint(BCLog::NET, "%s -- GETDATA skipping inv=(%s), peer=%d\n", __func__, inv.ToString(), pto->GetId()); state.m_object_download.m_object_announced.erase(inv); state.m_object_download.m_object_in_flight.erase(inv); continue; } if (!AlreadyHave(inv)) { // If this object was last requested more than GetObjectInterval ago, // then request. const auto last_request_time = GetObjectRequestTime(inv.hash); if (last_request_time <= current_time - GetObjectInterval(inv.type)) { LogPrint(BCLog::NET, "Requesting %s peer=%d\n", inv.ToString(), pto->GetId()); vGetData.push_back(inv); if (vGetData.size() >= MAX_GETDATA_SZ) { connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData)); vGetData.clear(); } UpdateObjectRequestTime(inv.hash, current_time); state.m_object_download.m_object_in_flight.emplace(inv, current_time); } else { // This object is in flight from someone else; queue // up processing to happen after the download times out // (with a slight delay for inbound peers, to prefer // requests to outbound peers). const auto next_process_time = CalculateObjectGetDataTime(inv, current_time, !state.fPreferredDownload); object_process_time.emplace(next_process_time, inv); LogPrint(BCLog::NET, "%s -- GETDATA re-queue inv=(%s), next_process_time=%d, delta=%d, peer=%d\n", __func__, inv.ToString(), next_process_time.count(), (next_process_time - current_time).count(), pto->GetId()); } } else { // We have already seen this object, no need to download. state.m_object_download.m_object_announced.erase(inv); state.m_object_download.m_object_in_flight.erase(inv); LogPrint(BCLog::NET, "%s -- GETDATA already seen inv=(%s), peer=%d\n", __func__, inv.ToString(), pto->GetId()); } } if (!vGetData.empty()) { connman->PushMessage(pto, msgMaker.Make(NetMsgType::GETDATA, vGetData)); LogPrint(BCLog::NET, "SendMessages -- GETDATA -- pushed size = %lu peer=%d\n", vGetData.size(), pto->GetId()); } } return true; } class CNetProcessingCleanup { public: CNetProcessingCleanup() {} ~CNetProcessingCleanup() { // orphan transactions mapOrphanTransactions.clear(); mapOrphanTransactionsByPrev.clear(); nMapOrphanTransactionsSize = 0; } } instance_of_cnetprocessingcleanup;
lw $s1, ($s0) addi $s0, $zero, 233 bne $s0, $s1, label label: addi $v0, $zero, 10 syscall
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r13 push %r15 push %r8 push %rbp push %rcx push %rdi push %rsi lea addresses_D_ht+0x166d, %r11 nop xor %r15, %r15 mov (%r11), %rbp nop nop xor %r8, %r8 lea addresses_UC_ht+0x3a6d, %rbp nop inc %rcx mov $0x6162636465666768, %rsi movq %rsi, %xmm4 vmovups %ymm4, (%rbp) nop nop nop nop xor $64388, %rsi lea addresses_D_ht+0x18b9b, %rsi xor $25397, %r15 mov (%rsi), %r11w nop nop nop nop nop add $43473, %rbp lea addresses_D_ht+0x1bf0d, %rsi lea addresses_A_ht+0x1c6d, %rdi nop nop nop nop and %r13, %r13 mov $91, %rcx rep movsb nop nop dec %r11 lea addresses_UC_ht+0x526d, %rsi lea addresses_normal_ht+0x15ed, %rdi nop nop nop nop nop dec %r8 mov $8, %rcx rep movsq nop nop nop nop nop inc %r13 lea addresses_WT_ht+0xb26d, %r8 clflush (%r8) nop nop nop nop nop cmp %rbp, %rbp movw $0x6162, (%r8) nop nop nop xor %rbp, %rbp lea addresses_D_ht+0x10a6d, %rsi lea addresses_A_ht+0x14385, %rdi nop nop nop add %r11, %r11 mov $5, %rcx rep movsq nop nop add $63935, %rdi lea addresses_WT_ht+0x2aed, %rsi lea addresses_WT_ht+0xfeed, %rdi clflush (%rdi) nop nop inc %r8 mov $31, %rcx rep movsq nop nop cmp $59020, %r13 lea addresses_normal_ht+0xdc1f, %rsi lea addresses_WC_ht+0x12a6d, %rdi cmp $26958, %r8 mov $9, %rcx rep movsq nop cmp %rcx, %rcx lea addresses_WC_ht+0x1219, %rsi lea addresses_normal_ht+0x1a25d, %rdi inc %r15 mov $124, %rcx rep movsq nop nop nop nop inc %rsi lea addresses_D_ht+0x6194, %rsi lea addresses_WC_ht+0x1c26d, %rdi clflush (%rsi) nop nop sub %r15, %r15 mov $22, %rcx rep movsb cmp %rsi, %rsi lea addresses_UC_ht+0x1536d, %rsi lea addresses_WC_ht+0x7d6d, %rdi nop and $63688, %r11 mov $98, %rcx rep movsl nop nop and $53185, %r11 pop %rsi pop %rdi pop %rcx pop %rbp pop %r8 pop %r15 pop %r13 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r13 push %r8 push %r9 push %rcx // Load lea addresses_US+0x145ed, %r11 add $41774, %r10 vmovups (%r11), %ymm7 vextracti128 $1, %ymm7, %xmm7 vpextrq $0, %xmm7, %rcx // Exception!!! mov (0), %r12 nop nop xor %rcx, %rcx // Store lea addresses_PSE+0x85a3, %r11 nop nop nop cmp %r8, %r8 movw $0x5152, (%r11) nop nop nop nop sub $15828, %r12 // Faulty Load lea addresses_D+0x1ea6d, %r10 nop cmp %r12, %r12 movb (%r10), %r13b lea oracles, %rcx and $0xff, %r13 shlq $12, %r13 mov (%rcx,%r13,1), %r13 pop %rcx pop %r9 pop %r8 pop %r13 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_D', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 1, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_D', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 7, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_D_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 8, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 6, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 2, 'AVXalign': True, 'NT': False, 'congruent': 11, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 3, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 7, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 1, 'same': True}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 3, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 0, 'same': True}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_UC_ht', 'congruent': 8, 'same': True}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 8, 'same': False}} {'36': 1} 36 */
/** * @author Nicholas Kidd * @author Akash Lal * * @version $Id$ * */ #include "wali/Worklist.hpp" #include "wali/Common.hpp" #include "wali/HashMap.hpp" #include "wali/SemElem.hpp" #include "wali/KeyPairSource.hpp" // ::wali::util #include "wali/util/Timer.hpp" // ::wali::wfa #include "wali/wfa/WFA.hpp" #include "wali/wfa/State.hpp" #include "wali/wfa/Trans.hpp" #include "wali/wfa/TransSet.hpp" #include "wali/wfa/TransFunctor.hpp" // ::wali::wpds #include "wali/wpds/Config.hpp" #include "wali/wpds/GenKeySource.hpp" #include "wali/wpds/Rule.hpp" // ::wali::wpds::ewpds #include "wali/wpds/ewpds/ERule.hpp" #include "wali/wpds/ewpds/ETrans.hpp" // ::wali::wpds::fwpds #include "wali/wpds/fwpds/FWPDS.hpp" #include "wali/wpds/fwpds/LazyTrans.hpp" // ::wali::graph #include "wali/graph/RegExp.hpp" #include "wali/graph/InterGraph.hpp" using namespace wali; using namespace wali::graph; using namespace wali::wpds; using namespace wali::wpds::fwpds; using namespace wali::wpds::ewpds; #define FWPDS_DYN_CAST 0 const std::string FWPDS::XMLTag("FWPDS"); FWPDS::FWPDS() : EWPDS(), interGr(NULL), checkingPhase(false), newton(false), topDown(true) { } FWPDS::FWPDS(ref_ptr<wpds::Wrapper> wr) : EWPDS(wr) , interGr(NULL), checkingPhase(false), newton(false), topDown(true) { } FWPDS::FWPDS( const FWPDS& f ) : EWPDS(f),interGr(NULL),checkingPhase(false), newton(f.newton), topDown(f.topDown) { } FWPDS::FWPDS(bool _newton) : EWPDS(), newton(_newton), topDown(true) { } FWPDS::~FWPDS() { // This means that if you delete an FWPDS, any WFA that was created by prestar/poststar on that FWPDS is useless. // I don't know where else to delete the InterGraph. // The ideal way to do this is to move the RegExpDag dag into FWPDS, and copy it the WFA after poststar. interGr = NULL; interGrs.clear(); } /////////////////////////////////////////////////////////////////// void FWPDS::topDownEval(bool f) { //Used to be --> //graph::RegExp::topDownEval(f); if(!(interGr == NULL)) interGr->dag->topDownEval(f); topDown = f; // is no worse than what it used to be } struct FWPDSCopyBackFunctor : public wfa::TransFunctor { graph::InterGraphPtr gr; FWPDSCopyBackFunctor(graph::InterGraphPtr _gr) : gr(_gr) {} virtual void operator()( wfa::ITrans* t ) { LazyTrans *lt = static_cast<LazyTrans *> (t); lt->setInterGraph(gr); if (!wali::is_lazy_fwpds()) { // Call to compute the weight lt->weight(); } } }; struct FWPDSSourceFunctor : public wfa::TransFunctor { graph::InterGraph & gr; bool post; FWPDSSourceFunctor( graph::InterGraph & g, bool p ) : gr(g), post(p) {} virtual void operator()( wfa::ITrans* t ) { //t->print(std::cout << "\n*********************\n +++SetSource: "); //std::cout << "\n*********************\n"; if(!post) { gr.setSource(Transition(*t),t->weight()); } else { //ETrans --> Esource LazyTrans *lt = static_cast<LazyTrans *> (t); ETrans* etrans = lt->getETrans(); if (0 != etrans) { gr.setESource(Transition(*t), etrans->getWeightAtCall(), etrans->weight()); } else { gr.setSource(Transition(*t), t->weight()); } } } }; struct FWPDSCompareFunctor : public wfa::ConstTransFunctor { graph::InterGraph & gr; bool iseq; FWPDSCompareFunctor( graph::InterGraph & p ) : gr(p) { iseq = true; } virtual void operator()( const wfa::ITrans* t ) { sem_elem_t wt1 = gr.get_weight(Transition(t->from(), t->stack(), t->to())); sem_elem_t wt2 = t->weight(); if( !wt2->equal(wt1) ) { iseq = false; wt1->print(*waliErr) << "\n"; t->print(*waliErr) << "\n"; *waliErr << "-----------------------------\n"; } const ETrans *et = dynamic_cast<const ETrans*>(t); if(et != 0) { wt1 = et->getWeightAtCall(); wt2 = gr.get_call_weight(Transition(t->from(), t->stack(), t->to())); if( !wt2->equal(wt1) ) { iseq = false; wt1->print(*waliErr) << "\n"; t->print(*waliErr) << "\n"; *waliErr << "-----------------------------\n"; } } } std::ostream& print( std::ostream& out ) { if(!iseq) { out << "Not equal\n"; assert(0); } return out; } }; //std::ostream& graphPrintKey( int k, std::ostream& o ) { std::ostream& graphPrintKey(std::ostream& o, int k) { return wali::printKey(o,(Key)k); } void FWPDS::useNewton(bool set){ newton = set; } void FWPDS::prestar( wfa::WFA const & input, wfa::WFA& output ) { // setup output addEtrans = true; EWPDS::prestarSetupFixpoint(input,output); addEtrans = false; // If theZero is invalid, then there // are no rules and not saturation to // be done. if (!theZero.is_valid()) { worklist->clear(); return; } // cache semiring 1 wghtOne = theZero->one(); // FIXME: Currently FWPDS always assumes that the // underlying pds is a EWPDS. In the absence of // merge functions, it can be treated as a WPDS. // However, there is no cost benefit in using WPDS // (it only saves on debugging effort) interGr = new graph::InterGraph(theZero, true, true); interGr->dag->topDownEval(topDown); interGrs.push_back(interGr); // Input transitions become source nodes in FWPDS FWPDSSourceFunctor sources(*interGr.get_ptr(), false); output.for_each(sources); // Build the InterGraph using EWPDS saturation without weights EWPDS::prestarComputeFixpoint(output); // Compute summaries if(newton) interGr->setupNewtonSolution(); else interGr->setupInterSolution(); //interGr->print(std::cout << "THE INTERGRAPH\n",graphPrintKey); // Copy information back from InterGraph to the // output WFA. This does not do computation on weights, // but instead uses LazyTrans to put in "lazy" weights // that are evaluated on demand. FWPDSCopyBackFunctor copier( interGr ); output.for_each(copier); checkResults(input,false); interGr = NULL; currentOutputWFA = 0; } void FWPDS::prestar_handle_call(wfa::ITrans *t1, wfa::ITrans *t2, rule_t &r, sem_elem_t delta ) { if(checkingPhase) { return EWPDS::prestar_handle_call(t1, t2, r, delta); } LazyTrans *lt1 = static_cast<LazyTrans *>(t1); LazyTrans *lt2 = static_cast<LazyTrans *>(t2); ETrans *et1 = lt1->getETrans(); ETrans *et2 = lt2->getETrans(); assert(!(et1 == 0 && et2 != 0)); if(et1 != 0) { ERule *er = (ERule *)(r.get_ptr()); interGr->addEdge(Transition(*t2), Transition(*t1), Transition(r->from()->state(), r->from()->stack(),t2->to()), er->merge_fn().get_ptr() ); } else { interGr->addEdge(Transition(*t2), Transition(*t1), Transition(r->from()->state(), r->from()->stack(),t2->to()), r->weight() ); } // update if(et2 != 0) { update_etrans( r->from()->state(), r->from()->stack(), t2->to(), wghtOne,r->from() ); } else { update( r->from()->state(), r->from()->stack(), t2->to(), wghtOne,r->from() ); } } void FWPDS::prestar_handle_trans( wfa::ITrans * t , wfa::WFA & fa , rule_t & r, sem_elem_t delta ) { //std::cout << "Prestar_handle_trans:\n"; //t->print(std::cout << "t: ") << "\n"; //r->print(std::cout << "r: ") << "\n"; if(checkingPhase) { return EWPDS::prestar_handle_trans(t, fa, r, delta); } Key fstate = r->from()->state(); Key fstack = r->from()->stack(); if( r->is_rule2() ) { KeyPair kp( t->to(),r->stack2() ); wfa::WFA::kp_map_t::iterator kpit = fa.kpmap.find( kp ); wfa::WFA::kp_map_t::iterator kpitEND = fa.kpmap.end(); wfa::TransSet::iterator tsit; if(kpit != kpitEND) { wfa::TransSet & transSet = kpit->second; for( tsit = transSet.begin(); tsit != transSet.end(); tsit++ ) { wfa::ITrans* tprime = *tsit; prestar_handle_call(t, tprime, r, delta); } } } else { LazyTrans *lt = static_cast<LazyTrans *> (t); ETrans *et = lt->getETrans(); interGr->addEdge(Transition(*t), Transition(fstate,fstack,t->to()), r->weight()); if(et != 0) { update_etrans( fstate, fstack, t->to(), wghtOne, r->from() ); } else { update( fstate, fstack, t->to(), wghtOne, r->from() ); } } } bool FWPDS::checkResults( wfa::WFA const & input, bool do_poststar ) { if( wali::get_verify_fwpds() ) { // set flag to use EWPDS's saturation checkingPhase = true; wfa::WFA tmpOutput; wfa::WFA tmpInput(input); util::Timer* wpdsTimer = new util::Timer("\t[WPDS] Total Timer "); if( do_poststar ) { EWPDS::poststar(tmpInput, tmpOutput); //WPDS::poststarSetupFixpoint(tmpInput,tmpOutput); //WPDS::poststarComputeFixpoint(tmpOutput); } else { EWPDS::prestar(tmpInput, tmpOutput); //WPDS::prestarSetupFixpoint(tmpInput,tmpOutput); //WPDS::prestarComputeFixpoint(tmpOutput); } delete wpdsTimer; { // compare results util::Timer timer("\t[(F)WPDS] Compare Results "); FWPDSCompareFunctor comp(*interGr); //output.print( std::cout << "\nFWPDS OUTPUT:\n\n" ); //tmpOutput.print( std::cout << "\nWPDS OUTPUT:\n\n" ); tmpOutput.for_each(comp); comp.print(std::cout); } *waliErr << "\t[(F)WPDS] CONGRATS DUDE...OUTPUT MATCHED.\n"; checkingPhase = false; } return true; } void FWPDS::poststar( wfa::WFA const & input, wfa::WFA& output ) { poststarIGR(input, output); //{ // util::Timer timer("FWPDS All Weights"); // interGr->update_all_weights(); //} //interGr->print_stats(*waliErr) << "\n"; } void FWPDS::poststarIGR( wfa::WFA const & input, wfa::WFA& output ) { EWPDS::poststarSetupFixpoint(input,output); // If theZero is invalid then no rules have // been added to the WPDS and no saturation // can be done. if(!theZero.is_valid()) { worklist->clear(); return; } // cache semiring 1 wghtOne = theZero->one(); // FIXME: Currently FWPDS always assumes that the // underlying pds is a EWPDS. In the absence of // merge functions, it can be treated as a WPDS. // However, there is no cost benefit in using WPDS interGr = new graph::InterGraph(theZero, true, false); interGr->dag->topDownEval(topDown); interGrs.push_back(interGr); // Input transitions become source nodes in FWPDS FWPDSSourceFunctor sources(*interGr.get_ptr(), true); output.for_each(sources); // Build the InterGraph using EWPDS saturation without weights EWPDS::poststarComputeFixpoint(output); { std::string msg = (get_verify_fwpds()) ? "FWPDS Saturation" : ""; util::Timer timer(msg); // Compute summaries if(newton){ interGr->setupNewtonSolution(); } else interGr->setupInterSolution(); } //interGr->print(std::cout << "THE INTERGRAPH\n",graphPrintKey); // Copy information back from InterGraph to the // output WFA. This does not do computation on weights, // but instead uses LazyTrans to put in "lazy" weights // that are evaluated on demand. FWPDSCopyBackFunctor copier( interGr ); output.for_each(copier); checkResults(input,true); currentOutputWFA = 0; } void FWPDS::poststar_handle_eps_trans(wfa::ITrans* teps, wfa::ITrans* tprime, sem_elem_t delta) { if(checkingPhase) { return EWPDS::poststar_handle_eps_trans(teps, tprime, delta); } // These casts should never fail. However, if WALi evolves // to allow for more types of transitions, then it is nice // to leave this here. #if FWPDS_DYN_CAST LazyTrans* lt = dynamic_cast<LazyTrans*>(tprime); { // <DEBUG> if (0 == lt) { *waliErr << "[ERROR] Oops, FWPDS is broken.\n"; *waliErr << " >> Expeced LazyTrans, Got >> "; tprime->print(*waliErr); assert(0); } } // </DEBUG> #else LazyTrans* lt = static_cast<LazyTrans*>(tprime); #endif ewpds::ETrans* etrans = lt->getETrans(); if (0 != etrans) { erule_t r = etrans->getERule(); interGr->addEdge(Transition(*tprime), Transition(*teps), Transition(teps->from(),tprime->stack(),tprime->to()), etrans->getMergeFn()); } else { interGr->addEdge(Transition(*tprime), Transition(*teps), Transition(teps->from(),tprime->stack(),tprime->to()), wghtOne); } Config * config = make_config( teps->from(),tprime->stack() ); update( teps->from() , tprime->stack() , tprime->to() , wghtOne , config ); } void FWPDS::poststar_handle_trans( wfa::ITrans* t, wfa::WFA &fa, rule_t &r, sem_elem_t delta) { if(checkingPhase) { return EWPDS::poststar_handle_trans(t, fa, r, delta); } Key rtstate = r->to_state(); Key rtstack = r->to_stack1(); if( r->to_stack2() == WALI_EPSILON ) { update( rtstate, rtstack, t->to(), wghtOne, r->to() ); interGr->addEdge(Transition(*t), Transition(rtstate,rtstack,t->to()), r->weight()); } else { // Push rule (p,g) -> (p,g',g2) // Is a rule 2 so we must generate a state // and create 2 new transitions Key gstate = gen_state( rtstate,rtstack ); // Note: QuasiOne is not supported in FWPDS wfa::ITrans* tprime = update_prime( gstate, t, r, delta, wghtOne); update( rtstate, rtstack, gstate, wghtOne, r->to() ); // add source edge interGr->setSource(Transition(rtstate,rtstack, gstate), wghtOne); // add edge (p,g,q) -> (p,g',(p,g')) interGr->addCallEdge(Transition(*t),Transition(rtstate,rtstack, gstate)); // add call-ret edge (p,g,q) -> ((p,g'),rstk2,q) interGr->addCallRetEdge(Transition(*t), Transition(gstate, r->to_stack2(),t->to()), r->weight()); if( tprime->modified() ) { wfa::WFA::eps_map_t::iterator epsit = fa.eps_map.find( tprime->from() ); if( epsit != fa.eps_map.end() ) { // get epsilon list ref wfa::TransSet& transSet = epsit->second; // iterate wfa::TransSet::iterator tsit = transSet.begin(); for( ; tsit != transSet.end() ; tsit++ ) { wfa::ITrans * teps = *tsit; poststar_handle_eps_trans(teps, tprime, delta); } } } } } bool FWPDS::isOutputTensored() { if(interGr != NULL) return interGr->isOutputTensored(); return false; } //////////////////////////////////////////// // These guys take care of LazyTrans stuff //////////////////////////////////////////// void FWPDS::update( Key from, Key stack, Key to, sem_elem_t se, Config * cfg ) { if(checkingPhase) { return EWPDS::update(from, stack, to, se, cfg); } wfa::ITrans *t; if(addEtrans) { t = new ETrans(from, stack, to, 0, se, 0); } else { t = new wfa::Trans(from, stack, to, se); } t->setConfig(cfg); LazyTrans * lt = new LazyTrans(t); t = currentOutputWFA->insert(lt).first; if( t->modified() ) { //t->print(std::cout << "Adding transition: ") << "\n"; worklist->put( t ); } } wfa::ITrans* FWPDS::update_prime( Key from, //<! Guaranteed to be a generated state wfa::ITrans* call, //<! The call transition rule_t r, //<! The push rule sem_elem_t delta, //<! Delta change on the call transition sem_elem_t wWithRule //<! delta \extends r->weight() ) { if(checkingPhase) { return EWPDS::update_prime(from, call, r, delta, wWithRule); } // // !!NOTE!! // This code is copied from EWPDS::update_prime. // Changes here should be reflected there. // ERule* er = (ERule*)r.get_ptr(); wfa::ITrans* et = new ETrans( from, r->to_stack2(), call->to(), delta, wWithRule, er); LazyTrans* lt = new LazyTrans(et); wfa::ITrans* t = currentOutputWFA->insert(lt).first; return t; } void FWPDS::operator()( wfa::ITrans const * orig ) { if(checkingPhase) { return EWPDS::operator()(orig); } if( is_strict() && is_pds_state(orig->to())) { *waliErr << "WALi Error: cannot have incoming transition to a PDS state\n"; orig->print( *waliErr << " " ) << std::endl; assert(0); } Config *c = make_config( orig->from(),orig->stack() ); sem_elem_t se = (wrapper.is_valid()) ? wrapper->wrap(*orig) : orig->weight(); LazyTrans *t = new LazyTrans( orig->copy() ); t->setConfig(c); t->setWeight(se); // fa.addTrans takes ownership of passed in pointer currentOutputWFA->addTrans( t ); // add t to the worklist for saturation worklist->put( t ); }
#ifndef PERSISTENCE_HPP #define PERSISTENCE_HPP #include "SimFunction.hpp" #include "ContourTreeData.hpp" namespace contourtree { class Persistence : public SimFunction { public: Persistence(const ContourTreeData& ctData); void init(std::vector<float> &fn, std::vector<Branch> &br); void update(const std::vector<Branch> &br, uint32_t brNo); void branchRemoved(std::vector<Branch>& br, uint32_t brNo, std::vector<bool>& invalid); float getBranchWeight(uint32_t brNo); public: const float *fnVals; float *fn; }; } #endif // PERSISTENCE_HPP
// Copyright Carl Philipp Reh 2009 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_CONTAINER_GET_OR_INSERT_RESULT_IMPL_HPP_INCLUDED #define FCPPT_CONTAINER_GET_OR_INSERT_RESULT_IMPL_HPP_INCLUDED #include <fcppt/container/get_or_insert_result_decl.hpp> template< typename Reference > fcppt::container::get_or_insert_result< Reference >::get_or_insert_result( Reference _reference, bool const _inserted ) : reference_( _reference ), inserted_{ _inserted } { } template< typename Reference > template< typename Other > fcppt::container::get_or_insert_result< Reference >::get_or_insert_result( get_or_insert_result< Other > const &_other ) : reference_( _other.element() ), inserted_( _other.inserted() ) { } template< typename Reference > Reference fcppt::container::get_or_insert_result< Reference >::element() const { return reference_.get(); } template< typename Reference > bool fcppt::container::get_or_insert_result< Reference >::inserted() const { return inserted_; } #endif
#INCLUDE<P16F84A.INC> ORG 0X00 GOTO INICIO ;--- Se uma entrada é acionada, uma saída deve permanecer acionada enquanto a entrada estiver acionada. ---; INICIO CLRW CLRF PORTA CLRF PORTB BSF STATUS,RP0 MOVLW 0 MOVWF TRISA ;porta A toda de saida MOVLW 1 MOVWF TRISB ;porta B apenas com o bit 0 de entrada BCF STATUS,RP0 MAIN BTFSS PORTB,0 GOTO APAGA ;se tiver em 0, nao ta pressionado e apaga GOTO ACENDE ;se tiver em 1 ta pressionado e acende ACENDE BSF PORTA,0 GOTO MAIN APAGA BCF PORTA,0 GOTO MAIN END
db "DELIVERY@" ; species name dw 211, 350 ; height, weight db "It always carries" next "its food with it," next "wherever it goes." page "If attacked, it" next "throws its food at" next "the opponent.@"
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r8 push %r9 push %rax push %rcx push %rdi push %rsi lea addresses_A_ht+0x1527c, %rsi lea addresses_D_ht+0x19204, %rdi clflush (%rdi) nop and $23394, %r9 mov $42, %rcx rep movsl nop lfence lea addresses_WC_ht+0x18f9c, %rsi lea addresses_WT_ht+0x16e84, %rdi nop cmp $33441, %rax mov $53, %rcx rep movsq add $59736, %rcx lea addresses_UC_ht+0x1223c, %rsi lea addresses_D_ht+0x2f04, %rdi nop nop nop nop nop sub %r10, %r10 mov $66, %rcx rep movsb xor %rdi, %rdi lea addresses_D_ht+0xa104, %rdi nop nop cmp %r12, %r12 mov $0x6162636465666768, %rax movq %rax, %xmm5 movups %xmm5, (%rdi) nop nop add $25191, %rdi lea addresses_UC_ht+0x1e874, %rax nop nop nop sub %rsi, %rsi mov (%rax), %r10d nop and $24466, %rdi lea addresses_normal_ht+0x117bc, %rdi nop nop cmp %r10, %r10 movb $0x61, (%rdi) nop nop nop nop add $52026, %rdi lea addresses_WC_ht+0xb104, %rsi lea addresses_normal_ht+0x12704, %rdi nop nop nop sub $29832, %r8 mov $36, %rcx rep movsq nop nop sub $32601, %r9 pop %rsi pop %rdi pop %rcx pop %rax pop %r9 pop %r8 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r13 push %r15 push %r9 push %rdi push %rdx push %rsi // Store lea addresses_normal+0x17104, %r15 nop nop and %rsi, %rsi mov $0x5152535455565758, %r13 movq %r13, %xmm4 vmovups %ymm4, (%r15) sub %rsi, %rsi // Store lea addresses_UC+0x22b4, %r15 cmp $16588, %rdi mov $0x5152535455565758, %r13 movq %r13, (%r15) and %rdx, %rdx // Store lea addresses_PSE+0x39c4, %r15 clflush (%r15) nop and $3677, %r9 mov $0x5152535455565758, %r10 movq %r10, %xmm2 movups %xmm2, (%r15) xor %r15, %r15 // Faulty Load lea addresses_D+0x19904, %rsi nop nop nop inc %r9 vmovups (%rsi), %ymm5 vextracti128 $1, %ymm5, %xmm5 vpextrq $0, %xmm5, %r15 lea oracles, %r13 and $0xff, %r15 shlq $12, %r15 mov (%r13,%r15,1), %r15 pop %rsi pop %rdx pop %rdi pop %r9 pop %r15 pop %r13 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'size': 16, 'NT': True, 'type': 'addresses_D', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_normal', 'same': False, 'AVXalign': False, 'congruent': 11}} {'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_UC', 'same': False, 'AVXalign': False, 'congruent': 4}} {'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_PSE', 'same': False, 'AVXalign': False, 'congruent': 6}} [Faulty Load] {'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_D', 'same': True, 'AVXalign': False, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_A_ht', 'congruent': 3}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 7}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 0}, 'dst': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 6}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 3}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 7}} {'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 10}} {'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_UC_ht', 'same': False, 'AVXalign': False, 'congruent': 3}} {'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 11}, 'dst': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 8}} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
; A010692: Constant sequence: a(n) = 10. ; 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10 mov $1,10
;Copyright (c) 2004-2020 Microchip Technology Inc. and its subsidiaries. ;SPDX-License-Identifier: MIT $NOMOD51 $INCLUDE (REG52.INC) NAME MISCUTIL3 PUBLIC _mac_cmp PUBLIC _ip_cmp PUBLIC _mac_copy PUBLIC _ip_copy PUBLIC _mem_cmp PUBLIC _mem_copy PUBLIC _mem_set PROG SEGMENT CODE RSEG PROG ;* ************************************************************************ */ ; char mac_cmp (uchar xdata *mac_addr_1, uchar xdata *mac_addr_2) small _mac_cmp: ;* ------------------------------------------------------------------------ -- ;* Purpose : Compare two mac addresses. ;* Remarks : Return -1, if mac_addr_1 < mac_addr_2. ;* Return 1, if mac_addr_1 > mac_addr_2 ;* Return 0, if mac_addr_1 == mac_addr_2 ;* Restrictions: ;* See also : ;* Example : ; * ************************************************************************ */ mov r1, #6 ; Number of bytes to compare L1_1: mov dph, r6 ; Get pointer to byte in first address mov dpl, r7 movx a, @dptr ; Get byte from first address mov r2, a ; Save byte temporary inc dptr ; Point to next byte in first address mov r6, dph ; Save pointer temporarily mov r7, dpl mov dph, r4 ; Get pointer to byte in second address mov dpl, r5 movx a, @dptr ; Get byte from second address inc dptr ; Point to next byte in second address mov r4, dph ; Save pointer temporarily mov r5, dpl xch a, r2 clr c subb a, r2 ; Compare the two bytes jnz L1_2 ; If different, go check sign djnz r1, L1_1 ; Check if more bytes to compare mov r7, #0 ; All bytes equal, return 0 ret L1_2: jc L1_3 ; If first address > second address mov r7, #1 ; then return 1 ret L1_3: mov r7, #0FFH ; else return -1 ret ;* ************************************************************************ */ ; char ip_cmp (uchar xdata *ip_addr_1, uchar xdata *ip_addr_2) small _ip_cmp: ;* ------------------------------------------------------------------------ -- ;* Purpose : Compare two ip addresses. ;* Remarks : Return -1, if ip_addr_1 < ip_addr_2. ;* Return 1, if ip_addr_1 > ip_addr_2 ;* Return 0, if ip_addr_1 == ip_addr_2 ;* Restrictions: ;* See also : ;* Example : ; * ************************************************************************ */ mov r1, #4 ; Number of bytes to compare jmp L1_1 ;* ************************************************************************ */ ; void mac_copy (uchar xdata *dst_mac_addr, uchar xdata *src_mac_addr) small _mac_copy: ;* ------------------------------------------------------------------------ -- ;* Purpose : Copy a mac address. ;* Remarks : ;* Restrictions: ;* See also : ;* Example : ; * ************************************************************************ */ mov r1, #6 ; Number of bytes to copy L3_1: mov dph, r4 ; Get pointer to byte in source address mov dpl, r5 movx a, @dptr ; Read byte from source address inc dptr ; Point to next byte in source address mov r4, dph ; Save pointer temporarily mov r5, dpl mov dph, r6 ; Get pointer to byte in destination address mov dpl, r7 movx @dptr, a ; Write byte from source address inc dptr ; Point to next byte in destination address mov r6, dph ; Save pointer temporarily mov r7, dpl djnz r1, L3_1 ; Check if copy completed ret ;* ************************************************************************ */ ; void ip_copy (uchar xdata *dst_ip_addr, uchar xdata *src_ip_addr) small _ip_copy: ;* ------------------------------------------------------------------------ -- ;* Purpose : Copy an ip address. ;* Remarks : ;* Restrictions: ;* See also : ;* Example : ; * ************************************************************************ */ mov r1, #4 ; Number of bytes to copy jmp L3_1 ;* ************************************************************************ */ ; uchar mem_cmp (uchar xdata *dst_mem_addr, uchar xdata *src_mem_addr, uchar size) small _mem_cmp: ;* ------------------------------------------------------------------------ -- ;* Purpose : memory compare. ;* Remarks : ;* Restrictions: length must be less than 256, and compare address is xdata ;* See also : ;* Example : ; * ************************************************************************ */ mov a, r3 mov r1, a ; Number of bytes to compare jmp L1_1 ;* ************************************************************************ */ ; uchar mem_copy (uchar xdata *dst_mem_addr, uchar xdata *src_mem_addr, uchar size) small _mem_copy: ;* ------------------------------------------------------------------------ -- ;* Purpose : memory compare. ;* Remarks : ;* Restrictions: length must be less than 256, and memory address is xdata ;* See also : ;* Example : ; * ************************************************************************ */ mov a, r3 mov r1, a ; Number of bytes to copy jmp L3_1 ;* ************************************************************************ */ ; uchar mem_set (uchar xdata *dst_mem_addr, uchar value, uchar size) small _mem_set: ;* ------------------------------------------------------------------------ -- ;* Purpose : memory compare. ;* Remarks : ;* Restrictions: length must be less than 256, and memory address is xdata ;* See also : ;* Example : ; * ************************************************************************ */ mov a, r3 mov r1, a ; Number of bytes to copy mov a, r5 ; Get the byte to store L4_1: mov dph, r6 ; Get pointer to byte in destination address mov dpl, r7 movx @dptr, a ; Write byte from source address inc dptr ; Point to next byte in destination address mov r6, dph ; Save pointer temporarily mov r7, dpl djnz r1, L4_1 ; Check if copy completed ret END
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %rcx lea addresses_D_ht+0x183cc, %r10 nop nop nop nop cmp %rcx, %rcx and $0xffffffffffffffc0, %r10 movntdqa (%r10), %xmm2 vpextrq $0, %xmm2, %r11 nop nop nop nop nop cmp $12356, %r11 pop %rcx pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r12 push %r13 push %r14 push %r8 push %r9 push %rax push %rbx // Store mov $0xcc, %rax clflush (%rax) nop inc %r12 movw $0x5152, (%rax) sub %rax, %rax // Store mov $0x34c, %r14 nop nop nop nop nop cmp $51435, %r13 movl $0x51525354, (%r14) nop nop nop inc %r12 // Faulty Load lea addresses_PSE+0x1d3cc, %rbx nop xor %r8, %r8 mov (%rbx), %rax lea oracles, %rbx and $0xff, %rax shlq $12, %rax mov (%rbx,%rax,1), %rax pop %rbx pop %rax pop %r9 pop %r8 pop %r14 pop %r13 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 1, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'type': 'addresses_P', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 7}} {'OP': 'STOR', 'dst': {'type': 'addresses_P', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 7}} [Faulty Load] {'src': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 8, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_D_ht', 'AVXalign': False, 'size': 16, 'NT': True, 'same': False, 'congruent': 11}, 'OP': 'LOAD'} {'33': 21829} 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 */
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r14 push %r15 push %r9 push %rbx push %rcx push %rdi push %rsi lea addresses_normal_ht+0x15e5c, %r15 xor %rbx, %rbx movw $0x6162, (%r15) nop nop nop nop nop cmp $57713, %rsi lea addresses_A_ht+0x1d5c, %rsi nop nop nop nop nop xor %r10, %r10 vmovups (%rsi), %ymm1 vextracti128 $1, %ymm1, %xmm1 vpextrq $0, %xmm1, %rcx nop nop nop nop nop dec %rsi lea addresses_WT_ht+0x1d95c, %rdi nop nop nop nop inc %r14 vmovups (%rdi), %ymm7 vextracti128 $1, %ymm7, %xmm7 vpextrq $1, %xmm7, %rsi sub %rdi, %rdi lea addresses_WC_ht+0x57e0, %rsi lea addresses_WC_ht+0x1711c, %rdi nop nop xor %r9, %r9 mov $108, %rcx rep movsq nop sub %rcx, %rcx lea addresses_WC_ht+0x91dd, %r14 nop nop nop inc %r15 movb (%r14), %cl nop nop nop add $21456, %r15 lea addresses_D_ht+0x765c, %rsi lea addresses_WT_ht+0x47ad, %rdi nop nop nop nop inc %r15 mov $74, %rcx rep movsl nop nop nop nop sub %rcx, %rcx lea addresses_normal_ht+0x1e328, %r10 clflush (%r10) nop nop nop nop cmp $11342, %rsi vmovups (%r10), %ymm2 vextracti128 $1, %ymm2, %xmm2 vpextrq $1, %xmm2, %r15 nop dec %r9 lea addresses_WC_ht+0x1807c, %rsi lea addresses_WT_ht+0xe95c, %rdi nop and $8988, %r15 mov $114, %rcx rep movsl nop nop nop nop inc %r14 lea addresses_WC_ht+0x755c, %rdi nop nop nop xor $41499, %rsi mov $0x6162636465666768, %r10 movq %r10, (%rdi) nop nop nop xor $12629, %r14 lea addresses_UC_ht+0x1655c, %r15 sub %rdi, %rdi movw $0x6162, (%r15) nop nop nop cmp $35516, %r9 lea addresses_UC_ht+0x3224, %r10 nop nop nop nop nop sub $8947, %r9 movl $0x61626364, (%r10) nop sub %r10, %r10 lea addresses_WT_ht+0x851e, %r15 nop and %rbx, %rbx movups (%r15), %xmm7 vpextrq $1, %xmm7, %rsi nop nop nop dec %rcx lea addresses_D_ht+0x1a61c, %rbx nop nop nop nop nop xor %rcx, %rcx mov $0x6162636465666768, %r14 movq %r14, (%rbx) nop xor %rcx, %rcx lea addresses_D_ht+0x10fdc, %rcx nop nop nop nop nop and %rdi, %rdi movb (%rcx), %r9b nop nop nop cmp $40804, %rcx pop %rsi pop %rdi pop %rcx pop %rbx pop %r9 pop %r15 pop %r14 pop %r10 ret .global s_faulty_load s_faulty_load: push %r13 push %r15 push %r8 push %r9 push %rcx push %rdi push %rdx // Store lea addresses_WT+0xea0c, %r13 nop nop nop nop cmp $18468, %rcx mov $0x5152535455565758, %r15 movq %r15, %xmm2 vmovups %ymm2, (%r13) nop nop nop nop nop xor %r13, %r13 // Faulty Load lea addresses_WT+0x1795c, %rdx nop add %rdi, %rdi mov (%rdx), %rcx lea oracles, %r8 and $0xff, %rcx shlq $12, %rcx mov (%r8,%rcx,1), %rcx pop %rdx pop %rdi pop %rcx pop %r9 pop %r8 pop %r15 pop %r13 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_WT', 'same': False, 'size': 2, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_WT', 'same': False, 'size': 32, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} [Faulty Load] {'src': {'type': 'addresses_WT', 'same': True, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'dst': {'type': 'addresses_normal_ht', 'same': False, 'size': 2, 'congruent': 1, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_A_ht', 'same': False, 'size': 32, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WT_ht', 'same': False, 'size': 32, 'congruent': 9, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_WC_ht', 'same': False, 'size': 1, 'congruent': 0, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'} {'src': {'type': 'addresses_D_ht', 'congruent': 8, 'same': True}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM'} {'src': {'type': 'addresses_normal_ht', 'same': False, 'size': 32, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 10, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 8, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_UC_ht', 'same': False, 'size': 2, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_UC_ht', 'same': False, 'size': 4, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_WT_ht', 'same': False, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'dst': {'type': 'addresses_D_ht', 'same': False, 'size': 8, 'congruent': 6, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_D_ht', 'same': False, 'size': 1, 'congruent': 3, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'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 */
; A160413: a(n) = A160411(n+1)/4. ; 2,1,7,2,13,3,19,4,25,5,31,6,37,7,43,8,49,9,55,10,61,11,67,12,73,13,79,14,85,15,91,16,97,17,103,18,109,19,115,20,121,21,127,22,133,23,139,24,145 mov $4,3 mul $4,$0 gcd $4,2 mov $1,$4 mov $2,$4 mul $4,2 mov $5,$2 mul $5,2 sub $5,$1 mul $0,$5 mov $1,$4 sub $1,1 mov $3,$0 add $0,1 mul $3,$1 add $1,3 lpb $0,1 mov $0,1 trn $0,$2 trn $3,1 add $1,$3 div $1,2 lpe sub $1,1
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/lambda/model/ListVersionsByFunctionResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::Lambda::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListVersionsByFunctionResult::ListVersionsByFunctionResult() { } ListVersionsByFunctionResult::ListVersionsByFunctionResult(const AmazonWebServiceResult<JsonValue>& result) { *this = result; } ListVersionsByFunctionResult& ListVersionsByFunctionResult::operator =(const AmazonWebServiceResult<JsonValue>& result) { const JsonValue& jsonValue = result.GetPayload(); if(jsonValue.ValueExists("NextMarker")) { m_nextMarker = jsonValue.GetString("NextMarker"); } if(jsonValue.ValueExists("Versions")) { Array<JsonValue> versionsJsonList = jsonValue.GetArray("Versions"); for(unsigned versionsIndex = 0; versionsIndex < versionsJsonList.GetLength(); ++versionsIndex) { m_versions.push_back(versionsJsonList[versionsIndex].AsObject()); } } return *this; }
Route2Gate_Object: db $a ; border block def_warps warp 4, 0, 3, LAST_MAP warp 5, 0, 3, LAST_MAP warp 4, 7, 4, LAST_MAP warp 5, 7, 4, LAST_MAP def_signs def_objects object SPRITE_SCIENTIST, 1, 4, STAY, LEFT, 1 ; person object SPRITE_YOUNGSTER, 5, 4, WALK, LEFT_RIGHT, 2 ; person def_warps_to ROUTE_2_GATE
/******************************************************************************** * File Name: * chimera_usart.cpp * * Description: * Implements the Chimera USART driver * * 2020-2021 | Brandon Braun | brandonbraun653@gmail.com *******************************************************************************/ /* STL Includes */ #include <memory> #include <cstring> /* Chimera Includes */ #include <Chimera/usart> namespace Chimera::USART { /*------------------------------------------------------------------------------- Static Data -------------------------------------------------------------------------------*/ static Backend::DriverConfig s_backend_driver; /*------------------------------------------------------------------------------- Public Functions -------------------------------------------------------------------------------*/ namespace Backend { Chimera::Status_t __attribute__( ( weak ) ) registerDriver( struct Chimera::USART::Backend::DriverConfig &cfg ) { cfg.isSupported = false; return Chimera::Status::NOT_SUPPORTED; } } // namespace Backend Chimera::Status_t initialize() { memset( &s_backend_driver, 0, sizeof( s_backend_driver ) ); /*------------------------------------------------ Register the backend interface with Chimera ------------------------------------------------*/ auto result = Backend::registerDriver( s_backend_driver ); if ( result != Chimera::Status::OK ) { return result; } /*------------------------------------------------ Try and invoke the registered init sequence ------------------------------------------------*/ if ( s_backend_driver.isSupported && s_backend_driver.initialize ) { return s_backend_driver.initialize(); } else { return Chimera::Status::NOT_SUPPORTED; } return result; } Chimera::Status_t reset() { if ( s_backend_driver.isSupported && s_backend_driver.reset ) { return s_backend_driver.reset(); } else { return Chimera::Status::NOT_SUPPORTED; } } bool isChannelUSART( const Chimera::Serial::Channel channel ) { if ( s_backend_driver.isSupported && s_backend_driver.isChannelUSART ) { return s_backend_driver.isChannelUSART( channel ); } else { return false; } } Driver_rPtr getDriver( const Chimera::Serial::Channel channel ) { if ( s_backend_driver.isSupported && s_backend_driver.getDriver ) { return s_backend_driver.getDriver( channel ); } else { return nullptr; } } } // namespace Chimera::USART
Spawn_Bees: { LDA #$79 JSL Sprite_SpawnDynamically BMI .done LDA $22 STA $0D10, Y LDA $23 STA $0D30, Y LDA $20 STA $0D00, Y LDA $21 STA $0D20, Y .done RTL }
; void __CALLEE__ *adt_ListSearch_callee(struct adt_List *list, void *match, void *item1) ; 02.2003, 08.2005 aralbrec SECTION code_clib PUBLIC adt_ListSearch_callee PUBLIC _adt_ListSearch_callee PUBLIC ASMDISP_ADT_LISTSEARCH_CALLEE EXTERN ADTListSearch, l_jpiy .adt_ListSearch_callee ._adt_ListSearch_callee pop hl pop de pop iy ex (sp),hl .asmentry ; enter: hl = struct adt_List * ; de = item1 * ; iy = void (*match)(DE = void *item1, BC = void *item2) -- MUST PRESERVE BC,DE,IX,HL ; sets carry if equal ; exit : no carry = item not found, current points past end of list, hl = 0 ; else hl = item found, current points at found item ; uses : af, bc, de, hl push ix ;save callers ix ld ix,compare call ADTListSearch pop ix ld l,c ld h,b ret c ld hl,0 ret .compare push hl push de push bc call l_jpiy ld a,l pop bc pop de pop hl or a ret nz scf ret DEFC ASMDISP_ADT_LISTSEARCH_CALLEE = # asmentry - adt_ListSearch_callee
; A344598: a(n) = Sum_{k=1..n} phi(k) * (floor(n/k)^2 - floor((n-1)/k)^2). ; 1,4,7,12,13,24,19,32,33,44,31,68,37,64,75,80,49,108,55,124,109,104,67,176,105,124,135,180,85,240,91,192,177,164,199,300,109,184,211,320,121,348,127,292,333,224,139,432,217,340,279,348,157,432,323,464,313,284,175,660,181 mov $2,$0 seq $0,18804 ; Pillai's arithmetical function: Sum_{k=1..n} gcd(k, n). sub $2,$0 sub $0,$2 sub $0,1
//---------------------------------------------------------------------------- // // TSDuck - The MPEG Transport Stream Toolkit // Copyright (c) 2005-2021, Thierry Lelegard // 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 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 OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------- #include "tsDebugPlugin.h" #include "tsPluginRepository.h" TSDUCK_SOURCE; TS_REGISTER_PROCESSOR_PLUGIN(u"debug", ts::DebugPlugin); //---------------------------------------------------------------------------- // Packet processor constructor //---------------------------------------------------------------------------- ts::DebugPlugin::DebugPlugin(TSP* tsp_) : ProcessorPlugin(tsp_, u"Debug traces", u"[options]"), _tag() { option(u"tag", 't', STRING); help(u"tag", u"'string'", u"Message tag to be displayed with each debug message. " u"Useful when the plugin is used several times in the same process."); } //---------------------------------------------------------------------------- // Get options methods //---------------------------------------------------------------------------- bool ts::DebugPlugin::getOptions() { _tag = value(u"tag"); if (!_tag.empty()) { _tag += u": "; } return true; } //---------------------------------------------------------------------------- // Packet processing. //---------------------------------------------------------------------------- ts::ProcessorPlugin::Status ts::DebugPlugin::processPacket(TSPacket& pkt, TSPacketMetadata& pkt_data) { tsp->verbose(u"%sPID: 0x%0X, labels: %s, timestamp: %s", { _tag, pkt.getPID(), pkt_data.labelsString(), pkt_data.inputTimeStampString()}); return TSP_OK; }
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_GeneralStringsContainer_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function GeneralStringsContainer.GeneralStringsContainer_C.ExecuteUbergraph_GeneralStringsContainer struct UGeneralStringsContainer_C_ExecuteUbergraph_GeneralStringsContainer_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
/* ----------------------------------------------------------------------------- The copyright in this software is being made available under the Clear BSD License, included below. No patent rights, trademark rights and/or other Intellectual Property Rights other than the copyrights concerning the Software are granted under this license. The Clear BSD License Copyright (c) 2019-2022, Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V. & The VVenC Authors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. 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. ------------------------------------------------------------------------------------------- */ /** \file Reshape.cpp \brief common reshaper class */ #include "Reshape.h" #include "UnitTools.h" #include <stdio.h> #include <string.h> #include <math.h> //! \ingroup CommonLib //! \{ namespace vvenc { // ===================================================================================================================== // ReshapeData // ===================================================================================================================== int ReshapeData::getPWLIdxInv( int lumaVal ) const { for (int idxS = m_sliceReshapeInfo.reshaperModelMinBinIdx; (idxS <= m_sliceReshapeInfo.reshaperModelMaxBinIdx); idxS++) { if (lumaVal < m_reshapePivot[idxS + 1]) return idxS; } return PIC_CODE_CW_BINS-1; } int ReshapeData::calculateChromaAdj( Pel avgLuma ) const { int iAdj = m_chromaAdjHelpLUT[getPWLIdxInv(avgLuma)]; return(iAdj); } int ReshapeData::calculateChromaAdjVpduNei( const TransformUnit& tu, const CompArea& areaY, const TreeType _treeType ) { CodingStructure &cs = *tu.cs; int xPos = areaY.lumaPos().x; int yPos = areaY.lumaPos().y; int numNeighborLog = std::min<unsigned>(6,cs.pcv->maxCUSizeLog2); int numNeighbor = 1<<numNeighborLog; const int mask = 1-numNeighbor-1; xPos &= mask; yPos &= mask; if( !cs.pcv->isEncoder ) { if( isVPDUprocessed( xPos, yPos ) ) { return m_chromaScale; } setVPDULoc( xPos, yPos ); } Position topLeft(xPos, yPos); CodingStructure* pcs = (CS::isDualITree(cs) && cs.slice->sliceType == VVENC_I_SLICE) ? tu.cs->picture->cs : tu.cs; CodingUnit *topLeftLuma = pcs->getCU(topLeft, CH_L, _treeType); const CodingUnit *cuAbove = pcs->getCURestricted( topLeftLuma->lumaPos().offset(0, -1), topLeftLuma->lumaPos(), topLeftLuma->slice->independentSliceIdx, topLeftLuma->tileIdx, CH_L, _treeType ); const CodingUnit *cuLeft = pcs->getCURestricted( topLeftLuma->lumaPos().offset(-1, 0), topLeftLuma->lumaPos(), topLeftLuma->slice->independentSliceIdx, topLeftLuma->tileIdx, CH_L, _treeType ); xPos = topLeftLuma->lumaPos().x; yPos = topLeftLuma->lumaPos().y; const CPelBuf piRecoY = cs.picture->getRecoBuf(topLeftLuma->Y()); const int strideY = piRecoY.stride; const Pel* recSrc0 = piRecoY.bufAt(0, 0); const uint32_t picH = tu.cs->picture->lheight(); const uint32_t picW = tu.cs->picture->lwidth(); int32_t recLuma = 0; int pelnum = 0; if (cuLeft != nullptr) { pelnum ++; for (int i = 0; i < numNeighbor; i++) { int k = (yPos + i) >= picH ? (picH - yPos - 1) : i; recLuma += recSrc0[-1 + k * strideY]; } } if (cuAbove != nullptr) { pelnum++; for (int i = 0; i < numNeighbor; i++) { int k = (xPos + i) >= picW ? (picW - xPos - 1) : i; recLuma += recSrc0[-strideY + k]; } } int lumaValue; if( pelnum ) { const int shift = numNeighborLog + pelnum - 1; lumaValue = (recLuma + (1 << (shift - 1))) >> shift; } else { lumaValue = 1 << (cs.sps->bitDepths[CH_L] - 1); } int chromaScale = calculateChromaAdj(lumaValue); if( !cs.pcv->isEncoder ) { m_chromaScale = chromaScale; } return chromaScale; } // ===================================================================================================================== // Reshape // ===================================================================================================================== void Reshape::createDec(int bitDepth) { m_lumaBD = bitDepth; m_reshapeLUTSize = 1 << m_lumaBD; m_initCW = m_reshapeLUTSize / PIC_CODE_CW_BINS; #if defined( TARGET_SIMD_X86 ) && ENABLE_SIMD_OPT_BUFFER if( m_fwdLUT.empty() ) m_fwdLUT.resize( m_reshapeLUTSize + 2, 0 ); if( m_invLUT.empty() ) m_invLUT.resize( m_reshapeLUTSize + 2, 0 ); #else if( m_fwdLUT.empty() ) m_fwdLUT.resize( m_reshapeLUTSize, 0 ); if( m_invLUT.empty() ) m_invLUT.resize( m_reshapeLUTSize, 0 ); #endif if (m_binCW.empty()) m_binCW.resize(PIC_CODE_CW_BINS, 0); if (m_inputPivot.empty()) m_inputPivot.resize(PIC_CODE_CW_BINS + 1, 0); if (m_fwdScaleCoef.empty()) m_fwdScaleCoef.resize(PIC_CODE_CW_BINS, 1 << FP_PREC); if (m_invScaleCoef.empty()) m_invScaleCoef.resize(PIC_CODE_CW_BINS, 1 << FP_PREC); if (m_reshapePivot.empty()) m_reshapePivot.resize(PIC_CODE_CW_BINS + 1, 0); if (m_chromaAdjHelpLUT.empty()) m_chromaAdjHelpLUT.resize(PIC_CODE_CW_BINS, 1<<CSCALE_FP_PREC); } /** Construct reshaper from syntax * \param void * \return void */ void Reshape::constructReshaper() { int pwlFwdLUTsize = PIC_CODE_CW_BINS; int pwlFwdBinLen = m_reshapeLUTSize / PIC_CODE_CW_BINS; for (int i = 0; i < m_sliceReshapeInfo.reshaperModelMinBinIdx; i++) m_binCW[i] = 0; for (int i = m_sliceReshapeInfo.reshaperModelMaxBinIdx + 1; i < PIC_CODE_CW_BINS; i++) m_binCW[i] = 0; for (int i = m_sliceReshapeInfo.reshaperModelMinBinIdx; i <= m_sliceReshapeInfo.reshaperModelMaxBinIdx; i++) m_binCW[i] = (uint16_t)(m_sliceReshapeInfo.reshaperModelBinCWDelta[i] + (int)m_initCW); for (int i = 0; i < pwlFwdLUTsize; i++) { m_reshapePivot[i + 1] = m_reshapePivot[i] + m_binCW[i]; m_inputPivot[i + 1] = m_inputPivot[i] + m_initCW; m_fwdScaleCoef[i] = ((int32_t)m_binCW[i] * (1 << FP_PREC) + (1 << (floorLog2(pwlFwdBinLen) - 1))) >> floorLog2(pwlFwdBinLen); if (m_binCW[i] == 0) { m_invScaleCoef[i] = 0; m_chromaAdjHelpLUT[i] = 1 << CSCALE_FP_PREC; } else { m_invScaleCoef[i] = (int32_t)(m_initCW * (1 << FP_PREC) / m_binCW[i]); m_chromaAdjHelpLUT[i] = (int32_t)(m_initCW * (1 << FP_PREC) / ( m_binCW[i] + m_sliceReshapeInfo.chrResScalingOffset ) ); } } for (int lumaSample = 0; lumaSample < m_reshapeLUTSize; lumaSample++) { int idxY = lumaSample / m_initCW; int tempVal = m_reshapePivot[idxY] + ((m_fwdScaleCoef[idxY] * (lumaSample - m_inputPivot[idxY]) + (1 << (FP_PREC - 1))) >> FP_PREC); m_fwdLUT[lumaSample] = Clip3((Pel)0, (Pel)((1 << m_lumaBD) - 1), (Pel)(tempVal)); int idxYInv = getPWLIdxInv(lumaSample); int invSample = m_inputPivot[idxYInv] + ((m_invScaleCoef[idxYInv] * (lumaSample - m_reshapePivot[idxYInv]) + (1 << (FP_PREC - 1))) >> FP_PREC); m_invLUT[lumaSample] = Clip3((Pel)0, (Pel)((1 << m_lumaBD) - 1), (Pel)(invSample)); } } void Reshape::initLumaLevelToWeightTableReshape() { const int lutSize = 1 << m_lumaBD; if (m_reshapeLumaLevelToWeightPLUT.empty()) m_reshapeLumaLevelToWeightPLUT.resize(lutSize, 1.0); if (m_lumaLevelToWeightPLUT.empty()) m_lumaLevelToWeightPLUT.resize(lutSize, 1.0); if (m_signalType == RESHAPE_SIGNAL_PQ) { for (int i = 0; i < lutSize; i++) { double x = m_lumaBD < 10 ? i << (10 - m_lumaBD) : m_lumaBD > 10 ? i >> (m_lumaBD - 10) : i; double y; y = 0.015*x - 1.5 - 6; y = y < -3 ? -3 : (y > 6 ? 6 : y); m_lumaLevelToWeightPLUT[i] = pow(2.0, y / 3.0); m_reshapeLumaLevelToWeightPLUT[i] = (uint32_t)(m_lumaLevelToWeightPLUT[i]* (double)(1 << 16)); } } } void Reshape::updateReshapeLumaLevelToWeightTableChromaMD( const Pel* ILUT) { const int lutSize = 1 << m_lumaBD; for( int i = 0; i < lutSize; i++ ) { m_reshapeLumaLevelToWeightPLUT[i] = (uint32_t)(m_lumaLevelToWeightPLUT[ILUT[i]]* (double)(1 << 16)); } } void Reshape::restoreReshapeLumaLevelToWeightTable() { const int lutSize = 1 << m_lumaBD; for (int i = 0; i < lutSize; i++) { m_reshapeLumaLevelToWeightPLUT[i] = (uint32_t)(m_lumaLevelToWeightPLUT[i]* (double)(1 << 16)); } } void Reshape::updateReshapeLumaLevelToWeightTable(LmcsParam &sliceReshape, Pel* wtTable, double cwt) { if (m_signalType == RESHAPE_SIGNAL_SDR || m_signalType == RESHAPE_SIGNAL_HLG) { if (sliceReshape.sliceReshaperModelPresent ) { double wBin = 1.0; double weight = 1.0; int histLens = (1 << m_lumaBD) / PIC_CODE_CW_BINS; for (int i = 0; i < PIC_CODE_CW_BINS; i++) { if ((i < sliceReshape.reshaperModelMinBinIdx) || (i > sliceReshape.reshaperModelMaxBinIdx)) weight = 1.0; else { if (sliceReshape.reshaperModelBinCWDelta[i] == 1 || (sliceReshape.reshaperModelBinCWDelta[i] == -1 * histLens)) weight = wBin; else { weight = (double)wtTable[i] / (double)histLens; weight = weight*weight; } } for (int j = 0; j < histLens; j++) { int ii = i*histLens + j; m_reshapeLumaLevelToWeightPLUT[ii] = (uint32_t)(weight* (double)(1 << 16)); } } m_chromaWeightRS = cwt; } else { THROW("updateReshapeLumaLevelToWeightTable ERROR!!"); } } else { THROW("updateReshapeLumaLevelToWeightTable not support other signal types!!"); } } } // namespace vvenc // //! \}
BITS 32 ;TEST_FILE_META_BEGIN ;TEST_TYPE=TEST_F ;TEST_IGNOREFLAGS= ;TEST_FILE_META_END ; put 2 into ecx for future load into xmm0 mov ecx, 2 cvtsi2ss xmm0, ecx mov ecx, 0 cvtsi2ss xmm1, ecx ;TEST_BEGIN_RECORDING lea ecx, [esp-4] movss [ecx], xmm1 ucomiss xmm0, [ecx] mov ecx, 0 ;TEST_END_RECORDING cvtsi2ss xmm0, ecx cvtsi2ss xmm1, ecx
; A264763: a(0) = a(1) = 1; for n>1, a(n) = a(n-1) + (a(n-2) mod 5). ; 1,1,2,3,5,8,8,11,14,15,19,19,23,27,30,32,32,34,36,40,41,41,42,43,45,48,48,51,54,55,59,59,63,67,70,72,72,74,76,80,81,81,82,83,85,88,88,91,94,95,99,99,103,107,110,112,112 mov $4,$0 add $4,1 mov $5,$0 lpb $4,1 mov $0,$5 sub $4,1 sub $0,$4 mov $2,$0 add $0,6 mul $2,2 add $2,1 add $0,$2 mov $6,$0 lpb $0,1 sub $0,1 mul $6,2 mod $6,5 lpe mov $0,7 add $6,5 add $0,$6 add $0,2 div $3,$6 trn $3,8 add $3,4 mul $3,4 add $3,$0 sub $3,4 mov $2,$3 sub $2,26 add $1,$2 lpe
BmpByteWidth equ 1 CharByteWidth equ 1 VdpIn_Data equ &98 VdpIn_Status equ &99 VdpOut_Data equ &98 VdpOut_Control equ &99 VdpOut_Palette equ &9A VdpOut_Indirect equ &9B Vdp_SendByteData equ &9B ;V9990 functions ;Vdp9k_Data equ &60 ;VRAM data port ;Vdp9k_Palette equ &61 ;Palette data port ;Vdp9k_Command equ &62 ;Command data port ;Vdp9k_RegData equ &63 ;Register data port ;Vdp9k_RegSel equ &64 ;Register select port (write only) ;Vdp9k_Status equ &65 ;Status port (read only) ;Vdp9k_Interrupt equ &66 ;Interrupt flag port ;Vdp9k_System equ &67 ;System control port (write only) ;Vdp9k_Superimpose equ &6F macro NextScrByte ;MSX autoincrements, so we do nothing here! Call MoveAlong endm macro ScreenStopDrawing endm macro ScreenStartDrawing endm macro SetScrByteBW out (VdpOut_Data),a NextScrByte ;Send the byte to screen endm ifdef vasm macro SetScrByte,sentbyte ld a,\sentbyte out (VdpOut_Data),a NextScrByte endm else macro SetScrByte sentbyte out (VdpOut_Data),sentbyte NextScrByte endm endif
.386 .model flat, stdcall .stack 4096 STD_OUTPUT_HANDLE EQU -11 GetStdHandle PROTO NEAR32 stdcall, nStdHandle:DWORD WriteFile PROTO NEAR32 stdcall, hFile:DWORD, lpBuffer:NEAR32, nNumberOfBytesToWrite:DWORD, lpNumberOfBytesWritten:NEAR32, lpOverlapped:NEAR32 ExitProcess PROTO NEAR32 stdcall, dwExitCode:DWORD .data unsortedArray BYTE 5, 6, 0, 3, 2, 9, 1 unsortedArrayLen DWORD LENGTHOF unsortedArray message BYTE "Hello, assembly!", 0Dh, 0Ah, 0 written WORD 0 hStdOut DWORD 0 numStr BYTE 24 DUP(0FFh) .data? conOut BYTE LENGTHOF unsortedArray + 1 DUP(?) .code main PROC push STD_OUTPUT_HANDLE call GetStdHandle mov hStdOut, eax mov eax, 128 mov edi, OFFSET numStr mov ecx, LENGTHOF numStr call uintToString mov numStr[eax], 0 push 0 ; Overlapped mode push 0 ; Bytes written push eax ; Length of string push OFFSET numStr ; Address of string push hStdOut ; File handle for screen call WriteFile mov eax, 0 ret main ENDP ;----------------------------------------------------------- ; uintToString ; Receives: ; eax - unsigned integer ; edi - out string ; ecx - out string length ; Returns ; eax - number of characters written ;----------------------------------------------------------- uintToString PROC USES ebx ecx edx esi mov ebx, 10 mov esi, 0 L1: xor edx, edx div ebx add edx, '0' push edx inc esi test eax, eax jnz L1 mov ecx, esi xor esi, esi L2: pop eax mov [edi + esi], al inc esi loop L2 mov eax, esi ret uintToString ENDP ;----------------------------------------------------------- ; arrayToString ; Receives: ; esi - DWORD array ; ecx - array length ; edi - out string array ;----------------------------------------------------------- arrayToString PROC arrayToString ENDP END main
prog 2 1 copy 3 2 jmpn $6 3 dec 3 inc 4 jmp $2 copy 0 3 copy 1 4
; A060901: Exact power of 3 that divides the n-th Fibonacci number (sequence A000045). ; 1,1,1,3,1,1,1,3,1,1,1,9,1,1,1,3,1,1,1,3,1,1,1,9,1,1,1,3,1,1,1,3,1,1,1,27,1,1,1,3,1,1,1,3,1,1,1,9,1,1,1,3,1,1,1,3,1,1,1,9,1,1,1,3,1,1,1,3,1,1,1,27,1,1,1,3,1,1,1,3,1,1,1,9,1,1,1,3,1,1,1,3,1,1,1,9,1,1,1,3 mov $2,$0 div $2,2 add $2,2 lpb $0 sub $0,1 add $2,1 mov $3,$2 lpe mov $1,1 div $3,2 lpb $3 mul $1,3 dif $3,3 lpe mov $0,$1
# /* ************************************************************************** # * * # * (C) Copyright Paul Mensonides 2002. # * Distributed under the Boost Software License, Version 1.0. (See # * accompanying file LICENSE_1_0.txt or copy at # * http://www.boost.org/LICENSE_1_0.txt) # * * # ************************************************************************** */ # # /* See http://www.boost.org for most recent version. */ # # ifndef AUTOBOOST_PREPROCESSOR_REPEAT_FROM_TO_3RD_HPP # define AUTOBOOST_PREPROCESSOR_REPEAT_FROM_TO_3RD_HPP # # include <autoboost/preprocessor/repetition/repeat_from_to.hpp> # # endif
printh: ; value of dx is the hex val push cx push di push bx mov si, HEX_PATTERN mov cl, 12 mov di, 2 hexLoop: mov bx, dx ; copy dx to bx to preserve val shr bx, cl ; shift by 12 bits (3 bytes) right and bx, 0x000f ; mask first 3 digits mov bx, [bx + HEX_TABLE] ; load ascii val of hex into bx mov [HEX_PATTERN + di], bl ; insert into correct spot sub cl, 4 ; change bits shifted in next itter inc di ; ++ insertion location for next itter cmp di, 6 je finish ; exit loop if done jmp hexLoop ; continue loop if not done finish: call printf ; print now built HEX_PATTERN string pop bx ; return values pop di pop cx ret ; return to prev pos HEX_PATTERN: db "0x****", 0x0a, 0x0d, 0 HEX_TABLE: db "0123456789abcdef"
.program: ji i4 noop DATA_SECTION_OFFSET[0..32] DATA_SECTION_OFFSET[32..64] lw $ds $is 1 add $$ds $$ds $is lw $r1 $fp i73 ; load input function selector lw $r0 data_4 ; load fn selector for comparison eq $r0 $r1 $r0 ; function selector comparison jnzi $r0 i14 ; jump to selected function lw $r0 data_5 ; load fn selector for comparison eq $r0 $r1 $r0 ; function selector comparison jnzi $r0 i28 ; jump to selected function rvrt $zero ; revert if no selectors matched move $r2 $sp ; save locals base register cfei i40 ; allocate 40 bytes for all locals addi $r0 $r2 i32 ; get offset reg for get_ptr lw $r0 data_0 ; literal instantiation sw $r2 $r0 i4 ; store value addi $r0 $r2 i0 ; get offset reg for get_ptr lw $r1 data_1 ; literal instantiation addi $r0 $r2 i0 ; get store offset mcpi $r0 $r1 i32 ; store value lw $r1 data_0 ; literal instantiation addi $r0 $r2 i0 ; get offset sww $r0 $r1 ; single word state access ret $zero ; returning unit as zero move $r1 $sp ; save locals base register cfei i64 ; allocate 64 bytes for all locals addi $r0 $r1 i32 ; get offset reg for get_ptr lw $r2 data_2 ; literal instantiation addi $r0 $r1 i32 ; get store offset mcpi $r0 $r2 i32 ; store value addi $r0 $r1 i0 ; get offset reg for get_ptr lw $r2 data_3 ; literal instantiation addi $r0 $r1 i0 ; get store offset mcpi $r0 $r2 i32 ; store value addi $r0 $r1 i32 ; get offset reg for get_ptr addi $r2 $r1 i32 ; get offset addi $r0 $r1 i0 ; get offset swwq $r0 $r2 ; quad word state access ret $zero ; returning unit as zero noop ; word-alignment of data section .data: data_0 .u64 0x00 data_1 .b256 0x7fbd1192666bfac3767b890bd4d048c940879d316071e20c7c8c81bce2ca41c5 data_2 .b256 0x0000000000000000000000000000000000000000000000000000000000000000 data_3 .b256 0xa15d6d36b54df993ed1fbe4544a45d4c4f70d81b4229861dfde0e20eb652202c data_4 .u32 0x1b9b478f data_5 .u32 0x858a3d18
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r11 push %r14 push %r9 push %rax push %rcx push %rdi push %rsi lea addresses_D_ht+0x45fb, %r9 nop nop nop xor %rax, %rax vmovups (%r9), %ymm0 vextracti128 $1, %ymm0, %xmm0 vpextrq $0, %xmm0, %r14 nop nop nop nop cmp %r10, %r10 lea addresses_WC_ht+0x15fb, %rsi lea addresses_UC_ht+0x163f3, %rdi nop nop nop nop nop add $25686, %r11 mov $32, %rcx rep movsb nop nop nop nop nop mfence lea addresses_WC_ht+0x9dfb, %r11 nop nop nop nop xor $49447, %rdi movw $0x6162, (%r11) cmp $56066, %r14 lea addresses_normal_ht+0x15e6f, %rcx nop nop nop nop nop dec %r10 movb $0x61, (%rcx) nop nop nop nop cmp $12183, %rsi lea addresses_WC_ht+0x1c71b, %rsi lea addresses_WC_ht+0x167fb, %rdi nop nop nop nop nop xor $31874, %r10 mov $65, %rcx rep movsw nop cmp $35911, %rsi lea addresses_A_ht+0xd9fb, %r11 nop nop nop nop xor $23832, %rsi movb $0x61, (%r11) nop nop nop nop dec %rsi lea addresses_A_ht+0xd9fb, %rsi lea addresses_A_ht+0xb6fb, %rdi nop nop nop nop dec %r9 mov $58, %rcx rep movsl nop nop cmp %rax, %rax lea addresses_WC_ht+0x597b, %r10 nop nop nop nop xor %rsi, %rsi movb $0x61, (%r10) nop nop nop nop nop cmp $20466, %r9 pop %rsi pop %rdi pop %rcx pop %rax pop %r9 pop %r14 pop %r11 pop %r10 ret .global s_faulty_load s_faulty_load: push %r12 push %r8 push %r9 push %rbp push %rcx push %rdi // Faulty Load lea addresses_US+0x25fb, %r9 nop nop nop nop cmp %r12, %r12 vmovups (%r9), %ymm2 vextracti128 $0, %ymm2, %xmm2 vpextrq $0, %xmm2, %rbp lea oracles, %r8 and $0xff, %rbp shlq $12, %rbp mov (%r8,%rbp,1), %rbp pop %rdi pop %rcx pop %rbp pop %r9 pop %r8 pop %r12 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_US', 'same': False, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_US', 'same': True, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_D_ht', 'same': False, 'size': 32, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_WC_ht', 'congruent': 11, 'same': True}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 3, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 2, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'dst': {'type': 'addresses_normal_ht', 'same': True, 'size': 1, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_WC_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_A_ht', 'same': False, 'size': 1, 'congruent': 10, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_A_ht', 'congruent': 10, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 1, 'congruent': 7, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'3c': 1, '00': 43, '48': 1, '10': 3} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 00 00 00 00 00 00 00 00 00 00 10 00 48 00 00 00 00 00 00 00 00 00 00 3c 10 00 */
// ---------------------------------------------------- // AIMP DotNet SDK // Copyright (c) 2014 - 2020 Evgeniy Bogdan // https://github.com/martin211/aimp_dotnet // Mail: mail4evgeniy@gmail.com // ---------------------------------------------------- #include "Stdafx.h" #include "AimpConverter.h" #include "ManagedAimpCore.h" #include "FileManager\AimpFileInfo.h" IUnknown* AimpConverter::MakeObject(REFIID objectId) { IUnknown* obj = nullptr; HRESULT r = ManagedAimpCore::GetAimpCore()->CreateObject(objectId, reinterpret_cast<void**>(&obj)); return obj; } IAIMPString* AimpConverter::ToAimpString(String^ value) { IAIMPString* strObject = CreateAimpObject<IAIMPString>(IID_IAIMPString); pin_ptr<const WCHAR> strDate = PtrToStringChars(value); strObject->SetData((PWCHAR)strDate, value->Length); return strObject; } IAIMPImage* AimpConverter::ToAimpImage(System::Drawing::Bitmap^ image) { System::IO::MemoryStream^ stream = nullptr; IAIMPStream* aimpStream = nullptr; IAIMPImage* img = nullptr; try { stream = gcnew System::IO::MemoryStream(); image->Save(stream, System::Drawing::Imaging::ImageFormat::Png); array<Byte>^ buffer = stream->ToArray(); if (Utils::CheckResult(GetCore()->CreateObject(IID_IAIMPMemoryStream, (void**)&aimpStream)) == AIMP::SDK:: ActionResultType::OK && Utils::CheckResult(GetCore()->CreateObject(IID_IAIMPImage, (void**)&img)) == AIMP::SDK::ActionResultType ::OK) { aimpStream->SetSize(stream->Length); pin_ptr<System::Byte> p = &buffer[0]; unsigned char* pby = p; if (Utils::CheckResult(aimpStream->Write(pby, (int)stream->Length, nullptr)) == AIMP::SDK::ActionResultType ::OK) { img->LoadFromStream(aimpStream); } return img; } } finally { if (stream != nullptr) { stream->Close(); } aimpStream->Release(); aimpStream = nullptr; } return nullptr; } IAIMPCore* AimpConverter::GetCore() { return AIMP::SDK::ManagedAimpCore::GetAimpCore(); } AIMP::SDK::Visuals::AimpVisualData^ AimpConverter::PAIMPVisualDataToManaged(PAIMPVisualData data) { AIMP::SDK::Visuals::AimpVisualData^ result = gcnew AIMP::SDK::Visuals::AimpVisualData(); result->Peaks = gcnew array<float>(2); result->Spectrum = gcnew array<array<float>^>(3); result->WaveForm = gcnew array<array<float>^>(2); result->Peaks[0] = data->Peaks[0]; result->Peaks[1] = data->Peaks[1]; for (int i = 0; i < 3; i++) { array<float>^ arr = gcnew array<float>(AIMP_VISUAL_SPECTRUM_MAX); for (int j = 0; j < AIMP_VISUAL_SPECTRUM_MAX; j++) { arr[j] = data->Spectrum[i][j]; } result->Spectrum[i] = arr; } for (int i = 0; i < 2; i++) { array<float>^ arr = gcnew array<float>(AIMP_VISUAL_WAVEFORM_MAX); for (int j = 0; j < AIMP_VISUAL_WAVEFORM_MAX; j++) { arr[j] = data->WaveForm[i][j]; } result->WaveForm[i] = arr; } return result; } System::Drawing::Bitmap^ AimpConverter::ToManagedBitmap(IAIMPImageContainer* imageContainer) { IAIMPImage* image = nullptr; try { if (Utils::CheckResult(ManagedAimpCore::GetAimpCore()->CreateObject(IID_IAIMPImage, (void**)&image)) != ActionResultType::OK) { return nullptr; } if (Utils::CheckResult(imageContainer->CreateImage(&image)) != ActionResultType::OK || image == nullptr) { return nullptr; } return ToManagedBitmap(image); } finally { if (image != nullptr) { image->Release(); image = NULL; } } return nullptr; } System::Drawing::Bitmap^ AimpConverter::ToManagedBitmap(IAIMPImage* image) { SIZE size; if (Utils::CheckResult(image->GetSize(&size)) == ActionResultType::OK) { if (size.cx == 0 || size.cy == 0) { return nullptr; } System::Drawing::Bitmap^ bmp = gcnew System::Drawing::Bitmap(size.cx, size.cy); IAIMPStream* stream = nullptr; ActionResultType res = Utils::CheckResult( AIMP::SDK::ManagedAimpCore::GetAimpCore()->CreateObject(IID_IAIMPMemoryStream, (void**)&stream)); if (res != ActionResultType::OK || stream == nullptr) { return nullptr; } image->SaveToStream(stream, AIMP_IMAGE_FORMAT_PNG); if (stream->GetSize() > 0) { Int64 size = stream->GetSize(); unsigned char* buf = new unsigned char[(int)size]; HRESULT r = stream->Seek(0, AIMP_STREAM_SEEKMODE_FROM_BEGINNING); r = stream->Read(buf, (int)size); System::IO::MemoryStream^ strm = gcnew System::IO::MemoryStream(); try { for (int i = 0; i < size; i++) { strm->WriteByte(buf[i]); } bmp = gcnew System::Drawing::Bitmap(strm); } finally { strm->Close(); strm = nullptr; delete[] buf; stream->Release(); stream = nullptr; } } return bmp; } return nullptr; } IAIMPImageContainer* AimpConverter::ToAimpImageContainer(System::Drawing::Bitmap^ image) { IAIMPImageContainer* container; if (Utils::CheckResult(ManagedAimpCore::GetAimpCore()->CreateObject(IID_IAIMPImageContainer, (void**)&container)) == ActionResultType::OK) { System::IO::Stream^ stream = nullptr; try { stream = gcnew System::IO::MemoryStream(); image->Save(stream, System::Drawing::Imaging::ImageFormat::Jpeg); stream->Seek(0, System::IO::SeekOrigin::Begin); if (Utils::CheckResult(container->SetDataSize((DWORD)stream->Length)) != ActionResultType::OK) { return nullptr; } byte* b = container->GetData(); for (int i = 0; i < stream->Length - 1; i++) { b[i] = stream->ReadByte(); } return container; } finally { if (stream != nullptr) { stream->Close(); } } } return nullptr; } String^ AimpConverter::ToManagedString(IAIMPString* value) { return gcnew String(value->GetData()); } VARIANT AimpConverter::ToNativeVariant(System::Object^ objectValue) { VARIANT varTag; VariantInit(&varTag); IntPtr h = IntPtr(&varTag); System::Runtime::InteropServices::Marshal::GetNativeVariantForObject(objectValue, h); return varTag; } System::Object^ AimpConverter::FromVaiant(VARIANT* variant) { void* p = variant; return System::Runtime::InteropServices::Marshal::GetObjectForNativeVariant(IntPtr(p)); } IAIMPObjectList* AimpConverter::GetAimpObjectList() { IAIMPObjectList* res = CreateAimpObject<IAIMPObjectList>(IID_IAIMPObjectList); return res; } IAIMPMLDataField* AimpConverter::GetAimpDataField() { IAIMPMLDataField* res = CreateAimpObject<IAIMPMLDataField>(IID_IAIMPMLDataField); return res; } template <typename TObject> TObject* AimpConverter::CreateAimpObject(REFIID objectId) { TObject* obj = nullptr; HRESULT r = ManagedAimpCore::GetAimpCore()->CreateObject(objectId, reinterpret_cast<void**>(&obj)); return obj; } IAIMPFileInfo* AimpConverter::ToAimpObject(IAimpFileInfo^ managedObject) { AimpFileInfo^ result = gcnew AimpFileInfo(); result->Album = managedObject->Album; result->AlbumArt = managedObject->AlbumArt; result->AlbumArtist = managedObject->AlbumArtist; result->Artist = managedObject->Artist; result->BitDepth = managedObject->BitDepth; result->BitRate = managedObject->BitRate; result->BPM = managedObject->BPM; result->Channels = managedObject->Channels; result->Codec = managedObject->Codec; result->Comment = managedObject->Comment; result->Composer = managedObject->Composer; result->CopyRight = managedObject->CopyRight; result->CUESheet = managedObject->CUESheet; result->CustomData = managedObject->CustomData; result->Date = managedObject->Date; result->DiskNumber = managedObject->DiskNumber; result->DiskTotal = managedObject->DiskTotal; result->Duration = managedObject->Duration; result->FileName = managedObject->FileName; result->FileSize = managedObject->FileSize; result->AlbumGain = managedObject->AlbumGain; result->Genre = managedObject->Genre; //result->LastPlayedDate = fi->LastPlayedDate; result->Lyrics = managedObject->Lyrics; result->StatMark = managedObject->StatMark; result->AlbumPeak = managedObject->AlbumPeak; //result->PlayCount = fi->PlayCount; result->Publisher = managedObject->Publisher; result->SampleRate = managedObject->SampleRate; result->StatMark = managedObject->StatMark; result->Title = managedObject->Title; result->TrackGain = managedObject->TrackGain; result->TrackNumber = managedObject->TrackNumber; result->TrackPeak = managedObject->TrackPeak; result->TrackTotal = managedObject->TrackTotal; return result->InternalAimpObject; } IAIMPObjectList* AimpConverter::ToAimpObjectList(List<String^>^ collection) { IAIMPObjectList* list = GetAimpObjectList(); for (int i = 0; i < collection->Count; i++) { list->Add(ToAimpString(collection[i])); } return list; } IAIMPString* AimpConverter::ToAimpString(Objects::IAimpString^ string) { IAIMPString* strObject = CreateAimpObject<IAIMPString>(IID_IAIMPString); const pin_ptr<const WCHAR> strDate = PtrToStringChars(string->GetData()); strObject->SetData(PWCHAR(strDate), string->GetLength()); return strObject; }
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r14 push %rbp push %rcx push %rdi push %rsi lea addresses_WT_ht+0xd995, %rsi lea addresses_WC_ht+0x17995, %rdi nop sub %r14, %r14 mov $26, %rcx rep movsb and $64946, %r11 lea addresses_UC_ht+0x1eb95, %rsi lea addresses_UC_ht+0x16b95, %rdi sub %r12, %r12 mov $50, %rcx rep movsq nop nop nop nop cmp $4915, %r11 lea addresses_WT_ht+0x16fdd, %rsi lea addresses_WC_ht+0x157ad, %rdi nop and %rbp, %rbp mov $19, %rcx rep movsw sub %rbp, %rbp lea addresses_WC_ht+0xd6b5, %rsi nop nop nop nop sub %rbp, %rbp movb (%rsi), %r11b nop add %r12, %r12 pop %rsi pop %rdi pop %rcx pop %rbp pop %r14 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r14 push %r8 push %rax push %rcx // Store lea addresses_UC+0x1ebf5, %r8 nop nop nop nop inc %r14 mov $0x5152535455565758, %r11 movq %r11, %xmm6 vmovups %ymm6, (%r8) cmp %r12, %r12 // Store lea addresses_UC+0x1d15d, %r12 nop nop nop nop nop cmp $2531, %rcx mov $0x5152535455565758, %rax movq %rax, %xmm6 movups %xmm6, (%r12) cmp %rcx, %rcx // Faulty Load lea addresses_RW+0x16995, %rcx clflush (%rcx) add %rax, %rax vmovups (%rcx), %ymm0 vextracti128 $0, %ymm0, %xmm0 vpextrq $1, %xmm0, %r11 lea oracles, %rax and $0xff, %r11 shlq $12, %r11 mov (%rax,%r11,1), %r11 pop %rcx pop %rax pop %r8 pop %r14 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_RW'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 5, 'AVXalign': False, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_UC'}} {'OP': 'STOR', 'dst': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_UC'}} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 32, 'NT': False, 'type': 'addresses_RW'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'congruent': 10, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_WC_ht'}} {'src': {'congruent': 6, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'REPM', 'dst': {'congruent': 9, 'same': False, 'type': 'addresses_UC_ht'}} {'src': {'congruent': 3, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'REPM', 'dst': {'congruent': 3, 'same': False, 'type': 'addresses_WC_ht'}} {'src': {'congruent': 5, 'AVXalign': False, 'same': False, 'size': 1, 'NT': False, 'type': 'addresses_WC_ht'}, 'OP': 'LOAD'} {'32': 21829} 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 32 */
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r13 push %r14 push %rbx push %rcx push %rdi push %rsi lea addresses_D_ht+0x14241, %rdi nop nop nop nop nop sub $51537, %r13 mov (%rdi), %r11 nop add $3921, %r12 lea addresses_WT_ht+0x1e02d, %rbx nop nop nop nop nop and %r14, %r14 mov (%rbx), %r11 nop nop add $42703, %r14 lea addresses_D_ht+0x1dd41, %rbx add $33828, %r14 mov $0x6162636465666768, %r13 movq %r13, %xmm0 and $0xffffffffffffffc0, %rbx movaps %xmm0, (%rbx) nop nop nop nop and %r11, %r11 lea addresses_WT_ht+0x15f41, %r13 nop nop nop sub $39459, %rcx mov $0x6162636465666768, %rbx movq %rbx, %xmm1 vmovups %ymm1, (%r13) nop sub $6944, %rcx lea addresses_WT_ht+0x9601, %rbx nop nop and $35985, %rdi mov (%rbx), %r11d nop nop cmp $56330, %r11 lea addresses_A_ht+0x2641, %rsi lea addresses_WC_ht+0x13641, %rdi nop nop nop and $3637, %r11 mov $54, %rcx rep movsl nop nop nop nop nop xor $62795, %rcx pop %rsi pop %rdi pop %rcx pop %rbx pop %r14 pop %r13 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r14 push %r9 push %rbx push %rcx push %rdx // Store lea addresses_RW+0x6641, %r14 nop nop nop nop nop xor %rdx, %rdx movl $0x51525354, (%r14) nop nop sub %rcx, %rcx // Faulty Load lea addresses_RW+0x6641, %r11 clflush (%r11) nop nop nop sub %rbx, %rbx movb (%r11), %r14b lea oracles, %r9 and $0xff, %r14 shlq $12, %r14 mov (%r9,%r14,1), %r14 pop %rdx pop %rcx pop %rbx pop %r9 pop %r14 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_RW', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0}} {'OP': 'STOR', 'dst': {'same': True, 'type': 'addresses_RW', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_RW', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 10}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 1}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_D_ht', 'NT': True, 'AVXalign': True, 'size': 16, 'congruent': 7}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 8}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 4}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 11, 'type': 'addresses_WC_ht'}} {'54': 21829} 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 54 */
; A021346: Decimal expansion of 1/342. ; 0,0,2,9,2,3,9,7,6,6,0,8,1,8,7,1,3,4,5,0,2,9,2,3,9,7,6,6,0,8,1,8,7,1,3,4,5,0,2,9,2,3,9,7,6,6,0,8,1,8,7,1,3,4,5,0,2,9,2,3,9,7,6,6,0,8,1,8,7,1,3,4,5,0,2,9,2,3,9,7,6,6,0,8,1,8,7,1,3,4,5,0,2,9,2,3,9,7,6,6 add $0,1 mov $1,10 pow $1,$0 mul $1,7 div $1,2394 mod $1,10 mov $0,$1
; A219810: Number of n X 2 arrays of the minimum value of corresponding elements and their horizontal, vertical or diagonal neighbors in a random, but sorted with lexicographically nondecreasing rows and nonincreasing columns, 0..2 n X 2 array. ; 3,6,16,33,61,106,176,281,433,646,936,1321,1821,2458,3256,4241,5441,6886,8608,10641,13021,15786,18976,22633,26801,31526,36856,42841,49533,56986,65256,74401,84481,95558,107696,120961,135421,151146,168208,186681 mov $1,5 mov $2,$0 bin $2,2 sub $2,2 pow $2,2 div $2,3 mov $5,$0 lpb $0 sub $1,$1 mov $0,$1 add $2,1 mov $4,$2 add $4,1 add $1,$4 lpe sub $1,2 mov $3,$5 mul $3,2 add $1,$3 mov $6,$5 mul $6,$5 mov $3,$6 mul $3,3 add $1,$3
/* MIT License Copyright (c) 2021 SAE Institute Geneva Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <gtest/gtest.h> #include "maths/vector2.h" namespace maths { TEST(Maths, Vector2f_Addition) { const Vector2f a{2.0f, 3.0f}; const Vector2f b{1.0f, 4.0f}; //Test operator +. Vector2f c = a + b; EXPECT_EQ(c.x, a.x + b.x); EXPECT_EQ(c.y, a.y + b.y); //Test operator +=. const Vector2f d{3.0f, 4.0f}; Vector2f e = d; e += a; EXPECT_EQ(e.x, d.x + a.x); EXPECT_EQ(e.y, d.y + a.y); } TEST(Maths, Vector2f_Substraction) { const Vector2f a{2.0f, 3.0f}; const Vector2f b{1.0f, 4.0f}; //Test operator -. Vector2f c = a - b; EXPECT_EQ(c.x, a.x - b.x); EXPECT_EQ(c.y, a.y - b.y); //Test operator -=. const Vector2f d{3.0f, 4.0f}; Vector2f e = d; e -= a; EXPECT_EQ(e.x, d.x - a.x); EXPECT_EQ(e.y, d.y - a.y); } TEST(Maths, Vector2f_MultiplicationByScalar) { const Vector2f a{2.0f, 3.0f}; const float b = 4.0f; //Test operator +. Vector2f c = a * b; EXPECT_EQ(c.x, a.x * b); EXPECT_EQ(c.y, a.y * b); //Test operator +=. const Vector2f d{3.0f, 4.0f}; Vector2f e = d; e *= b; EXPECT_EQ(e.x, d.x * b); EXPECT_EQ(e.y, d.y * b); } TEST(Maths, Vector2f_DivisionByScalar) { const Vector2f a{2.0f, 3.0f}; const float b = 4.0f; //Test operator /. Vector2f c = a / b; EXPECT_EQ(c.x, a.x / b); EXPECT_EQ(c.y, a.y / b); //Test operator /=. const Vector2f d{3.0f, 4.0f}; Vector2f e = d; e /= b; EXPECT_EQ(e.x, d.x / b); EXPECT_EQ(e.y, d.y / b); } TEST(Maths, Vector2f_Equal) { const Vector2f a{ 2.0f, 3.0f }; const Vector2f b = a; //Test operator ==. EXPECT_TRUE(a.x == b.x); EXPECT_TRUE(a.y == b.y); } TEST(Maths, Vector2f_NotEqual) { const Vector2f a{ 2.0f, 3.0f }; const Vector2f b{ 1.0f, 4.0f }; //Test operator !=. EXPECT_TRUE(a.x != b.x); EXPECT_TRUE(a.y != b.y); } TEST(Maths, Vector2f_SubscriptOperator) { const Vector2f a{ 2.0f, 3.0f }; //Test operator []. EXPECT_EQ(a[0], 2.0f); EXPECT_EQ(a[1], 3.0f); } TEST(Maths, Vector2f_Magnitude) { const Vector2f a{2.0f, 3.0f}; //Test .Magnitude(). EXPECT_EQ(a.Magnitude(), std::sqrt((a.x * a.x) + (a.y * a.y))); } TEST(Maths, Vector2f_SqrMagnitude) { const Vector2f a{2.0f, 3.0f}; //Test .SqrMagnitude(). EXPECT_EQ(a.SqrMagnitude(), (a.x * a.x) + (a.y * a.y)); } TEST(Maths, Vector2f_DotProduct) { const Vector2f a{0.0f, 3.0f}; const Vector2f b{1.0f, 0.0f}; //Test .Dot() . EXPECT_EQ(a.Dot(b), 0.0f); //Test static Dot(). EXPECT_EQ(maths::Vector2f::Dot(a, b), 0.0f); const Vector2f c{2.0f, 3.0f}; const Vector2f d{1.0f, 1.0f}; //Test .Dot(). EXPECT_EQ(c.Dot(d), c.x * d.x + c.y * d.y); //Test static Dot(). EXPECT_EQ(maths::Vector2f::Dot(c, d), c.x * d.x + c.y * d.y); } TEST(Maths, Vector2f_CrossProduct) { const Vector2f a{2.0f, 3.0f}; const Vector2f b{1.0f, -3.0f}; //Test .Cross(). EXPECT_EQ(a.Cross(b).x, 0); EXPECT_EQ(a.Cross(b).y, 0); EXPECT_EQ(a.Cross(b).z, a.x * b.y - a.y * b.x); //Test static Cross(). EXPECT_EQ(maths::Vector2f::Cross(a, b).x, 0); EXPECT_EQ(maths::Vector2f::Cross(a, b).y, 0); EXPECT_EQ(maths::Vector2f::Cross(a, b).z, a.x * b.y - a.y * b.x); } TEST(Maths, Vector2f_AngleBetween) { const Vector2f a{0.0f, 3.0f}; const Vector2f b{1.0f, 0.0f}; //Test .AngleBetween(). EXPECT_EQ(a.AngleBetween(b), maths::acos(a.Dot(b) / (a.Magnitude() * b.Magnitude()))); //Test static AngleBetween(). EXPECT_EQ(maths::Vector2f::AngleBetween(a, b), maths::acos(maths::Vector2f::Dot(a, b) / (a.Magnitude() * b.Magnitude()))); } TEST(Maths, Vector2f_Normalize) { const Vector2f a{0.0f, 3.0f}; const Vector2f b = a.Normalized(); //Test .Normalized(). EXPECT_EQ(b.Magnitude(), 1.0f); //Test .Normalize(). Vector2f c = a; c.Normalize(); EXPECT_EQ(c.Magnitude(), 1.0f); } TEST(Maths, Vector2f_Lerp) { const Vector2f a{2.0f, 3.0f}; const Vector2f b{1.0f, 4.0f}; const float t0 = 0.0f; const float t1 = 1.0f; //Test static Vector2f Lerp t = 0. Vector2f c = Vector2f::Lerp(a, b, t0); EXPECT_EQ(c.x, a.x); EXPECT_EQ(c.y, a.y); //Test static Vector2f Lerp t = 1. Vector2f d = Vector2f::Lerp(a, b, t1); EXPECT_EQ(d.x, b.x); EXPECT_EQ(d.y, b.y); //Test Vector2f Lerp t = 0. Vector2f e = a.Lerp(b, t0); EXPECT_EQ(e.x, a.x); EXPECT_EQ(e.y, a.y); //Test Vector2f Lerp t = 1. Vector2f f = a.Lerp(b, t1); EXPECT_EQ(f.x, b.x); EXPECT_EQ(f.y, b.y); } TEST(Maths, Vector2f_Slerp) { float threshold = 0.0001f; const Vector2f a{2.0f, 3.0f}; const Vector2f b{1.0f, 4.0f}; const float t0 = 0.0f; const float t1 = 1.0f; //Test Vector2f Slerp t = 0. Vector2f c = a.Slerp(b, t0); //Check difference between result & expected value //Because slerp function lose too much precision with double. EXPECT_TRUE(std::abs(c.x - a.x) < threshold); EXPECT_TRUE(std::abs(c.y - a.y) < threshold); //Test Vector2f Slerp t = 1. Vector2f d = a.Slerp(b, t1); EXPECT_TRUE(std::abs(d.x - b.x) < threshold); EXPECT_TRUE(std::abs(d.y - b.y) < threshold); } TEST(Maths, Vector2f_Rotation) { const Vector2f a = Vector2f{1.0f, 3.0f}; const degree_t b = degree_t(45.f); const radian_t c = b; //Test .Rotation(). EXPECT_EQ(a.Rotation(b).x, (a.x * maths::cos(c)) + (a.y * -maths::sin(c))); EXPECT_EQ(a.Rotation(b).y, (a.x * maths::sin(c)) + (a.y * maths::cos(c))); //Test static Rotation() . EXPECT_EQ(maths::Vector2f::Rotation(a, b).x, (a.x * maths::cos(c)) + (a.y * -maths::sin(c))); EXPECT_EQ(maths::Vector2f::Rotation(a, b).y, (a.x * maths::sin(c)) + (a.y * maths::cos(c))); } } // namespace maths
; A343461: a(n) is the maximal number of congruent n-gons that can be arranged around a vertex without overlapping. ; 6,4,3,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2 add $0,1 mov $1,4 div $1,$0 add $1,2
;=============================================================================== ; Copyright 2016-2020 Intel Corporation ; ; Licensed under the Apache License, Version 2.0 (the "License"); ; you may not use this file except in compliance with the License. ; You may obtain a copy of the License at ; ; http://www.apache.org/licenses/LICENSE-2.0 ; ; Unless required by applicable law or agreed to in writing, software ; distributed under the License is distributed on an "AS IS" BASIS, ; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; See the License for the specific language governing permissions and ; limitations under the License. ;=============================================================================== ; ; ; Purpose: Cryptography Primitive. ; P256r1 basic arithmetic function ; ; Content: ; sm2_add ; sm2_sub ; sm2_neg ; sm2_div_by_2 ; sm2_mul_mont_slm ; sm2_sqr_mont_slm ; sm2_mred ; sm2_mont_back ; %include "asmdefs.inc" %include "ia_emm.inc" %if (_IPP >= _IPP_P8) segment .text align=IPP_ALIGN_FACTOR ;; ;; some SM2 constants ;; sm2_data: _prime_sm2 DD 0FFFFFFFFh,0FFFFFFFFh,000000000h,0FFFFFFFFh,0FFFFFFFFh,0FFFFFFFFh,0FFFFFFFFh, 0FFFFFFFEh %assign LENSM2 (256/32) ; dword's length of operands ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; Ipp32u _add_256(Ipp32u* r, const Ipp32u* a, const Ipp32u* b) ;; ;; input: edi = r ;; esi = a ;; ebx = b ;; ;; output: eax = carry = 0/1 ;; align IPP_ALIGN_FACTOR IPPASM _add_256,PRIVATE ; r = a+b mov eax, dword [esi] add eax, dword [ebx] mov dword [edi], eax mov eax, dword [esi+sizeof(dword)] adc eax, dword [ebx+sizeof(dword)] mov dword [edi+sizeof(dword)], eax mov eax, dword [esi+sizeof(dword)*2] adc eax, dword [ebx+sizeof(dword)*2] mov dword [edi+sizeof(dword)*2], eax mov eax, dword [esi+sizeof(dword)*3] adc eax, dword [ebx+sizeof(dword)*3] mov dword [edi+sizeof(dword)*3], eax mov eax, dword [esi+sizeof(dword)*4] adc eax, dword [ebx+sizeof(dword)*4] mov dword [edi+sizeof(dword)*4], eax mov eax, dword [esi+sizeof(dword)*5] adc eax, dword [ebx+sizeof(dword)*5] mov dword [edi+sizeof(dword)*5], eax mov eax, dword [esi+sizeof(dword)*6] adc eax, dword [ebx+sizeof(dword)*6] mov dword [edi+sizeof(dword)*6], eax mov eax, dword [esi+sizeof(dword)*7] adc eax, dword [ebx+sizeof(dword)*7] mov dword [edi+sizeof(dword)*7], eax mov eax, 0 adc eax, 0 ret ENDFUNC _add_256 ;; ;; Ipp32u _sub_256(Ipp32u* r, const Ipp32u* a, const Ipp32u* b) ;; ;; input: edi = r ;; esi = a ;; ebx = b ;; ;; output: eax = borrow = 0/1 ;; align IPP_ALIGN_FACTOR IPPASM _sub_256,PRIVATE ; r = a-b mov eax, dword [esi] sub eax, dword [ebx] mov dword [edi], eax mov eax, dword [esi+sizeof(dword)] sbb eax, dword [ebx+sizeof(dword)] mov dword [edi+sizeof(dword)], eax mov eax, dword [esi+sizeof(dword)*2] sbb eax, dword [ebx+sizeof(dword)*2] mov dword [edi+sizeof(dword)*2], eax mov eax, dword [esi+sizeof(dword)*3] sbb eax, dword [ebx+sizeof(dword)*3] mov dword [edi+sizeof(dword)*3], eax mov eax, dword [esi+sizeof(dword)*4] sbb eax, dword [ebx+sizeof(dword)*4] mov dword [edi+sizeof(dword)*4], eax mov eax, dword [esi+sizeof(dword)*5] sbb eax, dword [ebx+sizeof(dword)*5] mov dword [edi+sizeof(dword)*5], eax mov eax, dword [esi+sizeof(dword)*6] sbb eax, dword [ebx+sizeof(dword)*6] mov dword [edi+sizeof(dword)*6], eax mov eax, dword [esi+sizeof(dword)*7] sbb eax, dword [ebx+sizeof(dword)*7] mov dword [edi+sizeof(dword)*7], eax mov eax, 0 adc eax, 0 ret ENDFUNC _sub_256 ;; ;; Ipp32u _shl_256(Ipp32u* r, const Ipp32u* a) ;; ;; input: edi = r ;; esi = a ;; ;; output: eax = extension = 0/1 ;; align IPP_ALIGN_FACTOR IPPASM _shl_256,PRIVATE ; r = a<<1 movdqu xmm0, oword [esi] movdqu xmm1, oword [esi+sizeof(oword)] mov eax, dword [esi+(LENSM2-1)*sizeof(dword)] movdqa xmm2, xmm0 psllq xmm0, 1 psrlq xmm2, 63 movdqa xmm3, xmm1 psllq xmm1, 1 psrlq xmm3, 63 palignr xmm3, xmm2, sizeof(qword) pslldq xmm2, sizeof(qword) por xmm1, xmm3 por xmm0, xmm2 movdqu oword [edi], xmm0 movdqu oword [edi+sizeof(oword)], xmm1 shr eax, 31 ret ENDFUNC _shl_256 ;; ;; void _shr_256(Ipp32u* r, const Ipp32u* a) ;; ;; input: edi = r ;; esi = a ;; eax = ext ;; output: eax = extension = 0/1 ;; align IPP_ALIGN_FACTOR IPPASM _shr_256,PRIVATE ; r = a>>1 movd xmm4, eax movdqu xmm0, oword [esi] movdqu xmm1, oword [esi+sizeof(oword)] psllq xmm4, 63 movdqa xmm2, xmm0 psrlq xmm0, 1 psllq xmm2, 63 movdqa xmm3, xmm1 psrlq xmm1, 1 psllq xmm3, 63 palignr xmm4, xmm3, sizeof(qword) palignr xmm3, xmm2, sizeof(qword) por xmm1, xmm4 por xmm0, xmm3 movdqu oword [edi], xmm0 movdqu oword [edi+sizeof(oword)], xmm1 ret ENDFUNC _shr_256 ;; ;; void cpy_256(Ipp32u* r, const Ipp32u* a) ;; %macro cpy_256 2.nolist %xdefine %%pdst %1 %xdefine %%psrc %2 movdqu xmm0, oword [%%psrc] movdqu xmm1, oword [%%psrc+sizeof(oword)] movdqu oword [%%pdst], xmm0 movdqu oword [%%pdst+sizeof(oword)], xmm1 %endmacro ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; void sm2_add(Ipp32u* r, const Ipp32u* a, const Ipp32u* b) ;; align IPP_ALIGN_FACTOR IPPASM sm2_add,PUBLIC USES_GPR esi,edi,ebx,ebp mov ebp, esp ; save original esp to use it to reach parameters %xdefine pR [ebp + ARG_1 + 0*sizeof(dword)] ; product address %xdefine pA [ebp + ARG_1 + 1*sizeof(dword)] ; source A address %xdefine pB [ebp + ARG_1 + 2*sizeof(dword)] ; source B address ; ; stack layout: ; %assign _buf_ 0 ; buffer[LENSM2] %assign _sp_ _buf_+(LENSM2)*sizeof(dword) ; esp[1] %assign _frame_ _sp_+sizeof(dword) ; +16 bytes for alignment mov eax, esp ; save esp sub esp, _frame_ ; allocate frame and esp, -16 ; provide 16-byte alignment mov dword [esp+_sp_], eax ; store esp mov edi, pR ; pR mov esi, pA ; pA mov ebx, pB ; pB CALL_IPPASM _add_256 ; R = A+B mov edx, eax lea edi, [esp+_buf_] ; T mov esi, pR ; R LD_ADDR ebx, sm2_data ; modulus lea ebx, [ebx+(_prime_sm2-sm2_data)] CALL_IPPASM _sub_256 ; T = R-modulus lea esi,[esp+_buf_] mov edi, pR sub edx, eax ; R = T<0? R : T cmovnz esi, edi cpy_256 edi, esi mov esp, [esp+_sp_] REST_GPR ret ENDFUNC sm2_add ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; void sm2_sub(Ipp32u* r, const Ipp32u* a, const Ipp32u* b) ;; align IPP_ALIGN_FACTOR IPPASM sm2_sub,PUBLIC USES_GPR esi,edi,ebx,ebp mov ebp, esp ; save original esp to use it to reach parameters %xdefine pR [ebp + ARG_1 + 0*sizeof(dword)] ; product address %xdefine pA [ebp + ARG_1 + 1*sizeof(dword)] ; source A address %xdefine pB [ebp + ARG_1 + 2*sizeof(dword)] ; source B address ; ; stack layout: ; %assign _buf_ 0 ; buffer[LENSM2] %assign _sp_ _buf_+(LENSM2)*sizeof(dword) ; esp[1] %assign _frame_ _sp_+sizeof(dword) ; +16 bytes for alignment mov eax, esp ; save esp sub esp, _frame_ ; allocate frame and esp, -16 ; provide 16-byte alignment mov dword [esp+_sp_], eax ; store esp mov edi, pR ; pR mov esi, pA ; pA mov ebx, pB ; pB CALL_IPPASM _sub_256 ; R = A-B mov edx, eax lea edi, [esp+_buf_] ; T mov esi, pR ; R LD_ADDR ebx, sm2_data ; modulus lea ebx, [ebx+(_prime_sm2-sm2_data)] CALL_IPPASM _add_256 ; T = R+modulus lea esi,[esp+_buf_] mov edi, pR test edx, edx ; R = T<0? R : T cmovz esi, edi cpy_256 edi, esi mov esp, [esp+_sp_] REST_GPR ret ENDFUNC sm2_sub ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; void sm2_neg(Ipp32u* r, const Ipp32u* a) ;; align IPP_ALIGN_FACTOR IPPASM sm2_neg,PUBLIC USES_GPR esi,edi,ebx,ebp mov ebp, esp ; save original esp to use it to reach parameters %xdefine pR [ebp + ARG_1 + 0*sizeof(dword)] ; product address %xdefine pA [ebp + ARG_1 + 1*sizeof(dword)] ; source A address ; ; stack layout: ; %assign _buf_ 0 ; buffer[LENSM2] %assign _sp_ _buf_+(LENSM2)*sizeof(dword) ; esp[1] %assign _frame_ _sp_+sizeof(dword) ; +16 bytes for alignment mov eax, esp ; save esp sub esp, _frame_ ; allocate frame and esp, -16 ; provide 16-byte alignment mov dword [esp+_sp_], eax ; store esp mov edi, pR ; outpur pR mov esi, pA ; input pA ; r = 0-a mov eax, 0 sub eax, dword [esi] mov dword [edi], eax mov eax, 0 sbb eax, dword [esi+sizeof(dword)] mov dword [edi+sizeof(dword)], eax mov eax, 0 sbb eax, dword [esi+sizeof(dword)*2] mov dword [edi+sizeof(dword)*2], eax mov eax, 0 sbb eax, dword [esi+sizeof(dword)*3] mov dword [edi+sizeof(dword)*3], eax mov eax, 0 sbb eax, dword [esi+sizeof(dword)*4] mov dword [edi+sizeof(dword)*4], eax mov eax, 0 sbb eax, dword [esi+sizeof(dword)*5] mov dword [edi+sizeof(dword)*5], eax mov eax, 0 sbb eax, dword [esi+sizeof(dword)*6] mov dword [edi+sizeof(dword)*6], eax mov eax, 0 sbb eax, dword [esi+sizeof(dword)*7] mov dword [edi+sizeof(dword)*7], eax sbb edx,edx lea edi, [esp+_buf_] ; T mov esi, pR ; R LD_ADDR ebx, sm2_data ; modulus lea ebx, [ebx+(_prime_sm2-sm2_data)] CALL_IPPASM _add_256 ; T = R+modulus lea esi,[esp+_buf_] mov edi, pR test edx, edx ; R = T<0? R : T cmovz esi, edi cpy_256 edi, esi mov esp, [esp+_sp_] REST_GPR ret ENDFUNC sm2_neg ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; void sm2_mul_by_2(Ipp32u* r, const Ipp32u* a) ;; align IPP_ALIGN_FACTOR IPPASM sm2_mul_by_2,PUBLIC USES_GPR esi,edi,ebx,ebp mov ebp, esp ; save original esp to use it to reach parameters %xdefine pR [ebp + ARG_1 + 0*sizeof(dword)] ; product address %xdefine pA [ebp + ARG_1 + 1*sizeof(dword)] ; source A address ; ; stack layout: ; %assign _buf_ 0 ; buffer[LENSM2] %assign _sp_ _buf_+(LENSM2)*sizeof(dword) ; esp[1] %assign _frame_ _sp_+sizeof(dword) ; +16 bytes for alignment mov eax, esp ; save esp sub esp, _frame_ ; allocate frame and esp, -16 ; provide 16-byte alignment mov dword [esp+_sp_], eax ; store esp lea edi, [esp+_buf_] ; T mov esi, pA ; pA CALL_IPPASM _shl_256 ; T = A<<1 mov edx, eax mov esi, edi ; T mov edi, pR ; R LD_ADDR ebx, sm2_data ; modulus lea ebx, [ebx+(_prime_sm2-sm2_data)] CALL_IPPASM _sub_256 ; R = T-modulus sub edx, eax ; R = R<0? T : R cmovz esi, edi cpy_256 edi, esi mov esp, [esp+_sp_] REST_GPR ret ENDFUNC sm2_mul_by_2 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; void sm2_mul_by_3(Ipp32u* r, const Ipp32u* a) ;; align IPP_ALIGN_FACTOR IPPASM sm2_mul_by_3,PUBLIC USES_GPR esi,edi,ebx,ebp mov ebp, esp ; save original esp to use it to reach parameters %xdefine pR [ebp + ARG_1 + 0*sizeof(dword)] ; product address %xdefine pA [ebp + ARG_1 + 1*sizeof(dword)] ; source A address ; ; stack layout: ; %assign _bufT_ 0 ; T buffer[LENSM2] %assign _bufU_ _bufT_+(LENSM2)*sizeof(dword) ; U buffer[LENSM2] %assign _mod_ _bufU_+(LENSM2)*sizeof(dword) ; modulus address [1] %assign _sp_ _mod_+sizeof(dword) ; esp [1] %assign _frame_ _sp_+sizeof(dword) ; +16 bytes for alignment mov eax, esp ; save esp sub esp, _frame_ ; allocate frame and esp, -16 ; provide 16-byte alignment mov dword [esp+_sp_], eax ; store esp LD_ADDR eax, sm2_data ; srore modulus address lea eax, [eax+(_prime_sm2-sm2_data)] mov dword [esp+_mod_], eax lea edi, [esp+_bufT_] ; T mov esi, pA ; A CALL_IPPASM _shl_256 ; T = A<<1 mov edx, eax mov esi, edi ; T lea edi, [esp+_bufU_] ; U mov ebx, [esp+_mod_] ; modulus CALL_IPPASM _sub_256 ; U = T-modulus sub edx, eax ; T = U<0? T : U cmovz esi, edi cpy_256 edi, esi mov esi, edi mov ebx, pA CALL_IPPASM _add_256 ; T +=A mov edx, eax mov edi, pR ; R mov ebx, [esp+_mod_] ; modulus CALL_IPPASM _sub_256 ; R = T-modulus sub edx, eax ; R = T<0? R : T cmovz esi, edi cpy_256 edi, esi mov esp, [esp+_sp_] REST_GPR ret ENDFUNC sm2_mul_by_3 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; void sm2_div_by_2(Ipp32u* r, const Ipp32u* a) ;; align IPP_ALIGN_FACTOR IPPASM sm2_div_by_2,PUBLIC USES_GPR esi,edi,ebx,ebp mov ebp, esp ; save original esp to use it to reach parameters %xdefine pR [ebp + ARG_1 + 0*sizeof(dword)] ; product address %xdefine pA [ebp + ARG_1 + 1*sizeof(dword)] ; source A address ; ; stack layout: ; %assign _buf_ 0 ; buffer[LENSM2] %assign _sp_ _buf_+(LENSM2)*sizeof(dword) ; esp[1] %assign _frame_ _sp_+sizeof(dword) ; +16 bytes for alignment mov eax, esp ; save esp sub esp, _frame_ ; allocate frame and esp, -16 ; provide 16-byte alignment mov dword [esp+_sp_], eax ; store esp lea edi, [esp+_buf_] ; T mov esi, pA ; A LD_ADDR ebx, sm2_data ; modulus lea ebx, [ebx+(_prime_sm2-sm2_data)] CALL_IPPASM _add_256 ; R = A+modulus mov edx, 0 mov ecx, dword [esi] ; shifted_data = (a[0]&1)? T : A and ecx, 1 cmovnz esi, edi cmovz eax, edx mov edi, pR CALL_IPPASM _shr_256 mov esp, [esp+_sp_] REST_GPR ret ENDFUNC sm2_div_by_2 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; void sm2_mul_mont_slm(Ipp32u* r, const Ipp32u* a, const Ipp32u* b) ;; align IPP_ALIGN_FACTOR IPPASM sm2_mul_mont_slm,PUBLIC USES_GPR ebp,ebx,esi,edi %xdefine pR [eax + ARG_1 + 0*sizeof(dword)] ; product address %xdefine pA [eax + ARG_1 + 1*sizeof(dword)] ; source A address %xdefine pB [eax + ARG_1 + 2*sizeof(dword)] ; source B address ; ; stack layout: ; %assign _buf_ 0 %assign _rp_ _buf_+(LENSM2+1)*sizeof(dword) ; pR %assign _ap_ _rp_ +sizeof(dword) ; pA %assign _bp_ _ap_+sizeof(dword) ; pB %assign _sp_ _bp_+sizeof(dword) ; esp storage %assign _ssize_ _sp_+sizeof(dword) ; size allocated stack mov eax, esp ; save esp sub esp, _ssize_ ; allocate stack and esp, -16 ; provide 16-byte stack alignment mov dword [esp+_sp_], eax ; store original esp ; clear buffer pxor mm0, mm0 movq qword [esp+_buf_], mm0 movq qword [esp+_buf_+sizeof(qword)], mm0 movq qword [esp+_buf_+sizeof(qword)*2], mm0 movq qword [esp+_buf_+sizeof(qword)*3], mm0 movd dword [esp+_buf_+sizeof(qword)*4], mm0 ; store parameters into the stack ; note: eax here stores an original esp, so it can be used to reach function parameters mov edi, pR mov esi, pA mov ebp, pB mov dword [esp+_rp_], edi mov dword [esp+_ap_], esi mov dword [esp+_bp_], ebp mov edi, LENSM2 movd mm1, dword [esi+sizeof(dword)] ; pre load a[1], a[2], a[3], a[4] movd mm2, dword [esi+sizeof(dword)*2] movd mm3, dword [esi+sizeof(dword)*3] movd mm4, dword [esi+sizeof(dword)*4] align IPP_ALIGN_FACTOR .mmul_loop: ; ; i-st pass ; modulus = 2^256 -2^224 +2^192 +2^96 -1 ; [8] [7] [6] [3] [0] ; m0 = 1 ; movd mm7, edi ; save pass counter mov edx, dword [ebp] ; b = b[i] mov eax, dword [esi] ; a[0] movd mm0, edx add ebp, sizeof(dword) mov dword [esp+_bp_], ebp pmuludq mm1, mm0 ; a[1]*b[i] pmuludq mm2, mm0 ; a[2]*b[i] mul edx ; (E:u) = (edx:eax) = a[0]*b[i]+buf[0] add eax, dword [esp+_buf_] adc edx, 0 pmuludq mm3, mm0 ; a[3]*b[i] pmuludq mm4, mm0 ; a[4]*b[i] ; multiplication round 1 - round 4 movd ecx, mm1 ; p = a[1]*b[i] + E psrlq mm1, 32 add ecx, edx movd edx, mm1 adc edx, 0 add ecx, dword [esp+_buf_+sizeof(dword)*1] movd mm1, dword [esi+sizeof(dword)*5] adc edx, 0 movd ebx, mm2 ; p = a[2]*b[i] + E psrlq mm2, 32 add ebx, edx movd edx, mm2 adc edx, 0 add ebx, dword [esp+_buf_+sizeof(dword)*2] movd mm2, dword [esi+sizeof(dword)*6] adc edx, 0 pmuludq mm1, mm0 ; a[5]*b[i] pmuludq mm2, mm0 ; a[6]*b[i] movd ebp, mm3 ; p = a[3]*b[i] + E psrlq mm3, 32 add ebp, edx movd edx, mm3 adc edx, 0 add ebp, dword [esp+_buf_+sizeof(dword)*3] movd mm3, dword [esi+sizeof(dword)*7] adc edx, 0 movd edi, mm4 ; p = a[4]*b[i] + E psrlq mm4, 32 add edi, edx movd edx, mm4 adc edx, 0 add edi, dword [esp+_buf_+sizeof(dword)*4] adc edx, 0 pmuludq mm3, mm0 ; a[7]*b[i] ;;; and reduction ;;; ; eax =u0 mov dword [esp+_buf_+sizeof(dword)*0], ecx ; copy add ebx, eax ; +u0 mov dword [esp+_buf_+sizeof(dword)*1], ebx mov ecx, eax sbb eax, 0 sub ebp, eax ; -u0 +cf mov dword [esp+_buf_+sizeof(dword)*2], ebp sbb edi, 0 ; -bf mov dword [esp+_buf_+sizeof(dword)*3], edi mov edi, 0 ; save edi = bf adc edi, 0 mov eax, ecx ; multiplication round 5 - round 7 movd ecx, mm1 ; p = a[5]*b[i] + E psrlq mm1, 32 add ecx, edx movd edx, mm1 adc edx, 0 add ecx, dword [esp+_buf_+sizeof(dword)*5] adc edx, 0 movd ebx, mm2 ; p = a[6]*b[i] + E psrlq mm2, 32 add ebx, edx movd edx, mm2 adc edx, 0 add ebx, dword [esp+_buf_+sizeof(dword)*6] adc edx, 0 movd ebp, mm3 ; p = a[7]*b[i] + E psrlq mm3, 32 add ebp, edx movd edx, mm3 adc edx, 0 add ebp, dword [esp+_buf_+sizeof(dword)*7] adc edx, 0 ;;; and reduction ;;; sub ecx, edi ; -bf mov dword [esp+_buf_+sizeof(dword)*4], ecx sbb ebx, 0 ; -bf mov dword [esp+_buf_+sizeof(dword)*5], ebx sbb ebp, eax ; -u0+bf mov dword [esp+_buf_+sizeof(dword)*6], ebp ; last multiplication round 8 movd edi, mm7 ; restore pass counter sbb eax, 0 ; u0-bf mov ebx, 0 add edx, dword [esp+_buf_+sizeof(dword)*8] adc ebx, 0 add edx, eax mov dword [esp+_buf_+sizeof(dword)*7], edx adc ebx, 0 mov dword [esp+_buf_+sizeof(dword)*8], ebx sub edi, 1 movd mm1, dword [esi+sizeof(dword)] ; speculative load a[1], a[2], a[3], a[4] movd mm2, dword [esi+sizeof(dword)*2] movd mm3, dword [esi+sizeof(dword)*3] movd mm4, dword [esi+sizeof(dword)*4] jz .exit_mmul_loop mov ebp, dword [esp+_bp_] ; restore pB jmp .mmul_loop .exit_mmul_loop: emms ; final reduction mov edi, [esp+_rp_] ; result lea esi, [esp+_buf_] ; buffer LD_ADDR ebx, sm2_data ; modulus lea ebx, [ebx+(_prime_sm2-sm2_data)] CALL_IPPASM _sub_256 mov edx, dword [esp+_buf_+LENSM2*sizeof(dword)] sub edx, eax ; copy cmovz esi, edi cpy_256 edi, esi mov esp, [esp+_sp_] ; release stack REST_GPR ret ENDFUNC sm2_mul_mont_slm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; void sm2_sqr_mont_slm(Ipp32u* r, const Ipp32u* a) ;; align IPP_ALIGN_FACTOR IPPASM sm2_sqr_mont_slm,PUBLIC USES_GPR esi,edi %xdefine pR [esp + ARG_1 + 0*sizeof(dword)] ; product address %xdefine pA [esp + ARG_1 + 1*sizeof(dword)] ; source A address ;; use sm2_mul_mont_slm to compute sqr mov esi, pA mov edi, pR push esi push esi push edi CALL_IPPASM sm2_mul_mont_slm,PUBLIC add esp, sizeof(dword)*3 REST_GPR ret ENDFUNC sm2_sqr_mont_slm ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; void sm2_mred(Ipp32u* r, Ipp32u* prod) ;; ; modulus = 2^256 -2^224 +2^192 +2^96 -1 ; [8] [7] [6] [3] [0] ; m0 = 1 ; align IPP_ALIGN_FACTOR IPPASM sm2_mred,PUBLIC USES_GPR ebx,esi,edi %xdefine pR [esp + ARG_1 + 0*sizeof(dword)] ; reduction address %xdefine pA [esp + ARG_1 + 1*sizeof(dword)] ; source product address ; get parameters: mov esi, pA mov ecx, LENSM2 xor edx, edx align IPP_ALIGN_FACTOR .mred_loop: mov eax, dword [esi] mov ebx, 0 mov dword [esi], ebx mov ebx, dword [esi+sizeof(dword)*2] add ebx, eax mov dword [esi+sizeof(dword)*2], ebx mov ebx, dword [esi+sizeof(dword)*3] push eax sbb eax, 0 sub ebx, eax mov dword [esi+sizeof(dword)*3], ebx pop eax mov ebx, dword [esi+sizeof(dword)*4] sbb ebx, 0 mov dword [esi+sizeof(dword)*4], ebx mov ebx, dword [esi+sizeof(dword)*5] sbb ebx, 0 mov dword [esi+sizeof(dword)*5], ebx mov ebx, dword [esi+sizeof(dword)*6] sbb ebx, 0 mov dword [esi+sizeof(dword)*6], ebx mov ebx, dword [esi+sizeof(dword)*7] sbb ebx, eax mov dword [esi+sizeof(dword)*7], ebx mov ebx, dword [esi+sizeof(dword)*8] sbb eax, 0 add eax, edx mov edx, 0 adc edx, 0 add ebx, eax mov dword [esi+sizeof(dword)*8], ebx adc edx, 0 lea esi, [esi+sizeof(dword)] sub ecx, 1 jnz .mred_loop ; final reduction mov edi, pR ; result LD_ADDR ebx, sm2_data ; addres of the modulus lea ebx, [ebx+(_prime_sm2-sm2_data)] CALL_IPPASM _sub_256 sub edx, eax cmovz esi, edi cpy_256 edi, esi REST_GPR ret ENDFUNC sm2_mred %endif ;; _IPP >= _IPP_P8
; ; Copyright (c) 2020 Phillip Stevens ; ; This Source Code Form is subject to the terms of the Mozilla Public ; License, v. 2.0. If a copy of the MPL was not distributed with this ; file, You can obtain one at http://mozilla.org/MPL/2.0/. ; ; feilipu, August 2020 ; ;------------------------------------------------------------------------- ; asm_am9511_3_popl - am9511 APU pop long ;------------------------------------------------------------------------- ; ; Load long from Am9511 APU stack ; ;------------------------------------------------------------------------- SECTION code_fp_am9511 EXTERN __IO_APU3_STATUS, __IO_APU3_DATA PUBLIC asm_am9511_3_popl_hl PUBLIC asm_am9511_3_popl .am9511_3_popl_hl_wait ex (sp),hl ex (sp),hl .asm_am9511_3_popl_hl ; float primitive ; pop a long from the Am9511 stack. ; ; enter : stack = ret1, ret0 ; : hl = pointer to long ; ; exit : stack = long, ret1 ; ; uses : af, bc, hl in a,(__IO_APU3_STATUS) ; read the APU status register rlca ; busy? __IO_APU_STATUS_BUSY jr C,am9511_3_popl_hl_wait ld bc,__IO_APU3_DATA ; the address of the APU data port in bc inc hl inc hl inc hl ind ; load MSW into APU inc b ind inc b ind ; load LSW into APU inc b ind ret .am9511_3_popl_wait ex (sp),hl ex (sp),hl .asm_am9511_3_popl ; float primitive ; pop a long from the Am9511 stack. ; ; enter : stack = ret0 ; ; exit : dehl = long ; ; uses : af, bc, de, hl in a,(__IO_APU3_STATUS) ; read the APU status register rlca ; busy? and __IO_APU_STATUS_BUSY jr C,am9511_3_popl_wait ld bc,__IO_APU3_DATA ; the address of the APU data port in bc in d,(c) ; load MSW from APU in e,(c) in h,(c) ; load LSW from APU in l,(c) ret
#include <hxcpp.h> #ifndef INCLUDED_flash_utils_ByteArray #include <flash/utils/ByteArray.h> #endif #ifndef INCLUDED_flash_utils_IDataInput #include <flash/utils/IDataInput.h> #endif #ifndef INCLUDED_flash_utils_IDataOutput #include <flash/utils/IDataOutput.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_openfl_utils_IMemoryRange #include <openfl/utils/IMemoryRange.h> #endif namespace openfl{ namespace utils{ HX_DEFINE_DYNAMIC_FUNC0(IMemoryRange_obj,getLength,return ) HX_DEFINE_DYNAMIC_FUNC0(IMemoryRange_obj,getStart,return ) HX_DEFINE_DYNAMIC_FUNC0(IMemoryRange_obj,getByteBuffer,return ) static ::String sMemberFields[] = { HX_CSTRING("getLength"), HX_CSTRING("getStart"), HX_CSTRING("getByteBuffer"), String(null()) }; static void sMarkStatics(HX_MARK_PARAMS) { HX_MARK_MEMBER_NAME(IMemoryRange_obj::__mClass,"__mClass"); }; static void sVisitStatics(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(IMemoryRange_obj::__mClass,"__mClass"); }; Class IMemoryRange_obj::__mClass; void IMemoryRange_obj::__register() { hx::Static(__mClass) = hx::RegisterClass(HX_CSTRING("openfl.utils.IMemoryRange"), hx::TCanCast< IMemoryRange_obj> ,0,sMemberFields, 0, 0, &super::__SGetClass(), 0, sMarkStatics, sVisitStatics); } void IMemoryRange_obj::__boot() { } } // end namespace openfl } // end namespace utils
; A167542: Natural numbers, swapped in pairs, with decimal digits reversed. ; Submitted by Jamie Morken(s3) ; 2,1,4,3,6,5,8,7,1,9,21,11,41,31,61,51,81,71,2,91,22,12,42,32,62,52,82,72,3,92,23,13,43,33,63,53,83,73,4,93,24,14,44,34,64,54,84,74,5,94,25,15,45,35,65,55,85,75,6,95,26,16,46,36,66,56,86,76,7,96,27,17,47,37,67 seq $0,103889 ; Odd and even positive integers swapped. seq $0,4086 ; Read n backwards (referred to as R(n) in many sequences).
// Copyright 2009-2021 NTESS. Under the terms // of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. // // Copyright (c) 2009-2021, NTESS // All rights reserved. // // This file is part of the SST software package. For license // information, see the LICENSE file in the top level directory of the // distribution. #include "sst_config.h" #include "sst/core/exit.h" #include "sst/core/warnmacros.h" #ifdef SST_CONFIG_HAVE_MPI DISABLE_WARN_MISSING_OVERRIDE #include <mpi.h> REENABLE_WARNING #endif #include "sst/core/component.h" #include "sst/core/simulation_impl.h" #include "sst/core/timeConverter.h" #include "sst/core/stopAction.h" using SST::Core::ThreadSafe::Spinlock; namespace SST { Exit::Exit( int num_threads, TimeConverter* period, bool single_rank ) : Action(), // m_functor( new EventHandler<Exit,bool,Event*> (this,&Exit::handler ) ), num_threads(num_threads), m_refCount( 0 ), m_period( period ), end_time(0), single_rank(single_rank) { setPriority(EXITPRIORITY); m_thread_counts = new unsigned int[num_threads]; for ( int i = 0; i < num_threads; i++ ) { m_thread_counts[i] = 0; } // if (!single_rank) sim->insertActivity( period->getFactor(), this ); } Exit::~Exit() { m_idSet.clear(); } bool Exit::refInc( ComponentId_t id, uint32_t thread ) { std::lock_guard<Spinlock> lock(slock); if ( m_idSet.find( id ) != m_idSet.end() ) { // CompMap_t comp_map = Simulation::getSimulation()->getComponentMap(); // bool found_in_map = false; // for(CompMap_t::iterator comp_map_itr = comp_map.begin(); // comp_map_itr != comp_map.end(); // ++comp_map_itr) { // if(comp_map_itr->second->getId() == id) { // found_in_map = true; // break; // } // } // if(found_in_map) { // _DBG( Exit, "component (%s) multiple increment\n", // Simulation::getSimulation()->getComponent(id)->getName().c_str() ); // } else { // _DBG( Exit, "component in construction increments exit multiple times.\n" ); // } return true; } m_idSet.insert( id ); ++m_refCount; ++m_thread_counts[thread]; return false; } bool Exit::refDec( ComponentId_t id, uint32_t thread ) { // TraceFunction trace(CALL_INFO_LONG); std::lock_guard<Spinlock> lock(slock); if ( m_idSet.find( id ) == m_idSet.end() ) { Simulation::getSimulation()->getSimulationOutput().verbose(CALL_INFO, 1, 1, "component (%s) multiple decrement\n", Simulation_impl::getSimulation()->getComponent(id)->getName().c_str() ); return true; } if ( m_refCount == 0 ) { Simulation::getSimulation()->getSimulationOutput().fatal(CALL_INFO, 1, "refCount is already 0\n" ); return true; } m_idSet.erase( id ); --m_refCount; --m_thread_counts[thread]; if ( single_rank && num_threads == 1 && m_refCount == 0 ) { //std::cout << "Exiting..." << std::endl; end_time = Simulation::getSimulation()->getCurrentSimCycle(); Simulation_impl* sim = Simulation_impl::getSimulation(); // sim->insertActivity( sim->getCurrentSimCycle() + m_period->getFactor(), this ); sim->insertActivity( sim->getCurrentSimCycle() + 1, this ); } else if ( m_thread_counts[thread] == 0 ) { SimTime_t end_time_new = Simulation::getSimulation()->getCurrentSimCycle(); // trace.getOutput().output(CALL_INFO,"end_time_new = %llu\n",end_time_new); // trace.getOutput().output(CALL_INFO,"end_time = %llu\n",end_time); if ( end_time_new > end_time ) end_time = end_time_new; if ( Simulation_impl::getSimulation()->isIndependentThread() ) { // Need to exit just this thread, so we'll need to use a // StopAction Simulation_impl* sim = Simulation_impl::getSimulation(); sim->insertActivity( sim->getCurrentSimCycle(), new StopAction() ); } } return false; } unsigned int Exit::getRefCount() { return m_refCount; } void Exit::execute() { check(); SimTime_t next = Simulation::getSimulation()->getCurrentSimCycle() + m_period->getFactor(); Simulation_impl::getSimulation()->insertActivity( next, this ); } SimTime_t Exit::computeEndTime() { #ifdef SST_CONFIG_HAVE_MPI // Do an all_reduce to get the end_time SimTime_t end_value; if ( !single_rank ) { MPI_Allreduce( &end_time, &end_value, 1, MPI_UINT64_T, MPI_MAX, MPI_COMM_WORLD ); end_time = end_value; } #endif if (single_rank) { endSimulation(end_time); } return end_time; } // bool Exit::handler( Event* e ) void Exit::check() { // TraceFunction trace(CALL_INFO_LONG); int value = ( m_refCount > 0 ); int out; #ifdef SST_CONFIG_HAVE_MPI if ( !single_rank ) { MPI_Allreduce( &value, &out, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD ); } else { out = value; } #else out = value; #endif global_count = out; // If out is 0, then it's time to end if ( !out ) { computeEndTime(); } // else { // // Reinsert into TimeVortex. We do this even when ending so that // // it will get deleted with the TimeVortex on termination. We do // // this in case we exit with a StopEvent instead. In that case, // // there is no way to know if the Exit object is deleted in the // // TimeVortex or not, so we just make sure it is always deleted // // there. // Simulation *sim = Simulation::getSimulation(); // SimTime_t next = sim->getCurrentSimCycle() + // m_period->getFactor(); // sim->insertActivity( next, this ); // } } } // namespace SST
; SameBoy CGB bootstrap ROM ; Todo: use friendly names for HW registers instead of magic numbers SECTION "BootCode", ROM0[$0] Start: ; Init stack pointer ld sp, $fffe ; Clear memory VRAM call ClearMemoryPage8000 ld a, 2 ld c, $70 ld [c], a ; Clear RAM Bank 2 (Like the original boot ROM) ld h, $D0 call ClearMemoryPage ld [c], a ; Clear chosen input palette ldh [InputPalette], a ; Clear title checksum ldh [TitleChecksum], a ld a, $80 ldh [$26], a ldh [$11], a ld a, $f3 ldh [$12], a ldh [$25], a ld a, $77 ldh [$24], a ld hl, $FF30 ; Init waveform ld c, $10 .waveformLoop ldi [hl], a cpl dec c jr nz, .waveformLoop ; Clear OAM ld h, $fe ld c, $a0 .clearOAMLoop ldi [hl], a dec c jr nz, .clearOAMLoop ; Init BG palette ld a, $fc ldh [$47], a ; Load logo from ROM. ; A nibble represents a 4-pixels line, 2 bytes represent a 4x4 tile, scaled to 8x8. ; Tiles are ordered left to right, top to bottom. ; These tiles are not used, but are required for DMG compatibility. This is done ; by the original CGB Boot ROM as well. ld de, $104 ; Logo start ld hl, $8010 ; This is where we load the tiles in VRAM .loadLogoLoop ld a, [de] ; Read 2 rows ld b, a call DoubleBitsAndWriteRowTwice inc de ld a, e cp $34 ; End of logo jr nz, .loadLogoLoop call ReadTrademarkSymbol ; Clear the second VRAM bank ld a, 1 ldh [$4F], a call ClearMemoryPage8000 call LoadTileset ld b, 3 IF DEF(FAST) xor a ldh [$4F], a ELSE ; Load Tilemap ld hl, $98C2 ld d, 3 ld a, 8 .tilemapLoop ld c, $10 .tilemapRowLoop call .write_with_palette ; Repeat the 3 tiles common between E and B. This saves 27 bytes after ; compression, with a cost of 17 bytes of code. push af sub $20 sub $3 jr nc, .notspecial add $20 call .write_with_palette dec c .notspecial pop af add d ; d = 3 for SameBoy logo, d = 1 for Nintendo logo dec c jr nz, .tilemapRowLoop sub 44 push de ld de, $10 add hl, de pop de dec b jr nz, .tilemapLoop dec d jr z, .endTilemap dec d ld a, $38 ld l, $a7 ld bc, $0107 jr .tilemapRowLoop .write_with_palette push af ; Switch to second VRAM Bank ld a, 1 ldh [$4F], a ld [hl], 8 ; Switch to back first VRAM Bank xor a ldh [$4F], a pop af ldi [hl], a ret .endTilemap ENDC ; Expand Palettes ld de, AnimationColors ld c, 8 ld hl, BgPalettes xor a .expandPalettesLoop: cpl ; One white ld [hli], a ld [hli], a ; Mixed with white ld a, [de] inc e or $20 ld b, a ld a, [de] dec e or $84 rra rr b ld [hl], b inc l ld [hli], a ; One black xor a ld [hli], a ld [hli], a ; One color ld a, [de] inc e ld [hli], a ld a, [de] inc e ld [hli], a xor a dec c jr nz, .expandPalettesLoop ld hl, BgPalettes call LoadBGPalettes64 ; Turn on LCD ld a, $91 ldh [$40], a IF !DEF(FAST) call DoIntroAnimation ld a, 45 ldh [WaitLoopCounter], a ; Wait ~0.75 seconds ld b, a call WaitBFrames ; Play first sound ld a, $83 call PlaySound ld b, 5 call WaitBFrames ; Play second sound ld a, $c1 call PlaySound .waitLoop call GetInputPaletteIndex call WaitFrame ld hl, WaitLoopCounter dec [hl] jr nz, .waitLoop ELSE ld a, $c1 call PlaySound ENDC call Preboot IF DEF(AGB) ld b, 1 ENDC ; Will be filled with NOPs SECTION "BootGame", ROM0[$fe] BootGame: ldh [$50], a SECTION "MoreStuff", ROM0[$200] ; Game Palettes Data TitleChecksums: db $00 ; Default db $88 ; ALLEY WAY db $16 ; YAKUMAN db $36 ; BASEBALL, (Game and Watch 2) db $D1 ; TENNIS db $DB ; TETRIS db $F2 ; QIX db $3C ; DR.MARIO db $8C ; RADARMISSION db $92 ; F1RACE db $3D ; YOSSY NO TAMAGO db $5C ; db $58 ; X db $C9 ; MARIOLAND2 db $3E ; YOSSY NO COOKIE db $70 ; ZELDA db $1D ; db $59 ; db $69 ; TETRIS FLASH db $19 ; DONKEY KONG db $35 ; MARIO'S PICROSS db $A8 ; db $14 ; POKEMON RED, (GAMEBOYCAMERA G) db $AA ; POKEMON GREEN db $75 ; PICROSS 2 db $95 ; YOSSY NO PANEPON db $99 ; KIRAKIRA KIDS db $34 ; GAMEBOY GALLERY db $6F ; POCKETCAMERA db $15 ; db $FF ; BALLOON KID db $97 ; KINGOFTHEZOO db $4B ; DMG FOOTBALL db $90 ; WORLD CUP db $17 ; OTHELLO db $10 ; SUPER RC PRO-AM db $39 ; DYNABLASTER db $F7 ; BOY AND BLOB GB2 db $F6 ; MEGAMAN db $A2 ; STAR WARS-NOA db $49 ; db $4E ; WAVERACE db $43 | $80 ; db $68 ; LOLO2 db $E0 ; YOSHI'S COOKIE db $8B ; MYSTIC QUEST db $F0 ; db $CE ; TOPRANKINGTENNIS db $0C ; MANSELL db $29 ; MEGAMAN3 db $E8 ; SPACE INVADERS db $B7 ; GAME&WATCH db $86 ; DONKEYKONGLAND95 db $9A ; ASTEROIDS/MISCMD db $52 ; STREET FIGHTER 2 db $01 ; DEFENDER/JOUST db $9D ; KILLERINSTINCT95 db $71 ; TETRIS BLAST db $9C ; PINOCCHIO db $BD ; db $5D ; BA.TOSHINDEN db $6D ; NETTOU KOF 95 db $67 ; db $3F ; TETRIS PLUS db $6B ; DONKEYKONGLAND 3 ; For these games, the 4th letter is taken into account FirstChecksumWithDuplicate: ; Let's play hangman! db $B3 ; ???[B]???????? db $46 ; SUP[E]R MARIOLAND db $28 ; GOL[F] db $A5 ; SOL[A]RSTRIKER db $C6 ; GBW[A]RS db $D3 ; KAE[R]UNOTAMENI db $27 ; ???[B]???????? db $61 ; POK[E]MON BLUE db $18 ; DON[K]EYKONGLAND db $66 ; GAM[E]BOY GALLERY2 db $6A ; DON[K]EYKONGLAND 2 db $BF ; KID[ ]ICARUS db $0D ; TET[R]IS2 db $F4 ; ???[-]???????? db $B3 ; MOG[U]RANYA db $46 ; ???[R]???????? db $28 ; GAL[A]GA&GALAXIAN db $A5 ; BT2[R]AGNAROKWORLD db $C6 ; KEN[ ]GRIFFEY JR db $D3 ; ???[I]???????? db $27 ; MAG[N]ETIC SOCCER db $61 ; VEG[A]S STAKES db $18 ; ???[I]???????? db $66 ; MIL[L]I/CENTI/PEDE db $6A ; MAR[I]O & YOSHI db $BF ; SOC[C]ER db $0D ; POK[E]BOM db $F4 ; G&W[ ]GALLERY db $B3 ; TET[R]IS ATTACK ChecksumsEnd: PalettePerChecksum: ; | $80 means game requires DMG boot tilemap db 0 ; Default Palette db 4 ; ALLEY WAY db 5 ; YAKUMAN db 35 ; BASEBALL, (Game and Watch 2) db 34 ; TENNIS db 3 ; TETRIS db 31 ; QIX db 15 ; DR.MARIO db 10 ; RADARMISSION db 5 ; F1RACE db 19 ; YOSSY NO TAMAGO db 36 ; db 7 | $80 ; X db 37 ; MARIOLAND2 db 30 ; YOSSY NO COOKIE db 44 ; ZELDA db 21 ; db 32 ; db 31 ; TETRIS FLASH db 20 ; DONKEY KONG db 5 ; MARIO'S PICROSS db 33 ; db 13 ; POKEMON RED, (GAMEBOYCAMERA G) db 14 ; POKEMON GREEN db 5 ; PICROSS 2 db 29 ; YOSSY NO PANEPON db 5 ; KIRAKIRA KIDS db 18 ; GAMEBOY GALLERY db 9 ; POCKETCAMERA db 3 ; db 2 ; BALLOON KID db 26 ; KINGOFTHEZOO db 25 ; DMG FOOTBALL db 25 ; WORLD CUP db 41 ; OTHELLO db 42 ; SUPER RC PRO-AM db 26 ; DYNABLASTER db 45 ; BOY AND BLOB GB2 db 42 ; MEGAMAN db 45 ; STAR WARS-NOA db 36 ; db 38 ; WAVERACE db 26 ; db 42 ; LOLO2 db 30 ; YOSHI'S COOKIE db 41 ; MYSTIC QUEST db 34 ; db 34 ; TOPRANKINGTENNIS db 5 ; MANSELL db 42 ; MEGAMAN3 db 6 ; SPACE INVADERS db 5 ; GAME&WATCH db 33 ; DONKEYKONGLAND95 db 25 ; ASTEROIDS/MISCMD db 42 ; STREET FIGHTER 2 db 42 ; DEFENDER/JOUST db 40 ; KILLERINSTINCT95 db 2 ; TETRIS BLAST db 16 ; PINOCCHIO db 25 ; db 42 ; BA.TOSHINDEN db 42 ; NETTOU KOF 95 db 5 ; db 0 ; TETRIS PLUS db 39 ; DONKEYKONGLAND 3 db 36 ; db 22 ; SUPER MARIOLAND db 25 ; GOLF db 6 ; SOLARSTRIKER db 32 ; GBWARS db 12 ; KAERUNOTAMENI db 36 ; db 11 ; POKEMON BLUE db 39 ; DONKEYKONGLAND db 18 ; GAMEBOY GALLERY2 db 39 ; DONKEYKONGLAND 2 db 24 ; KID ICARUS db 31 ; TETRIS2 db 50 ; db 17 ; MOGURANYA db 46 ; db 6 ; GALAGA&GALAXIAN db 27 ; BT2RAGNAROKWORLD db 0 ; KEN GRIFFEY JR db 47 ; db 41 ; MAGNETIC SOCCER db 41 ; VEGAS STAKES db 0 ; db 0 ; MILLI/CENTI/PEDE db 19 ; MARIO & YOSHI db 34 ; SOCCER db 23 ; POKEBOM db 18 ; G&W GALLERY db 29 ; TETRIS ATTACK Dups4thLetterArray: db "BEFAARBEKEK R-URAR INAILICE R" ; We assume the last three arrays fit in the same $100 byte page! PaletteCombinations: palette_comb: MACRO ; Obj0, Obj1, Bg db (\1) * 8, (\2) * 8, (\3) *8 ENDM raw_palette_comb: MACRO ; Obj0, Obj1, Bg db (\1) * 2, (\2) * 2, (\3) * 2 ENDM palette_comb 4, 4, 29 palette_comb 18, 18, 18 palette_comb 20, 20, 20 palette_comb 24, 24, 24 palette_comb 9, 9, 9 palette_comb 0, 0, 0 palette_comb 27, 27, 27 palette_comb 5, 5, 5 palette_comb 12, 12, 12 palette_comb 26, 26, 26 palette_comb 16, 8, 8 palette_comb 4, 28, 28 palette_comb 4, 2, 2 palette_comb 3, 4, 4 palette_comb 4, 29, 29 palette_comb 28, 4, 28 palette_comb 2, 17, 2 palette_comb 16, 16, 8 palette_comb 4, 4, 7 palette_comb 4, 4, 18 palette_comb 4, 4, 20 palette_comb 19, 19, 9 raw_palette_comb 4 * 4 - 1, 4 * 4 - 1, 11 * 4 palette_comb 17, 17, 2 palette_comb 4, 4, 2 palette_comb 4, 4, 3 palette_comb 28, 28, 0 palette_comb 3, 3, 0 palette_comb 0, 0, 1 palette_comb 18, 22, 18 palette_comb 20, 22, 20 palette_comb 24, 22, 24 palette_comb 16, 22, 8 palette_comb 17, 4, 13 raw_palette_comb 28 * 4 - 1, 0 * 4, 14 * 4 raw_palette_comb 28 * 4 - 1, 4 * 4, 15 * 4 palette_comb 19, 22, 9 palette_comb 16, 28, 10 palette_comb 4, 23, 28 palette_comb 17, 22, 2 palette_comb 4, 0, 2 palette_comb 4, 28, 3 palette_comb 28, 3, 0 palette_comb 3, 28, 4 palette_comb 21, 28, 4 palette_comb 3, 28, 0 palette_comb 25, 3, 28 palette_comb 0, 28, 8 palette_comb 4, 3, 28 palette_comb 28, 3, 6 palette_comb 4, 28, 29 ; SameBoy "Exclusives" palette_comb 30, 30, 30 ; CGA palette_comb 31, 31, 31 ; DMG LCD palette_comb 28, 4, 1 palette_comb 0, 0, 2 Palettes: dw $7FFF, $32BF, $00D0, $0000 dw $639F, $4279, $15B0, $04CB dw $7FFF, $6E31, $454A, $0000 dw $7FFF, $1BEF, $0200, $0000 dw $7FFF, $421F, $1CF2, $0000 dw $7FFF, $5294, $294A, $0000 dw $7FFF, $03FF, $012F, $0000 dw $7FFF, $03EF, $01D6, $0000 dw $7FFF, $42B5, $3DC8, $0000 dw $7E74, $03FF, $0180, $0000 dw $67FF, $77AC, $1A13, $2D6B dw $7ED6, $4BFF, $2175, $0000 dw $53FF, $4A5F, $7E52, $0000 dw $4FFF, $7ED2, $3A4C, $1CE0 dw $03ED, $7FFF, $255F, $0000 dw $036A, $021F, $03FF, $7FFF dw $7FFF, $01DF, $0112, $0000 dw $231F, $035F, $00F2, $0009 dw $7FFF, $03EA, $011F, $0000 dw $299F, $001A, $000C, $0000 dw $7FFF, $027F, $001F, $0000 dw $7FFF, $03E0, $0206, $0120 dw $7FFF, $7EEB, $001F, $7C00 dw $7FFF, $3FFF, $7E00, $001F dw $7FFF, $03FF, $001F, $0000 dw $03FF, $001F, $000C, $0000 dw $7FFF, $033F, $0193, $0000 dw $0000, $4200, $037F, $7FFF dw $7FFF, $7E8C, $7C00, $0000 dw $7FFF, $1BEF, $6180, $0000 ; SameBoy "Exclusives" dw $7FFF, $7FEA, $7D5F, $0000 ; CGA 1 dw $4778, $3290, $1D87, $0861 ; DMG LCD KeyCombinationPalettes db 1 * 3 ; Right db 48 * 3 ; Left db 5 * 3 ; Up db 8 * 3 ; Down db 0 * 3 ; Right + A db 40 * 3 ; Left + A db 43 * 3 ; Up + A db 3 * 3 ; Down + A db 6 * 3 ; Right + B db 7 * 3 ; Left + B db 28 * 3 ; Up + B db 49 * 3 ; Down + B ; SameBoy "Exclusives" db 51 * 3 ; Right + A + B db 52 * 3 ; Left + A + B db 53 * 3 ; Up + A + B db 54 * 3 ; Down + A + B TrademarkSymbol: db $3c,$42,$b9,$a5,$b9,$a5,$42,$3c SameBoyLogo: incbin "SameBoyLogo.pb12" AnimationColors: dw $7FFF ; White dw $774F ; Cyan dw $22C7 ; Green dw $039F ; Yellow dw $017D ; Orange dw $241D ; Red dw $6D38 ; Purple dw $7102 ; Blue AnimationColorsEnd: ; Helper Functions DoubleBitsAndWriteRowTwice: call .twice .twice ; Double the most significant 4 bits, b is shifted by 4 ld a, 4 ld c, 0 .doubleCurrentBit sla b push af rl c pop af rl c dec a jr nz, .doubleCurrentBit ld a, c ; Write as two rows ldi [hl], a inc hl ldi [hl], a inc hl ret WaitFrame: push hl ld hl, $FF0F res 0, [hl] .wait bit 0, [hl] jr z, .wait pop hl ret WaitBFrames: call GetInputPaletteIndex call WaitFrame dec b jr nz, WaitBFrames ret PlaySound: ldh [$13], a ld a, $87 ldh [$14], a ret ClearMemoryPage8000: ld hl, $8000 ; Clear from HL to HL | 0x2000 ClearMemoryPage: xor a ldi [hl], a bit 5, h jr z, ClearMemoryPage ret ReadTwoTileLines: call ReadTileLine ; c = $f0 for even lines, $f for odd lines. ReadTileLine: ld a, [de] and c ld b, a inc e inc e ld a, [de] dec e dec e and c swap a or b bit 0, c jr z, .dontSwap swap a .dontSwap inc hl ldi [hl], a swap c ret ReadCGBLogoHalfTile: call .do_twice .do_twice call ReadTwoTileLines inc e ld a, e ret ; LoadTileset using PB12 codec, 2020 Jakub Kądziołka ; (based on PB8 codec, 2019 Damian Yerrick) SameBoyLogo_dst = $8080 SameBoyLogo_length = (128 * 24) / 64 LoadTileset: ld hl, SameBoyLogo ld de, SameBoyLogo_dst - 1 ld c, SameBoyLogo_length .refill ; Register map for PB12 decompression ; HL: source address in boot ROM ; DE: destination address in VRAM ; A: Current literal value ; B: Repeat bits, terminated by 1000... ; Source address in HL lets the repeat bits go straight to B, ; bypassing A and avoiding spilling registers to the stack. ld b, [hl] dec b jr z, .sameboyLogoEnd inc b inc hl ; Shift a 1 into lower bit of shift value. Once this bit ; reaches the carry, B becomes 0 and the byte is over scf rl b .loop ; If not a repeat, load a literal byte jr c, .simple_repeat sla b jr c, .shifty_repeat ld a, [hli] jr .got_byte .shifty_repeat sla b jr nz, .no_refill_during_shift ld b, [hl] ; see above. Also, no, factoring it out into a callable inc hl ; routine doesn't save bytes, even with conditional calls scf rl b .no_refill_during_shift ld c, a jr nc, .shift_left srl a db $fe ; eat the add a with cp d8 .shift_left add a sla b jr c, .go_and or c db $fe ; eat the and c with cp d8 .go_and and c jr .got_byte .simple_repeat sla b jr c, .got_byte ; far repeat dec de ld a, [de] inc de .got_byte inc de ld [de], a sla b jr nz, .loop jr .refill ; End PB12 decoding. The rest uses HL as the destination .sameboyLogoEnd ld h, d ld l, $80 ; Copy (unresized) ROM logo ld de, $104 .CGBROMLogoLoop ld c, $f0 call ReadCGBLogoHalfTile add a, 22 ld e, a call ReadCGBLogoHalfTile sub a, 22 ld e, a cp $1c jr nz, .CGBROMLogoLoop inc hl ; fallthrough ReadTrademarkSymbol: ld de, TrademarkSymbol ld c,$08 .loadTrademarkSymbolLoop: ld a,[de] inc de ldi [hl],a inc hl dec c jr nz, .loadTrademarkSymbolLoop ret DoIntroAnimation: ; Animate the intro ld a, 1 ldh [$4F], a ld d, 26 .animationLoop ld b, 2 call WaitBFrames ld hl, $98C0 ld c, 3 ; Row count .loop ld a, [hl] cp $F ; Already blue jr z, .nextTile inc [hl] and $7 jr z, .nextLine ; Changed a white tile, go to next line .nextTile inc hl jr .loop .nextLine ld a, l or $1F ld l, a inc hl dec c jr nz, .loop dec d jr nz, .animationLoop ret Preboot: IF !DEF(FAST) ld b, 32 ; 32 times to fade .fadeLoop ld c, 32 ; 32 colors to fade ld hl, BgPalettes push hl .frameLoop push bc ; Brighten Color ld a, [hli] ld e, a ld a, [hld] ld d, a ; RGB(1,1,1) ld bc, $421 ; Is blue maxed? ld a, e and $1F cp $1F jr nz, .blueNotMaxed dec c .blueNotMaxed ; Is green maxed? ld a, e cp $E0 jr c, .greenNotMaxed ld a, d and $3 cp $3 jr nz, .greenNotMaxed res 5, c .greenNotMaxed ; Is red maxed? ld a, d and $7C cp $7C jr nz, .redNotMaxed res 2, b .redNotMaxed ; add de, bc ; ld [hli], de ld a, e add c ld [hli], a ld a, d adc b ld [hli], a pop bc dec c jr nz, .frameLoop call WaitFrame pop hl call LoadBGPalettes64 call WaitFrame dec b jr nz, .fadeLoop ENDC ld a, 1 call ClearVRAMViaHDMA call _ClearVRAMViaHDMA call ClearVRAMViaHDMA ; A = $40, so it's bank 0 ld a, $ff ldh [$00], a ; Final values for CGB mode ld d, a ld e, c ld l, $0d ld a, [$143] bit 7, a call z, EmulateDMG bit 7, a ldh [$4C], a ldh a, [TitleChecksum] ld b, a jr z, .skipDMGForCGBCheck ldh a, [InputPalette] and a jr nz, .emulateDMGForCGBGame .skipDMGForCGBCheck IF DEF(AGB) ; Set registers to match the original AGB-CGB boot ; AF = $1100, C = 0 xor a ld c, a add a, $11 ld h, c ; B is set to 1 after ret ELSE ; Set registers to match the original CGB boot ; AF = $1180, C = 0 xor a ld c, a ld a, $11 ld h, c ; B is set to the title checksum ENDC ret .emulateDMGForCGBGame call EmulateDMG ldh [$4C], a ld a, $1 ret GetKeyComboPalette: ld hl, KeyCombinationPalettes - 1 ; Return value is 1-based, 0 means nothing down ld c ,a ld b, 0 add hl, bc ld a, [hl] ret EmulateDMG: ld a, 1 ldh [$6C], a ; DMG Emulation call GetPaletteIndex bit 7, a call nz, LoadDMGTilemap and $7F ld b, a ldh a, [InputPalette] and a jr z, .nothingDown call GetKeyComboPalette jr .paletteFromKeys .nothingDown ld a, b .paletteFromKeys call WaitFrame call LoadPalettesFromIndex ld a, 4 ; Set the final values for DMG mode ld de, 8 ld l, $7c ret GetPaletteIndex: ld hl, $14B ld a, [hl] ; Old Licensee cp $33 jr z, .newLicensee dec a ; 1 = Nintendo jr nz, .notNintendo jr .doChecksum .newLicensee ld l, $44 ld a, [hli] cp "0" jr nz, .notNintendo ld a, [hl] cp "1" jr nz, .notNintendo .doChecksum ld l, $34 ld c, $10 xor a .checksumLoop add [hl] inc l dec c jr nz, .checksumLoop ld b, a ; c = 0 ld hl, TitleChecksums .searchLoop ld a, l sub LOW(ChecksumsEnd) ; use sub to zero out a ret z ld a, [hli] cp b jr nz, .searchLoop ; We might have a match, Do duplicate/4th letter check ld a, l sub FirstChecksumWithDuplicate - TitleChecksums jr c, .match ; Does not have a duplicate, must be a match! ; Has a duplicate; check 4th letter push hl ld a, l add Dups4thLetterArray - FirstChecksumWithDuplicate - 1 ; -1 since hl was incremented ld l, a ld a, [hl] pop hl ld c, a ld a, [$134 + 3] ; Get 4th letter cp c jr nz, .searchLoop ; Not a match, continue .match ld a, l add PalettePerChecksum - TitleChecksums - 1; -1 since hl was incremented ld l, a ld a, b ldh [TitleChecksum], a ld a, [hl] ret .notNintendo xor a ret GetPaletteCombo: ld hl, PaletteCombinations ld b, 0 ld c, a add hl, bc ret LoadPalettesFromIndex: ; a = index of combination call GetPaletteCombo ; Obj Palettes ld e, 0 .loadObjPalette ld a, [hli] push hl ld hl, Palettes ld b, 0 ld c, a add hl, bc ld d, 8 ld c, $6A call LoadPalettes pop hl bit 3, e jr nz, .loadBGPalette ld e, 8 jr .loadObjPalette .loadBGPalette ;BG Palette ld a, [hli] ld hl, Palettes ld b, 0 ld c, a add hl, bc ld d, 8 jr LoadBGPalettes LoadBGPalettes64: ld d, 64 LoadBGPalettes: ld e, 0 ld c, $68 LoadPalettes: ld a, $80 or e ld [c], a inc c .loop ld a, [hli] ld [c], a dec d jr nz, .loop ret ClearVRAMViaHDMA: ldh [$4F], a ld hl, HDMAData _ClearVRAMViaHDMA: ld c, $51 ld b, 5 .loop ld a, [hli] ldh [c], a inc c dec b jr nz, .loop ret GetInputPaletteIndex: ld a, $20 ; Select directions ldh [$00], a ldh a, [$00] cpl and $F ret z ; No direction keys pressed, no palette push bc ld c, 0 .directionLoop inc c rra jr nc, .directionLoop ; c = 1: Right, 2: Left, 3: Up, 4: Down ld a, $10 ; Select buttons ldh [$00], a ldh a, [$00] cpl rla rla and $C add c ld b, a ldh a, [InputPalette] ld c, a ld a, b ldh [InputPalette], a cp c pop bc ret z ; No change, don't load ; Slide into change Animation Palette ChangeAnimationPalette: push bc push de call GetKeyComboPalette call GetPaletteCombo inc l inc l ld a, [hl] ld hl, Palettes + 1 ld b, 0 ld c, a add hl, bc ld a, [hld] cp $7F ; Is white color? jr nz, .isWhite inc hl inc hl .isWhite push af ld a, [hli] push hl ld hl, BgPalettes ; First color, all palettes call ReplaceColorInAllPalettes ld l, LOW(BgPalettes + 2) ; Second color, all palettes call ReplaceColorInAllPalettes pop hl ldh [BgPalettes + 6], a ; Fourth color, first palette ld a, [hli] push hl ld hl, BgPalettes + 1 ; First color, all palettes call ReplaceColorInAllPalettes ld l, LOW(BgPalettes + 3) ; Second color, all palettes call ReplaceColorInAllPalettes pop hl ldh [BgPalettes + 7], a ; Fourth color, first palette pop af jr z, .isNotWhite inc hl inc hl .isNotWhite ; Mixing code by ISSOtm ldh a, [BgPalettes + 7 * 8 + 2] and ~$21 ld b, a ld a, [hli] and ~$21 add a, b ld b, a ld a, [BgPalettes + 7 * 8 + 3] res 2, a ; and ~$04, but not touching carry ld c, [hl] res 2, c ; and ~$04, but not touching carry adc a, c rra ; Carry sort of "extends" the accumulator, we're bringing that bit back home ld [BgPalettes + 7 * 8 + 3], a ld a, b rra ld [BgPalettes + 7 * 8 + 2], a dec l ld a, [hli] ldh [BgPalettes + 7 * 8 + 6], a ; Fourth color, 7th palette ld a, [hli] ldh [BgPalettes + 7 * 8 + 7], a ; Fourth color, 7th palette ld a, [hli] ldh [BgPalettes + 4], a ; Third color, first palette ld a, [hli] ldh [BgPalettes + 5], a ; Third color, first palette call WaitFrame ld hl, BgPalettes call LoadBGPalettes64 ; Delay the wait loop while the user is selecting a palette ld a, 45 ldh [WaitLoopCounter], a pop de pop bc ret ReplaceColorInAllPalettes: ld de, 8 ld c, e .loop ld [hl], a add hl, de dec c jr nz, .loop ret LoadDMGTilemap: push af call WaitFrame ld a, $19 ; Trademark symbol ld [$9910], a ; ... put in the superscript position ld hl,$992f ; Bottom right corner of the logo ld c,$c ; Tiles in a logo row .tilemapLoop dec a jr z, .tilemapDone ldd [hl], a dec c jr nz, .tilemapLoop ld l, $0f ; Jump to top row jr .tilemapLoop .tilemapDone pop af ret HDMAData: db $88, $00, $98, $A0, $12 db $88, $00, $80, $00, $40 BootEnd: IF BootEnd > $900 FAIL "BootROM overflowed: {BootEnd}" ENDC SECTION "HRAM", HRAM[$FF80] TitleChecksum: ds 1 BgPalettes: ds 8 * 4 * 2 InputPalette: ds 1 WaitLoopCounter: ds 1
; A007070: a(n) = 4*a(n-1) - 2*a(n-2) with a(0) = 1, a(1) = 4. ; 1,4,14,48,164,560,1912,6528,22288,76096,259808,887040,3028544,10340096,35303296,120532992,411525376,1405035520,4797091328,16378294272,55918994432,190919389184,651839567872,2225519493120,7598398836736,25942556360704,88573427769344,302408598355968,1032487537885184,3525132954828800 mov $1,1 lpb $0 sub $0,1 add $2,$1 mul $1,2 add $1,1 add $1,$2 lpe
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r15 push %rax push %rbx push %rcx push %rdi push %rsi lea addresses_normal_ht+0x10b7b, %rax nop nop nop nop nop cmp %r10, %r10 mov $0x6162636465666768, %rcx movq %rcx, %xmm3 movups %xmm3, (%rax) nop nop nop nop nop sub $45645, %r10 lea addresses_A_ht+0x8e1b, %rsi lea addresses_WT_ht+0x11a93, %rdi clflush (%rdi) nop cmp $57160, %r15 mov $99, %rcx rep movsw nop nop nop nop sub $22750, %rax lea addresses_UC_ht+0x105eb, %r10 clflush (%r10) nop nop cmp %rsi, %rsi movw $0x6162, (%r10) nop nop nop add $43569, %rdi lea addresses_WC_ht+0x18a9b, %rsi lea addresses_A_ht+0x1a41b, %rdi nop nop nop nop nop xor $49679, %rbx mov $97, %rcx rep movsw nop nop nop nop nop sub $38633, %rcx lea addresses_D_ht+0xb79b, %rsi lea addresses_UC_ht+0x1cd1b, %rdi nop nop nop add $39101, %rbx mov $111, %rcx rep movsw xor $15036, %rbx lea addresses_UC_ht+0x1e39b, %rcx nop and $47105, %rdi movb $0x61, (%rcx) nop inc %rcx lea addresses_UC_ht+0x15ccf, %rdi add $19623, %rcx movl $0x61626364, (%rdi) nop cmp %rbx, %rbx lea addresses_normal_ht+0x97fb, %rsi nop xor %r10, %r10 mov $0x6162636465666768, %rax movq %rax, %xmm2 vmovups %ymm2, (%rsi) nop nop nop nop nop cmp %rax, %rax lea addresses_normal_ht+0x13a01, %rsi nop sub $3717, %r10 movw $0x6162, (%rsi) nop nop nop and $11091, %r15 lea addresses_UC_ht+0x5c1b, %rax nop add %r15, %r15 mov (%rax), %esi nop and %rbx, %rbx pop %rsi pop %rdi pop %rcx pop %rbx pop %rax pop %r15 pop %r10 ret .global s_faulty_load s_faulty_load: push %r13 push %r15 push %r8 push %r9 push %rbp push %rbx push %rcx // Load lea addresses_US+0x16c1b, %rcx nop nop nop nop xor %rbx, %rbx mov (%rcx), %r13w inc %r9 // Load lea addresses_WT+0x1341b, %rbp nop nop nop nop nop and %r8, %r8 movups (%rbp), %xmm6 vpextrq $1, %xmm6, %r13 nop nop add %r8, %r8 // Faulty Load lea addresses_US+0x16c1b, %rbx nop nop nop nop cmp %r13, %r13 mov (%rbx), %bp lea oracles, %r15 and $0xff, %rbp shlq $12, %rbp mov (%r15,%rbp,1), %rbp pop %rcx pop %rbx pop %rbp pop %r9 pop %r8 pop %r15 pop %r13 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 2, 'AVXalign': True, 'NT': False, 'congruent': 0, 'same': True}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 8, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_US', 'size': 2, 'AVXalign': True, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 5, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 9, 'same': True}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 3, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 4, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 7, 'same': True}, 'dst': {'type': 'addresses_A_ht', 'congruent': 11, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 8, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 2, 'same': True}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 2, 'AVXalign': False, 'NT': True, 'congruent': 1, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_UC_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}} {'00': 3} 00 00 00 */
#include "GameConfig.h" int main(int argc,char * argv[]){ using namespace game::config; GameConfig gc(argc,argv); std::cout<<gc.get<std::string>("ShaderResDir")<< gc.get<std::string>("ModelResDir")<<std::endl; std::cout<<std::boolalpha<<gc.get<bool>("GLProfileCore")<<std::endl; }
// Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, // 2006, 2007, 2008, 2009 // Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. #include <locale> _GLIBCXX_BEGIN_NAMESPACE(std) // Definitions for static const data members of time_base. template<> const char* __timepunct_cache<char>::_S_timezones[14] = { "GMT", "HST", "AKST", "PST", "MST", "CST", "EST", "AST", "NST", "CET", "IST", "EET", "CST", "JST" }; #ifdef _GLIBCXX_USE_WCHAR_T template<> const wchar_t* __timepunct_cache<wchar_t>::_S_timezones[14] = { L"GMT", L"HST", L"AKST", L"PST", L"MST", L"CST", L"EST", L"AST", L"NST", L"CET", L"IST", L"EET", L"CST", L"JST" }; #endif // Definitions for static const data members of money_base. const money_base::pattern money_base::_S_default_pattern = { {symbol, sign, none, value} }; const char* money_base::_S_atoms = "-0123456789"; const char* __num_base::_S_atoms_in = "-+xX0123456789abcdefABCDEF"; const char* __num_base::_S_atoms_out ="-+xX0123456789abcdef0123456789ABCDEF"; // _GLIBCXX_RESOLVE_LIB_DEFECTS // According to the resolution of DR 231, about 22.2.2.2.2, p11, // "str.precision() is specified in the conversion specification". void __num_base::_S_format_float(const ios_base& __io, char* __fptr, char __mod) { ios_base::fmtflags __flags = __io.flags(); *__fptr++ = '%'; // [22.2.2.2.2] Table 60 if (__flags & ios_base::showpos) *__fptr++ = '+'; if (__flags & ios_base::showpoint) *__fptr++ = '#'; // As per DR 231: _always_, not only when // __flags & ios_base::fixed || __prec > 0 *__fptr++ = '.'; *__fptr++ = '*'; if (__mod) *__fptr++ = __mod; ios_base::fmtflags __fltfield = __flags & ios_base::floatfield; // [22.2.2.2.2] Table 58 if (__fltfield == ios_base::fixed) *__fptr++ = 'f'; else if (__fltfield == ios_base::scientific) *__fptr++ = (__flags & ios_base::uppercase) ? 'E' : 'e'; else *__fptr++ = (__flags & ios_base::uppercase) ? 'G' : 'g'; *__fptr = '\0'; } bool __verify_grouping(const char* __grouping, size_t __grouping_size, const string& __grouping_tmp) { const size_t __n = __grouping_tmp.size() - 1; const size_t __min = std::min(__n, size_t(__grouping_size - 1)); size_t __i = __n; bool __test = true; // Parsed number groupings have to match the // numpunct::grouping string exactly, starting at the // right-most point of the parsed sequence of elements ... for (size_t __j = 0; __j < __min && __test; --__i, ++__j) __test = __grouping_tmp[__i] == __grouping[__j]; for (; __i && __test; --__i) __test = __grouping_tmp[__i] == __grouping[__min]; // ... but the first parsed grouping can be <= numpunct // grouping (only do the check if the numpunct char is > 0 // because <= 0 means any size is ok). if (static_cast<signed char>(__grouping[__min]) > 0 && __grouping[__min] != __gnu_cxx::__numeric_traits<char>::__max) __test &= __grouping_tmp[0] <= __grouping[__min]; return __test; } _GLIBCXX_END_NAMESPACE
#include "extensions/tracers/xray/config.h" #include <string> #include "envoy/config/core/v3/address.pb.h" #include "envoy/config/trace/v3/xray.pb.h" #include "envoy/config/trace/v3/xray.pb.validate.h" #include "envoy/registry/registry.h" #include "common/common/utility.h" #include "common/config/datasource.h" #include "extensions/tracers/xray/xray_tracer_impl.h" namespace Envoy { namespace Extensions { namespace Tracers { namespace XRay { XRayTracerFactory::XRayTracerFactory() : FactoryBase("envoy.tracers.xray") {} Tracing::DriverSharedPtr XRayTracerFactory::createTracerDriverTyped(const envoy::config::trace::v3::XRayConfig& proto_config, Server::Configuration::TracerFactoryContext& context) { std::string sampling_rules_json; try { sampling_rules_json = Config::DataSource::read(proto_config.sampling_rule_manifest(), true, context.serverFactoryContext().api()); } catch (EnvoyException& e) { ENVOY_LOG(error, "Failed to read sampling rules manifest because of {}.", e.what()); } if (proto_config.daemon_endpoint().protocol() != envoy::config::core::v3::SocketAddress::UDP) { throw EnvoyException("X-Ray daemon endpoint must be a UDP socket address"); } if (proto_config.daemon_endpoint().port_specifier_case() != envoy::config::core::v3::SocketAddress::PortSpecifierCase::kPortValue) { throw EnvoyException("X-Ray daemon port must be specified as number. Not a named port."); } const std::string endpoint = fmt::format("{}:{}", proto_config.daemon_endpoint().address(), proto_config.daemon_endpoint().port_value()); auto aws = absl::flat_hash_map<std::string, ProtobufWkt::Value>{}; for (const auto& field : proto_config.segment_fields().aws().fields()) { aws.emplace(field.first, field.second); } const auto& origin = proto_config.segment_fields().origin(); XRayConfiguration xconfig{endpoint, proto_config.segment_name(), sampling_rules_json, origin, std::move(aws)}; return std::make_shared<XRay::Driver>(xconfig, context); } /** * Static registration for the XRay tracer. @see RegisterFactory. */ REGISTER_FACTORY(XRayTracerFactory, Server::Configuration::TracerFactory); } // namespace XRay } // namespace Tracers } // namespace Extensions } // namespace Envoy
#include <SAMP-EDGEngine/Everything.hpp> extern samp_edgengine::GameModeSetupResult SAMPGameModeSetup(); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports() { return sampgdk_Supports() | SUPPORTS_PROCESS_TICK; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL Load(void **ppData) { return sampgdk_Load(ppData); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT void PLUGIN_CALL Unload() { sampgdk_Unload(); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT void PLUGIN_CALL ProcessTick() { sampgdk_ProcessTick(); if (Server) Server->sampEvent_OnUpdate(); } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnGameModeInit() { Server = std::make_unique<samp_edgengine::ServerClass>(); // call user defined startup method if (auto pGameMode = SAMPGameModeSetup()) { Server->setup( std::move(pGameMode) ); } return Server->sampEvent_OnGameModeInit(); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnGameModeExit() { return Server->sampEvent_OnGameModeExit(); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerConnect(int playerid) { return Server->sampEvent_OnPlayerConnect( playerid ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerDisconnect(int playerid, int reason) { return Server->sampEvent_OnPlayerDisconnect( playerid, static_cast<samp_edgengine::Player::DisconnectReason>(reason) ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerSpawn(int playerid) { return Server->sampEvent_OnPlayerSpawn( playerid ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerDeath(int playerid, int killerid, int reason) { return Server->sampEvent_OnPlayerDeath( playerid, killerid, static_cast<samp_edgengine::Weapon::Type>(reason) ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnVehicleSpawn(int vehicleid) { return Server->sampEvent_OnVehicleSpawn( vehicleid ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnVehicleDeath(int vehicleid, int killerid) { return Server->sampEvent_OnVehicleDeath( vehicleid, killerid ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerText(int playerid, const char * text) { return Server->sampEvent_OnPlayerSendText( playerid, std::string_view{ text } ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerCommandText(int playerid, const char * cmdtext) { return Server->sampEvent_OnPlayerSendCommand( playerid, std::string_view{ cmdtext } ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerRequestClass(int playerid, int classid) { return Server->sampEvent_OnPlayerRequestClass( playerid, classid ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerEnterVehicle(int playerid, int vehicleid, bool ispassenger) { return Server->sampEvent_OnPlayerEnterVehicle( playerid, vehicleid, ispassenger ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerExitVehicle(int playerid, int vehicleid) { return Server->sampEvent_OnPlayerExitVehicle( playerid, vehicleid ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerStateChange(int playerid, int newstate, int oldstate) { return Server->sampEvent_OnPlayerStateChange( playerid, newstate, oldstate ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerEnterCheckpoint(int playerid) { return false; } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerLeaveCheckpoint(int playerid) { return false; } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerEnterRaceCheckpoint(int playerid) { return false; } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerLeaveRaceCheckpoint(int playerid) { return false; } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnRconCommand(const char * cmd) { return Server->sampEvent_OnRconCommand(std::string_view{ cmd }); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerRequestSpawn(int playerid) { return Server->sampEvent_OnPlayerRequestSpawn(playerid); } ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnObjectMoved(int objectid) { return Server->sampEvent_OnObjectMoved(objectid); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerObjectMoved(int playerid, int objectid) { return Server->sampEvent_OnPlayerObjectMoved(playerid, objectid); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerPickUpPickup(int playerid, int pickupid) { return Server->sampEvent_OnPlayerPickUpPickup(playerid, pickupid); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnVehicleMod(int playerid, int vehicleid, int componentid) { return Server->sampEvent_OnVehicleMod(playerid, vehicleid, componentid); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnEnterExitModShop(int playerid, bool enterexit, int interiorid) { if (enterexit) return Server->sampEvent_OnPlayerEnterModShop(playerid, interiorid); else return Server->sampEvent_OnPlayerExitModShop(playerid, interiorid); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnVehiclePaintjob(int playerid, int vehicleid, int paintjobid) { return Server->sampEvent_OnVehiclePaintjob(playerid, vehicleid, paintjobid); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnVehicleRespray(int playerid, int vehicleid, int color1, int color2) { return Server->sampEvent_OnVehicleRespray( playerid, vehicleid, std::make_pair( color1, color2 ) ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnVehicleDamageStatusUpdate(int vehicleid, int playerid) { return Server->sampEvent_OnVehicleDamageStatusUpdate( vehicleid, playerid ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnUnoccupiedVehicleUpdate(int vehicleid, int playerid, int passenger_seat, float new_x, float new_y, float new_z, float vel_x, float vel_y, float vel_z) { if (passenger_seat != 0) return Server->sampEvent_OnUnoccupiedVehicleUpdate(vehicleid, playerid, passenger_seat, { new_x, new_y, new_z }, { vel_x, vel_y, vel_z }); return Server->sampEvent_OnUnoccupiedVehicleUpdate(vehicleid, playerid, { new_x, new_y, new_z }, { vel_x, vel_y, vel_z }); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerSelectedMenuRow(int playerid, int row) { return Server->sampEvent_OnPlayerSelectedMenuRow(playerid, row); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerExitedMenu(int playerid) { return Server->sampEvent_OnPlayerExitedMenu(playerid); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerInteriorChange(int playerid, int newinteriorid, int oldinteriorid) { return Server->sampEvent_OnPlayerInteriorChange( playerid, newinteriorid, oldinteriorid ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerKeyStateChange(int playerid, int newkeys, int oldkeys) { samp_edgengine::Int32 upDown; samp_edgengine::Int32 leftRight; samp_edgengine::Int32 unusedKeys; sampgdk_GetPlayerKeys(playerid, &unusedKeys, &upDown, &leftRight); // Note: // Old keyboard state has does not ever know whether up/down/left or right key was pressed. // TODO: fix this if possible. return Server->sampEvent_OnPlayerKeyboardStateChange( playerid, samp_edgengine::Keyboard{ newkeys, upDown, leftRight }, samp_edgengine::Keyboard{ oldkeys } ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnRconLoginAttempt(const char * ip, const char * password, bool success) { return Server->sampEvent_OnRconLoginAttempt( std::string_view{ ip }, std::string_view{ password }, success ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerUpdate(int playerid) { return Server->sampEvent_OnPlayerUpdate( playerid ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerStreamIn(int playerid, int forplayerid ) { return Server->sampEvent_OnPlayerStreamIn( playerid, forplayerid ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerStreamOut(int playerid, int forplayerid ) { return Server->sampEvent_OnPlayerStreamOut( playerid, forplayerid ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnVehicleStreamIn(int vehicleid, int forplayerid ) { return Server->sampEvent_OnVehicleStreamIn( vehicleid, forplayerid); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnVehicleStreamOut(int vehicleid, int forplayerid ) { return Server->sampEvent_OnVehicleStreamOut( vehicleid, forplayerid ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnActorStreamIn(int actorid, int forplayerid ) { return Server->sampEvent_OnActorStreamIn( actorid, forplayerid ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnActorStreamOut(int actorid, int forplayerid ) { return Server->sampEvent_OnActorStreamOut( actorid, forplayerid ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnDialogResponse(int playerid, int dialogid, int response, int listitem, const char * inputtext) { return Server->sampEvent_OnDialogResponse( playerid, dialogid, static_cast<samp_edgengine::DialogButton>(response), listitem, inputtext ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerTakeDamage(int playerid, int issuerid, float amount, int weaponid, int bodypart) { return Server->sampEvent_OnPlayerTakeDamage( playerid, issuerid, amount, static_cast<samp_edgengine::Weapon::Type>(weaponid), static_cast<samp_edgengine::Player::BodyPart>(bodypart) ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerGiveDamage(int playerid, int damagedid, float amount, int weaponid, int bodypart) { return Server->sampEvent_OnPlayerGiveDamage( playerid, damagedid, amount, static_cast<samp_edgengine::Weapon::Type>(weaponid), static_cast<samp_edgengine::Player::BodyPart>(bodypart) ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerGiveDamageActor(int playerid, int damaged_actorid, float amount, int weaponid, int bodypart) { return Server->sampEvent_OnPlayerGiveDamageActor( playerid, damaged_actorid, amount, static_cast<samp_edgengine::Weapon::Type>(weaponid), static_cast<samp_edgengine::Player::BodyPart>(bodypart) ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerClickMap(int playerid, float fX, float fY, float fZ) { return Server->sampEvent_OnPlayerClickMap(playerid, { fX, fY, fZ } ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerClickTextDraw(int playerid, int clickedid) { return Server->sampEvent_OnPlayerClickTextDraw(playerid, clickedid); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerClickPlayerTextDraw(int playerid, int playertextid) { return Server->sampEvent_OnPlayerClickPlayerTextDraw(playerid, playertextid); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnIncomingConnection(int playerid, const char * ip_address, int port) { return Server->sampEvent_OnIncomingConnection(playerid, std::string_view{ ip_address }, port); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnTrailerUpdate(int playerid, int vehicleid) { return Server->sampEvent_OnTrailerUpdate(playerid, vehicleid); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnVehicleSirenStateChange(int playerid, int vehicleid, int newstate) { return Server->sampEvent_OnVehicleSirenStateChange(playerid, vehicleid, newstate == 1); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerClickPlayer(int playerid, int clickedplayerid, int source) { return Server->sampEvent_OnPlayerClickPlayer(playerid, clickedplayerid, source); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerEditObject(int playerid, bool playerobject, int objectid, int response, float fX, float fY, float fZ, float fRotX, float fRotY, float fRotZ) { if (playerobject == 1) return Server->sampEvent_OnPlayerEditPlayerObject(playerid, objectid, static_cast<samp_edgengine::IMapObject::EditResponse>(response), { fX, fY, fZ }, { fRotX, fRotY, fRotZ }); else return Server->sampEvent_OnPlayerEditObject(playerid, objectid, static_cast<samp_edgengine::IMapObject::EditResponse>(response), { fX, fY, fZ }, { fRotX, fRotY, fRotZ }); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerEditAttachedObject(int playerid, int response, int index, int modelid, int boneid, float fOffsetX, float fOffsetY, float fOffsetZ, float fRotX, float fRotY, float fRotZ, float fScaleX, float fScaleY, float fScaleZ) { return Server->sampEvent_OnPlayerEditAttachedObject(playerid, response == 1, index, modelid, boneid, { fOffsetX, fOffsetY, fOffsetZ }, { fRotX, fRotY, fRotZ }, { fScaleX, fScaleY, fScaleZ } ); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerSelectObject(int playerid, int type, int objectid, int modelid, float fX, float fY, float fZ) { if (type == SELECT_OBJECT_GLOBAL_OBJECT) return Server->sampEvent_OnPlayerSelectObject(playerid, objectid, modelid, { fX, fY, fZ } ); else // if (type == SELECT_OBJECT_PLAYER_OBJECT) // Note: there is currently no other option. return Server->sampEvent_OnPlayerSelectPlayerObject(playerid, objectid, modelid, { fX, fY, fZ }); } ///////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////// PLUGIN_EXPORT bool PLUGIN_CALL OnPlayerWeaponShot(int playerid, int weaponid, int hittype, int hitid, float fX, float fY, float fZ) { return Server->sampEvent_OnPlayerWeaponShot( playerid, static_cast<samp_edgengine::Weapon::Type>(weaponid), samp_edgengine::Weapon::HitResult{ static_cast<samp_edgengine::Weapon::HitResult::Target>(hittype), hitid, { fX, fY, fZ } } ); } /////////////////////////////////////////////////////////////////////////////////////////
; SFROM: (128,256KB)PRG-ROM + (16,32,64)KB CHR-ROM ; http://bootgod.dyndns.org:7777/search.php?keywords=SFROM&kwtype=pcb ;------------------------------------------------------------------------------; ; number of 16K PRG banks ; Valid configurations: $08 (128K), $10 (256K) PRG_BANKS = $08 ; number of 8K CHR banks ; Valid configurations: $02 (16K), $04 (32K), $08 (64K) CHR_BANKS = $02 ; MMC1 mirroring is mapper controlled. This just sets the default. ; If you want one-screen mapping, you will need to set it via MMC1 writes. ; %0000 = Horizontal ; %0001 = Vertical MIRRORING = %0001 ; Mapper 001 (MMC1 - SFROM) iNES header .byte "NES",$1A .byte PRG_BANKS ; 16K PRG banks .byte CHR_BANKS ; 8K CHR banks .byte $10|MIRRORING ; flags 6 .byte $00 ; flags 7 .byte $00 ; no PRG RAM .dsb 7, $00 ; clear the remaining bytes
 #pragma once #include "physics/apsides.hpp" #include <optional> #include <vector> #include "base/array.hpp" #include "base/jthread.hpp" #include "numerics/root_finders.hpp" namespace principia { namespace physics { namespace internal_apsides { using base::BoundedArray; using geometry::Barycentre; using geometry::Instant; using geometry::Position; using geometry::Sign; using numerics::Bisect; using numerics::Hermite3; using quantities::IsFinite; using quantities::Length; using quantities::Speed; using quantities::Square; using quantities::Variation; template<typename Frame> void ComputeApsides(Trajectory<Frame> const& reference, typename DiscreteTrajectory<Frame>::Iterator const begin, typename DiscreteTrajectory<Frame>::Iterator const end, int const max_points, DiscreteTrajectory<Frame>& apoapsides, DiscreteTrajectory<Frame>& periapsides) { std::optional<Instant> previous_time; std::optional<DegreesOfFreedom<Frame>> previous_degrees_of_freedom; std::optional<Square<Length>> previous_squared_distance; std::optional<Variation<Square<Length>>> previous_squared_distance_derivative; Instant const t_min = reference.t_min(); Instant const t_max = reference.t_max(); for (auto it = begin; it != end; ++it) { auto const& [time, degrees_of_freedom] = *it; if (time < t_min) { continue; } if (time > t_max) { break; } DegreesOfFreedom<Frame> const body_degrees_of_freedom = reference.EvaluateDegreesOfFreedom(time); RelativeDegreesOfFreedom<Frame> const relative = degrees_of_freedom - body_degrees_of_freedom; Square<Length> const squared_distance = relative.displacement().Norm²(); // This is the derivative of |squared_distance|. Variation<Square<Length>> const squared_distance_derivative = 2.0 * InnerProduct(relative.displacement(), relative.velocity()); if (previous_squared_distance_derivative && Sign(squared_distance_derivative) != Sign(*previous_squared_distance_derivative)) { CHECK(previous_time && previous_degrees_of_freedom && previous_squared_distance); // The derivative of |squared_distance| changed sign. Construct a Hermite // approximation of |squared_distance| and find its extrema. Hermite3<Instant, Square<Length>> const squared_distance_approximation( {*previous_time, time}, {*previous_squared_distance, squared_distance}, {*previous_squared_distance_derivative, squared_distance_derivative}); BoundedArray<Instant, 2> const extrema = squared_distance_approximation.FindExtrema(); // Now look at the extrema and check that exactly one is in the required // time interval. This is normally the case, but it can fail due to // ill-conditioning. Instant apsis_time; int valid_extrema = 0; for (auto const& extremum : extrema) { if (extremum >= *previous_time && extremum <= time) { apsis_time = extremum; ++valid_extrema; } } if (valid_extrema != 1) { // Something went wrong when finding the extrema of // |squared_distance_approximation|. Use a linear interpolation of // |squared_distance_derivative| instead. apsis_time = Barycentre<Instant, Variation<Square<Length>>>( {time, *previous_time}, {*previous_squared_distance_derivative, -squared_distance_derivative}); } // This can happen for instance if the square distance is stationary. // Safer to give up. if (!IsFinite(apsis_time - Instant{})) { break; } // Now that we know the time of the apsis, use a Hermite approximation to // derive its degrees of freedom. Note that an extremum of // |squared_distance_approximation| is in general not an extremum for // |position_approximation|: the distance computed using the latter is a // 6th-degree polynomial. However, approximating this polynomial using a // 3rd-degree polynomial would yield |squared_distance_approximation|, so // we shouldn't be far from the truth. DegreesOfFreedom<Frame> const apsis_degrees_of_freedom = begin.trajectory()->EvaluateDegreesOfFreedom(apsis_time); if (Sign(squared_distance_derivative).is_negative()) { apoapsides.Append(apsis_time, apsis_degrees_of_freedom); } else { periapsides.Append(apsis_time, apsis_degrees_of_freedom); } if (apoapsides.Size() >= max_points && periapsides.Size() >= max_points) { break; } } previous_time = time; previous_degrees_of_freedom = degrees_of_freedom; previous_squared_distance = squared_distance; previous_squared_distance_derivative = squared_distance_derivative; } } template<typename Frame, typename Predicate> Status ComputeNodes(typename DiscreteTrajectory<Frame>::Iterator begin, typename DiscreteTrajectory<Frame>::Iterator end, Vector<double, Frame> const& north, int const max_points, DiscreteTrajectory<Frame>& ascending, DiscreteTrajectory<Frame>& descending, Predicate predicate) { static_assert( std::is_convertible<decltype(predicate( std::declval<DegreesOfFreedom<Frame>>())), bool>::value, "|predicate| must be a predicate on |DegreesOfFreedom<Frame>|"); std::optional<Instant> previous_time; std::optional<Length> previous_z; std::optional<Speed> previous_z_speed; for (auto it = begin; it != end; ++it) { RETURN_IF_STOPPED; auto const& [time, degrees_of_freedom] = *it; Length const z = (degrees_of_freedom.position() - Frame::origin).coordinates().z; Speed const z_speed = degrees_of_freedom.velocity().coordinates().z; if (previous_z && Sign(z) != Sign(*previous_z)) { CHECK(previous_time && previous_z_speed); // |z| changed sign. Construct a Hermite approximation of |z| and find // its zeros. Hermite3<Instant, Length> const z_approximation( {*previous_time, time}, {*previous_z, z}, {*previous_z_speed, z_speed}); Instant node_time; if (Sign(z_approximation.Evaluate(*previous_time)) == Sign(z_approximation.Evaluate(time))) { // The Hermite approximation is poorly conditioned, let's use a linear // approximation node_time = Barycentre<Instant, Length>({*previous_time, time}, {z, -*previous_z}); } else { // The normal case, find the intersection with z = 0 using bisection. // TODO(egg): Bisection on a polynomial seems daft; we should have // Newton's method. node_time = Bisect( [&z_approximation](Instant const& t) { return z_approximation.Evaluate(t); }, *previous_time, time); } DegreesOfFreedom<Frame> const node_degrees_of_freedom = begin.trajectory()->EvaluateDegreesOfFreedom(node_time); if (predicate(node_degrees_of_freedom)) { if (Sign(InnerProduct(north, Vector<double, Frame>({0, 0, 1}))) == Sign(z_speed)) { // |north| is up and we are going up, or |north| is down and we are // going down. ascending.Append(node_time, node_degrees_of_freedom); } else { descending.Append(node_time, node_degrees_of_freedom); } if (ascending.Size() >= max_points && descending.Size() >= max_points) { break; } } } previous_time = time; previous_z = z; previous_z_speed = z_speed; } return Status::OK; } } // namespace internal_apsides } // namespace physics } // namespace principia
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r14 push %r15 push %r9 push %rcx push %rdi push %rdx push %rsi lea addresses_normal_ht+0x14f86, %rsi lea addresses_normal_ht+0xec26, %rdi add $46076, %r14 mov $11, %rcx rep movsl nop nop nop inc %r11 lea addresses_WC_ht+0x10254, %rdx nop inc %r15 movb (%rdx), %cl nop nop nop nop cmp $48349, %rdi lea addresses_A_ht+0x1e08, %rsi lea addresses_A_ht+0x1ca1f, %rdi sub $47134, %r15 mov $42, %rcx rep movsw nop nop dec %rcx lea addresses_UC_ht+0x168f6, %rsi nop nop inc %rcx mov (%rsi), %rdx nop nop nop sub $44505, %rdi lea addresses_normal_ht+0x1a726, %rcx nop nop nop xor $41402, %r11 movups (%rcx), %xmm0 vpextrq $0, %xmm0, %r14 nop nop nop dec %rdi lea addresses_WC_ht+0x1f26, %rdi nop nop nop inc %rdx movups (%rdi), %xmm3 vpextrq $1, %xmm3, %rcx nop nop inc %r11 lea addresses_A_ht+0x12326, %rdx clflush (%rdx) nop nop nop nop nop dec %rdi mov $0x6162636465666768, %r14 movq %r14, %xmm3 movups %xmm3, (%rdx) nop nop xor %rdx, %rdx lea addresses_WT_ht+0x6d26, %rsi lea addresses_normal_ht+0x1b926, %rdi add %r9, %r9 mov $74, %rcx rep movsb nop nop cmp $9066, %rdi lea addresses_A_ht+0x14026, %r14 nop nop nop add $557, %r15 mov $0x6162636465666768, %rdx movq %rdx, %xmm7 vmovups %ymm7, (%r14) nop nop nop add %rdi, %rdi lea addresses_D_ht+0xa126, %rcx nop cmp $64610, %rdx mov $0x6162636465666768, %rsi movq %rsi, (%rcx) nop nop add %r11, %r11 lea addresses_WC_ht+0x1d926, %r14 nop nop nop nop nop xor $2219, %r15 mov $0x6162636465666768, %rsi movq %rsi, %xmm0 vmovups %ymm0, (%r14) nop nop cmp $21691, %r11 lea addresses_WC_ht+0x18d26, %r11 nop nop nop sub $49281, %rdx mov $0x6162636465666768, %rdi movq %rdi, %xmm5 movups %xmm5, (%r11) nop nop nop nop nop sub %r11, %r11 lea addresses_normal_ht+0xf8bf, %r15 nop add %r9, %r9 movups (%r15), %xmm3 vpextrq $1, %xmm3, %r14 nop nop nop nop nop cmp $44976, %rsi pop %rsi pop %rdx pop %rdi pop %rcx pop %r9 pop %r15 pop %r14 pop %r11 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r13 push %r14 push %r15 push %rbx push %rdx // Store lea addresses_D+0x7f68, %r13 nop nop nop nop mfence mov $0x5152535455565758, %r11 movq %r11, %xmm4 vmovups %ymm4, (%r13) nop nop nop xor %r12, %r12 // Store lea addresses_normal+0x15732, %r14 nop nop nop nop and %r13, %r13 mov $0x5152535455565758, %rbx movq %rbx, %xmm4 vmovups %ymm4, (%r14) nop nop nop nop sub $48349, %r11 // Store lea addresses_RW+0x1e3df, %r13 nop nop nop dec %r15 movl $0x51525354, (%r13) nop nop nop and $6743, %r12 // Store lea addresses_WT+0x1f0dd, %r11 nop nop nop xor $49142, %rdx movl $0x51525354, (%r11) cmp %r13, %r13 // Store lea addresses_A+0x5146, %r12 nop nop nop nop nop xor %rbx, %rbx movb $0x51, (%r12) dec %rbx // Faulty Load mov $0x13140d0000000926, %rdx nop nop sub $57676, %r12 mov (%rdx), %ebx lea oracles, %r12 and $0xff, %rbx shlq $12, %rbx mov (%r12,%rbx,1), %rbx pop %rdx pop %rbx pop %r15 pop %r14 pop %r13 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_NC', 'size': 32, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 1, 'NT': False, 'type': 'addresses_D', 'size': 32, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 2, 'NT': False, 'type': 'addresses_normal', 'size': 32, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_RW', 'size': 4, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_WT', 'size': 4, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 2, 'NT': False, 'type': 'addresses_A', 'size': 1, 'AVXalign': False}} [Faulty Load] {'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_NC', 'size': 4, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'type': 'addresses_normal_ht', 'congruent': 5, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 8, 'same': False}} {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_WC_ht', 'size': 1, 'AVXalign': True}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_A_ht', 'congruent': 0, 'same': False}} {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_UC_ht', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 9, 'NT': False, 'type': 'addresses_normal_ht', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'same': False, 'congruent': 9, 'NT': False, 'type': 'addresses_WC_ht', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 9, 'NT': False, 'type': 'addresses_A_ht', 'size': 16, 'AVXalign': False}} {'src': {'type': 'addresses_WT_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_A_ht', 'size': 32, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 8, 'NT': False, 'type': 'addresses_D_ht', 'size': 8, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_WC_ht', 'size': 32, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_WC_ht', 'size': 16, 'AVXalign': False}} {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_normal_ht', 'size': 16, 'AVXalign': False}, 'OP': 'LOAD'} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
SECTION code_clib SECTION code_ctype PUBLIC asm_islower asm_islower: ; determine if char is in [a-z ; enter : a = char ; exit : carry if not lower ; uses : f cp 'a' ret c cp 'z'+1 ccf ret
processor 6502 include "vcs.h" include "macro.h" SEG.U vars ORG $80 SpriteHeight = 7 SpritePosition ds 1 PlayerX ds 2 PS_temp ds 1 Sprite ds 2 Sprite1 ds 2 SpriteEnd ds 1 Sprite1End ds 1 XIncrement ds 1 X1Increment ds 1 YIncrement ds 1 Y1Increment ds 1 YVelocity ds 1 Y1Velocity ds 1 YCounter ds 1 Y1Counter ds 1 XVelocity ds 1 X1Velocity ds 1 XCounter ds 1 X1Counter ds 1 XTemp ds 1 YTemp ds 1 YMaxLimit ds 1 YMinLimit ds 1 Y1MaxLimit ds 1 Y1MinLimit ds 1 XMaxLimit ds 1 XMinLimit ds 1 X1MaxLimit ds 1 X1MinLimit ds 1 InAir ds 1 VelTemp ds 1 PlayedCrashSound ds 1 PlayedP1CrashSound ds 1 Volume ds 1 CCDetached ds 1 CCParachuteDelay ds 1 ChuteDeployed ds 1 P0Crashed ds 1 P1Crashed ds 1 P0Success ds 1 P1Success ds 1 SEG code ORG $F000 fineAdjustBegin DC.B %01110000; Left 7 DC.B %01100000; Left 6 DC.B %01010000; Left 5 DC.B %01000000; Left 4 DC.B %00110000; Left 3 DC.B %00100000; Left 2 DC.B %00010000; Left 1 DC.B %00000000; No movement. DC.B %11110000; Right 1 DC.B %11100000; Right 2 DC.B %11010000; Right 3 DC.B %11000000; Right 4 DC.B %10110000; Right 5 DC.B %10100000; Right 6 DC.B %10010000; Right 7 fineAdjustTable EQU fineAdjustBegin - %11110001; NOTE: %11110001 = -15 Reset ; Clear RAM and all TIA registers ldx #0 lda #0 Clear sta 0,x inx bne Clear ;--------------------- ldx #$0F stx COLUBK ; set the background color StartOfIntroFrame lda #2 sta VBLANK sta VSYNC sta WSYNC sta WSYNC sta WSYNC lda #43 sta TIM64T lda #0 sta VSYNC ;------------------- ldx #0 lda #$82 ; blue color sta COLUPF ; set the playfield color bit INPT4 bpl StartOfGame bit INPT5 bpl StartOfGame WaitForIntroVblankEnd lda INTIM bne WaitForIntroVblankEnd ;------------------- ldx #0 lda #0 sta WSYNC sta VBLANK lda #83 sta TIM64T WaitForCenter lda INTIM bne WaitForCenter sta WSYNC DrawBLUE lda LEFTPF0,x sta PF0 lda LEFTPF1,x sta PF1 lda LEFTPF2,x sta PF2 SLEEP 6 lda RIGHTPF0,x sta PF0 lda RIGHTPF1,x sta PF1 lda RIGHTPF2,x sta PF2 nop sta WSYNC inx cpx #15 beq BlackPF cpx #60 bne DrawBLUE lda #0 sta PF0 sta PF1 sta PF2 BlankLines sta WSYNC inx cpx #118 bne BlankLines ;------------------ EndOfIntroFrame ; 30 scanlines of overscan ldx #0 lda #2 OverscanIntro sta WSYNC sta VBLANK inx cpx #30 bne OverscanIntro ldx #0 sta WSYNC jmp StartOfIntroFrame BlackPF lda #$00 ; black color sta COLUPF ; set the playfield color jmp DrawBLUE StartOfGame ;--------------------- lda #$20 ; brown color sta COLUPF ; set the playfield color ldx #0 stx COLUBK ; set the background color lda #$0F sta COLUP0 sta COLUP1 ;; Set the ball size to be 4 pixels wide lda #$20 sta CTRLPF lda #80 sta PlayerX+1 lda #<Sprite0Data sta Sprite lda #>Sprite0Data sta Sprite+1 lda #<Sprite1Data sta Sprite1 lda #>Sprite1Data sta Sprite1+1 lda #191 sta YIncrement lda #186 sta Y1Increment lda #140 sta XIncrement lda #140 sta X1Increment lda #192 sta YMaxLimit sta Y1MaxLimit lda #6 sta YMinLimit sta Y1MinLimit lda #161 sta XMaxLimit sta X1MaxLimit lda #2 sta XMinLimit sta X1MinLimit lda #$20 sta NUSIZ0 ;--------------------- StartOfFrame lda #2 sta VBLANK sta VSYNC sta WSYNC sta WSYNC sta WSYNC lda #43 sta TIM64T lda #0 sta VSYNC ;------------------- CheckForReset lda SWCHB and #1 bne CheckParachuteDelay jmp Reset CheckParachuteDelay bit CCDetached bvc CheckCCCommand lda CCParachuteDelay cmp #50 bcs CheckCCCommand inc CCParachuteDelay jmp CheckForDetachCommand CheckCCCommand bit CCDetached bvc CheckForDetachCommand bit INPT5 bpl DeployChute jmp DecrementY DeployChute lda #<Sprite1DataPara sta Sprite1 lda #>Sprite1DataPara sta Sprite1+1 lda #$FF sta ChuteDeployed jmp DecrementY CheckForDetachCommand bit INPT5 bpl DetachCC jmp DecrementY DetachCC lda #$FF sta CCDetached lda #<Sprite0DataNoCC sta Sprite lda #>Sprite0DataNoCC sta Sprite+1 dec Y1Velocity ; gotta keep it separated DecrementY ; UP JOYSTICK ;; If up button pressed lda #$10 bit SWCHA bne MuteRocketSound ; else not pressed, goto X lda #1 sta InAir ; we are now in the air ;; Do not increase velocity if we are at max lda #-126 cmp YVelocity beq IncrementX ; Do not increase velocity lda #-127 ; check both since we can change by two cmp YVelocity beq IncrementX ; Do not increase velocity lda #150 cmp YIncrement bcc loudest lda #120 cmp YIncrement bcc louder lda #90 cmp YIncrement bcc loud lda #70 cmp YIncrement bcc normal lda #50 cmp YIncrement bcc quiet lda #30 cmp YIncrement bcc quieter lda #10 cmp YIncrement bcc quietest jmp quietest loudest lda #15 jmp setVolume louder lda #12 jmp setVolume loud lda #10 jmp setVolume normal lda #8 jmp setVolume quiet lda #5 jmp setVolume quieter lda #3 jmp setVolume quietest lda #1 jmp setVolume setVolume sta AUDV0 lda #9 sta AUDF0 lda #14 sta AUDC0 dec YVelocity dec YVelocity jmp IncrementX MuteRocketSound lda #0 sta AUDV0 IncrementX ; RIGHT JOYSTICK lda #$80 bit SWCHA bne DecrementX ;; Dont go past the wall ldx XIncrement cpx XMaxLimit beq DecrementX ;; However, do not increase velocity if we are at max lda #127 cmp XVelocity beq DecrementX ; Do not increase velocity inc XVelocity DecrementX ; LEFT JOYSTICK lda #$40 bit SWCHA bne MovePlayer ;; Dont go past the wall ldx XIncrement cpx XMinLimit beq MovePlayer ;; Do not increase velocity if we are at max lda #-126 cmp XVelocity beq MovePlayer ; Do not increase velocity dec XVelocity MovePlayer ;; If we are not in air then do not move lda InAir beq SetupSpriteEnd ;; Add gravity ;; However, do not increase velocity if we are at max lda #127 cmp YVelocity beq ChangeYCounter ; Do not increase velocity ;; check if we are at our largest YIncrement (lowest point on the screen) ldx YIncrement cpx YMaxLimit beq ChangeYCounter inc YVelocity ChangeYCounter lda YVelocity clc adc YCounter ; attempt to overflow sta YCounter bvc SetupSpriteEnd ; did not overflow so do not move ;; decrement y (move player up) if YVelocity is negative lda YVelocity bpl MoveDown ;; check if we are at out smallest YIncrement (highest point on the screen) ldx YIncrement cpx YMinLimit beq SetupSpriteEnd ; don't move if we are at our limit ;; overflowed and had negative velocity so move up (decrement x) dec YIncrement jmp SetupSpriteEnd MoveDown ;; check if we are at out largest YIncrement (lowest point on the screen) ldx YIncrement cpx YMaxLimit beq SetupSpriteEnd ; don't move if we are at our limit ;; overflowed and had positive velocity so move down (increment x) inc YIncrement SetupSpriteEnd ldx #0 lda #0 clc adc YIncrement sta SpriteEnd bit CCDetached bvs DetachedY ; CC is detached lda YIncrement ; CC is not detached sta Y1Increment lda #-5 clc adc Y1Increment sta Y1Increment lda YVelocity sta Y1Velocity jmp StoreY1 DetachedY lda #0 clc adc Y1Increment ;; Do not increase velocity past chute max if chute deployed bit ChuteDeployed bvc AddGravityOnCC ; Add gravity as normal if chute not deployed lda #60 cmp Y1Velocity beq AddCCVelocityToPos ; We are at max velocity bvc AddGravityOnCC lda #60 sta Y1Velocity AddGravityOnCC ;; Add gravity ;; However, do not increase velocity if we are at max lda #127 cmp Y1Velocity beq AddCCVelocityToPos ; Do not increase velocity ;; check if we are at our largest YIncrement (lowest point on the screen) ldx Y1Increment cpx Y1MaxLimit beq AddCCVelocityToPos inc Y1Velocity AddCCVelocityToPos lda Y1Velocity clc adc Y1Counter ; attempt to overflow sta Y1Counter bvc StoreY1 ; did not overflow so do not move ;; decrement y (move player up) if YVelocity is negative lda Y1Velocity bpl MoveY1Down ;; check if we are at out smallest YIncrement (highest point on the screen) ldx Y1Increment cpx Y1MinLimit beq StoreY1 ; don't move if we are at our limit ;; overflowed and had negative velocity so move up (decrement x) dec Y1Increment jmp StoreY1 MoveY1Down ;; check if we are at out largest Y1Increment (lowest point on the screen) ldx Y1Increment cpx Y1MaxLimit beq StoreY1 ; don't move if we are at our limit ;; overflowed and had positive velocity so move down (increment x) inc Y1Increment StoreY1 lda #0 clc adc Y1Increment sta Sprite1End CheckXVelocity lda XVelocity clc adc XCounter ; attempt to overflow sta XCounter bvc MoveX ; did not overflow so do not move ;; decrement x (move player left) if XVelocity is negative lda XVelocity bpl MoveRight ;; check if we are at out smallest XIncrement ldx XIncrement cpx XMinLimit beq MoveX ; don't move if we are at our limit ;; overflowed and had negative velocity so move left (decrement x) dec XIncrement jmp MoveX MoveRight ;; check if we are at our largest XIncrement (furthest right point on the screen) ldx XIncrement cpx XMaxLimit beq MoveX ; don't move if we are at our limit ;; overflowed and had positive velocity so move right (increment x) inc XIncrement MoveX lda #0 clc adc XIncrement sta PlayerX ;; Move PM4 in X stx XTemp ldx #0 jsr PosObject bit CCDetached bvs MoveCCinX lda XIncrement sta X1Increment lda XVelocity sta X1Velocity jmp StoreX1 MoveCCinX lda X1Velocity clc adc X1Counter ; attempt to overflow sta X1Counter bvc StoreX1 ; did not overflow so do not move ;; decrement x (move player left) if XVelocity is negative lda X1Velocity bpl MoveX1Right ;; check if we are at out smallest XIncrement ldx X1Increment cpx X1MinLimit beq StoreX1 ; don't move if we are at our limit ;; overflowed and had negative velocity so move left (decrement x) dec X1Increment jmp StoreX1 MoveX1Right ;; check if we are at our largest XIncrement (furthest right point on the screen) ldx X1Increment cpx X1MaxLimit beq StoreX1 ; don't move if we are at our limit ;; overflowed and had positive velocity so move right (increment x) inc X1Increment StoreX1 lda X1Increment ;; Move Crew Capsule in X ldx #1 jsr PosObject ldx XTemp MoveMissle lda #40 ;; Start of missle X positioning sta WSYNC ; 00 Sync to start of scanline. sec ; 02 Set the carry flag so no borrow will be applied during the division. .divideby15missle sbc #15 ; 04 Waste the necessary amount of time dividing X-pos by 15! bcs .divideby15missle ; 06/07 11/16/21/26/31/36/41/46/51/56/61/66 tay lda fineAdjustTable,y ; 13 -> Consume 5 cycles by guaranteeing we cross a page boundary sta RESM0 ; 21/ 26/31/36/41/46/51/56/61/66/71 - Set the rough position. sta WSYNC sta HMOVE ;; End of missle positioning ExtraGameSetup ldx #0 stx COLUBK ; set the background color lda #0 sta PF0 sta PF1 sta PF2 ;; disable missle 0 lda #0 sta ENAM0 CheckCCLanding lda P1Crashed bne CrashedP1 ; P1 has already crashed bit CXP1FB bpl CheckPMLanding CheckP1Landing lda #61 cmp Y1Velocity bcs P1SuccessLand ; Successful CC landing! ;; crash! CrashedP1 lda #0 lda #<Sprite0CrashData sta Sprite1 lda #>Sprite0CrashData sta Sprite1+1 lda #1 sta P1Crashed lda PlayedP1CrashSound bne LowerCrashVolume1 lda #15 sta Volume LowerCrashVolume1 lda Volume beq DoNotLowerAnymore1 dec Volume DoNotLowerAnymore1 ;; Don't play the crash sound more than once lda #35 cmp PlayedP1CrashSound beq TurnOffCrashSound1 clc lda #1 adc PlayedP1CrashSound sta PlayedP1CrashSound ;; crash sound lda Volume sta AUDV0 sta AUDV1 lda #31 sta AUDF0 lda #15 sta AUDC0 lda #8 sta AUDC1 lda #31 sta AUDF1 jmp FreezeP1 TurnOffCrashSound1 lda #0 sta AUDV0 jmp FreezeP1 P1SuccessLand lda #1 sta P1Success FreezeP1 lda X1Increment sta X1MaxLimit sta X1MinLimit lda Y1Increment sta Y1MaxLimit sta Y1MinLimit lda #0 sta Y1Velocity jmp CheckPMLanding CheckPMLanding lda P0Crashed bne CheckCrash bit CXM0P bvc CheckCrash ;; Landed successfully! lda #1 sta P0Success jmp FreezeP0 CheckCrash bit CXP0FB bpl WaitForVblankEnd ;; Crash! lda #0 lda #<Sprite0CrashData sta Sprite lda #>Sprite0CrashData sta Sprite+1 lda #1 sta P0Crashed lda PlayedCrashSound bne LowerCrashVolume lda #15 sta Volume LowerCrashVolume lda Volume beq DoNotLowerAnymore dec Volume DoNotLowerAnymore ;; Don't play the crash sound more than once lda #35 cmp PlayedCrashSound beq TurnOffCrashSound clc lda #1 adc PlayedCrashSound sta PlayedCrashSound ;; crash sound lda Volume sta AUDV0 sta AUDV1 lda #31 sta AUDF0 lda #15 sta AUDC0 lda #8 sta AUDC1 lda #31 sta AUDF1 jmp FreezeP0 TurnOffCrashSound lda #0 sta AUDV0 jmp FreezeP0 WaitForVblankEnd ;; Check For Success lda P0Success beq WaitForVblankEndReal lda P1Success beq WaitForVblankEndReal jmp SuccessWaitForVblank WaitForVblankEndReal lda INTIM bne WaitForVblankEndReal ContinueAfterWait ;------------------- ldx #192 ; 2 lda #0 sta WSYNC sta VBLANK ScanLoop sta WSYNC lda #SpriteHeight; 2 dcp SpriteEnd ; 5 bcc SkipDrawRight ; 2 = 9 ldy SpriteEnd lda (Sprite),y continueRight sta GRP0 jmp DrawRight SkipDrawRight ; 3 from BCC lda #0 sta GRP0 DrawRight ; 3 from BCC lda #SpriteHeight; 2 dcp Sprite1End ; 5 bcc SkipDrawing ; 2 = 9 ldy Sprite1End lda (Sprite1),y sta GRP1 jmp EndDrawing SkipDrawing lda #0 ; 2 sta GRP1 EndDrawing ;; End of y positioning of P0 cpx #3 bne ContinueGround lda #3 ;; enable missle 0 sta ENAM0 HandlePlayfield SLEEP 72 lda #$FF ldy #$FC sta PF0 sty PF1 ContinueGround cpx #2 bne NoBackground lda #$FF sta PF1 sta PF2 DrawGround ldy #$20 ;; disable missle 0 lda #0 sta ENAM0 SLEEP 10 sty COLUBK ; set the background color NoBackground dex ; 2 bne ScanLoop ;------------------ EndOfFrame ; 30 scanlines of overscan ldx #0 lda #2 Overscan sta WSYNC sta VBLANK inx cpx #30 bne Overscan ldx #0 sta WSYNC jmp StartOfFrame PosObject SUBROUTINE sta WSYNC ; 00 Sync to start of scanline. sec ; 02 Set the carry flag so no borrow will be applied during the division. .divideby15 sbc #15 ; 04 Waste the necessary amount of time dividing X-pos by 15! bcs .divideby15 ; 06/07 11/16/21/26/31/36/41/46/51/56/61/66 tay ; 2 lda fineAdjustTable,y ; 13 -> Consume 5 cycles by guaranteeing we cross a page boundary sta HMP0,x ; 3 sta RESP0,x ; 21/ 26/31/36/41/46/51/56/61/66/71 - Set the rough position. ;; End of X positioning rts FreezeP0 lda XIncrement sta XMaxLimit sta XMinLimit lda YIncrement sta YMaxLimit sta YMinLimit lda #0 sta YVelocity jmp WaitForVblankEnd SuccessWaitForVblank lda INTIM bne SuccessWaitForVblank ContinueAfterSuccessWait ;------------------- ldx #192 ; 2 ldy #0 lda #0 sta WSYNC sta VBLANK SuccessLoop sta WSYNC lda #$C6 ; green color sta COLUPF ; set the playfield color DrawSuccess lda WINLEFTPF0,y sta PF0 lda WINLEFTPF1,y sta PF1 lda WINLEFTPF2,y sta PF2 lda #SpriteHeight; 2 dcp SpriteEnd ; 5 lda #SpriteHeight; 2 dcp Sprite1End ; 5 lda WINRIGHTPF0,y sta PF0 lda WINRIGHTPF1,y sta PF1 lda WINRIGHTPF2,y sta PF2 nop dex ; 2 iny cpy #26 bne SuccessLoop lda #0 sta PF0 sta PF1 sta PF2 lda #$20 ; brown color sta COLUPF ; set the playfield color jmp ScanLoop LEFTPF0 .byte $30,$30,$30,$50,$50,$30,$30,$50,$50,$50,$30,$30,$30,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0 LEFTPF1 .byte $89,$89,$89,$89,$89,$89,$89,$89,$89,$89,$E6,$E6,$E6,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$1,$2,$4,$8,$10,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0 LEFTPF2 .byte $8E,$8E,$8E,$42,$42,$46,$46,$46,$42,$42,$8E,$8E,$8E,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$80,$80,$80,$80,$D0,$D0,$F0,$F0,$F0,$F8,$78,$BC,$DE,$EE,$F6,$FA,$FC,$FF,$7E,$3C,$3C,$14,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0 RIGHTPF0 .byte $90,$90,$90,$A0,$A0,$A0,$A0,$A0,$A0,$A0,$90,$90,$90,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$A0,$A0,$E0,$F0,$F0,$F0,$F0,$F0,$F0,$70,$F0,$B0,$F0,$D0,$F0,$E0,$70,$70,$70,$70,$70,$70,$10,$10,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0 RIGHTPF1 .byte $93,$93,$93,$54,$54,$54,$95,$95,$95,$54,$57,$53,$53,$0,$0,$2,$6,$6,$E,$1E,$3E,$3C,$3C,$34,$7C,$FC,$EC,$FC,$F8,$D8,$F8,$F8,$B0,$F0,$F0,$70,$F0,$E0,$E0,$E0,$C0,$80,$80,$80,$80,$80,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0 RIGHTPF2 .byte $94,$94,$B4,$B5,$B5,$B4,$B5,$D5,$D5,$D5,$D5,$94,$94,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0 WINLEFTPF0 .byte $0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0 WINLEFTPF1 .byte $0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$1,$1,$1,$1,$1,$1,$1,$1 WINLEFTPF2 .byte $0,$0,$0,$0,$0,$C0,$20,$50,$10,$10,$50,$50,$90,$20,$C0,$0,$0,$0,$E8,$48,$48,$48,$4A,$4F,$4D,$E8 WINRIGHTPF0 .byte $0,$0,$0,$0,$0,$30,$40,$A0,$80,$80,$A0,$A0,$90,$40,$30,$0,$0,$0,$20,$60,$60,$60,$A0,$A0,$A0,$20 WINRIGHTPF1 .byte $0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$A8,$A8,$A8,$A8,$80,$80,$A8,$A8 WINRIGHTPF2 .byte $0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0,$0 Sprite0Data .byte #%00000000 .byte #%00111100 .byte #%00011000 .byte #%00011000 .byte #%00011000 .byte #%00111100 .byte #%00011000 .byte #%00000000 Sprite0DataNoCC .byte #%00000000 .byte #%00111100 .byte #%00011000 .byte #%00011000 .byte #%00011000 .byte #%00111100 .byte #%00000000 .byte #%00000000 Sprite1DataPara .byte #%00000000 .byte #%00011100 .byte #%00001000 .byte #%00001000 .byte #%00001000 .byte #%01001001 .byte #%00111110 .byte #%00000000 Sprite1Data .byte #%00000000 .byte #%00011000 .byte #%00000000 .byte #%00000000 .byte #%00000000 .byte #%00000000 .byte #%00000000 .byte #%00000000 Sprite0CrashData .byte #%00000000 .byte #%01010101 .byte #%10101010 .byte #%01010101 .byte #%10101010 .byte #%01010101 .byte #%10101010 .byte #%00000000 ORG $FFFA InterruptVectors .word Reset ; NMI .word Reset ; RESET .word Reset ; IRQ END
/* * FreeRTOS Kernel V10.3.0 * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * http://www.FreeRTOS.org * http://aws.amazon.com/freertos * * 1 tab == 4 spaces! */ #include "FreeRTOSConfig.h" #include "portasm.h" /* These wrappers are only used when interrupt method 2 is being used. See FreeRTOSConfig.h for an explanation. */ #if configINTERRUPT_EXAMPLE_METHOD == 2 .CODE /* Wrapper for the Rx UART interrupt. */ _vUARTRx_Wrapper portSAVE_CONTEXT call #_vRxISR portRESTORE_CONTEXT /*-----------------------------------------------------------*/ /* Wrapper for the Tx UART interrupt. */ _vUARTTx_Wrapper portSAVE_CONTEXT call #_vTxISR portRESTORE_CONTEXT /*-----------------------------------------------------------*/ /* Place the UART ISRs in the correct vectors. */ .VECTORS .KEEP ORG UART1RX_VECTOR DW _vUARTRx_Wrapper ORG UART1TX_VECTOR DW _vUARTTx_Wrapper #endif /* configINTERRUPT_EXAMPLE_METHOD */ END
; A190960: a(n) = 3*a(n-1) - 6*a(n-2), with a(0)=0, a(1)=1. ; 0,1,3,3,-9,-45,-81,27,567,1539,1215,-5589,-24057,-38637,28431,317115,780759,439587,-3365793,-12734901,-18009945,22379571,175198383,391317723,122762871,-1979617725,-6675430401,-8148584853,15606827847,95711992659,193495010895,6213076731,-1142330835177,-3464270965917,-3538827886689,10169142135435,51740393726439,94206328366707,-27823377258513,-648708101975781,-1779184042376265,-1445303515274109,6339193708435263,27689402216950443,45033044400239751,-31037280100983405,-363310106704388721 mov $2,1 lpb $0 sub $0,1 mul $1,2 mul $2,3 sub $2,$1 add $1,$2 lpe div $1,3 mov $0,$1
# Dan Ellard - 05/10/2000 # Echos input until EOI is reached, converting from lowercase # to uppercase. # Register usage: # r2 - holds each character read in # r3 - address of $process # r4 - address of $print # r5 - address of $uppercase # r6 - 'a', the smallest lowercase ASCII value (0x61) # r7 - 'z', the largest lowercase ASCII value (0x7A) # r8 - the mask to convert from lowercase to uppercase lc r3, $process lc r4, $print lc r5, $uppercase lc r6, 'a' lc r7, 'z' lc r8, 1 # set r8 to 1. lc r9, 5 shf r8, r8, r9 # slide over the 1 by 5 positions nor r8, r8, r8 # and then use nor to flip all the bits loop: in r2, ASCII # r2 = getchar (); beq r3, r1, r0 # if not at EOF, go to $process. jmp $exit # otherwise, go to $exit. process: bgt r4, r2, r7 # if the char is > 'z', just print it beq r5, r2, r6 # else if the char is 'a', uppercase it bgt r5, r2, r6 # else if the char is > 'a', uppercase it jmp $print # else the char is < 'a', so just print it uppercase: and r2, r2, r8 # zero the fifth bit of r2 print: out r2, ASCII # putchar (r2); jmp $loop # iterate, go back to $loop. exit: hlt # Exit # end of shout.asm
; A014106: a(n) = n*(2*n + 3). ; 0,5,14,27,44,65,90,119,152,189,230,275,324,377,434,495,560,629,702,779,860,945,1034,1127,1224,1325,1430,1539,1652,1769,1890,2015,2144,2277,2414,2555,2700,2849,3002,3159,3320,3485,3654,3827,4004,4185,4370,4559,4752,4949,5150,5355,5564,5777,5994,6215,6440,6669,6902,7139,7380,7625,7874,8127,8384,8645,8910,9179,9452,9729,10010,10295,10584,10877,11174,11475,11780,12089,12402,12719,13040,13365,13694,14027,14364,14705,15050,15399,15752,16109,16470,16835,17204,17577,17954,18335,18720,19109,19502,19899,20300,20705,21114,21527,21944,22365,22790,23219,23652,24089,24530,24975,25424,25877,26334,26795,27260,27729,28202,28679,29160,29645,30134,30627,31124,31625,32130,32639,33152,33669,34190,34715,35244,35777,36314,36855,37400,37949,38502,39059,39620,40185,40754,41327,41904,42485,43070,43659,44252,44849,45450,46055,46664,47277,47894,48515,49140,49769,50402,51039,51680,52325,52974,53627,54284,54945,55610,56279,56952,57629,58310,58995,59684,60377,61074,61775,62480,63189,63902,64619,65340,66065,66794,67527,68264,69005,69750,70499,71252,72009,72770,73535,74304,75077,75854,76635,77420,78209,79002,79799,80600,81405,82214,83027,83844,84665,85490,86319,87152,87989,88830,89675,90524,91377,92234,93095,93960,94829,95702,96579,97460,98345,99234,100127,101024,101925,102830,103739,104652,105569,106490,107415,108344,109277,110214,111155,112100,113049,114002,114959,115920,116885,117854,118827,119804,120785,121770,122759,123752,124749 mov $1,$0 mul $0,2 add $0,3 mul $1,$0
DATA SEGMENT STR1 DB 0AH,0DH ,'ENTER STRING : $' STR2 DB 'YOUR STRING IS :$' STR3 DB 'REVERSE STRING IS :$' INSTR1 DB 20 DUP() RSTR DB 20 DUP() N DB ? S DB ? MSG1 DB 'STRING IS PALINDROME $' MSG2 DB 'STRING IS NOT PALINDROME $' A DB '1' DATA ENDS CODE SEGMENT START: MOV AX,DATA MOV DS,AX LEA SI,INSTR1 ;GET STRING MOV AH,09H LEA DX,STR1 INT 21H MOV AH,0AH MOV DX,SI INT 21H MOV AH,09H INT 21H ;PRINT THE STRING MOV AH,09H LEA DX,STR2 INT 21H MOV AH,09H LEA DX,INSTR1+2 INT 21H MOV AH,09H INT 21H ;PRINT THE REVERSE OF THE STRING MOV AH,09H LEA DX,STR3 INT 21H MOV CL,INSTR1+1 ADD CL,1 ADD SI,2 L1: INC SI CMP BYTE PTR[SI],'$' JNE L1 DEC SI LEA DI,RSTR L2:MOV AL,BYTE PTR[SI] MOV BYTE PTR[DI],AL DEC SI INC DI LOOP L2 MOV AH,09H INT 21H MOV AH,09H LEA DX,RSTR INT 21H MOV AH,09H INT 21H ;PRINT THE STRING IS PALINDROME OR NOT LEA SI,INSTR1 LEA DI,RSTR MOV AH,09H INT 21H ADD SI,2 L7: MOV BL,BYTE PTR[DI] CMP BYTE PTR[SI],BL JNE LL2 INC SI INC DI MOV BL,BYTE PTR[DI] MOV AH,02H MOV DL,BL INT 21H MOV AH,09H INT 21H CMP BYTE PTR[DI],'$' JNE L7 MOV AH,09H INT 21H MOV AH,09H LEA DX,MSG1 INT 21H JMP L5 LL2: MOV AH,09H INT 21H MOV AH,09H LEA DX,MSG2 INT 21H L5: MOV AH,4CH INT 21H CODE ENDS END START
//! \file /* ** Copyright (c) 2016 - Ponce ** Authors: ** Alberto Garcia Illera agarciaillera@gmail.com ** Francisco Oca francisco.oca.gonzalez@gmail.com ** ** This program is under the terms of the BSD License. */ #pragma once #include <idp.hpp> #include <list> #include "globals.hpp" //This struct is used to define a pending action when a breakpoint is triggered typedef struct { //The address where the breakpoint was set ea_t address; //If we found a previous breakpoint in the same address we should ignore it bool ignore_breakpoint; //This is the callback will be executed when this breakpoint is reached void(*callback)(ea_t); } breakpoint_pending_action; extern std::list<breakpoint_pending_action> breakpoint_pending_actions; #ifdef __IDA70__ ssize_t idaapi tracer_callback(void * /*user_data*/, int notification_code, va_list va); ssize_t idaapi ui_callback(void * /*ud*/, int notification_code, va_list va); #else int idaapi tracer_callback(void * /*user_data*/, int notification_code, va_list va); int idaapi ui_callback(void * /*ud*/, int notification_code, va_list va); #endif void tritonize(va_list va); void reanalize_current_instruction(); void set_SMT_results(Input* input_ptr);
-- HUMAN RESOURCE MACHINE PROGRAM -- COMMENT 11 INBOX COPYTO 0 INBOX COPYTO 1 INBOX OUTBOX COPYFROM 1 OUTBOX COPYFROM 0 OUTBOX COMMENT 12 INBOX OUTBOX INBOX OUTBOX INBOX OUTBOX a: b: c: d: e: f: COMMENT 0 INBOX COPYTO 0 INBOX SUB 0 JUMPN i COMMENT 1 COPYTO 1 INBOX SUB 0 JUMPN h COMMENT 3 COPYTO 2 SUB 1 JUMPN g COMMENT 7 COPYFROM 0 OUTBOX COPYFROM 1 ADD 0 OUTBOX COPYFROM 2 ADD 0 OUTBOX JUMP e COMMENT 8 g: COPYFROM 0 OUTBOX COPYFROM 2 ADD 0 OUTBOX COPYFROM 1 ADD 0 OUTBOX JUMP f COMMENT 4 h: ADD 0 OUTBOX COPYFROM 0 OUTBOX COPYFROM 1 ADD 0 OUTBOX JUMP b COMMENT 2 i: COPYTO 1 INBOX SUB 0 JUMPN j COMMENT 6 COPYTO 2 COPYFROM 1 ADD 0 OUTBOX COPYFROM 0 OUTBOX COPYFROM 2 ADD 0 OUTBOX JUMP a COMMENT 5 j: COPYTO 2 SUB 1 JUMPN k COMMENT 9 COPYFROM 1 ADD 0 OUTBOX COPYFROM 2 ADD 0 OUTBOX COPYFROM 0 OUTBOX JUMP c COMMENT 10 k: COPYFROM 2 ADD 0 OUTBOX COPYFROM 1 ADD 0 OUTBOX COPYFROM 0 OUTBOX JUMP d DEFINE COMMENT 0 eJyzYGBgOKTbrP5dK0hFWM1R+Z1SkuoE4bmWFwWT3VqEosP2yikly6vfyJPWu1D33+hEX4Txr4kRxjbT nhvMn5OjpnLsmkLaKWOptFMlEq4ngEYxePo/1z0eFB1WFXwjryq4/DRIjMcrOI0h3igFxNYs9C6rr/jY sKCpbtaCpvrd7Q2PDlbXu57orrx1kbfs9SXG0pMX/ErSTn0t9t1xpX7HOpCeDZPydm2YpFWyYMbPggnz fhbwLdIqebZUqwQk57O3x2LTvo8Nm/ZdPPB5z6ODILHvW2si+HfMjRI+vi+GYRSMglGAFwAAkolgVw; DEFINE COMMENT 1 eJxTYmBgOKeX7MavKz2FX9d3B5DL8EjRuHWqRUg7iK0bsi7aMZaz6EZSaodbTuiK8oIVa5sLdbaB5JbH la2STHRZ3lx4oe5GRUp6fl1NRHV9TjhIbsnED/Fck51TX83bXxuxwmd6yPoVa0Hi76a7LA+eKbykYo7N NOXVMeXXVksV79ywPYdhFIyCUTAgAABzQjRD; DEFINE COMMENT 2 eJzTZmBgeCX8oF5Y7UIdkMlQ6jI1a7/X+hoJb6UWW7/Szj/+XJN1Qx4usAx9uAAk/93hQ/wyj58Fj32F mleHH5jXF3NzQ1pC3q4PKQf3g+RnuaeujPQ0WTYv7EKdZrRU8fK447kgcaPKddGctSnpC5qkine0rK8x 6whp9++ymRbdDcK5M6V6+2ZL9R6YFz7p5HqQerUKk2XdlcJL4luMW/dOjg47OSU6jGEUjIJRQHUAABHQ Rso; DEFINE COMMENT 3 eJxTZ2BgWKui6LRWpSZCWO1FvrCa9FYGkBhfTPlcrZhyDX3OIhWzF/kgsb4YAccXMTc3gNgarttzTNxu 5MVFSBWLZkgVV2VyFl3JPJ4LkpteZejs1mQVwtR9PHfGhAf13hND2nNmP1xQMcdlOUj+Z1PdrOBmn+la 7dO6v3aGtPt3MTblT9meM2f+c7+tC4/58C2a6im9uMWDYRSMglFAcwAAJgg6Aw; DEFINE COMMENT 4 eJyzZ2BgEBLQCj4qcHA/kMlgz1raeZVrWre2kHHrQXHjVpCYhaZQc6M+YxOIfdpbMui0t3Pqfq/9tRLe ry+BxFY5hrTPC3NpA7HLC6xLecu8y0Bswfz5c86U980GsXe0LPW62+4derZ3fc2SiSHtSyZyTZ4yfcc6 kNzFtrpZd9t9ppt1vJzA18PYxNezv9aof3vO036jlKtTJYNAanqWXvd9t3Z7Dog9d+tzv4XrGJs619hM 01/DtBgktuiIoXPucQHHWZcEHD9fKnHXuCAZNOmUVknq/rJVEft0tt0/OX1N44Xpa0Bqdx2TKv5+2rqU YRSMglHAAAAvA2A+; DEFINE COMMENT 5 eJyTZWBgaBHKrfCRqa08phZTDuQyaLhal3IEShUHht/IA/Gz8hkcHjZwFsm19VXd7OubPWPC+rl7J7ss PzkldMWU6dJbp0yP2/lwWv8ekFqnYp/pUaUn+jbUPKivro8pX9AkVczUzZjI17Mvxn5CTnj+lOu+DKNg FIyCQQMAUhouAA; DEFINE COMMENT 6 eJxzZ2BgOMkZU94iZF0aI+ZdBuQy9BoEu/Ya+Ey/pf9wAYgvr15bGaMjVcxu/SIfxP/sfiPPMvRGnmvY zwIQ/2uxYBKI3lKqlLyk+kEciM1YmtoRVhPSDmLz9VSbG/UzOHycMNWzZmpNRM3UfTFrZ27PAcmZz1N0 ujgnJzx+lmDSw2mxM0Biyqvf2+3cIBnUurkk4/vWnwUrtzE2HdoxrfvQDukpt3bVzQKp2btSesra9c6p xzY+iLu3+Yc/83YGh0M7ztnc2uVlApIXPl5tznNVwrDwmoRh3XVL49PXtnnzXNUKZriyLtrh0oO4Q+de 5Gee218777RLm8vp5T33T2pPzbv7cgJI77azSskS14xSGEbBKBgBAAAJ/nG9; DEFINE COMMENT 7 eJyLYWBgWKgs4Phb+XhuguqFugTVhwuOqe1YBxRmWCm6v1ZaYl61uPy86k7F3IrfyrkVlerWpbf0rUtB 8o9979s+9hVM+uC3vuaDX/8ekJiA88eGeWEP6rdH7K8F8cNq3tv9rc6tuFGhPdWo8uYGkJhl9s8CzULr UqZuiDkLZpyPnTN/XwyI/WvG/tpX89bXgNh7V1abP1rj5CK/ySilcVdIe+Ou7b29u2/0O+yJnZG6X3hJ 6n6X5QaHTq4HqZ25bP6cpcvrZv1bbjMtZeWviXtXLu/RXyPUrL9mf+3UtbWVCRs+xFdsqom4tEkr+NWW 677ftzI4MG+/b7tte7YZSL/CiXM2meesQkwu1kSA+PuvrrXiufqzgOFKbsXtCybLSs9D7NG932Ph+hAo 93qtVdGbFg+e1+uiv7wQTJr9oiQj8NGviW3362Zdvhe6Yvtjk2V1b02WgfTIPOUsuv3sRX7RG84ihlEw CgYZAACKLaUS; DEFINE COMMENT 8 eJzzYWBgWKhc4r5QObciQTV3ZoLq9DVAIYZeKcamldoP6kFsHi/JIB4vl+WF3ifXF3qXrQKJ5drElF+2 ra3MdJ5XfTl4XvWb0P212yPmVYPkjuR/bGBtYWxqbhdqntDh0gYSs58QHWY9PSccxN4wafqaq1NXrNWe CzFLefXcqIQN3mUB21I7Pu8JXfF5z6uN//f67gDJWa9tX82+4cA89g0205i351bEbJcqfrbbKAUkZ3Eq 2LXvYouHyF2OwLy7OeEcd+ZGSVx7UO97ua1r21mX5QLnTq6XOb9ircnFFWslrqWutL2ZuhKk7/x5qWKZ p1olIHba66VenJ8+xFd9mZrl9C+kHSS2/P+6aNnfqR2rf/yauPqHz/TJ34SX5H3W2Zb0CeKmUTAKhhMA AIp9gFU; DEFINE COMMENT 9 eJxzZGBg+Mem1PJKWKgZyGR4pPigvlVjfU2j/voaEL/JdV+MhuuN/lIXpsUgvoX9g3pbv48NIHZS+o08 3awbeSD29JSXEyZnv5wAYtumTM0Kyl2WDWLbVWWbfazaZ81Zy+BwpX6p146WnPAdLeuiQXIHe/ZZ8/X8 8HfqnJr1sqO28kir9lSQePBMTaOYhRwG/5ZrGv1bft82ZmFwmvk8zqL4WfOqf82Y1r10+fIekLpX86LD jJdCzOLfsdSrdCdHoMKJB/WXTxi3upze3gsSzz1u6Cx8/JiPzeGaiMIDWiWb9sWUz9wj1Ky+K7WjdOfL CXO32kxjGAWjYAQDAMJ0ZfA; DEFINE COMMENT 10 eJzzYGBgEBJYX/NJ+kIdkMmQodtX1WleWwlif/DLrdgekVsBYkeVPogTrXsQt6GGMRHELy5P7ZjSmNoB Ym+YVG1esrjavGFJj0XDkn3WBxc5uWxdGOw6Yd75WPN523PiZ/VV6U/Lnck1uWxV+CTuLUpTT65nWuiy /NaSTwtB+vWnLcveOet4rvHSG3lcKzmLQGKtm+daft+q6GSy+7qv+IF9Mb+PGKUEnrEuBcmdP9/icehc b+S2s4yJzGdD2i1O2UzTOSm8JPd42arc49Jbfx/ZsC/kaP1ukFqFe1M9tz+eG5X2OrdC8s3Hhunvb/Qr fumbDZI78VkrePEHpeSud9alp9+sr9n/urTT96XP9BfPd6w7/5R7S9lT0+MMo2AUDHMAAOnmgJw; DEFINE COMMENT 11 eJzrZGBguCd0T8aaZ4qGPjeHwVUuQ+eH3FM93XmP+TiLeIc2SOaEA5UwyKsrKF5Sv6ZzST3YdaLmVM+J moyJIPFDutu8Pxse80k1kQwSN/UOFTf9EH/K1CgFJPfd4ZjPMo9jPvu9WjwkvJ1ceLzO2TB4zrU0cas2 3+ZUbe7icM7mtf352O8OgkmlLiUZyzxKMkD6NKMtjXkSLI050+daVmUmu13JjA6rytwXk5dxPjYpXSn5 TGJKukAkCDMmvoiZG6Wa5B0algZx55Lqd7JLqqdmgdh+JZbG7Q2WxuVtEoYgfnGvdWlx78cGEPsql/LS tXzKS/nEL86vVAdhpsU5ai7L2VVTV/ZKtZ85KD7h7lGBijcJ/Lc/bZTl+XZMjecbSN8tybRT4vJhJ0Fs GwvT4+usLh64b1e/W8bl5PrbrjvWgcR/W6ocW+V46eEqR5FnpS63PzW5/vnS5LrrA0hOIdhl+f2QFWuz Irm3NEXn7Voed3D//gTT4yA5zvTQFV6pKse6k9vP3EiacLco8fEj37iGvyC5PbUiR/UaHh0069ix7mBP 6AqQWH6d6fEFTbcuLmjiudrcvvBedHfYq5t9M9+B5HJmT18Ts/Diga0LRY5+WsZz1Xt53K2UlRPupqw8 9GDhOoiaX+umr4lYwXzEeKnMtZULPj9+NW/mu1fz0l+D5NJ7rELO9iolS/X2VTGMgmENAJnw3NI; DEFINE COMMENT 12 eJxrZ2BgyBB/JztB+J2sO6+jsj73d729HJbG/9jmWv5je2/nzabo5M22zZuL44f/K2HvUKByhmsKWaLX FLSCQewQlWpzYbVq85XamkalesGu/LrRYSDx35bnbA47v7e77XrO5rZrlKmGq6bRb0tNo0WW7+107IJd Ax2DXWOdStxjnZZ6nXexCpnlDtHnGlaspprUrG6YvETzSfJ3PduUuZZPkq1C6pJywlWT5katDv8Q/yNs XfSPMMmg1eHbvLMig13LogydixKneoL0F5dniRaXL9FMK2NwWF7y3M+vJCUdJJ6VX22+pLranLM2yhTE n9Pp5GLUH+za0y8ZdLBHKTm62zm1uV2rJL5lfc2aZsYmrfYH9U/7L9RtmLS+BqTemufTQm2hk+udRep3 q0u6nlCXLD/dK3XyAkiuQrB+N5946IoGSZNlM6U/LQSJ/eJlPsLGz3zkomD/HhD/kG7ZqghjpsX7TA7M A/EzdLm3fDZcsNfH6OIBEP+w8/w5pS5MiyM9y1aB+B/8+mZ/8AtdoeJz8YCEt8hRCe+0UyDx5XE3NzDE r1jLkzB9jWRi6ArVpNAVi1MvzudMvzgfJM8QL73VNuXTocWp7WfWp7Wf+ZMadhKsr2T9XL2G3JlWjbkz pzSun3ulfsc60bqbG5JrpbfaVW3Yd6BsxTneMp6rahWvLynV37q4oGnFOYZRMCIAAHwdy+4; DEFINE LABEL 0 eJwTYWBgOKaWpCqvvkRT3DQlvcn14nxDX+Yjtn4qxz74zTgLlGZ4btB+xsD81yYL+/lzBJyX98xyN24t 9OYsWh9glJIXlBPeFvLczzVsm3dguKITwygYBaNgSAEACGAdmQ; DEFINE LABEL 1 eJwzZGBgmCvCc3Wl6O/LxlIb9vnIlK06Ja89NUSlNfOeRnTYPY2pnhr6W7VMDAQUHAwFFHyMtmr9Nzpn I2461fOUqXPqNTPvMhuLvqpFlst7Qq0W7E20Prif3dr1hIdl2Ekbi/Yz3CY7z2/T2Xn+leaMszUK5aeB 1jE8kyo/HaCddgrEPu0919LQV8DRMlQy6EtsSUZ3slTxk2TvMpBcUK6TS1DuUq8rmTfydqfPq05KT+2w TWFarJo0fQ1D/KODDPEy1+5EX3rIMApGwSggGwAAiGtNsg; DEFINE LABEL 2 eJzTZmBgiJDdeX6jrMhRa6W6WeyqN/Iq1c/HrtSuNs/QlTAs1dM0+m903bfQtCRDxSy34rG5Ussiy9SV vy3TTtWarTgnr37yQo3CzvNAYxj2e6216vJda7U+oNp8dXiUqWNslGlRYrbZh5S5lotTz9l4pSo6PUl2 cpkd65y6PUKr5HJwagdHoM209QF9s+t8XJZLeHNvWeZx8cD6gIP7FYIX7L2R1L8HZO7uQO8yyUTvMoZR MApGAdUBADzERcU;
INCLUDE "clib_cfg.asm" SECTION code_math PUBLIC l_fast_mulu_16_8x8 l_fast_mulu_16_8x8: ; unsigned multiplication of two 8-bit ; multiplicands into a sixteen bit product ; ; enter : l = 8-bit multiplicand ; e = 8-bit multiplicand ; ; exit : hl = 16-bit product ; a = 0 ; d = 0 ; carry reset ; ; uses : af, b, de, hl xor a ld d,a ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_IMATH_FAST & $08 ld h,l ld l,e ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ELSE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ld h,l ld l,a ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_IMATH_FAST & $04 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ENABLE LOOP UNROLLING ;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_IMATH_FAST & $08 ; eliminate leading zero bits loop_00: sla h jr c, loop_11 sla h jr c, loop_12 sla h jr c, loop_13 sla h jr c, loop_14 sla h jr c, loop_15 sla h jr c, loop_16 sla h jr c, loop_17 sla h ccf ret nc xor a ld l,a ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ELSE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; loop_10: sla h jr nc, loop_11 add hl,de ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; general multiplication loop loop_11: add hl,hl jr nc, loop_12 add hl,de loop_12: add hl,hl jr nc, loop_13 add hl,de loop_13: add hl,hl jr nc, loop_14 add hl,de loop_14: add hl,hl jr nc, loop_15 add hl,de loop_15: add hl,hl jr nc, loop_16 add hl,de loop_16: add hl,hl jr nc, loop_17 add hl,de loop_17: add hl,hl ret nc add hl,de ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ELSE ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; DISABLE LOOP UNROLLING ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ld b,8 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_IMATH_FAST & $08 ; eliminate leading zeroes loop_00: sla h jr c, loop_01 djnz loop_00 xor a ld l,a ret ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; general multiply loop loop_11: add hl,hl jr nc, loop_01 add hl,de loop_01: djnz loop_11 ret ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
dnl AMD64 mpn_addmul_1 and mpn_submul_1 optimised for Intel Nehalem. dnl Contributed to the GNU project by Torbjörn Granlund. dnl Copyright 2003-2005, 2007, 2008, 2011-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 AMD K8,K9 C AMD K10 C AMD bull C AMD pile C AMD bobcat C AMD jaguar C Intel P4 C Intel core C Intel NHM 4.55 with minor fluctuations C Intel SBR C Intel IBR C Intel HWL C Intel BWL C Intel atom C VIA nano C The loop of this code is the result of running a code generation and C optimization tool suite written by David Harvey and Torbjorn Granlund. C N.B.: Be careful if editing, making sure the loop alignment padding does not C become large, as we currently fall into it. define(`rp', `%rdi') C rcx define(`up', `%rsi') C rdx define(`n_param', `%rdx') C r8 define(`v0', `%rcx') C r9 define(`n', `%rbx') ifdef(`OPERATION_addmul_1',` define(`ADDSUB', `add') define(`func', `mpn_addmul_1') ') ifdef(`OPERATION_submul_1',` define(`ADDSUB', `sub') define(`func', `mpn_submul_1') ') ABI_SUPPORT(DOS64) ABI_SUPPORT(STD64) MULFUNC_PROLOGUE(mpn_addmul_1 mpn_submul_1) ASM_START() TEXT ALIGN(32) PROLOGUE(func) FUNC_ENTRY(4) push %rbx mov (up), %rax lea -8(up,n_param,8), up mov (rp), %r8 lea -8(rp,n_param,8), rp test $1, R8(n_param) jnz L(bx1) L(bx0): test $2, R8(n_param) jnz L(b10) L(b00): mov $3, R32(n) sub n_param, n mul v0 mov $0, R32(%r11) mov %r8, %r10 ADDSUB %rax, %r10 mov -8(up,n,8), %rax adc %rdx, %r11 jmp L(lo0) L(b10): mov $1, R32(n) sub n_param, n mul v0 mov %r8, %r10 mov $0, R32(%r11) ADDSUB %rax, %r10 mov 8(up,n,8), %rax adc %rdx, %r11 jmp L(lo2) L(bx1): test $2, R8(n_param) jz L(b01) L(b11): mov $2, R32(n) sub n_param, n mul v0 ADDSUB %rax, %r8 mov $0, R32(%r9) mov (up,n,8), %rax adc %rdx, %r9 jmp L(lo3) L(b01): mov $0, R32(n) sub n_param, n xor %r11, %r11 add $4, n jc L(end) ALIGN(32) L(top): mul v0 ADDSUB %rax, %r8 mov $0, R32(%r9) mov -16(up,n,8), %rax adc %rdx, %r9 L(lo1): mul v0 ADDSUB %r11, %r8 mov $0, R32(%r11) mov -16(rp,n,8), %r10 adc $0, %r9 ADDSUB %rax, %r10 mov -8(up,n,8), %rax adc %rdx, %r11 mov %r8, -24(rp,n,8) ADDSUB %r9, %r10 adc $0, %r11 L(lo0): mov -8(rp,n,8), %r8 mul v0 ADDSUB %rax, %r8 mov $0, R32(%r9) mov (up,n,8), %rax adc %rdx, %r9 mov %r10, -16(rp,n,8) ADDSUB %r11, %r8 adc $0, %r9 L(lo3): mul v0 mov (rp,n,8), %r10 mov $0, R32(%r11) ADDSUB %rax, %r10 mov 8(up,n,8), %rax adc %rdx, %r11 mov %r8, -8(rp,n,8) ADDSUB %r9, %r10 adc $0, %r11 L(lo2): mov 8(rp,n,8), %r8 mov %r10, (rp,n,8) add $4, n jnc L(top) L(end): mul v0 ADDSUB %rax, %r8 mov $0, R32(%rax) adc %rdx, %rax ADDSUB %r11, %r8 adc $0, %rax mov %r8, (rp) pop %rbx FUNC_EXIT() ret EPILOGUE() ASM_END()
/* * Copyright Andrey Semashev 2020 * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * https://www.boost.org/LICENSE_1_0.txt) */ /*! * \file rotr.hpp * * This header defines \c rotr algorithm, which rotates integer right. */ #ifndef BOOST_BIT_OPS_ROTATING_ROTR_HPP_INCLUDED_ #define BOOST_BIT_OPS_ROTATING_ROTR_HPP_INCLUDED_ #include <limits> #include <boost/bit_ops/detail/config.hpp> #include <boost/bit_ops/detail/type_traits/enable_if.hpp> #include <boost/bit_ops/detail/type_traits/integral_constant.hpp> #include <boost/bit_ops/detail/type_traits/is_integral.hpp> #include <boost/bit_ops/detail/type_traits/is_unsigned.hpp> #if defined(_MSC_VER) #include <intrin.h> #endif namespace boost { namespace bit_ops { namespace detail { #if defined(BOOST_BIT_OPS_DETAIL_HAS_ROTR8) template< typename T > inline T rotr(T value, unsigned int count, bit_ops::detail::integral_constant< unsigned int, 1u >) BOOST_NOEXCEPT { return static_cast< T >(_rotr8(value, count)); } #endif // defined(BOOST_BIT_OPS_DETAIL_HAS_ROTR8) #if defined(BOOST_BIT_OPS_DETAIL_HAS_ROTR16) template< typename T > inline T rotr(T value, unsigned int count, bit_ops::detail::integral_constant< unsigned int, 2u >) BOOST_NOEXCEPT { return static_cast< T >(_rotr16(value, count)); } #endif // defined(BOOST_BIT_OPS_DETAIL_HAS_ROTR16) #if defined(BOOST_BIT_OPS_DETAIL_HAS_ROTR) template< typename T > inline T rotr(T value, unsigned int count, bit_ops::detail::integral_constant< unsigned int, 4u >) BOOST_NOEXCEPT { return static_cast< T >(_rotr(value, count)); } #endif // defined(BOOST_BIT_OPS_DETAIL_HAS_ROTR) #if defined(BOOST_BIT_OPS_DETAIL_HAS_ROTR64) template< typename T > inline T rotr(T value, unsigned int count, bit_ops::detail::integral_constant< unsigned int, 8u >) BOOST_NOEXCEPT { return static_cast< T >(_rotr64(value, count)); } #endif // defined(BOOST_BIT_OPS_DETAIL_HAS_ROTR64) template< typename T, unsigned int N > inline T rotr(T value, unsigned int count, bit_ops::detail::integral_constant< unsigned int, N >) BOOST_NOEXCEPT { return static_cast< T >((value >> count) | (value << (std::numeric_limits< T >::digits - count))); } } // namespace detail //! Returns \a value rotated left by \a count bits template< typename T > inline typename bit_ops::detail::enable_if< bit_ops::detail::is_integral< T >::value && bit_ops::detail::is_unsigned< T >::value, T >::type rotr(T value, unsigned int count) BOOST_NOEXCEPT { return bit_ops::detail::rotr(value, count, bit_ops::detail::integral_constant< unsigned int, sizeof(T) >()); } } // namespace bit_ops } // namespace boost #endif // BOOST_BIT_OPS_ROTATING_ROTR_HPP_INCLUDED_
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/tbm/v20180129/model/BrandReportArticle.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Tbm::V20180129::Model; using namespace rapidjson; using namespace std; BrandReportArticle::BrandReportArticle() : m_titleHasBeenSet(false), m_urlHasBeenSet(false), m_fromSiteHasBeenSet(false), m_pubTimeHasBeenSet(false), m_flagHasBeenSet(false), m_hotHasBeenSet(false), m_levelHasBeenSet(false), m_abstractHasBeenSet(false), m_articleIdHasBeenSet(false) { } CoreInternalOutcome BrandReportArticle::Deserialize(const Value &value) { string requestId = ""; if (value.HasMember("Title") && !value["Title"].IsNull()) { if (!value["Title"].IsString()) { return CoreInternalOutcome(Error("response `BrandReportArticle.Title` IsString=false incorrectly").SetRequestId(requestId)); } m_title = string(value["Title"].GetString()); m_titleHasBeenSet = true; } if (value.HasMember("Url") && !value["Url"].IsNull()) { if (!value["Url"].IsString()) { return CoreInternalOutcome(Error("response `BrandReportArticle.Url` IsString=false incorrectly").SetRequestId(requestId)); } m_url = string(value["Url"].GetString()); m_urlHasBeenSet = true; } if (value.HasMember("FromSite") && !value["FromSite"].IsNull()) { if (!value["FromSite"].IsString()) { return CoreInternalOutcome(Error("response `BrandReportArticle.FromSite` IsString=false incorrectly").SetRequestId(requestId)); } m_fromSite = string(value["FromSite"].GetString()); m_fromSiteHasBeenSet = true; } if (value.HasMember("PubTime") && !value["PubTime"].IsNull()) { if (!value["PubTime"].IsString()) { return CoreInternalOutcome(Error("response `BrandReportArticle.PubTime` IsString=false incorrectly").SetRequestId(requestId)); } m_pubTime = string(value["PubTime"].GetString()); m_pubTimeHasBeenSet = true; } if (value.HasMember("Flag") && !value["Flag"].IsNull()) { if (!value["Flag"].IsUint64()) { return CoreInternalOutcome(Error("response `BrandReportArticle.Flag` IsUint64=false incorrectly").SetRequestId(requestId)); } m_flag = value["Flag"].GetUint64(); m_flagHasBeenSet = true; } if (value.HasMember("Hot") && !value["Hot"].IsNull()) { if (!value["Hot"].IsUint64()) { return CoreInternalOutcome(Error("response `BrandReportArticle.Hot` IsUint64=false incorrectly").SetRequestId(requestId)); } m_hot = value["Hot"].GetUint64(); m_hotHasBeenSet = true; } if (value.HasMember("Level") && !value["Level"].IsNull()) { if (!value["Level"].IsUint64()) { return CoreInternalOutcome(Error("response `BrandReportArticle.Level` IsUint64=false incorrectly").SetRequestId(requestId)); } m_level = value["Level"].GetUint64(); m_levelHasBeenSet = true; } if (value.HasMember("Abstract") && !value["Abstract"].IsNull()) { if (!value["Abstract"].IsString()) { return CoreInternalOutcome(Error("response `BrandReportArticle.Abstract` IsString=false incorrectly").SetRequestId(requestId)); } m_abstract = string(value["Abstract"].GetString()); m_abstractHasBeenSet = true; } if (value.HasMember("ArticleId") && !value["ArticleId"].IsNull()) { if (!value["ArticleId"].IsString()) { return CoreInternalOutcome(Error("response `BrandReportArticle.ArticleId` IsString=false incorrectly").SetRequestId(requestId)); } m_articleId = string(value["ArticleId"].GetString()); m_articleIdHasBeenSet = true; } return CoreInternalOutcome(true); } void BrandReportArticle::ToJsonObject(Value &value, Document::AllocatorType& allocator) const { if (m_titleHasBeenSet) { Value iKey(kStringType); string key = "Title"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_title.c_str(), allocator).Move(), allocator); } if (m_urlHasBeenSet) { Value iKey(kStringType); string key = "Url"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_url.c_str(), allocator).Move(), allocator); } if (m_fromSiteHasBeenSet) { Value iKey(kStringType); string key = "FromSite"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_fromSite.c_str(), allocator).Move(), allocator); } if (m_pubTimeHasBeenSet) { Value iKey(kStringType); string key = "PubTime"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_pubTime.c_str(), allocator).Move(), allocator); } if (m_flagHasBeenSet) { Value iKey(kStringType); string key = "Flag"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_flag, allocator); } if (m_hotHasBeenSet) { Value iKey(kStringType); string key = "Hot"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_hot, allocator); } if (m_levelHasBeenSet) { Value iKey(kStringType); string key = "Level"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_level, allocator); } if (m_abstractHasBeenSet) { Value iKey(kStringType); string key = "Abstract"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_abstract.c_str(), allocator).Move(), allocator); } if (m_articleIdHasBeenSet) { Value iKey(kStringType); string key = "ArticleId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_articleId.c_str(), allocator).Move(), allocator); } } string BrandReportArticle::GetTitle() const { return m_title; } void BrandReportArticle::SetTitle(const string& _title) { m_title = _title; m_titleHasBeenSet = true; } bool BrandReportArticle::TitleHasBeenSet() const { return m_titleHasBeenSet; } string BrandReportArticle::GetUrl() const { return m_url; } void BrandReportArticle::SetUrl(const string& _url) { m_url = _url; m_urlHasBeenSet = true; } bool BrandReportArticle::UrlHasBeenSet() const { return m_urlHasBeenSet; } string BrandReportArticle::GetFromSite() const { return m_fromSite; } void BrandReportArticle::SetFromSite(const string& _fromSite) { m_fromSite = _fromSite; m_fromSiteHasBeenSet = true; } bool BrandReportArticle::FromSiteHasBeenSet() const { return m_fromSiteHasBeenSet; } string BrandReportArticle::GetPubTime() const { return m_pubTime; } void BrandReportArticle::SetPubTime(const string& _pubTime) { m_pubTime = _pubTime; m_pubTimeHasBeenSet = true; } bool BrandReportArticle::PubTimeHasBeenSet() const { return m_pubTimeHasBeenSet; } uint64_t BrandReportArticle::GetFlag() const { return m_flag; } void BrandReportArticle::SetFlag(const uint64_t& _flag) { m_flag = _flag; m_flagHasBeenSet = true; } bool BrandReportArticle::FlagHasBeenSet() const { return m_flagHasBeenSet; } uint64_t BrandReportArticle::GetHot() const { return m_hot; } void BrandReportArticle::SetHot(const uint64_t& _hot) { m_hot = _hot; m_hotHasBeenSet = true; } bool BrandReportArticle::HotHasBeenSet() const { return m_hotHasBeenSet; } uint64_t BrandReportArticle::GetLevel() const { return m_level; } void BrandReportArticle::SetLevel(const uint64_t& _level) { m_level = _level; m_levelHasBeenSet = true; } bool BrandReportArticle::LevelHasBeenSet() const { return m_levelHasBeenSet; } string BrandReportArticle::GetAbstract() const { return m_abstract; } void BrandReportArticle::SetAbstract(const string& _abstract) { m_abstract = _abstract; m_abstractHasBeenSet = true; } bool BrandReportArticle::AbstractHasBeenSet() const { return m_abstractHasBeenSet; } string BrandReportArticle::GetArticleId() const { return m_articleId; } void BrandReportArticle::SetArticleId(const string& _articleId) { m_articleId = _articleId; m_articleIdHasBeenSet = true; } bool BrandReportArticle::ArticleIdHasBeenSet() const { return m_articleIdHasBeenSet; }
; -------------------------------------------------------------------------------------------------- ; Decoded payload, stage 1 ; -------------------------------------------------------------------------------------------------- 0x04006354: 60 81 02 10 MOVqw R1, @R0 (+2, +0) ; arg1 0x04006358: f7 32 f2 28 f6 95 b8 75 5d bb MOVIqq R2, 0xbb5d75b895f628f2 ; 0x04006362: f7 33 8b 7b 73 c6 6e 28 0a d3 MOVIqq R3, 0xd30a286ec6737b8b ; 0x0400636c: f7 34 55 51 68 5d 0d 53 fa 1b MOVIqq R4, 0x1bfa530d5d685155 ; 0x04006376: f7 35 55 33 08 d2 b3 4d 9c a2 MOVIqq R5, 0xa29c4db3d2083355 ; 0x04006380: f7 36 34 51 ff b2 83 0d 0a ab MOVIqq R6, 0xab0a0d83b2ff5134 ; 0x0400638a: f7 37 3d ab 69 e3 39 83 51 67 MOVIqq R7, 0x67518339e369ab3d ; 0x04006394: 4c 61 ADD R1, R6 ; 0x04006396: 4d 51 SUB R1, R5 ; 0x04006398: f7 37 ae 52 b4 cb c4 98 12 da MOVIqq R7, 0xda1298c4cbb452ae ; 0x040063a2: 56 71 XOR R1, R7 ; 0x040063a4: 4d 61 SUB R1, R6 ; 0x040063a6: 56 71 XOR R1, R7 ; 0x040063a8: 4c 21 ADD R1, R2 ; 0x040063aa: 4d 21 SUB R1, R2 ; 0x040063ac: f7 33 ea 6d c6 1a 42 e6 f0 48 MOVIqq R3, 0x48f0e6421ac66dea ; 0x040063b6: 56 71 XOR R1, R7 ; 0x040063b8: 4d 61 SUB R1, R6 ; 0x040063ba: 56 61 XOR R1, R6 ; 0x040063bc: 4c 51 ADD R1, R5 ; 0x040063be: 4d 31 SUB R1, R3 ; 0x040063c0: 4c 51 ADD R1, R5 ; 0x040063c2: 4a 11 NOT R1, R1 ; 0x040063c4: f7 36 9f 9a dd 41 22 f9 03 43 MOVIqq R6, 0x4303f92241dd9a9f ; 0x040063ce: 56 71 XOR R1, R7 ; 0x040063d0: 4d 21 SUB R1, R2 ; 0x040063d2: f7 35 59 c1 c7 40 77 46 a9 e0 MOVIqq R5, 0xe0a9467740c7c159 ; 0x040063dc: 4d 41 SUB R1, R4 ; 0x040063de: 4d 71 SUB R1, R7 ; 0x040063e0: f7 36 fd f5 18 76 fc ab e8 58 MOVIqq R6, 0x58e8abfc7618f5fd ; 0x040063ea: 4a 11 NOT R1, R1 ; 0x040063ec: f7 36 69 7e b8 36 bb 91 07 31 MOVIqq R6, 0x310791bb36b87e69 ; 0x040063f6: 4c 51 ADD R1, R5 ; 0x040063f8: 4b 11 NEG R1, R1 ; 0x040063fa: 4d 41 SUB R1, R4 ; 0x040063fc: f7 36 ca 5c f9 9f 30 6d f8 ed MOVIqq R6, 0xedf86d309ff95cca ; 0x04006406: 56 61 XOR R1, R6 ; 0x04006408: 4d 21 SUB R1, R2 ; 0x0400640a: 4c 41 ADD R1, R4 ; 0x0400640c: 56 31 XOR R1, R3 ; 0x0400640e: f7 34 1b 21 a8 70 48 f5 83 94 MOVIqq R4, 0x9483f54870a8211b ; 0x04006418: 56 41 XOR R1, R4 ; 0x0400641a: 4d 61 SUB R1, R6 ; 0x0400641c: f7 36 2a 3e f5 75 a2 56 ac b1 MOVIqq R6, 0xb1ac56a275f53e2a ; 0x04006426: 4d 71 SUB R1, R7 ; 0x04006428: f7 35 aa 1b 1d 98 4f b6 85 e8 MOVIqq R5, 0xe885b64f981d1baa ; 0x04006432: 56 21 XOR R1, R2 ; 0x04006434: 4d 31 SUB R1, R3 ; 0x04006436: f7 36 cb b0 21 4d 0b 6e 60 0d MOVIqq R6, 0x0d606e0b4d21b0cb ; 0x04006440: 4c 31 ADD R1, R3 ; 0x04006442: 56 51 XOR R1, R5 ; 0x04006444: f7 37 64 a6 78 8f 55 4c 0b 7f MOVIqq R7, 0x7f0b4c558f78a664 ; 0x0400644e: 4a 11 NOT R1, R1 ; 0x04006450: f7 37 d5 cb a0 bb 35 3b 82 9d MOVIqq R7, 0x9d823b35bba0cbd5 ; 0x0400645a: 56 61 XOR R1, R6 ; 0x0400645c: f7 36 88 e8 0a 39 c4 3b d5 a5 MOVIqq R6, 0xa5d53bc4390ae888 ; 0x04006466: 56 61 XOR R1, R6 ; 0x04006468: f7 36 af 8f ed 03 81 13 58 e8 MOVIqq R6, 0xe858138103ed8faf ; 0x04006472: 4d 71 SUB R1, R7 ; 0x04006474: f7 33 3f fe 7b a4 06 d1 7a e9 MOVIqq R3, 0xe97ad106a47bfe3f ; 0x0400647e: 4d 31 SUB R1, R3 ; 0x04006480: 4a 11 NOT R1, R1 ; 0x04006482: f7 36 a5 6d b5 31 1d 83 e9 12 MOVIqq R6, 0x12e9831d31b56da5 ; 0x0400648c: 4a 11 NOT R1, R1 ; 0x0400648e: 4b 11 NEG R1, R1 ; 0x04006490: f7 34 87 8e da 8c 44 f2 ef ee MOVIqq R4, 0xeeeff2448cda8e87 ; 0x0400649a: 4d 71 SUB R1, R7 ; 0x0400649c: 4c 71 ADD R1, R7 ; 0x0400649e: f7 37 e0 01 6e d8 a7 bc f6 d9 MOVIqq R7, 0xd9f6bca7d86e01e0 ; 0x040064a8: 4d 41 SUB R1, R4 ; 0x040064aa: 4d 61 SUB R1, R6 ; 0x040064ac: f7 36 e8 27 c4 5f 53 f7 07 cd MOVIqq R6, 0xcd07f7535fc427e8 ; 0x040064b6: 4d 41 SUB R1, R4 ; 0x040064b8: f7 34 3e 40 b7 ac f1 d7 77 da MOVIqq R4, 0xda77d7f1acb7403e ; 0x040064c2: 4c 41 ADD R1, R4 ; 0x040064c4: f7 35 59 79 70 28 4c f6 fa 6a MOVIqq R5, 0x6afaf64c28707959 ; 0x040064ce: 4d 71 SUB R1, R7 ; 0x040064d0: 4c 41 ADD R1, R4 ; 0x040064d2: f7 37 0f b9 f2 8b ff 1d a1 c1 MOVIqq R7, 0xc1a11dff8bf2b90f ; 0x040064dc: 4b 11 NEG R1, R1 ; 0x040064de: 4d 21 SUB R1, R2 ; 0x040064e0: 4c 61 ADD R1, R6 ; 0x040064e2: f7 36 4f 02 a1 95 58 53 64 97 MOVIqq R6, 0x9764535895a1024f ; 0x040064ec: 56 31 XOR R1, R3 ; 0x040064ee: 4a 11 NOT R1, R1 ; 0x040064f0: 56 51 XOR R1, R5 ; 0x040064f2: 4c 21 ADD R1, R2 ; 0x040064f4: 56 71 XOR R1, R7 ; 0x040064f6: 4a 11 NOT R1, R1 ; 0x040064f8: f7 35 fd 32 d9 f4 c5 20 93 36 MOVIqq R5, 0x369320c5f4d932fd ; 0x04006502: 4c 51 ADD R1, R5 ; 0x04006504: 4d 41 SUB R1, R4 ; 0x04006506: f7 32 26 aa 5e cd 37 76 ed 9e MOVIqq R2, 0x9eed7637cd5eaa26 ; 0x04006510: 4b 11 NEG R1, R1 ; 0x04006512: f7 36 78 96 ec 62 5f 01 fb 7b MOVIqq R6, 0x7bfb015f62ec9678 ; 0x0400651c: 4a 11 NOT R1, R1 ; 0x0400651e: 4b 11 NEG R1, R1 ; 0x04006520: 4c 61 ADD R1, R6 ; 0x04006522: 56 31 XOR R1, R3 ; 0x04006524: f7 36 09 fd fe b2 f3 fc c1 29 MOVIqq R6, 0x29c1fcf3b2fefd09 ; 0x0400652e: 4a 11 NOT R1, R1 ; 0x04006530: f7 33 dd 0a 0a 5a 6f ef a7 1f MOVIqq R3, 0x1fa7ef6f5a0a0add ; 0x0400653a: 4c 21 ADD R1, R2 ; 0x0400653c: 4d 51 SUB R1, R5 ; 0x0400653e: f7 37 c7 a5 40 5c bb 2d 9e b6 MOVIqq R7, 0xb69e2dbb5c40a5c7 ; 0x04006548: 56 51 XOR R1, R5 ; 0x0400654a: 4a 11 NOT R1, R1 ; 0x0400654c: 4b 11 NEG R1, R1 ; 0x0400654e: 4d 71 SUB R1, R7 ; 0x04006550: 4c 31 ADD R1, R3 ; 0x04006552: 56 51 XOR R1, R5 ; 0x04006554: 4c 21 ADD R1, R2 ; 0x04006556: f7 36 1d 30 58 ef 5d ab cb 23 MOVIqq R6, 0x23cbab5def58301d ; 0x04006560: 4c 41 ADD R1, R4 ; 0x04006562: 4d 51 SUB R1, R5 ; 0x04006564: 56 41 XOR R1, R4 ; 0x04006566: 4d 51 SUB R1, R5 ; 0x04006568: 4c 51 ADD R1, R5 ; 0x0400656a: 4d 51 SUB R1, R5 ; 0x0400656c: 4d 41 SUB R1, R4 ; 0x0400656e: 4b 11 NEG R1, R1 ; 0x04006570: f7 32 c5 c9 aa a4 52 4a 59 91 MOVIqq R2, 0x91594a52a4aac9c5 ; 0x0400657a: 56 31 XOR R1, R3 ; 0x0400657c: f7 33 af d2 17 59 f5 a5 af ad MOVIqq R3, 0xadafa5f55917d2af ; 0x04006586: 4b 11 NEG R1, R1 ; 0x04006588: f7 32 7a d0 13 6f 74 88 12 8d MOVIqq R2, 0x8d1288746f13d07a ; 0x04006592: 4c 31 ADD R1, R3 ; 0x04006594: f7 34 65 b9 d1 07 98 3e 33 1a MOVIqq R4, 0x1a333e9807d1b965 ; 0x0400659e: 56 31 XOR R1, R3 ; 0x040065a0: f7 36 58 f0 e7 57 f3 74 46 3f MOVIqq R6, 0x3f4674f357e7f058 ; 0x040065aa: 4d 31 SUB R1, R3 ; 0x040065ac: f7 33 8c 7b 41 65 31 e3 0b e9 MOVIqq R3, 0xe90be33165417b8c ; 0x040065b6: 56 41 XOR R1, R4 ; 0x040065b8: f7 35 86 20 ee b7 19 0f 85 84 MOVIqq R5, 0x84850f19b7ee2086 ; 0x040065c2: 56 61 XOR R1, R6 ; 0x040065c4: 4c 31 ADD R1, R3 ; 0x040065c6: f7 35 ce d6 45 50 52 ad 38 70 MOVIqq R5, 0x7038ad525045d6ce ; 0x040065d0: 56 51 XOR R1, R5 ; 0x040065d2: 56 41 XOR R1, R4 ; 0x040065d4: 4c 51 ADD R1, R5 ; 0x040065d6: f7 34 3a 4a e3 d6 be 95 3f 70 MOVIqq R4, 0x703f95bed6e34a3a ; 0x040065e0: 4c 21 ADD R1, R2 ; 0x040065e2: 4d 41 SUB R1, R4 ; 0x040065e4: 4d 71 SUB R1, R7 ; 0x040065e6: 4c 71 ADD R1, R7 ; 0x040065e8: 4c 41 ADD R1, R4 ; 0x040065ea: 4d 51 SUB R1, R5 ; 0x040065ec: f7 37 ed fa 32 30 19 fc a7 80 MOVIqq R7, 0x80a7fc193032faed ; 0x040065f6: 45 71 CMPeq R1, R7 ; 0x040065f8: 82 03 JMP8cc 0x03 ; 0x040065fa: 77 31 01 00 MOVIqw R1, 0x0001 ; 0x040065fe: 02 02 JMP8 0x02 ; 0x04006600: 77 31 00 00 MOVIqw R1, 0x0000 ; 0x04006604: 20 17 MOVqw R7, R1 ; 0x04006606: 04 00 RET ;
; int isupper_fastcall(int c) SECTION code_clib SECTION code_ctype PUBLIC _isupper_fastcall EXTERN asm_isupper, error_zc _isupper_fastcall: inc h dec h jp nz, error_zc ld a,l call asm_isupper ld l,h ret c inc l ret
; A178821: Triangle read by rows: T(n,k) = binomial(n+4,4) * binomial(n,k), 0 <= k <= n. ; Submitted by Christian Krause ; 1,5,5,15,30,15,35,105,105,35,70,280,420,280,70,126,630,1260,1260,630,126,210,1260,3150,4200,3150,1260,210,330,2310,6930,11550,11550,6930,2310,330,495,3960,13860,27720,34650,27720,13860,3960,495,715,6435,25740,60060,90090,90090,60060,25740,6435,715,1001,10010,45045,120120,210210,252252,210210,120120,45045,10010,1001,1365,15015,75075,225225,450450,630630,630630,450450,225225,75075,15015,1365,1820,21840,120120,400400,900900,1441440,1681680,1441440,900900,400400,120120,21840,1820,2380,30940,185640 lpb $0 add $2,1 sub $0,$2 lpe mov $1,$2 bin $1,$0 add $2,4 bin $2,4 mul $1,$2 mov $0,$1
; A010999: a(n) = binomial coefficient C(n,46). ; 1,47,1128,18424,230300,2349060,20358520,154143080,1040465790,6358402050,35607051480,184509266760,891794789340,4047376351620,17345898649800,70539987842520,273342452889765,1012974972473835,3601688791018080,12321566916640800,40661170824914640 add $0,46 mov $1,$0 bin $1,46
;****************************************************************************** ;* Copyright (c) 2012 Michael Niedermayer ;* ;* This file is part of FFmpeg. ;* ;* FFmpeg is free software; you can redistribute it and/or ;* modify it under the terms of the GNU Lesser General Public ;* License as published by the Free Software Foundation; either ;* version 2.1 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 ;* Lesser General Public License for more details. ;* ;* You should have received a copy of the GNU Lesser 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 32 dw1: times 8 dd 1 w1 : times 16 dw 1 SECTION .text %macro MIX2_FLT 1 cglobal mix_2_1_%1_float, 7, 7, 6, out, in1, in2, coeffp, index1, index2, len %ifidn %1, a test in1q, mmsize-1 jne mix_2_1_float_u_int %+ SUFFIX test in2q, mmsize-1 jne mix_2_1_float_u_int %+ SUFFIX test outq, mmsize-1 jne mix_2_1_float_u_int %+ SUFFIX %else mix_2_1_float_u_int %+ SUFFIX: %endif VBROADCASTSS m4, [coeffpq + 4*index1q] VBROADCASTSS m5, [coeffpq + 4*index2q] shl lend , 2 add in1q , lenq add in2q , lenq add outq , lenq neg lenq .next: %ifidn %1, a mulps m0, m4, [in1q + lenq ] mulps m1, m5, [in2q + lenq ] mulps m2, m4, [in1q + lenq + mmsize] mulps m3, m5, [in2q + lenq + mmsize] %else movu m0, [in1q + lenq ] movu m1, [in2q + lenq ] movu m2, [in1q + lenq + mmsize] movu m3, [in2q + lenq + mmsize] mulps m0, m0, m4 mulps m1, m1, m5 mulps m2, m2, m4 mulps m3, m3, m5 %endif addps m0, m0, m1 addps m2, m2, m3 mov%1 [outq + lenq ], m0 mov%1 [outq + lenq + mmsize], m2 add lenq, mmsize*2 jl .next REP_RET %endmacro %macro MIX1_FLT 1 cglobal mix_1_1_%1_float, 5, 5, 3, out, in, coeffp, index, len %ifidn %1, a test inq, mmsize-1 jne mix_1_1_float_u_int %+ SUFFIX test outq, mmsize-1 jne mix_1_1_float_u_int %+ SUFFIX %else mix_1_1_float_u_int %+ SUFFIX: %endif VBROADCASTSS m2, [coeffpq + 4*indexq] shl lenq , 2 add inq , lenq add outq , lenq neg lenq .next: %ifidn %1, a mulps m0, m2, [inq + lenq ] mulps m1, m2, [inq + lenq + mmsize] %else movu m0, [inq + lenq ] movu m1, [inq + lenq + mmsize] mulps m0, m0, m2 mulps m1, m1, m2 %endif mov%1 [outq + lenq ], m0 mov%1 [outq + lenq + mmsize], m1 add lenq, mmsize*2 jl .next REP_RET %endmacro %macro MIX1_INT16 1 cglobal mix_1_1_%1_int16, 5, 5, 6, out, in, coeffp, index, len %ifidn %1, a test inq, mmsize-1 jne mix_1_1_int16_u_int %+ SUFFIX test outq, mmsize-1 jne mix_1_1_int16_u_int %+ SUFFIX %else mix_1_1_int16_u_int %+ SUFFIX: %endif movd m4, [coeffpq + 4*indexq] SPLATW m5, m4 psllq m4, 32 psrlq m4, 48 mova m0, [w1] psllw m0, m4 psrlw m0, 1 punpcklwd m5, m0 add lenq , lenq add inq , lenq add outq , lenq neg lenq .next: mov%1 m0, [inq + lenq ] mov%1 m2, [inq + lenq + mmsize] mova m1, m0 mova m3, m2 punpcklwd m0, [w1] punpckhwd m1, [w1] punpcklwd m2, [w1] punpckhwd m3, [w1] pmaddwd m0, m5 pmaddwd m1, m5 pmaddwd m2, m5 pmaddwd m3, m5 psrad m0, m4 psrad m1, m4 psrad m2, m4 psrad m3, m4 packssdw m0, m1 packssdw m2, m3 mov%1 [outq + lenq ], m0 mov%1 [outq + lenq + mmsize], m2 add lenq, mmsize*2 jl .next %if mmsize == 8 emms RET %else REP_RET %endif %endmacro %macro MIX2_INT16 1 cglobal mix_2_1_%1_int16, 7, 7, 8, out, in1, in2, coeffp, index1, index2, len %ifidn %1, a test in1q, mmsize-1 jne mix_2_1_int16_u_int %+ SUFFIX test in2q, mmsize-1 jne mix_2_1_int16_u_int %+ SUFFIX test outq, mmsize-1 jne mix_2_1_int16_u_int %+ SUFFIX %else mix_2_1_int16_u_int %+ SUFFIX: %endif movd m4, [coeffpq + 4*index1q] movd m6, [coeffpq + 4*index2q] SPLATW m5, m4 SPLATW m6, m6 psllq m4, 32 psrlq m4, 48 mova m7, [dw1] pslld m7, m4 psrld m7, 1 punpcklwd m5, m6 add lend , lend add in1q , lenq add in2q , lenq add outq , lenq neg lenq .next: mov%1 m0, [in1q + lenq ] mov%1 m2, [in2q + lenq ] mova m1, m0 punpcklwd m0, m2 punpckhwd m1, m2 mov%1 m2, [in1q + lenq + mmsize] mov%1 m6, [in2q + lenq + mmsize] mova m3, m2 punpcklwd m2, m6 punpckhwd m3, m6 pmaddwd m0, m5 pmaddwd m1, m5 pmaddwd m2, m5 pmaddwd m3, m5 paddd m0, m7 paddd m1, m7 paddd m2, m7 paddd m3, m7 psrad m0, m4 psrad m1, m4 psrad m2, m4 psrad m3, m4 packssdw m0, m1 packssdw m2, m3 mov%1 [outq + lenq ], m0 mov%1 [outq + lenq + mmsize], m2 add lenq, mmsize*2 jl .next %if mmsize == 8 emms RET %else REP_RET %endif %endmacro INIT_MMX mmx MIX1_INT16 u MIX1_INT16 a MIX2_INT16 u MIX2_INT16 a INIT_XMM sse MIX2_FLT u MIX2_FLT a MIX1_FLT u MIX1_FLT a INIT_XMM sse2 MIX1_INT16 u MIX1_INT16 a MIX2_INT16 u MIX2_INT16 a %if HAVE_AVX_EXTERNAL INIT_YMM avx MIX2_FLT u MIX2_FLT a MIX1_FLT u MIX1_FLT a %endif
; uint z80_get_int_state(void) SECTION code_clib SECTION code_z80 PUBLIC z80_get_int_state EXTERN asm_z80_get_int_state defc z80_get_int_state = asm_z80_get_int_state
.org 0x8004BE30 .definelabel VROM_CODE, 0x3480000 // addr of code //MUST BE 0x01 0000 aligned! .definelabel VROM_CODE_SIZE, 0x0B00 // MUST NOT BE GREATER THAN 0x7FFF! .definelabel VROM_CODE_ADDR, 0x001DAFA0 .definelabel VROM_CODE_VADDR, 0x80000000 | VROM_CODE_ADDR // a0 = Global Context addiu $sp, $sp, 0xFFD0 //safety stack push sw a0, 0x0030($sp) sw $ra, 0x002C($sp) li t0, VROM_CODE_VADDR sw t0, 0x0028($sp) li a0, VROM_CODE_VADDR li a1, VROM_CODE jal 0x0DF0 li a2, VROM_CODE_SIZE lw a0, 0x0028($sp) jal 0x3440 // osWritebackDCache li a1, VROM_CODE_SIZE lw a0, 0x0028($sp) jal 0x41A0 // osInvalICache li a1, VROM_CODE_SIZE jal VROM_CODE_ADDR lw a0, 0x0030($sp) lw a0, 0x0030($sp) lw $ra, 0x002C($sp) addiu $sp, $sp, 0x30 // hook back addiu $sp, $sp, 0xFF70 j 0x9A758 sw s2, 0x0028($sp) // for convenience, here's the hook // j 0x4BE30
;; ;; Copyright (c) 2020-2021, Intel Corporation ;; ;; Redistribution and use in source and binary forms, with or without ;; modification, are permitted provided that the following conditions are met: ;; ;; * Redistributions of source code must retain the above copyright notice, ;; this list of conditions and the following disclaimer. ;; * Redistributions in binary form must reproduce the above copyright ;; notice, this list of conditions and the following disclaimer in the ;; documentation and/or other materials provided with the distribution. ;; * Neither the name of Intel Corporation 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 OWNER OR CONTRIBUTORS BE LIABLE ;; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL ;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ;; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER ;; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, ;; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ;; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;; %include "include/aesni_emu.inc" %define NROUNDS 13 %define AES_CBC_MAC aes256_cbc_mac_x4_no_aesni %define SUBMIT_JOB_AES_CCM_AUTH submit_job_aes256_ccm_auth_sse_no_aesni %define FLUSH_JOB_AES_CCM_AUTH flush_job_aes256_ccm_auth_sse_no_aesni %include "sse/mb_mgr_aes128_ccm_by8_auth_submit_flush_sse.asm"
; A139596: A033587(n) followed by even hexagonal number A014635(n+1). ; 0,6,14,28,44,66,90,120,152,190,230,276,324,378,434,496,560,630,702,780,860,946,1034,1128,1224,1326,1430,1540,1652,1770,1890,2016,2144,2278,2414,2556,2700,2850,3002,3160,3320,3486,3654,3828 mul $0,2 add $0,2 bin $0,2 div $0,2 mov $1,$0 mul $1,2