Arguments to attribute constructor style functions

2019-07-13 17:29发布

问题:

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?

回答1:

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.



标签: c gcc llvm-clang