问题
I am opening an existing file to write into it, using sys_open and sys_write. The sys_write works correctly when I create a new file as shown below. But if I use sys_open, the return value is negative (-13, which is "Permission denied") and the write doesn't work (of course).
This works:
section .data
File_Name: db '/opt/Test_Output_Files/Linux_File_Test',0
File_Mode: dq 754q
Write_Buffer: db 'This is what I want to write',0
section .text
; Create file
mov rax,85 ; sys_creat
mov rdi,File_Name
mov rsi,File_Mode ; mode (permissions)
syscall
mov rdi,rax ; return code from sys_creat
mov rax,1 ; sys_write
mov rsi,Write_Buffer
mov rdx,29
syscall
But when I open the existing file, the sys_open command fails:
mov rax,2 ; sys_open
mov rdi,File_Name
mov rsi,2 ;read-write
mov rdx,[File_Mode]
syscall
Because this is a permissions error, the issue is most likely the flags value in rsi because the mode value in rdx is the same as I use with sys_creat (754). According to the Linux man pages at http://man7.org/linux/man-pages/man2/open.2.html and https://linux.die.net/man/3/open, there are three required options:
O_RDONLY - Open for reading only.
O_WRONLY - Open for writing only.
O_RDWR - Open for reading and writing. The result is undefined if this flag is applied to a FIFO.
I know that read-only is zero, so I assumed write only and read-write are 1 and 2, but I haven't found any listing of the numeric values that we would use in assembly language, unlike the mode which is based on chmod -- and it's the same mode value I used for create, which works.
I've researched this extensively, but there is sparse information on 64-bit syscalls -- most of it is 32-bit. For NASM I need to use a numeric value for the flags in rsi. The man pages say "In addition, zero or more file creation flags and file status flags can be bitwise-or'd in flags. The file creation flags are O_CLOEXEC, O_CREAT, O_DIRECTORY, O_EXCL, O_NOCTTY, O_NOFOLLOW, O_TMPFILE, and O_TRUNC." I could bitwise OR them if I knew what their values are.
Thanks for any help with this.
回答1:
My guess is, you do not have O_RDWR permission for the file that you are trying to open.
You should try O_RDONLY.
Anyway, to answer your question. As far as flag values are concerned, those will be:
O_CREAT(0x40)
O_TRUNC(0x200)
O_APPEND(0x400)
You can find the entire list in:
/usr/include/asm-generic/fcntl.h
Note: if O_CREAT is not set then 'mode' (the value that you set in rdx) will be ignored.
来源:https://stackoverflow.com/questions/59202746/linux-sys-open-in-64-bit-nasm-returns-negative-value