c - 编写 ARM 机器指令并从 C 执行它们(在 Raspberry pi 上)

标签 c assembly arm jit raspberry-pi

我正在尝试用 C 和 ARM 编写一些自修改代码。我之前问过similar question关于 MIPS,现在正尝试将该项目移植到 ARM。
我的系统 := Raspbian on raspberry pi, ARMv6, GCC

有几件事我不确定:

  • ARM 是否需要 D-cache 回写/I-cache 失效(缓存刷新)?如果是这样,我们该怎么做?

我也试过一个例子

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

int inc(int x){ //increments x
    uint16_t *ret = malloc(2 * sizeof(uint16_t));

    *(ret + 0) = 0x3001; //add r0 1 := r0 += 1
    *(ret + 1) = 0x4770; //bx lr    := jump back to inc()

    int(*f)(int) = (int (*)(int)) ret;
    return (*f)(x);
}

int main(){
    printf("%d",inc(6)); //expect '7' to be printed
exit(0);}

但我一直遇到段错误。我正在使用 aapcs 调用约定,据我了解这是所有 ARM 的默认调用约定

如果有人指出正确的方向,我将不胜感激

奖金问题(意思是,它实际上不必回答,但知道会很酷)- 我“来自 MIPS 背景”,ARM 程序员在没有 0 寄存器的情况下怎么办? (例如,硬编码为值 0 的寄存器)

最佳答案

阅读Caches and Self-Modifying Codeblogs.arm.com 上。文章还包含一个示例,该示例执行您所描述的内容。

回答文章中的问题

... the ARM architecture is often considered to be a Modified Harvard Architecture. ...

The typical drawback of a pure Harvard architecture is that instruction memory is not directly accessible from the same address space as data memory, though this restriction does not apply to ARM. On ARM, you can write instructions into memory, but because the D-cache and I-cache are not coherent, the newly-written instructions might be masked by the existing contents of the I-cache, causing the processor to execute old (or possibly invalid) instructions.

参见 __clear_cache了解如何使缓存失效。

如果您打算将指令推送到内存中,我希望您也了解 ARM/Thumb 指令集。

关于c - 编写 ARM 机器指令并从 C 执行它们(在 Raspberry pi 上),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15819298/

相关文章:

用于http头解析的C正则表达式库

assembly - 为什么这段代码使用 VMULPD 来写入将被 VFMADD 覆盖的寄存器?那不是没用吗?

c - 为什么C在调用汇编函数时不将指针压入堆栈?

arm - 使用 NEON/ARM 加载 8 位值

windows - Windows 上的 openocd 无效命令 "jtag",使用 olimex arm-usb-ocd-h jtag 加密狗,使用 phytec lpc3250 目标

c - 奇怪的 scanf 行为

c - 1升是什么意思?

计算文件中的字符我找不到问题

linux - 使用自定义引导加载程序创建可引导 ISO 镜像

assembly - ARM NEON 中的指令调度