查找转义字符
问题描述:
问题1:我有以下汇编代码,其目的是循环通过一个输入字符串,和计数的换码字符“%”它遇到的数目:查找转义字符
.globl sprinter
.data
.escape_string: .string "%"
.num_escape: .long 0
.num_characters: .long 0
.text
sprinter:
pushl %ebp
movl %esp,%ebp
movl 8(%ebp),%ecx # %ecx = parameter 1
loop:
cmpb $0, (%ecx) # if end of string reached
jz exit
cmpl $.escape_string,(%ecx) # if escape character found
je increment
back:
incl .num_characters
incl %ecx
jmp loop
increment:
incl .num_escape
jmp back # jump to 'back'
exit:
movl .num_escape, %eax # return num_escape
popl %ebp
ret
该组件代码与下面的C代码一起编译:
#include <stdio.h>
extern int sprinter (char* string);
int main (void)
{
int n = sprinter("a %d string of some %s fashion!");
printf("value: %d",n);
return 0;
}
从运行该代码的期望的输出是value: 2
(因为有字符串中2“%”字符),但它返回value: 0
,意味着以下行失败(因为它从来没有增加计数器):
cmpl $.escape_string,(%ecx) # if escape character found
我使用的字符串比较的方法不对?外层循环工作正常,并且.num_characters正确地包含了我的字符串中的字符数。我产生了一个简单的C程序相比,字符串“hello”到“hello2”一些汇编代码,这是相关代码:
.LC0:
.string "hello"
.LC1:
.string "hello2"
...
movl $.LC0, -4(%ebp)
cmpl $.LC1, -4(%ebp)
它看起来非常相似,我试过了,不是吗?
问题2。这段代码是用汇编语言编写的一个简化的sprintf函数的一部分。这意味着第一个参数应该是结果字符串,第二个参数是格式。如何将一个字节从当前位置复制到另一个寄存器中的当前位置?假设我们指定了我们的参数分为两个寄存器:
movl 8(%ebp),%edx # %edx = result-string
movl 12(%ebp),%ecx # %ecx = format-string
我试图在循环中的以下内容:
movb (%ecx), %al
movb %al, (%edx) # copy current character to current position in result register
incl %ecx
incl %edx
但结果字符串只包含(在我的字符串的第一个字符)a
,而不是我所期望的那样。
所有帮助赞赏,因为这个比较问题(问题1)目前让我卡住。
答
关于问题1,看起来您正在比较单字节字符,所以'cmpl'在检查转义字符时应该是'cmpb'。你还需要将你的角色加载到一个寄存器中。我不是很熟悉AT & T组件,所以我希望这是正确的。
环之前:
movb .escape_string, %al
比较:
cmpb %al, %(ecx)
这将返回:'/tmp/ccZauarM.o:在函数 '循环': (的.text + 0xd中):搬迁截断为fit:R_386_8对'.data' collect2:error:ld返回1退出状态,这导致我相信该字符串实际上被存储为一个long,并且它截断了字符串以适合字节比较,这是错误的错误解释? – ponycat 2013-05-08 19:24:30
我相信.escape_string指的是文字字符串的地址。你将需要将你的角色加载到一个字节寄存器中。 – TractorPulledPork 2013-05-08 19:37:13
将它移入一个字节寄存器,然后比较运作良好!谢谢! – ponycat 2013-05-08 19:52:13