how to call C functions from assembly routines and link the C and assembly files using nasm and gcc - c

I want to call at least 1 C function from assembly. It is because I'm doing my own tiny OS from scratch(out of nothing). The reason i want to call c function from my boot loader. I can understand assembly but poor in writing my own program. So if i could transfer control from assembly procedure to c procedure my job is made easier.
So how to link assembly pgm and C program files into one. It is ok for me even if the file size exceeds 512 bytes.
I am doing this on Windows 7 with help of mingw. my c compiler is gcc and assembler is nasm.

easier to just show you an example, I found this on the internet a while ago and saved it as a source on my computer, not sure where from though
; printf1.asm print an integer from storage and from a register
; Assemble: nasm -f elf -l printf.lst printf1.asm
; Link: gcc -o printf1 printf1.o
; Run: printf1
; Output: a=5, eax=7
; Equivalent C code
; /* printf1.c print an int and an expression */
; #include
; int main()
; {
; int a=5;
; printf("a=%d, eax=%d\n", a, a+2);
; return 0;
; }
; Declare some external functions
;
extern printf ; the C function, to be called
SECTION .data ; Data section, initialized variables
a: dd 5 ; int a=5;
fmt: db "a=%d, eax=%d", 10, 0 ; The printf format, "\n",'0'
SECTION .text ; Code section.
global main ; the standard gcc entry point
main: ; the program label for the entry point
push ebp ; set up stack frame
mov ebp,esp
mov eax, [a] ; put a from store into register
add eax, 2 ; a+2
push eax ; value of a+2
push dword [a] ; value of variable a
push dword fmt ; address of ctrl string
call printf ; Call C function
add esp, 12 ; pop stack 3 push times 4 bytes
mov esp, ebp ; takedown stack frame
pop ebp ; same as "leave" op
mov eax,0 ; normal, no error, return value
ret ; return

Related

Assembly NASM x86 - Putting char into array

I need to make a program that open a file, read it character by character and save it into an array in Assembly NASM x86. Currently, the program is able to open a file using stdin and read the character by using getchar(). However, i am stuck on the saving the char into an array and need help on this part.
Thank you
; Run it this way:
; test < (input file)
; Build using these commands:
; nasm -f elf -g -F stabs test.asm
; gcc –m32 -o test.o test
;
SECTION .bss ; Section containing uninitialized data
TextLenght EQU 1024 ; Define length of a line of text data
Text resb TextLenght ; Define array
SECTION .data ; Section containing initialised data
fileFmt: db "%c",0
SECTION .text ; Section containing code
extern putchar
extern getchar
extern printf
global main; Linker needs this to find the entry point!
main :
start:
nop ; This no-op keeps gdb happy...
mov eax, 0
mov edx, 0
mov ecx, 0
mov ebx, 0
; Read a buffer full of text from stdin:
read:
call getchar ; call getchar to get input from stdin, char is save in eax
cmp al, -1
jle Done ; if return -1, we at EOF
cmp eax, 97 ; get rid of 'enter' char
jl read
;mov Text, eax; try to save char in eax into array, don;t work
push eax ;push eax to print
push fileFmt
call printf
add esp, 8 ; clear the stack
jmp read
Done:
mov eax,1 ; Code for Exit Syscall
mov ebx,0 ; Return a code of zero
int 80H ; Make sys_exit kernel call

Nasm, not printing the correct value

