MisterHazza
MisterHazza

Reputation: 198

How do I write to files in ARM assembly?

I am learning ARM assembly on my raspberry pi, and I am trying to write to a file called "user_data.txt". I do know how to create a file, like so...

.data

.balign 1
file_name: .asciz "user_data.txt"

.text

.global _start
_start:
    MOV R7, #8
    LDR R0, =file_name
    MOV R1, #0777
    SWI 0
_end:
    MOV R7, #1
    SWI #0

...but, as I said, I can't figure out how I would write to this file. I have looked at other tutorials, but none that I looked at explain what each line does. I understand that I would move 4 into R7, in order to call the sys_write system call, but how would I tell ARM the file name I want to write to?

Can anyone give some code which clearly shows and explains some ARM that writes to a file?

Thanks,

Upvotes: 0

Views: 1374

Answers (1)

Gedobbles
Gedobbles

Reputation: 56

So you wanted code:

.data

.balign 1
file_name: .asciz "user_data.txt"

.text

.global _start
_start:
    MOV R7, #8
    LDR R0, =file_name
    MOV R1, #0777
    SWI 0
    MOV R7, #4         ;write(int fd, void* buf, int len)
    LDR R1, =file_name ;buf
    MOV R2, #9         ;len
    SWI 0
    MOV R7, #6         ;close(int fd)
    SWI 0
_end:
    MOV R7, #1
    SWI #0

This will (for simplicity) write 9 chars of file_name (user_data) into the file and close it. Note that R0 always holds fd.

The manpages (https://linux.die.net/man/2/creat, https://linux.die.net/man/2/write) and this table (https://syscalls.w3challs.com/?arch=arm_thumb) are useful resources I often consult.

Upvotes: 2

Related Questions