如何在Mac OS X中获得指向二进制节的指针? [英] How to get a pointer to a binary section in Mac OS X?

查看:63
本文介绍了如何在Mac OS X中获得指向二进制节的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing some code which stores some data structures in a special named binary section. These are all instances of the same struct which are scattered across many C files and are not within scope of each other. By placing them all in the named section I can iterate over all of them.

这与GCC和GNU ld完美配合.由于缺少 __ start ___ mysection __ stop ___ mysection 符号,因此在Mac OS X上失败.我猜llvm ld不够聪明,无法自动提供它们.

This works perfectly with GCC and GNU ld. Fails on Mac OS X due to missing __start___mysection and __stop___mysection symbols. I guess llvm ld is not smart enough to provide them automatically.

在GCC和GNU ld中,我使用 __ attribute __((section(...))以及一些特别命名的extern指针,这些指针由链接器神奇地填充.这是一个简单的示例:

In GCC and GNU ld, I use __attribute__((section(...)) plus some specially named extern pointers which are magically filled in by the linker. Here's a trivial example:

#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链接器获取指向节的开头/结尾的一般方法是什么.有人有什么想法吗?

What is the general way to get a pointer to the beginning/end of a section with FreeBSD linker. Anyone have any ideas?

参考链接为:

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

在这里有人问到有关MSVC的类似问题:如何在MSVC中获取指向二进制节的指针?

Similar question was asked about MSVC here: How to get a pointer to a binary section in MSVC?

推荐答案

您可以获取Darwin链接程序来为您执行此操作.

You can get the Darwin linker to do this for you.

#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;
}

这篇关于如何在Mac OS X中获得指向二进制节的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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