Calling C function in assembly code (gas)

寵の児 提交于 2019-12-02 10:08:06

问题


I found an example and was editing it for gas.

extern printf
.global _start
.data
hello:
db "Hello", 0xa, 0
.text
_start:
mov %rdi, hello
mov %rax, 0
call printf
mov %rax, 0
ret

But it doesn't work. What's wrong? What does this mean:

    hello:
db "Hello", 0xa, 0

I understand what it scope of memory, but I don't understand this string

db "Hello", 0xa, 0

And here

_start:
mov %rdi, hello
mov %rax, 0
call printf
mov %rax, 0
ret

os: linux (debian). intel 64-bit


回答1:


It's is the null-byte-terminattor. Well-know as C-string.Such byte at end-of-string say where the string ends. For example,you pass the pointer to your string to call a routine,the routine will understand that the area of such string on memory is from begging a[0](in C terminology) until a[x] == 0 is seen.




回答2:


Here is the corrected annotated listing:

        .extern printf
        .global main

        .section .data
hello:  .asciz "Hello\n"

This defines a null-terminated string, equivalent to "Hello\n" in C.

        .section .text
main:
        movq $hello, %rdi
        movq $0, %rax
        call printf

This is equivalent to printf (hello). To call a vararg function you need to put the number of floating point registers used in rax, in this case zero.

        movq $0, %rax
        ret

This is equivalent to return 0.

Assemble and link with 'cc -o x x.s'.




回答3:


All that does is place bytes into the program. The bytes are the characters "Hello", followed by 0xa (which is the line termination), and finally a NULL byte. In C it would be something like "char *hello = "Hello\n";"

At your _start: label, you place the address of the hello label into register %rdi, you place 0 into %rax, and you call the printf function.




回答4:


The following declares a string with Hello followed by a line feed and null terminator. The null terminator is required for C strings

db "Hello", 0xa, 0

To call printf, you need to pass the parameter on the stack so it would be something like

mov hello, (%esp)
call printf

As far as I know, the convention is mov source, destination. You seem to have coded it the other way round.



来源:https://stackoverflow.com/questions/15589226/calling-c-function-in-assembly-code-gas

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