Write to file in ARM Assembly

放肆的年华 提交于 2019-12-11 01:53:25

问题


I'm attempting to write the integer contents of a register to a text file in ARM Assembly. I have been reading with little success - I have deduced from reading the technical manual I will require some SWI instruction, but I cannot for the life of me find a concrete example of how to do this.

Operating system is Raspbian running on Pi B model.

Thank you in advance for any help, if you require any clarifications please let me know!

EDIT : To clarify, I am assembling and executing my code successfully using GCC. I want to store the values of my data registers to a text file.

Example :

.global main
.func main

main:
    mov r1, #19
    mov r2, #11
    add r0, r1, r2
    bx lr

In the above case, r0 would hold the value 30. I want to write that value to a text file.


回答1:


I did give this a try, thinking about things you need to know beforehand. Of course there are many ways to utilize assembly programming but I aimed for no help from the compiler or libraries.

  • Be able to use toolchain correctly
  • Linker expects a _start symbol
  • Define a string, address it
  • Constants for O_WRONLY, O_CREAT
  • How to encode permission
  • Find out call signatures of open, write, fsync, close, exit
  • How to make a syscall
  • Some kind of memory management, I used stack
  • Pointers
  • ASCII representation of a digit
  • Load / Store of registers, addressing modes
  • How to debug! Funny thing I started thinking this should be straight forward only to find out hard way that you need to call fsync before exiting the process to ask kernel for flushing. Probably O_DIRECT | O_SYNC is an easier choice.

    $ as open_e.s -o open_e.o
    $ ld open_e.o -o open_e
    $ cat open_e.s
    .global _start
    
    _start:
    @open syscall 
    ldr r0, =filename
    mov r1, #0101 @ O_WRONLY | O_CREAT
    ldr r2, =0666 @ permissions
    mov r7, #5 @ 5 is system call number for open
    svc #0
    cmp r0, #0
    blt exit
    
    @r0 contains fd (file descriptor, an integer)
    mov r5, r0
    
    @write syscall
    @use stack as buffer
    sub sp, #8 @ stack is full descending, this is how we leave some space
    mov r1, #'4'
    strb r1, [sp]
    mov r1, #'2'
    strb r1, [sp, #1]
    mov r1, #'\n'
    strb r1, [sp, #2]
    mov r1, sp
    mov r2, #3
    mov r7, #4 @ 4 is write
    svc #0
    
    @fsync syscall
    mov r0, r5
    mov r7, #118
    svc #0
    
    @close syscall
    mov r7, #6 @ 6 is close
    svc #0
    
    exit:
    mov r0, #0
    mov r7, #1
    svc #0
    
    .data
    .align 2
    filename: .asciz "out.txt"
    


来源:https://stackoverflow.com/questions/28817574/write-to-file-in-arm-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!