在循环中总结字符

时间:2014-04-04 04:30:54

标签: assembly gas

我试图从循环中求出字符串的ascii值。我想我错过了一些东西,但是我在程序结束时返回错误值(即不匹配我使用ascii表手动求和的值)或者seg错误。

我的节目:

.data                           # .data section begins
name: .ascii "Json"             # name is ASCII chars (.ascii or .byte)
len:  .int 4                    # name length is 4 chars, an integer
newline: .ascii "\n"            # new line character

count: .int 0                   # counter for loop (start at 0)

return: .int 0                  # return code value
tmp: .int 0                     # temp value

.text                           # text section starts
.global _start                  # main program entry

_start:                         # start instruction

again:                          # begin loop

    mov $1, %edx                # 1 byte at a time
    mov $name, %ecx             # mem addr
    add count, %ecx             # offset in string

    #### Trouble area ####

    # this seg faults
    mov count(%ecx), %ebx
    add %ebx, return

    #### Trouble area ####

    mov $1, %ebx                # file descriptor 1 is computer display
    mov $4, %eax                # system call 4 is sys_write (output)
    int $128                    # interrupt 128 is entry to OS services

    add $1, count               # incr count
    mov count, %eax             # copy count to eax
    cmp %eax, len               #   and compare values

    jne again                   # if not equal, goto again

    mov $newline, %ecx          # mem addr

    mov $1, %ebx                # file desc 1
    mov $4, %eax                # sys call 4
    int $128                    # interrupt 128

    mov $1, %eax                # system call 1 is sys_exit
    mov return, %ebx            # status return
    int $128                    # interrupt 128

我认为我遗漏了一些基本的东西,但我理解这是将ecx寄存器偏移的值移动count的值(即循环迭代,因此数组元素) ),进入注册ebx。然后将ebx中的值添加到return。然后在程序结束时,将return中的求和值移动到寄存器ebx,然后调用中断。在运行期间,这段错误,但我不确定为什么。

我希望它不会出现故障(显然是lol),并且在致电~]# echo $?时打印410(即' J' +' s& #39; +' o' +' n'或... 74 + 115 + 111 + 110)。

UPDATE:------------>

我更新了#34;麻烦地点"以下来自@Michael的建议(如果我理解正确的话)。

    #### Trouble area ####

    # this returns a garbage number, 154 instead of 410
    mov count, %edi 
    mov name(%edi), %ebx
    add %ebx, return

    #### Trouble area ####

1 个答案:

答案 0 :(得分:1)

退出代码

POSIX退出状态代码实际上是无符号字节。

#include <stdio.h>

int main() {
    printf("%d\n", (unsigned char)410);
    return 410;
}

这将打印并返回154 410 % 256

在此处阅读POSIX部分:http://en.wikipedia.org/wiki/Exit_status#POSIX

获取价值的其他方式

  1. 您可以在gdb中运行您的流程,并使用i r打印注册内容,或print return

  2. 您可以将int转换为字符串[1]并使用指向结果字符串(write)的指针调用stdout上的write(1, "string\n", len) syscall [2]。

  3. [1] 整数到字符串:mod 10得到最右边的数字,除以10去除最右边的数字,重复直到n = 0,然后反转字符串拨打sprintf()itoa()等电话

    [2] http://asm.sourceforge.net/articles/linasm.html#Syscalls