X86-64 NASM calling extern c functions

前端 未结 2 1789
伪装坚强ぢ
伪装坚强ぢ 2021-01-29 06:19

Im very new to assembly but know a bit of c. Im playing around with extern function calls like

extern _printf
str db \"Hello\", 0
push str
call _printf
         


        
2条回答
  •  鱼传尺愫
    2021-01-29 06:56

    Edit: I made a few mistakes here, see comments for details!

    Here is a 32bit version (64bit below):

    SECTION .data
        ; global functions in this file
        global main
    
        ; extern functions
        extern strcmp
    
    hworld: ; our first string
        db "hello world", 0
    
    hworld2: ; our second string
        db "hello world2", 0
    
    SECTION .text
    
    ;=============================================================================
    ; The program entrypoint
    ;
    main:
    
        ; int rv = strcmp("hello world", "hello world2");
        push    hworld2
        push    hworld
        call    strcmp
    
        ; _exit(rv);
        mov     ebx, eax
        mov     eax, 1
        int     0x80
    

    Then you can compile it with:

    nasm -f elf main.s -o main.o
    cc -m32 main.o -o hello_world
    

    And here is the 64bit version:

    SECTION .data
        ; global functions in this file
        global main
    
        ; extern functions
        extern strcmp
    
    hworld: ; our first string
        db "hello world", 0
    
    hworld2: ; our second string
        db "hello world2", 0
    
    SECTION .text
    
    ;=============================================================================
    ; The program entrypoint
    ;
    main:
    
        ; int rv = strcmp("hello world", "hello world2");
        mov     rsi, hworld2
        mov     rdi, hworld
        call    strcmp
    
        ; _exit(rv);
        mov     rdi, rax
        mov     rax, 60
        syscall
    

    Then you can compile the x64 version with:

    nasm -f elf64 main.s -o main.o
    cc main.o -o hello_world
    

    And run it:

    $ ./hello_world 
    $ echo $?
    206
    

提交回复
热议问题