Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- .globl read_matrix
- .text
- # ==============================================================================
- # FUNCTION: Allocates memory and reads in a binary file as a matrix of integers
- # If any file operation fails or doesn't read the proper number of bytes,
- # exit the program with exit code 1.
- # FILE FORMAT:
- # The first 8 bytes are two 4 byte ints representing the # of rows and columns
- # in the matrix. Every 4 bytes afterwards is an element of the matrix in
- # row-major order.
- # Arguments:
- # a0 is the pointer to string representing the filename
- # a1 is a pointer to an integer, we will set it to the number of rows
- # a2 is a pointer to an integer, we will set it to the number of columns
- # Returns:
- # a0 is the pointer to the matrix in memory
- # ==============================================================================
- read_matrix:
- # Prologue
- addi sp, sp, -36
- sw ra, 0(sp)
- sw s0, 4(sp)
- sw s1, 8(sp)
- sw s2, 12(sp)
- sw s3, 16(sp)
- sw s4, 20(sp)
- sw s5, 24(sp)
- sw s6, 28(sp)
- sw s7, 32(sp)
- mv s0, a0 # preserve arguments
- mv s1, a1
- mv s2, a2
- li t1, 4 # size of bytes
- mv a1, a0 # move file name into a1
- li a2, 0 # read permissions
- jal ra fopen # open file
- addi t0, x0, -1
- beq x0 a0 eof_or_error # check error file
- mv t0, a0 # t0 is now file descriptor
- # read rows
- mv a1, t0
- mv a2, s1
- mv a3, t1 # 4 bytes
- mv s6, a3 # save this variable
- jal ra fread
- bne a0, s6, eof_or_error
- lw s3, 0(a2) # load num of rows
- # read columns
- mv a1, t0
- mv a2, s2
- mv a3, t1 # 4 bytes
- mv s6, a3 # save this variable
- jal ra fread
- bne a0, s6, eof_or_error
- lw s4, 0(a2) # load num of columns
- # mutiply and malloc space
- mul s5, s3, s4 # number of entries
- mul s5, s5, t1 # mul by byte size
- mv a0, s5 # malloc s5 amount of memory
- jal ra malloc # returns mallocd pointer to matrix in a0
- # read rest of matrix
- mv a1, t0 # file descriptor
- mv a2, a0 # mallocd memory
- mv a3, s5 # size
- mv s6, a3 # save byte length
- mv s7, a0 # save memory pointer
- jal ra fread
- bne a0, s6, eof_or_error
- # close file
- mv a1, t0
- jal ra fclose
- bne a0, x0, eof_or_error
- mv a0, s7 # move pointer to a0
- mv a1, s3 # num rows
- mv a2, s4 # num columns
- # Epilogue
- lw ra, 0(sp)
- lw s0, 4(sp)
- lw s1, 8(sp)
- lw s2, 12(sp)
- lw s3, 16(sp)
- lw s4, 20(sp)
- lw s5, 24(sp)
- lw s6, 28(sp)
- lw s7, 32(sp)
- addi sp, sp, 36
- ret
- eof_or_error:
- li a1 1
- jal exit2
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement