测试前,需要了解下sysv的传参方式:
1、输入参数通过r0-r3传递,多余的放入堆栈中;返回值放入r0,不够的话放入{r0,r1}或者{r0,r1,r2,r3},比如:
int foo(int a, int b, int c, int d), 输入:r0 = a, r1 = b, r2 = c, r3 = d,返回:r0 = 类型为int的retvalue
int *foo(char a, double b, int c, char d), 输入:r0 = a, r1用于对齐(double 要求8字节对齐), b = {r2, r3},c放在堆栈的sp[0]位置,d放在堆栈的sp[4]位置,这里的sp是指进入函数时的sp;返回:r0 = 类型为int *的retvalue
2、注意如果返回值是结构体,情况有些特殊:
struct client foo(int a, char b, float c), 输入:r0 = 一个strcut client *变量,由调用者给出, r1 = a, r2 = b, r3 = c;返回:strcut client *变量,和调用者给的一样
为了测试arm平台函数参数如何对齐,多余参数如何传递,以及如何返回一个结构体类型的变量,编写如下代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct _Foo{
int a;
char b;
double c;
float d;
}Foo;
Foo test(int a, char b, double c, float d)
{
Foo *f = (Foo *)malloc(sizeof(Foo));
f->a = a;
f->b = b;
f->c = c;
f->d = d;
return *f;
}
int main(void)
{
Foo retvalue;
retvalue = test(1,2,3,4);
return retvalue.a;
}
malloc会有内存溢出,这样写是为了反汇编更简单些,编译时不开优化,使用-marm参数指定使用arm指令集,然后反汇编得到:
00000000 <test>:
0: e92d4810 push {r4, fp, lr}
4: e28db008 add fp, sp, #8 //fp = sp + 8
8: e24dd01c sub sp, sp, #28 //sp = sp -28
c: e50b0018 str r0, [fp, #-24] ; 0xffffffe8 //fp[-24] = r0 = Foo * temp
10: e50b101c str r1, [fp, #-28] ; 0xffffffe4 //fp[-28] = r1 = int a
14: e1a03002 mov r3, r2 //fp[-29] = r2 = char b, r3 not used
18: e54b301d strb r3, [fp, #-29] ; 0xffffffe3
1c: e3a00018 mov r0, #24
20: ebfffffe bl 0 <malloc> //malloc(24)
24: e1a03000 mov r3, r0 //r3 = f
28: e50b3010 str r3, [fp, #-16] //fp[-16] = f
2c: e51b3010 ldr r3, [fp, #-16] //r3 = f
30: e51b201c ldr r2, [fp, #-28] ; 0xffffffe4 //r2 = fp[-28] = int a
34: e5832000 str r2, [r3] //f->a = r2 = a
38: e51b3010 ldr r3, [fp, #-16]
3c: e55b201d ldrb r2, [fp, #-29] ; 0xffffffe3 //r2 = fp[-29] = char b
40: e5c32004 strb r2, [r3, #4] //f-&g