【问题标题】:ELF files and additional symbolsELF 文件和附加符号
【发布时间】:2014-11-15 19:15:11
【问题描述】:

我正在阅读有关 ELF 文件格式的内容,我注意到一个用 C++ 编写的小型 hello world 测试程序在 _start 符号中包含一些额外的初始化:

0000000000400770 <_start>:
...
      40077f:       49 c7 c0 60 09 40 00    mov    $0x400960,%r8
      400786:       48 c7 c1 f0 08 40 00    mov    $0x4008f0,%rcx
      40078d:       48 c7 c7 5d 08 40 00    mov    $0x40085d,%rdi
...

40077f__libc_csu_fini

4008f0__libc_csu_init

40085dmain

不应该只是_startmain 吗?为什么不?如果我只是删除了对40077f40008f0 的两个调用并替换为nop 会发生什么?基本上,需要libc有什么意义?

【问题讨论】:

标签: linux glibc elf


【解决方案1】:

看着glibc source code

/* These functions are passed to __libc_start_main by the startup code.
   These get statically linked into each program.  For dynamically linked
   programs, this module will come from libc_nonshared.a and differs from
   the libc.a module in that it doesn't call the preinit array.  */


void
__libc_csu_init (int argc, char **argv, char **envp)
{
  /* For dynamically linked executables the preinit array is executed by
     the dynamic linker (before initializing any shared object).  */

#ifndef LIBC_NONSHARED
  /* For static executables, preinit happens right before init.  */
  {
    const size_t size = __preinit_array_end - __preinit_array_start;
    size_t i;
    for (i = 0; i < size; i++)
      (*__preinit_array_start [i]) (argc, argv, envp);
  }
#endif

#ifndef NO_INITFINI
  _init ();
#endif

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

/* This function should not be used anymore.  We run the executable's
   destructor now just like any other.  We cannot remove the function,
   though.  */
void
__libc_csu_fini (void)
{
#ifndef LIBC_NONSHARED
  size_t i = __fini_array_end - __fini_array_start;
  while (i-- > 0)
    (*__fini_array_start [i]) ();

# ifndef NO_INITFINI
  _fini ();
# endif
#endif
}

这允许库初始化代码运行。链接到程序的库可以在 gcc 中使用__attribute__((constructor)) 标记函数,并且这种机制将在main 之前运行这些函数,从而允许库在程序启动之前自行初始化。

【讨论】:

    猜你喜欢
    • 2014-07-11
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 2013-10-23
    • 1970-01-01
    • 2015-12-21
    相关资源
    最近更新 更多