|
发表于 2023-9-30 22:37:40
|
显示全部楼层
汇编写的MR(n, b)
- ;bool mrtest(uint64_t p, uint64_t b);win64下,前4个参数如果是整数或者指针保存到rcx, rdx, r8, r9;如果是浮点数,保存到xmm0, xmm1, xmm2, xmm3;如果是混合参数,则按照对应位置选择寄存器;多于4个的参数从右到左压栈,同时栈顶为前4个参数保留32字节影子空间;函数内可以自由使用rax, rcx, rdx, r8, r9, r10, r11, xmm0-xmm5;其他寄存器需要使用时候,则要保证在退出函数时恢复值;返回值保存在rax内,如果是浮点数保存在xmm0;linux, FreeBSD, MacOS等64位系统则遵循另外一个规则;前6个参数保存到rdi, rsi, rdx, rcx, r8, r9,;浮点数则保存到xmm0-xmm5;多于6个从右到左依次压栈,没有影子空间,;函数内可以自由使用rax, rcx, rdx, rsi, rdi, r8, r9, r10, r11;返回值保存到rax或者xmm0USE64section .bsssection .datasection .textGLOBAL mrtestmrtest:%ifidn __OUTPUT_FORMAT__, win64 mov r8, rcx mov r9, rdx%else mov r8, rdi mov r9, rsi%endif;r8 = p, r9 = b mov r10, r8 mov rax, 1 movq xmm0, rax movq xmm3, r8;xmm3 = p-1 psubq xmm3, xmm0 pxor xmm2, xmm2;xmm2 = 1 paddq xmm2, xmm0 sub r10, 1;r10 = p - 1 bsf rcx, r10;rcx = k shr r10, cl;r10 = m, p - 1 = m * 2^k mov r11, 1 cmp r10, 1 je jmp1loop0: cmp r10, 0 je jmp0 test r10, 1 jz loop1;r11 = r11 * r9 % r8 mov rax, r11 mul r9 div r8 mov r11, rdxloop1:;r9 = r9 * r9 % r8 mov rax, r9 mul r9 div r8 mov r9, rdx shr r10, 1 jmp loop0jmp0:; xmm0 = (r11 == 1 || r11 == p-1)? -11 : 0 movq xmm0, r11 movq xmm1, r11 pcmpeqq xmm0, xmm2;xmm0=r11 == 1?(-1):0 pcmpeqq xmm1, xmm3;xmm1=r11 == (p-1)?(-1):0 por xmm0, xmm1;if (rax = -xmm0 == 1) then exit movq rax, xmm0 neg rax cmp rax, 1 je exit0 mov r9, r11jmp1: sub rcx, 1 jz exit0loop3: mov rax, r9 mul r9 div r8 mov r9, rdx;xmm1 = r9 == p-1? (-1):0 movq xmm1, r9 pcmpeqq xmm1, xmm3 movq rax, xmm1 neg rax cmp rax, 1 je exit0 sub rcx, 1 jnz loop3exit0: ret
复制代码
测试代码- extern bool mrtest(uint64_t p, uint64_t b);uint64_t ts[8][2] = {{257,2}, {255,2}, {2047, 2}, {121, 3}, {10095020520187, 2}, {581130733, 3}, {55031295157, 234587}, {55031295179, 234587}};void testmrtest( void ){ for (uint64_t i = 0; i < 8; i ++) if (mrtest(ts[i][0], ts[i][1])) printf("mrtest(%lu, %lu) is true\n", ts[i][0], ts[i][1]); else printf("mrtest(%lu, %lu) is false\n", ts[i][0], ts[i][1]);}int main( void ){ testmrtest();}
复制代码
假设汇编名为 mr.asm, C代码 mrtest.c
linux下
nasm -f elf64 mr.asm -o mr.o
gcc mrtest.c mr.o -o mrtest
windows下
nasm -f win64 mr.asm
gcc mrtest.c mr.obj -o mrtest
即可生成测试程序
汇编代码也可以用yasm编译通过 |
|