【问题标题】:How to get a pointer to a binary section in Mac OS X?如何在 Mac OS X 中获取指向二进制部分的指针?
【发布时间】:2013-07-16 06:35:42
【问题描述】:

我正在编写一些代码,将一些数据结构存储在一个特殊命名的二进制部分中。这些都是相同结构的所有实例,它们分散在许多 C 文件中,并且不在彼此的范围内。通过将它们全部放在命名部分中,我可以遍历所有这些。

这与 GCC 和 GNU ld 完美配合。由于缺少 __start___mysection__stop___mysection 符号,在 Mac OS X 上失败。我猜 llvm ld 不够聪明,无法自动提供它们。

在 GCC 和 GNU ld 中,我使用 __attribute__((section(...)) 加上一些特殊命名的外部指针,它们由链接器神奇地填充。这是一个简单的例子:

#include <stdio.h>

extern int __start___mysection[];
extern int __stop___mysection[];

static int x __attribute__((section("__mysection"))) = 4;
static int y __attribute__((section("__mysection"))) = 10;
static int z __attribute__((section("__mysection"))) = 22;

#define SECTION_SIZE(sect) \
    ((size_t)((__stop_##sect - __start_##sect)))

int main(void)
{
    size_t sz = SECTION_SIZE(__mysection);
    int i;

    printf("Section size is %u\n", sz);

    for (i=0; i < sz; i++) {
        printf("%d\n", __start___mysection[i]);
    }

    return 0;
}

使用 FreeBSD 链接器获取指向节开头/结尾的指针的一般方法是什么。有人有什么想法吗?

供参考的链接器是:

@(#)PROGRAM:ld  PROJECT:ld64-127.2
llvm version 3.0svn, from Apple Clang 3.0 (build 211.12)

在此处询问了有关 MSVC 的类似问题:How to get a pointer to a binary section in MSVC?

【问题讨论】:

    标签: linker ld


    【解决方案1】:

    您可以让 Darwin 链接器为您执行此操作。

    #include <stdio.h>
    
    extern int start_mysection __asm("section$start$__DATA$__mysection");
    extern int stop_mysection  __asm("section$end$__DATA$__mysection");
    
    // If you don't reference x, y and z explicitly, they'll be dead-stripped.
    // Prevent that with the "used" attribute.
    static int x __attribute__((used,section("__DATA,__mysection"))) = 4;
    static int y __attribute__((used,section("__DATA,__mysection"))) = 10;
    static int z __attribute__((used,section("__DATA,__mysection"))) = 22;
    
    int main(void)
    {
        long sz = &stop_mysection - &start_mysection;
        long i;
    
        printf("Section size is %ld\n", sz);
    
        for (i=0; i < sz; ++i) {
            printf("%d\n", (&start_mysection)[i]);
        }
    
        return 0;
    }
    

    【讨论】:

      【解决方案2】:

      使用 Mach-O 信息:

      #include <mach-o/getsect.h>
      
      char *secstart;
      unsigned long secsize;
      secstart = getsectdata("__SEGMENT", "__section", &secsize);
      

      上面给出了关于声明为的部分的信息:

      int x __attribute__((section("__SEGMENT,__section"))) = 123;
      

      更多信息:https://developer.apple.com/library/mac/documentation/developertools/conceptual/machoruntime/Reference/reference.html

      【讨论】:

        猜你喜欢
        • 2011-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多