开始当然得要点汇编知识了
arm寄存器的两种名字
@ r0-r3 a1-a4
@ r4-r9 v1-v7
@ r10 sl
@ r11 fp
@ r12 ip
@ r13 sp
@ r14 lr
@ r15 pc
基本指令(没有什么深奥的知识,看注释秒懂)
mov r0, r1 @ r0 = r1
mov r0, #13 @ 数字还是存在于32位中,不可能很长,这时可以用伪指令
ldr r0, =1234 @ 1234存入r0
ldr r1, =0x2000000
ldr r0, [r1] @ r1所指向的地址中的内容存入r0
str r0, [r1] @ r0的值存入r1所指向的地址中去
ldr r2, str
ldr r3, str1
ldr r2, =str @ 不是r2 = 77777,而是r2 = 存放77777的地址(链接时确定的)
add r0, r1, r0 @ r0 = r1 + r0
sub r0, r1, r0 @ r0 = r1 - r0
str:
.word 77777 @ 4 Byte
str1:
.word 88888
重点来了,循序渐进介绍一下栈为何会这么做的
@ 0. apcs:fn调用完pc从lr里取回,注意arm有3级流水线
mov lr, pc
ldr pc, show
mov pc, lr
show:
.word 0x33f94aa8
@ 但这么做,如果之前还有函数调用,也势必要使用lr寄存器,lr所保存的值就被覆盖了
@ 1. 把前函数的lr的值放在内存中
ldr r5, =0x20000000
str lr, [r5]
mov lr, pc
ldr pc, show
ldr lr, [r5]
mov pc, lr
show:
.word 0x33f94aa8
@ 但这么做,如果r5在show函数中被使用,则出错
@ apcs中规定r0-r3一定被破坏,r4-r9(v1-v7)调用前后需保持一致,然而此时也没保证r5的值调用前后一致
@ 2. 于是乎有了堆栈
sub sp, sp, #4
str lr, [sp]
ldr r0, =fmt
mov lr, pc
ldr pc, show
ldr lr, [sp]
add sp, sp, #4
mov pc, lr
show:
.word 0x33f94aa8
fmt:
.asciz "hello world.\n" @ .ascii "hello world.\n\0"
@ 函数嵌套就挺麻烦,于是想到把sp也存入栈中
@ 3. ip(r12)存当前sp且也存入栈中
mov ip, sp
sub sp, sp, #8
str lr, [sp]
str ip, [sp, #4]
ldr r0, =fmt
mov lr, pc
ldr pc, show
mov sp, #555 @ sp的修改还是影响后续
ldr lr, [sp]
ldr ip, [sp, #4]
mov sp, ip
mov pc, lr
show:
.word 0x33f94aa8
fmt:
.asciz "hello world.\n" @ .ascii "hello world.\n\0"
@ 4. fp(r11) 当下的frame pointer也需要保存
mov ip, sp
sub sp, sp, #12
str lr, [sp]
str ip, [sp, #4]
str fp, [sp, #8]
sub fp, ip, #4
ldr r0, =fmt
mov lr, pc
ldr pc, show
mov sp, #555
ldr lr, [fp, #-8]
ldr ip, [fp, #-4]
ldr fp, [fp, #0]
mov sp, ip
mov pc, lr
show:
.word 0x33f94aa8
fmt:
.asciz "hello world.\n" @ .ascii "hello world.\n\0"
@ 5. 简写
aaa:
mov ip, sp
stmfd sp!, {fp, ip, lr, pc} @ stmdb sp!, {fp, ip, lr, pc} 不写!则sp不变,这个pc是调试信息
sub fp, ip, #4
bl test @ mov lr, pc @ ldr pc, test
sub sp, fp, #12
ldmfd sp, {fp, sp, pc}
test:
mov ip, sp
stmfd sp!, {fp, ip, lr, pc}
sub fp, ip, #4
ldr r0, =fmt
bl show
sub sp, fp, #12
ldmfd sp, {fp, sp, pc}
show:
.word 0x33f94aa8
fmt:
.asciz "hello world.\n"
网友评论