I am having a problem reading some arguments from the command line when I call the program.
I need to call it using ./try number string
,
for example: ./try 0 dfjjg
When I run it I get a bus error. Can anybody help me? I'm new to assembly and it's pretty hard
thanks a lot!
.data
.balign 4
file_operation: .asciz "r\000"
.balign 4
file_name: .asciz "data.txt\000"
.balign 4
end_line: .asciz "%[^\012]\000"
.balign 4
output: .asciz "data from the file: %s\000"
.balign 4
string: .asciz "ARGV: %s\n"
.global main
main:
PUSH {fp, lr}
ADD fp, sp, #4
SUB sp, sp, #56
@OPEN FILE
LDR r1, addr_file_operation
LDR r0, addr_file_name
BL fopen
MOV r3, r0
STR r3, [fp, #-8]
@READ FROM FILE
SUB r3, fp, #60
MOV r2, r3
LDR r1, addr_end_line
LDR r0, [fp, #-8]
BL fscanf
@READ FROM COMMAND LINE
PUSH {ip, lr}
LDR r1, [r1, #4]
LDR r0, addr_string
BL printf
POP {ip, pc}
@PRINT TO SCREEN
SUB r3, fp, #60
MOV r1, r3
LDR r0, addr_output
BL printf
@CLOSE FILE
LDR r0, [fp, #-8]
BL fclose
MOV r3, #0
MOV r0, r3
SUB sp, fp, #4
POP {fp, lr}
BX lr
@DEFINE ADDRESSES
addr_file_operation: .word file_operation
addr_file_name: .word file_name
addr_end_line: .word end_line
addr_output: .word output
addr_string: .word string
.global fscanf
.global fopen
.global fclose
.global printf
It was working fine reading from a file and printing to console but when I added the part "READ FROM COMMAND LINE" it says "BUS ERROR".
Function calls overwrite the registers r0, r1, r2, and r3, so whatever you expect to be in r1 when you say
LDR r1, [r1, #4]
is no longer there. Whatever is in r1 at that point is probably not a valid pointer, so your program crashes. To fix this issue, save the original r1 to the stack or a register in the range r4 to r11 at the beginning of your function, as these registers are not overwritten by other functions.