我正在尝试编写一个程序来使用 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
但是在调试 session 期间,我在执行“Exponentiatecore(m,n)”时遇到了硬故障错误。
如调试窗口中所示。
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>
我在对齐过程中是否造成了一些堆栈损坏,或者我的解释是否有错误? 请帮忙。 提前谢谢您
最佳答案
您的代码存在几个问题。第一个是你有一个无限循环,因为你的 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 是您正在更改非 volatile 寄存器 (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
关于pointers - 在汇编中通过引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15542360/