I am new to assembly language and took quite some time to understand and write a code. Currently I have to use mmap to load a file and execute the lines written in that file. This other (lets say call.nasm) file contains the following exit code:
mov rdi,0
mov rax,60 ; exit(2)
syscall
I have to call this exit from current.nasm. I was able to successfully map call.nasm file but unable to read the file and execute the exit system call. Here is the mapping and read code in current.nasm for mapping call.nasm:
mov rdi,filepath
mov rsi,0
mov rdx,0
mov rax,2 ; open(2)
syscall
mov rdi,0
mov rsi,bytes ; bytes for mapping
mov rdx,1
mov r10,0x02 ; MAP_PRIVATE
mov r12,rax ; fd
mov r9,0 ; offset
mov rax,9 ; mmap(2)
syscall
mov rdi,rax ; fd
mov rsi,[r8] ; buffer
mov rdx,1024 ; count
mov rax,0 ; read(2)
syscall
This is written in x86_64 nasm. I have even changed the permission of the call.nasm file but so far I was not able to read or execute the lines in the other file.
When I run strace to execute current.nasm file I get a -1 EBADF (Bad file descriptor)
error for read operation.
Any help will be appreciated. Thanks.
UPDATE:
I was able to solve the error -1 EBADF (Bad file descriptor)
. Thanks to @PeterCordes for pointing out the mistake. The following code for read fixed the error:
mov rdi,r12 ; fd
mov rsi,buffer ; buffer
mov rdx,bytes ; count
mov rax,0 ; read(2)
syscall
For jumping to the exit code had to just point to the memory address. My bad that I was pointing to .nasm and not the binary file that I compiled into for mmap.