Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MIPS: Reading a string from command line argument

I'm new to Assembly. I'm having some trouble reading a string from the command line arguments.

I would like to read the string thisismymessage from the 2nd argument into a buffer.

I thought of using SYSCALL, but not sure how.

$ spim -f program.s file thisismymessage
like image 440
Joel Avatar asked Jun 03 '13 06:06

Joel


1 Answers

Here is a few lines of code to illistrate what you are asking:

# $a0 = argc, $a1 = argv
# 4($a1) is first command line argv 8($a1) is second

main:
    lw $a0, 8($a1)       # get second command line argv
    li $v0, 4              # print code for the argument (string)
    syscall                # tells system to print
    li $v0, 10              # exit code
    syscall                # terminate cleanly

The amount of arguments is in $a0 and you could check the amount of arguments against an integer value loaded (li) into a temporary register for validation purposes.

The command line argument values, argv, are stored in $a1 and can be accessed by loading the word. A word is 4 bytes and thus we can access argv[0] with 0($a1), argv[1] with 4($a1) and so forth.

In this case we want argv[2] which we can load the word (lw) from 8($a1) into whatever register we choose. In this case I loaded it into $a0 because I am directly printing it afterwards.

To recap:

# $a0 is argc, $a1 is argv
lw $t0, 8($a1)             # gets argv[2] and stores it in $t0
like image 60
wazy Avatar answered Sep 18 '22 06:09

wazy