I'm using AT&T syntax. I wrote code, which calls function mmap2 from c.
This is my C file:
#include <stdio.h>
int* callloc(int length);
int main(){
int *adres = callloc(1000);
printf("%u\n",adres);
return 0;
}
And this is my assembly function:
#define PROT_READ 0x1 /* Page can be read. */
#define PROT_WRITE 0x2 /* Page can be written. */
#define PROT_EXEC 0x4 /* Page can be executed. */
#define PROT_NONE 0x0 /* Page can not be accessed. */
#define __NR_mmap 90
#define __NR_munmap 91
#define __NR_mmap2 192
.data
MMAP2 = 192
MUNMAP = 91
PROT_READ = 0x1
MAP_ANONYMOUS = 0x20
.global callloc
callloc:
#mmap2 function takes 6 arguments when called
#void *addr - it must be equal 0
#sieze_t length - this is variable from call in C
#int prot - access level, I guess it should be equal 0x1
#int flags - map_anonymous, then fd i offset are ignored
#int fd, off_t offset - those parameters are ignored
push %ebp
mov %esp,%ebp #esp has address of beginning of function
xor %ebx,%ebx
mov 8(%ebp),%ecx #length of memory to allocate is kept in stack since 8 byte
mov $PROT_READ,%edx
mov $MAP_ANONYMOUS,%esi
mov $MMAP2,%eax
int $0x80
mov %ebp,%esp
pop %ebp
ret
My problem is - how could I check if this code is good? I guess that answer is in eax register, but - how can i access this value? I don't know how to use gdb in this case.
The first check should be to see if the returned value is a small negative number or not. Next, you can of course try to use it, as per your passed in flags. The simplest way is try to read the first byte. Furthermore, in gdb when stopped after the interrupt, you can compare the value in eax
to the process memory map accessible using info proc mappings
(or examining /proc
directly in a separate terminal) to see whether it points to the beginning of an appropriate region. You can also use strace
or ltrace
to see the details about the performed system call.
Note that your code has various issues:
.data
section and that won't work. You
should change that to .text
.#define
constants conflict with the asm versions, keep one or
the other. It doesn't even assemble as-is.fd
may be ignored, but it's best to set it to -1
MAP_SHARED
or MAP_PRIVATE
must be setebx
and esi
but you destroy them. You should save them on the
stack using push
and pop
them back after the system call.