MIPS32:递归子程序在“jr ra”行崩溃

时间:2012-05-02 00:04:40

标签: c merge mips

我写了一个MIPS子程序,它实现了合并排序算法(代码在帖子的末尾)。它接收指向数组的指针及其大小。对它进行排序,不要返回任何内容。

我一直在调试它,修复了一些错误,并且由于子例程似乎运行良好,直到它到达基本情况(大小为1的数组),现在我正在使用gdb和这个C代码来调试它具体情况:

#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;
}

我的问题是当我踩到子程序行时,当我到达倒数第二行(jr ra)时,它崩溃并退出代码060,并且gdb显示此消息:

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

我无法弄清楚为什么会这样。我认为这可能是存储在ra中的地址有问题,堆栈分配错误,或者C和MIPS代码之间的链接错误,但我不知道我做错了什么。

这是merge_sort的MIPS代码:
对于基本情况,代码一直运行到行beq t1, zero, SALIDA,然后跳转到SALIDA,然后结束。所以我只是粘贴代码的一部分(SALIDA意味着退出西班牙语: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

1 个答案:

答案 0 :(得分:3)

我认为您的问题是在子程序结束时的以下问题:

lw  $fp, O_FP($fp)    // restores $fp
lw  ra, O_RA($fp)     // restore ra, but $fp isn't pointing to our frame anymore

我认为如果你颠倒这些指示可能会更好。