跳转到ARM汇编不同的子程序? [英] Branching to different subroutines in ARM assembly?
问题描述
说我有下面的汇编code:
Say I have the following assembly code:
subroutineA:
....some assembly code....
subroutineB:
....some assembly code....
subroutineC:
....some assembly code....
现在,在另一个子程序中,我想建立的东西,将随机跳转到3子程序上述之一。
Now, in another subroutine, I want to build something that will randomly branch to one of the 3 subroutines above.
是这样的:
subroutineD:
....some code to randomly branch to either
subroutineA, or subroutineB, or subroutineC ....
如何能做到这一点有效地ARM汇编?
How can do this efficiently in ARM assembler?
下面是我如何结束了解决这个问题,它可能会帮助别人的某一天(伪code以下):
Here is how I ended up solving the issue and it might help someone else some day (pseudo code below):
我宣布大会阵列来存储所有的子程序标签(它们的内存地址):
I declared an array in Assembly to store all the subroutine label (their memory address):
.global my_arr
my_arr:
.long subroutineA
.long subroutineB
.long subroutineC
.......
我也有在大会(LFSR)一些随机数发生器。说我在 R0随机数
(当然,让0和子程序的总数之间肯定随机数),那么我会做这样的事情:
I also have some random number generator in Assembly (LFSR). Say I have have the random number in R0
(of course, make sure random number between 0 and total number of subroutine), then I would do something like:
ldr R4, =my_arr
ldr R5, [R4, R0]
然后在 R5
,我具有随机子程序的地址。然后,我可以简单地做:
And then in R5
, I have address of random subroutine. And then I can simply do:
blr R5
去子程序。
推荐答案
您可以高效地实现这样的跳转表,
You may efficiently implement a jump table like this,
adr lr, return
cmp r0, #3
ldrlo pc, [pc, r0, lsl #2] @ pc is 8 bytes ahead
b error @ also functions as padding
.long subroutineA
.long subroutineB
.long subroutineC
return:
@ one of three routines finished here.
...
error:
@ random out of array range.
这是非常通用的。大卫密封给予实现交换机类型语句的好方法的 9.2.5多路分支的ARM的ARM第二版,
This is very generic. David Seal gives a nice way to implement a switch type statement in 9.2.5 Multi-Way branch of the ARM ARM 2nd edition,
cmp r0,#max
addlo pc, pc, r0, LSL #routineSizeLog2
b outOfRange
index0:
...
index1:
...
index2:
...
编译器通常会做我的第一个版本(函数指针类型),但不需要保存 LR
来实现切换。通常情况
陈述不是那么线性的。然而,许多人创建中断处理程序等汇编使用大卫印的方法。
Compilers usually do my first version (function pointer type), but do not need to save lr
to implement a switch. Usually case
statements are not so linear. However, many people create interrupt handlers, etc in assembler using David Seal's method.
这篇关于跳转到ARM汇编不同的子程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!