Arguments to attribute constructor style functions

2019-07-13 17:40发布

I've seen code like this: (Apple based code)

__attribute__((constructor))
void do_action(int argc, const char **argv, const char **envp, const char **things, struct ProgramVars *)
{
   //
}

Which is odd to be because I read that constructors style functions are supposed to be void. Where are those arguments coming from, can I choose what those parameters can be? Is this an Apple only thing for gcc/clang?

This code is supposed to be used with DYLD_INSERT_LIBRARIES, (Linux's LD_PRELOAD). Is that a special reason why it gets arguments?

标签: c gcc llvm-clang
1条回答
我命由我不由天
2楼-- · 2019-07-13 18:10

Functions with attribute constructor can have the same arguments as main has. They can't differ. LD_PRELOAD has nothing common with it. This feature is heavily based on glibc library (don't know about others) and is acceptable for all compilers, that use glibc and support constructor attribute. On Linux it works fine.

Look at the piece of code, where your function do_action is called:

for (size_t i = 0; i < size; i++)
  (*__init_array_start [i]) (argc, argv, envp);

It is placed in glibc library within path *csu/elf-init.c

I also deem, that your argument struct ProgramVars * can't be assigned and can be only nullptr.

查看更多
登录 后发表回答