x86 assembly - printing a character given an ascii code

心已入冬 提交于 2020-05-15 09:18:40

问题


I am new to assembly programming and am having trouble printing a character to the screen. Every time I execute my program I get a segmentation fault and I am not sure why.

.section .data
  A:
    .long  65  # ascii code for 'A'

.section .text
.globl _start

_start:
 movl $1, %edx # length of character to print, 1
 movl  A, %ecx # what I want printed
 movl $1, %ebx # file descriptor for STDOUT
 movl $4, %eax # syscall number for sys_write

 int $0x80     # calls kernel

 movl $0, %ebx # return status
 movl $1, %eax # syscall number for sys_exit

 int $0x80     # calls kernel

These are the commands I use to build (my file is named write.s)

as write.s -o write.o
ld write.o -o write

Is this not the correct way to print a character? Any help would be appreciated.


回答1:


movl A, %ecx

means: Copy the value at the address of the label A into %ecx. The correct instruction would be:

movl $A, %ecx

or

leal A, %ecx

You can use GDB for debugging in these cases (note that you have to assemble with the -g flag to get debug information):

$ as -g write.s -o write.o
$ ld write.o -o write
$ gdb write
GNU gdb (GDB) 7.5
   [.. snip ..]
(gdb) b test.s:13
Breakpoint 1 at 0x4000c6: file test.s, line 13.
(gdb) run
Starting program: /home/niklas/tmp/asm/write 

Breakpoint 1, _start () at test.s:13
13   int $0x80     # calls kernel
(gdb) info registers ecx
ecx            0x41 65

As you see, %ecx has the integer value 65, which is not what you want.


If you run strace ./write, it will decode the system call args and return value for you. You'll see that write() just returns -EFAULT without doing anything else when you pass it a bad pointer.



来源:https://stackoverflow.com/questions/12219113/x86-assembly-printing-a-character-given-an-ascii-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!