为汇编程序提供结构偏移属性 [英] give structure offset attribute to assembler

查看:23
本文介绍了为汇编程序提供结构偏移属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 C 结构的偏移量发送到汇编代码?例如

how can I send the offset of a C struct to en assembly code ? For example

在我的 C 代码中

typedef struct
{
  unsigned int a;
  unsigned int b;
} CMyStruct;

我向 ASM 函数发送了一个 CMyStruct 结构的指针假设我的指针指向 R0

I send to an ASM function a pointer of a CMyStruct structure Let suppose that my pointer is into R0

要访问 a 和 b 属性,我需要这样做.

To access to a and b attribute I need to do that.

ldr      r1, [r0, #0] // read a
ldr      r2, [r0, #4] // read b

无论如何不要将#0 和#4 指定为常量值?类似的东西

Is there anyway to not specify #0 and #4 as contant value ? Something like

ldr      r1, [r0, CMyStruct.a] // read a
ldr      r2, [r0, CMyStruct.b] // read b

谢谢艾蒂安

推荐答案

其实有个办法.该解决方案包含一些魔法,但它有效.它只是有效.

There is a way, actually. The solution is contains a little bit of magic, but it's works. It's just works.

在c文件中:

#define DEFINE(sym, val) asm volatile("\n-> " #sym " %0 " #val "\n" : : "i" (val))
#define OFFSETOF(s, m) \
    DEFINE(offsetof_##s##_##m, offsetof(s, m));

#define SIZEOF(s) \
    DEFINE(sizeof_##s, sizeof(s));

void foo()
{
    OFFSETOF(KERNEL, error);
    OFFSETOF(KERNEL, pool);
    SIZEOF(KERNEL);
}

在生成文件中:

asm_defines.h: asm_defines.c
    $(GCC) $(FLAGS_CC) -S $< -o - | awk '($$1 == "->") { print "#define " $$2 " " $$3 }' > $(BUILD_DIR)/$@

最后您将获得 asm_defines.h,您可以将其包含在您的 .S 文件中.

Finally you will got asm_defines.h, which you can include in your .S file.

#define offsetof_KERNEL_error #16
#define offsetof_KERNEL_pool #4
#define sizeof_KERNEL #120

这篇关于为汇编程序提供结构偏移属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