I’ve wrote a MIPS subroutine that implements the merge sort algorithm (the code is in the end of the post). It receives the pointer to the array, and its size. Sort it, and don’t return anything.
I’ve been debugging it, fixed some errors, and since the subroutine seems to work well until it reaches the base case (array of size 1), now I’m using gdb and this C code to debug it for that specific situation:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
extern void merge_sort(char*, int);
int main(int argc,char **argv){
char* vector;
vector = (char*)malloc(sizeof(char));
if(vector == NULL) printf("error");
size_t vector_size = 1;
memcpy(vector,"5",vector_size);
merge_sort(vector, vector_size);
int i;
for(i = 0; i < vector_size; i++){
printf("%c ", vector[i]);
}
printf("\n");
return 0;
}
My problem is that when I’m stepping through the subroutine lines, when I get to the penultimate line (jr ra), it crashes and exit with code 060, and gdb show this message:
Warning: GDB can't find the start of the function at 0x400730.
GDB is unable to find the start of the function at 0x400730
and thus can't determine the size of that function's stack
frame. This means that GDB may be unable to access that stack
frame, or the frames below it.
This problem is most likely caused by an invalid program
counter or stack pointer. However, if you think GDB should
simply search farther back from 0x400730 for code which looks
like the beginning of a function, you can increase the range
of the search using the `set heuristic-fence-post' command.
0x004008a0 in _start
I can’t figure out why that happens. I think it could be either a problem with the address stored in ra, a bad stack allocation, or wrong linkage between the C and MIPS code, but I have no idea about what I’m doing wrong.
Here is the MIPS code of merge_sort:
For the base case, the code runs up to the line beq t1, zero, SALIDA, then jumps to SALIDA, and finishes. So I just paste that parts of code (SALIDA means exit in spanish :P).
#include <mips/regdef.h>
#include <sys/syscall.h>
#define SSIZE (56)
#define O_RA (48)
#define O_FP (44)
#define O_GP (40)
#define O_S3 (36)
#define O_S2 (32)
#define O_S1 (28)
#define O_S0 (24)
#define O_ARG0 (SSIZE)
#define O_ARG1 ((SSIZE) + 4)
.text
.align 2
.globl merge_sort
.ent merge_sort
merge_sort:
.frame $fp, SSIZE, ra
.set noreorder
.cpload t9
.set reorder
subu sp,sp,SSIZE
sw s0, O_S0(sp)
sw s1, O_S1(sp)
sw s2, O_S2(sp)
sw s3, O_S3(sp)
sw gp, O_GP(sp)
sw $fp, O_FP(sp)
sw ra, O_RA(sp)
move $fp, sp
sw a0, O_ARG0($fp)
sw a1, O_ARG1($fp)
lw t0, O_ARG1($fp)
addi t1, t0, -1
beq t1, zero, SALIDA
SALIDA:
lw s0, O_S0($fp)
lw s1, O_S1($fp)
lw s2, O_S2($fp)
lw s3, O_S3($fp)
move sp, $fp
lw gp, O_GP($fp)
lw $fp, O_FP($fp)
lw ra, O_RA($fp)
addiu sp, sp, SSIZE
jr ra
.end merge_sort
I think your problem is the following near the end of the subroutine:
I think it might work better if you reverse those instructions.