I've made a nasm procedure that calculates the eucledian distance between two vectors of a certain size.
This nasm function is called from a C file which get the result of the function. I've tested, and it works, the value returned is correct, I can print it withoud any problem.
My issue is when I try to print the result inside the nasm file.
This is the nasm code:
extern printf
%macro print_dist2 1
section .data
.str db %1,0 ; %1 is macro call first actual parameter
section .text
push dword [dist]
push dword .str
push dword fmt2
call printf
add esp, 12 ; pop stack 3 * 4 bytes
%endmacro
section .data
dist: dd 258
fmt2: db "%s, dist: %g",10,0 ; format string for printf
section .bss
section .text
global distanza
x equ 8
y equ 12
dim equ 16
ris equ 20
distanza:
; ------------------------------------------------------------
; Function entrance sequence
; ------------------------------------------------------------
push ebp
mov ebp, esp
push ebx
push esi
push edi
; ------------------------------------------------------------
; read the parameters from the current stack frame
; ------------------------------------------------------------
mov eax, [ebp+x] ; address of x
mov ebx, [ebp+y] ; address of y
mov ecx, [ebp+dim] ; size of the vectors (it's the same)
.
.
. omitted calculations.
.
sqrtss xmm1, xmm1
movss [dist], xmm1 ; move the result to dist
fld dword [dist] ; mov in st0, that will be used by the C file
print_dist2 "distanza"
; ------------------------------------------------------------
; Function exit sequence
; ------------------------------------------------------------
pop edi
pop esi
pop ebx
mov esp, ebp
pop ebp
ret
This is the C file:
float a[] = {6.1f, 9.5f, 12.6f};
float b[] = {25.1f, 34.1f, 9.6f};
dim = 3;
float dist = distanza(a, b, dim);
printf("d(x,y) = %f\n", dist);
This is the output:
distanza, dist: 5.46877e-315
d(x,y) = 31.227551
The C, code print the correct value, the nasm doesn't.
If I change the format string of the nasm code:
fmt2: db "%s, dist: %f",10,0
I've used %f instead of %g, the nasm output is this one:
distanza, dist: 0.000000
I have no idea what is wrong with my code, why it is not printing the correct value?
Your dist is a single 32-bit float, but printf needs a double 64-bit float. You have to transform it:
%macro print_dist2 1
section .data
.str db %1,0 ; %1 is macro call first actual parameter
section .text
sub esp, 8 ; Space for a 64-bit double floating point number
fld dword [dist] ; Load a 32-bit single floating point number
fstp qword [esp] ; Store it as 64-bit floating point number
push dword .str
push dword fmt2
call printf
add esp, 16 ; pop stack 4 * 4 bytes
%endmacro

NASM Assembly while loop counter

I'm writing a while loop in assembly to compile in the Linux terminal with nasm and gcc. The program compares x and y until y >= x and reports number of loops at the end. Here's the code:
segment .data
out1 db "It took ", 10, 0
out2 db "iterations to complete loop. That seems like a lot.", 10, 0
x db 10
y db 2
count db 0
segment .bss
segment .text
global main
extern printf
main:
mov eax, x
mov ebx, y
mov ecx, count
jmp lp ;jump to loop lp
lp:
cmp ebx, eax ;compare x and y
jge end ;jump to end if y >= x
inc eax ;add 1 to x
inc ebx ;add 2 to y
inc ebx
inc ecx ;add 1 to count
jp lp ;repeat loop
end:
push out1 ;print message part 1
call printf
push count ;print count
call printf
push out2 ;print message part 2
call printf
;mov edx, out1 ;
;call print_string ;
;
;mov edx, ecx ;these were other attempts to print
;call print_int ;using an included file
;
;mov edx, out2 ;
;call print_string ;
This is compiled and run in the terminal with:
nasm -f elf test.asm
gcc -o test test.o
./test
Terminal output comes out as:
It took
iterations to complete loop. That seems like a lot.
Segmentation fault (core dumped)
I can't see anything wrong with the logic. I think it's syntactical but we've only just started learning assembly and I've tried all sorts of different syntax like brackets around variables and using ret at the end of a segment, but nothing seems to work. I've also searched for segmentation faults but I haven't found anything really helpful. Any help would be appreciated because I'm an absolute beginner.
The reason it crashes is probably that your main function doesn't have a ret instruction. Also be sure to set eax to 0 to signal success:
xor eax, eax ; or `mov eax, 0` if you're more comfortable with that
ret
Additionally, global variables designate pointers, not values. mov eax, x sets eax to the address of x. You need to write back to it if you want anything to happen (or not use global variables).
Finally, you're calling printf with a single non-string argument:
push count ;print count
call printf
The first argument needs to be a format string, like "%i". Here, count is a pointer to a null byte, so you get nothing instead. Off my head, you should try this:
out3 db "%i ", 0
; snip
push ecx
push out3
call printf
I think your problem might just be that you are referencing the addresses of your constants and not their intrinsic value. One must think of a label in nasm as a pointer rather than a value. To access it you just need to use [label]:
segment .data
x dw 42
segment .text
global main
extern printf
main:
mov eax, x
push eax
call printf ; will print address of x (like doing cout<<&x in C++)
mov eax, [x]
push eax
call printf ; will print 42
sub esp, 8
xor eax, eax
ret
PS:I don't think anyone has mentioned it but volatile registers are modified very often when calling external code (C or C++ or other) since at compilation those functions you use are "translated" to assembly and then linked with your asm file. The PC is not a human so it is not distinguishing between what was written in high-level or low-level, the processor is just reading opcodes and operands stored in registers and memory, hence why an external function when using low-level language (call printf) is going to modify (or not! always depends on compiler and architecture) registers that you are also using.
To solve this there are various solutions:
You check what registers are not being modified by using gcc your_c_file.c -S and then in the file your_c_file.swill be the pre-prepared assembly code your compiler has produced from your C file. (It tends to be quite hard to figure out what is what and if you are going to use this method check out Name Mangling, to see how func names will be changed.)
Push all the registers you want to save to stack, and then after the call pop them back to their registers keeping in mind LIFO method.
Use the instructions PUSHA and POPAwhich push or pop all registers respectively.
This is the NASM manual chapter 3 which explains the basis of the language to use: http://www.csie.ntu.edu.tw/~comp03/nasm/nasmdoc3.html
Hope you managed to solve it.

Can't pass parameter from C to Assembly code

From what I understand, when a parameter is passed in a function call in C, the callee can find the first parameter at [ebp+8].
Returning a value through eax works for me, reading the right parameter value from the stack doesn't.
Right now I'm just trying to write an assembly function, that can be called from C and returns the same value, that it is being passed.
When I run the following program, it prints number: 1 to the console, no matter what value is passed into myFunc. What am I doing wrong?
assembly.s
section .text
global _myFunc
_myFunc:
mov eax, [ebp+8]
ret
main.c
#include <stdio.h>
extern unsigned int myFunc(unsigned int somedata);
int main() {
unsigned int i = myFunc(6);
printf("number: %i\n",i);
return 0;
}
I'm using a Mac, nasm to assemble the code and gcc for C compilation.
Makefile
macho32:
nasm -f macho32 assembly.s
gcc -m32 -o macho32 assembly.o main.c
You need to setup to access the the parameters first by saving esp. This is explained in:
http://www.nasm.us/doc/nasmdoc9.html
in section "9.1.2 Function Definitions and Function Calls"
The following works for me
assembly.s
section .text
global myFunc:function
myFunc:
push ebp
mov ebp, esp
mov eax, [ebp+8]
mov esp, ebp
pop ebp
ret
main.c
#include <stdio.h>
extern unsigned int myFunc(unsigned int somedata);
int main() {
unsigned int i = myFunc(6);
printf("number: %i\n",i);
return 0;
}
Assembly & Compilation
ericu#eric-phenom-linux:~$ nasm -f elf32 assembly.s
ericu#eric-phenom-linux:~$ gcc -m32 assembly.o main.c
ericu#eric-phenom-linux:~$ ./a.out
number: 6
I am on a linux machine so I use elf32. The use of macho32 is correct on your Mac.
you refer to argument on stack, by reading from [EBP+offset] - has EBP been set up to actually point at stack? If no, you may have to do that first, conventionally done by:
push ebp
mov ebp,esp
Only then points EBP to its stacked previous contents, below stacked return address, and below passed arguments.
Your function should look like this,
_myFunc:
push ebp ; setup ebp as frame pointer
mov ebp, esp
mov eax, [ebp + 8]
leave ; mov esp,ebp / pop ebp
ret
The convention is to use ebp to access the parameters, to do so you need to save ebp on the stack and make it to point to the new top of the stack. At function exit you should restore ebp and esp, as the leave instruction does.
In nasm there is a macro package, c32.mak, that can help in supporting the C calling convention, these macros are arg, proc and endproc.
Using these macros your code should look like,
proc _myfunc
%$i arg
mov eax, [ebp + %$i]
endproc

Segfault while calling C function (printf) from Assembly

I am using NASM on linux to write a basic assembly program that calls a function from the C libraries (printf). Unfortunately, I am incurring a segmentation fault while doing so. Commenting out the call to printf allows the program to run without error.
; Build using these commands:
; nasm -f elf64 -g -F stabs <filename>.asm
; gcc <filename>.o -o <filename>
;
SECTION .bss ; Section containing uninitialized data
SECTION .data ; Section containing initialized data
text db "hello world",10 ;
SECTION .text ; Section containing code
global main
extern printf
;-------------
;MAIN PROGRAM BEGINS HERE
;-------------
main:
push rbp
mov rbp,rsp
push rbx
push rsi
push rdi ;preserve registers
****************
;code i wish to execute
push text ;pushing address of text on to the stack
;x86-64 uses registers for first 6 args, thus should have been:
;mov rdi,text (place address of text in rdi)
;mov rax,0 (place a terminating byte at end of rdi)
call printf ;calling printf from c-libraries
add rsp,8 ;reseting the stack to pre "push text"
**************
pop rdi ;preserve registers
pop rsi
pop rbx
mov rsp,rbp
pop rbp
ret
x86_64 does not use the stack for the first 6 args. You need to load them in the proper registers. Those are:
rdi, rsi, rdx, rcx, r8, r9
The trick I use to remember the first two is to imagine the function is memcpy implemented as rep movsb,
You're calling a varargs function -- printf expects a variable number of arguments and you have to account for that in the argument stack. See here: http://www.csee.umbc.edu/portal/help/nasm/sample.shtml#printf1

Resources