I’m starting to learn Assembler and I’m working in Unix. I want to open a file and write ‘Hello world’ on it.
section .data
textoutput db 'Hello world!', 10
lentext equ $ - textoutput
filetoopen db 'hi.txt'
section .text
global _start
_start:
mov eax, 5 ;open
mov ebx, filetoopen
mov ecx, 2 ;read and write mode
int 80h
mov eax, 4
mov ebx, filetoopen ;I'm not sure what do i have to put here, what is the "file descriptor"?
mov ecx, textoutput
mov edx, lentext
mov eax, 1
mov ebx, 0
int 80h ; finish without errors
But when I compile it, it doesn’t do anything. What am I doing wrong?
When I open a file where does the file descriptor value return to?
This is x86 Linux (x86 is not the only assembly language, and Linux is not the only Unix!)…
The filename string requires a 0-byte terminator:
filetoopen db 'hi.txt', 02is theO_RDWRflag for theopensyscall. If you want the file to be created if it doesn’t already exist, you will need theO_CREATflag as well; and if you specifyO_CREAT, you need a third argument which is the permissions mode for the file. If you poke around in the C headers, you’ll find thatO_CREATis defined as0100– beware of the leading zero: this is an octal constant! You can write octal constants innasmusing theosuffix.So you need something like
mov ecx, 0102oto get the right flags andmov edx, 0666oto set the permssions.The return code from a syscall is passed in
eax. Here, this will be the file descriptor (if the open succeeded) or a small negative number, which is a negativeerrnocode (e.g. -1 forEPERM). Note that the convention for returning error codes from a raw syscall is not quite the same as the C syscall wrappers (which generally return-1and seterrnoin the case of an error)……so here you need to
mov ebx, eaxfirst (to save theopenresult beforeeaxis overwritten) thenmov eax, 4. (You might want to think about checking that the result was positive first, and handling the failure to open in some way if it isn’t.)Missing
int 80hhere.