9
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

単体でも実行可能で動的リンクも可能な共有ライブラリを作成する

Last updated at Posted at 2016-04-17

#TL;DR

libcのように実行もできる共有ライブラリを作成する方法まとめ

基本的には共有ライブラリのビルドに -pie -rdynamic を付加すれば良い。

libc実行結果例
$ /lib/x86_64-linux-gnu/libc-2.19.so 
GNU C Library (Ubuntu EGLIBC 2.19-0ubuntu6.6) stable release version 2.19, by Roland McGrath et al.
Copyright (C) 2014 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.8.2.
Compiled on a Linux 3.13.11 system on 2015-02-25.
Available extensions:
        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
libc ABIs: UNIQUE IFUNC
For bug reporting instructions, please see:
<https://bugs.launchpad.net/ubuntu/+source/eglibc/+bugs>.

作成方法

実行可能な共有ライブラリを作成する。デフォルトのエントリポイント(_start)から呼ばれる関数 main を定義する。

excutable_shared_lib.c
#include <stdio.h>

extern int hoge(const char *s) {
    printf("hoge: %s\n", s);
}

int main(int argc, char const* argv[])
{
    printf("in %s %s:%d\n", __func__, __FILE__, __LINE__);
    return hoge("aaa");
}

動的リンクでも動作することを確認するようの適当な実行ファイルも作成する

main.c
#include <stdio.h>

int main(int argc, char const* argv[])
{
    printf("in %s %s:%d\n", __func__, __FILE__, __LINE__);
    return hoge("main");
}

実行結果は以下のようになる。基本的な共有ライブラリの作成に -pie -rdynamic を付加する。

ビルドと実行結果
$ gcc -shared -fPIC -pie -rdynamic excutable_shared_lib.c -o libesl.so
$ ./libesl.so 
in main excutable_shared_lib.c:9
hoge: aaa

$ gcc main.c ./libesl.so
$ ldd a.out 
        linux-vdso.so.1 =>  (0x00007ffcf8a99000)
        ./libesl.so (0x00007f8cb92a1000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f8cb8ec0000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f8cb94a5000)
$ ./a.out 
in main main.c:5
hoge: main

以上で実行可能な共有ライブラリと、それをリンクした実行バイナリが作成できた。

参考

linux - Why and how are some shared libraries runnable, as though they are executables? - Unix & Linux Stack Exchange
c - building a .so that is also an executable - Stack Overflow
Make your own executable shared library on Linux | [Po]lentino's blog
実行可能な共有ライブラリ - Okiraku Programming
PIE (位置独立実行形式) を作成する - bkブログ

9
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?