I would like to know how to call fgets from assembly code.
I read these questions which are exactly the same as the this one: How to call fgets in x86 assembly?
and this one: How to use c library function fgets in assembly language?
But both of them aren't satisfying for two reasons:
1. I really want to use fgets since i want my code to run on both windows and linux ( I'm using NASM )
2.I looked at the disassembled version of fgets, unfortunately it doesn't provide the necessary details to reproduce it naming how is stdin represented in assembly.
Here are my C and assembly codes i got by using gcc -S fgets.c .
fgets.c
#include <stdio.h>
int main()
{
char name[15];
fgets(name, 16, stdin);
return 0;
}
fgets.s
.file "fgets.c"
.def ___main; .scl 2; .type 32; .endef
.text
.globl _main
.def _main; .scl 2; .type 32; .endef
_main:
pushl %ebp
movl %esp, %ebp
andl $-16, %esp
subl $32, %esp
call ___main
movl __imp___iob, %eax
movl %eax, 8(%esp)
movl $16, 4(%esp)
leal 17(%esp), %eax
movl %eax, (%esp)
call _fgets
movl $0, %eax
leave
ret
.def _fgets; .scl 2; .type 32; .endef
First, i'm not good at reading AT&T syntax and thus understanding the above assembly source easily.
So can anyone help me figure out: (i) where is my local variable name located? in ESP+17 ? (ii) If __imp___iob is representing stdin, where is coming from so that i can use it?
Thanks
Yes, name is at esp+17. You'd be wise to initialize it. Arguments in the cdecl calling conventions are passed right-to-left with the right-most deepest on the stack. The __imp___iob is exported from the CRT, you'll find it back in the stdio.h header file. Search for stdin. The __imp prefix is a Microsoft convention to make exports from DLLs faster. Getting this right is clearly the job of a compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With