4

我正在尝试编写一个程序来使用 ARM-C 互通计算数字的指数。我正在使用 LPC1769(cortex m3) 进行调试。以下是代码:

/*here is the main.c file*/

#include<stdio.h>
#include<stdlib.h>
extern int Start (void);
extern int Exponentiatecore(int *m,int *n);
void print(int i);
int Exponentiate(int *m,int *n);
int main()
{
Start();
return 0;
}


int Exponentiate(int *m,int *n)
{
    if (*n==0)
        return 1;
    else
    {
        int result;
        result=Exponentiatecore(m,n);
        return (result);
    }

}

void print(int i)
{
printf("value=%d\n",i);
}

这是补充上述 C 代码的汇编代码

.syntax unified
        .cpu cortex-m3
        .thumb
        .align
        .global Start
        .global Exponentiatecore
        .thumb
        .thumb_func

Start:
    mov r10,lr
    ldr r0,=label1
    ldr r1,=label2
    bl Exponentiate
    bl print
    mov lr,r10
    mov pc,lr

Exponentiatecore:    // r0-&m, r1-&n

mov r9,lr
ldr r4,[r0]
ldr r2,[r1]
loop:
mul r4,r4
sub r2,#1
bne loop
mov r0,r4
mov lr,r9
mov pc,lr

label1:
.word 0x02


label2:
.word 0x03

但是在调试会话期间,我遇到了执行“Exponentiatecore(m,n)”的 Hardfault 错误。

如调试窗口所示。

Name : HardFault_Handler
Details:{void (void)} 0x21c <HardFault_Handler>
Default:{void (void)} 0x21c <HardFault_Handler>
Decimal:<error reading variable>
Hex:<error reading variable>
Binary:<error reading variable>
Octal:<error reading variable>

我是在对齐过程中造成了一些堆栈损坏,还是我的解释有误?请帮忙。先感谢您

4

2 回答 2

3

您的代码有几个问题。首先是你有一个无限循环,因为你的 SUB 指令没有设置标志。将其更改为 SUBS。下一个问题是您不必要地操作 LR 寄存器。你不会从 Exponentiatecore 调用其他函数,所以不要碰 LR。函数的最后一条指令应该是“BX LR”返回给调用者。问题 #3 是您的乘法指令是错误的。除了取 3 个参数外,如果将数字乘以自身,它会增长得太快。例如:

指数核心(10, 4);
通过每个循环的值:
R4 = 10,n = 4
R4 = 100,n = 3
R4 = 10000,n = 2
R4 = 100,000,000 n = 1

问题 #4 是您正在更改非易失性寄存器 (R4)。除非您保存/恢复它们,否则您只能丢弃 R0-R3。试试这个:

Start:
    stmfd sp!,{lr}
    ldr r0,=label1
    ldr r1,=label2
    bl Exponentiatecore // no need to call C again
    bl print
    ldmfd sp!,{pc}

        Exponentiatecore:    // r0-&m, r1-&n

        ldr r0,[r0]
        mov r2,r0
        ldr r1,[r1]
        cmp r1,#0      // special case for exponent value of 0
        moveq r0,#1
        moveq pc,lr    // early exit
    loop:
        mul r0,r0,r2      // multiply the original value by itself n times
        subs r1,r1,#1
        bne loop
        bx lr
于 2013-03-21T16:25:28.330 回答
1

我只是添加 Start: push {r4-r11,lr} ... pop {r4-r11,pc}

指数核:@ r0-&m, r1-&n push {r4-r11,lr} ... pop {r4-r11,pc}

并在开始中清理 bl 打印,一切正常

于 2014-01-22T14:21:32.753 回答