Search code examples
macosassemblyx86nasm32-bit

Open and write to file in assembly on mac


I'm learning 32 bit assembly on mac, and I've have been trying to write to a file on my desktop. I used this code:

global _start
section .data
path:   db  "/Users/jackliu/Desktop/test.txt",0
string: db  "hello",0
.len:   equ $ - string

section .text

_start:
mov eax, 5
push dword 2
push dword path
sub esp, 8
int 0x80
add esp, 16
mov ebx, eax

mov eax, 4
push dword string.len
push dword string
push dword ebx
sub esp, 4
int 0x80
add esp, 16

mov eax, 1
push 0
sub esp, 12
int 0x80

The file is empty and it already exists on my desktop. After running it, it doesn't change the file at all.

Is there anything wrong with my code?


Solution

  • On MAC OS int 0x80 open system call is:

    5 AUE_OPEN_RWTC ALL { int open(user_addr_t path, int flags, int mode); }

    Your code passes 2 parameters:

    mov eax, 5       ; Open system call = 5
    push dword 2     ; Read/Write flag
    push dword path  ; Path
    sub esp, 8       ; Alignment
    int 0x80
    

    Since you are opening an existing file specify a mode of 0 for the third parameter. Your code could look like this:

    mov eax, 5       ; Open system call = 5
    push dword 0     ; Mode = 0
    push dword 2     ; Read/Write flag
    push dword path  ; Path
    sub esp, 4       ; Reserved space for system call
    int 0x80