![]() |
[ASM] Calling C functions on 64bit architecture - Printable Version +- Sinisterly (https://sinister.ly) +-- Forum: Coding (https://sinister.ly/Forum-Coding) +--- Forum: Assembly (https://sinister.ly/Forum-Assembly) +--- Thread: [ASM] Calling C functions on 64bit architecture (/Thread-ASM-Calling-C-functions-on-64bit-architecture) |
[ASM] Calling C functions on 64bit architecture - Deque - 11-06-2012 Hello HC, Calling C functions on 32 bit systems is pretty easy. You just push your parameters on the stack. Here is a simple hello world example that uses the printf function of C. It is NASM code for Linux. The keyword extern tells the compiler that printf is defined somewhere else. Using gcc will provide the C libraries. Code: ;type this to create an executable file: Since I use a book that only covers 32 bit assembly, I got into trouble trying it on my 64 bit system. The code above threw a segmentation fault. I found the answer in this document: www.x86-64.org/documentation/abi.pdf Obviously calling C functions became more complicated. First you need to know the classification of your parameter (MEMORY, INTEGER, SSE, ...). For INTEGER arguments general purpose registers are used to pass the parameters. The order is the following: %rdi, %rsi, %rdx, %rcx, %r8 and %r9 That means %rdi is used for the first parameter, %rsi for the second and so on. The printf parameters in our example are INTEGER, because you pass memory addresses instead of the string itself. The printf function however has another speciality. The number of arguments is arbitrary. The ellipsis in the declaration shows this: Code: int printf ( const char * format, ... ); Because of that you also have to put the number of arguments you passed in vector registers into %al. Vector registers are %xmm0 - %xmm15 and %ymm0-%ymm15 The following example shows the implementation of a hello world using printf with two parameters. Since no vector registers are used, 0 is put into %al. Code: ;type this to create an executable file: This code works well. The call to the printf function is equal to this (yes, I could have done this with one argument, but I want to show how to use several of them): Code: printf("%s\n", "Hello World"); This example should be enough for a quick start into using C functions in 64 bit assembly. Have a look at the documentation I linked above to get all the information you need. Deque RE: [ASM] Calling C functions on 64bit architecture - kabalevsky - 11-07-2012 this is great. thanks! I'd run into this problem before so this really helps. RE: [ASM] Calling C functions on 64bit architecture - Deque - 11-07-2012 You are welcome. Thanks for your feedback. |