草庐IT

c - GNU libc.so 如何既是共享对象又是独立可执行文件?

coder 2023-06-18 原文

在Linux中,GNU标准C库的共享库(libc.so)不仅是一个共享库,还可以作为独立的可执行文件运行,打印出版本信息:

[me@computer ~]$ /lib/libc.so.6 

GNU C Library stable release version 2.12, by Roland McGrath et al.
Copyright (C) 2010 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.
There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE.
Compiled by GNU CC version 4.4.7 20120313 (Red Hat 4.4.7-11).
Compiled on a Linux 2.6.32 system on 2015-01-07.
Available extensions:
    The C stubs add-on version 2.1.2.
    crypt add-on version 2.1 by Michael Glad and others
    GNU Libidn by Simon Josefsson
    Native POSIX Threads Library by Ulrich Drepper et al
    BIND-8.2.3-T5B
    RT using linux kernel aio
libc ABIs: UNIQUE IFUNC
For bug reporting instructions, please see:
<http://www.gnu.org/software/libc/bugs.html>.

他们是怎么做到的?我尝试创建一个共享库,它也恰好有一个 main() 函数,但是当我尝试运行它时它出现了段错误。

我尝试过的:

/* myso.c */
#include <stdlib.h>
#include <stdio.h>

static void foo(void) {
    printf("hello foo\n");
}

int main(int argc, char *argv[]) {
    printf("hello world\n");
    foo();
    return 0;
}

然后:

$ gcc -Wall -fPIC -shared -o myso.so myso.c
$ ./myso.so
Segmentation fault (core dumped)

注意:我真的不想出于任何实际目的这样做,我只是想知道 GNU 人(和女孩)是如何做到的。

最佳答案

glibc 的文件 Makerules 中:

# Give libc.so an entry point and make it directly runnable itself.
LDFLAGS-c.so += -e __libc_main

并且在csu/version.c

extern void __libc_print_version (void);
void
__libc_print_version (void)
{
  __write (STDOUT_FILENO, banner, sizeof banner - 1);
}

这由 __libc_main() 调用。

在文件 elf/interp.c 中,程序解释器被添加到共享对象。

这在 64 位 Linux 上对我有用:gcc -Wall -Wextra -fPIC -shared -o myso.so myso.c

//myso.c
#include <unistd.h>

char const __invoke_dynamic_linker__[] __attribute__ ((section (".interp")))
#ifdef __LP64__
  = "/lib64/ld-linux-x86-64.so.2";
#else
  = "/lib/ld-linux.so.2";
#endif

void _start(void)
{
    static char const msg[] = "Hello world!\n";

    write(STDOUT_FILENO, msg, sizeof msg - 1);          
    _exit(0);
}

__invoke_dynamic_linker__[] 行是必需的,因为没有它,write_exit 的动态链接就无法完成。这个变量的名字并不重要。 ld 有一个选项,-dynamic-linker,它会做同样的事情,但它会被 -shared 忽略,但是把行到源代码中。

这是一个没有动态链接的变体:

#include <unistd.h>
#include <sys/syscall.h>

__asm__(
#ifdef __LP64__
    "syscall: mov    %rdi,%rax;"
    "   mov    %rsi,%rdi;"
    "   mov    %rdx,%rsi;"
    "   mov    %rcx,%rdx;"
    "   mov    %r8,%r10;"
    "   mov    %r9,%r8;"
    "   mov    0x8(%rsp),%r9;"
    "   syscall;"
    "   cmp    $0xfffffffffffff001,%rax;"
    "   jae    __syscall_error;"
    "   retq;   "
    "__syscall_error: neg    %rax;"
    "   mov    %eax,%fs:0xffffffffffffffd0;"
    "   or     $0xffffffffffffffff,%rax;"
    "   retq;"   
#else
    "syscall:   push   %ebp;"
    "   push   %edi;"
    "   push   %esi;"
    "   push   %ebx;"
    "   mov    0x2c(%esp),%ebp;"
    "   mov    0x28(%esp),%edi;"
    "   mov    0x24(%esp),%esi;"
    "   mov    0x20(%esp),%edx;"
    "   mov    0x1c(%esp),%ecx;"
    "   mov    0x18(%esp),%ebx;"
    "   mov    0x14(%esp),%eax;"
    "   int    $0x80;"
    "   pop    %ebx;"
    "   pop    %esi;"
    "   pop    %edi;"
    "   pop    %ebp;"
    "   cmp    $0xfffff001,%eax;"
    "   jae    __syscall_error;"
    "   ret;"    
    "__syscall_error:   neg    %eax;"
    "   mov    %gs:0x0,%ecx;"
    "   mov    %eax,-0x18(%ecx);"
    "   mov    $0xffffffff,%eax;"
    "   ret;"    
#endif
);

void _start(void)
{
    static char const msg[] = "Hello world!\n";

    syscall(SYS_write, STDOUT_FILENO, msg, sizeof msg - 1);
    syscall(SYS_exit, 0);
}

关于c - GNU libc.so 如何既是共享对象又是独立可执行文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30621632/

有关c - GNU libc.so 如何既是共享对象又是独立可执行文件?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  4. ruby - 其他文件中的 Rake 任务 - 2

    我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时

  5. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  6. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  7. ruby-on-rails - Rails 3 中的多个路由文件 - 2

    Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题

  8. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  9. ruby-openid:执行发现时未设置@socket - 2

    我在使用omniauth/openid时遇到了一些麻烦。在尝试进行身份验证时,我在日志中发现了这一点:OpenID::FetchingError:Errorfetchinghttps://www.google.com/accounts/o8/.well-known/host-meta?hd=profiles.google.com%2Fmy_username:undefinedmethod`io'fornil:NilClass重要的是undefinedmethodio'fornil:NilClass来自openid/fetchers.rb,在下面的代码片段中:moduleNetclass

  10. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

随机推荐