第25部分- Linux x86 64位汇编 字符串扫描
扫描字符串可以使用SCAS指令。提供了扫描字符串搜索特定的一个字符或者一组字符。
SCAS指令系统包含:SCASB,SCASW,SCASL,SCASQ
使用EDI寄存器作为隐含的目标操作数。EDI寄存器必须包含要扫描的字符串的内存地址。递增和递减取决于DF标志。
比较时,会相应的设置EFLAGS的辅助进位,进位,奇偶校验,溢出、符号和零标志。把EDI寄存器当前指向的字符和AL寄存器的字符进行比较,和CMPS指令类似。和REPE和REPNE前缀一起,才显得方便。REPE和REPNE常常用于找到搜索字符时停止扫描。
扫描字符串示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | .extern printf ;//调用外部的printf函数 .section .data string1: .ascii "This is a test - a long text string to scan." length: .int 44 string2: .ascii "-" noresult: .ascii "No result." .byte 0x0a,0x0 yesresult: .ascii "Yes have result." .byte 0x0a,0x0 .section .text .globl _start _start: nop leal string1, %edi leal string2, %esi movl length, %ecx lodsb;//加载第一个-到al寄存器 cld repne scasb;//扫描字符串string1,知道找到-字符。 jne notfound movq $yesresult,%rdi call printf movq $60,%rax syscall notfound: movq $noresult,%rdi call printf movq $60,%rax syscall |
as -g -o scastest.o scastest.s
ld -o scastest scastest.o -lc -I /lib64/ld-linux-x86-64.so.2
搜索字符示例
Scasw和scasl可以用于搜索2个或4个字符,查找AX或者EAX寄存器中的字符序列。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | .extern printf ;//调用外部的printf函数 .section .data string1: .ascii "This is a test - a long text string to scan." length: .int 11 string2: .ascii "test" noresult: .ascii "No result." .byte 0x0a,0x0 yesresult: .ascii "Yes have result." .byte 0x0a,0x0 .section .text .globl _start _start: nop leal string1, %edi leal string2, %esi movl length, %ecx lodsl;//加载test到eax寄存器 cld repne scasl;//进行比较知道找到位置 jne notfound subw length, %cx neg %cx movq $yesresult,%rdi call printf movq $60,%rax syscall notfound: movq $noresult,%rdi call printf movq $60,%rax syscall |
as -g -o scastest.o scastest2.s
ld -o scastest scastest.o -lc -I /lib64/ld-linux-x86-64.so.2
这里没找到test,是因为11次对比的方式是这样的,一次4个字节,打乱了原先的test。
将test改成其他图中的4个字符就可以找到了。
计算字符串长度示例
SCAS指令有一个功能是确定零结尾(也称为空结尾)的字符串长度。
搜索零的位置,找到后就可以会到总共搜索了多少个字符,也就是字符的长度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | .extern printf ;//调用外部的printf函数 .section .data string1: .asciz "Testing, one, two, three, testing.\n" noresult: .ascii "No Result." .byte 0x0a,0x0 yesresult: .ascii "Yes have result : %d." .byte 0x0a,0x0 .section .text .globl _start _start: nop leal string1, %edi movl $0xffff, %ecx;//假设字符串长65535 movb $0, %al cld repne scasb jne notfound subw $0xffff, %cx;//减去初始值,变成了负值 neg %cx;//取反就是正数了 dec %cx;//去掉最后一个空符号,就是字符串长度了。 movq $yesresult,%rdi movq %rcx,%rsi call printf movq $60,%rax syscall notfound: movq $noresult,%rdi call printf movq $60,%rax syscall |
as -g -o strsize.o strsize.s
ld -o strsize strsize.o -lc -I /lib64/ld-linux-x86-64.so.2