Reputation:
I have this code written in NASM assembly. I want to open a file that is provided via command line argument. Then I want to read the content. Unfortunately sys_open fails (the file_descriptor in rax register is wired 0xffffffffffffffffe). When I hardcode filename in section .data - program runs fine. It fails when I read filename via command line argument. Thanks for tips
code:
SYS_READ equ 0
SYS_OPEN equ 2
SYS_CLOSE equ 3
SYS_EXIT equ 60
O_RDONLY equ 0
section .bss
argc resb 1
filename resb 10
array resb 256
number resb 1
fd resb 8
section .text
global _start
_start:
pop rax ; pop argc value - should be 2
cmp rax, 0x2
jne _sys_exit_1
pop rax ; pop addres pointing to "./prog"
pop rax ; pop addres pointing to filename
mov [filename], rax
call _sys_open
mov [fd], rax ; store file descriptor
_read_seq_loop:
call _sys_read
xor rbx, rbx
mov bl, byte [number] ; store read number in bl register
cmp bl, 0
mov byte [array + rbx], 1 ;save it to array
jne _read_seq_loop
jmp _sys_exit_0
_sys_open:
mov rax, SYS_OPEN
mov rdi, filename
mov rsi, O_RDONLY
mov rdx, 0
syscall
ret
_sys_read:
mov rax, SYS_READ
mov rdi, [fd]
mov rsi, number
mov rdx, 1
syscall
ret
_sys_exit_1:
mov rax, SYS_EXIT
mov rdi, 1
syscall
_sys_exit_0:
mov rax, SYS_EXIT
mov rdi, 0
syscall
Upvotes: 0
Views: 1084
Reputation: 1243
Make these two changes and I think you'll see right away, that instead of passing a pointer to a string, your passing a pointer to a pointer that points to a string.
pop rax ; pop argc value - should be 2
cmp rax, 0x2
jne _sys_exit_1
pop rax ; pop addres pointing to "./prog"
pop rdi ; pop address of ARG0
call _sys_open
mov [fd], rax ; store file descriptor
As RDI is already set, it can be taken out of routine
_sys_open:
mov rax, SYS_OPEN
mov rsi, O_RDONLY
mov rdx, 0
syscall
ret
Upvotes: 1