作者PkmX (阿貓)
看板C_and_CPP
標題Re: [問題] dynamic shared library設計問題
時間Sat Oct 7 22:11:27 2017
我覺得這個直接拿個例子來解釋如何在執行時載入 C++ shared library,
並建構和操作 DSO 內定義的 class 和 function:
==============================================================================
// foo.hpp
struct foo {
virtual ~foo() = 0;
virtual auto vfn() const -> int = 0;
auto fn() const -> int;
};
inline foo::~foo() = default;
template<typename... Ts>
using make_foo_fn = auto (*)(Ts...) -> foo*;
==============================================================================
// foo.cpp
#include "foo.hpp"
struct foo_impl : foo {
virtual ~foo_impl() = default;
virtual auto vfn() const -> int override { return fn(); }
};
extern "C" {
auto new_foo() -> foo* { return new foo_impl; }
}
==============================================================================
// main.cpp
#include <cassert>
#include <iostream>
#include <memory>
#include <dlfcn.h>
#include "foo.hpp"
// C++17 scopeguard utility
#include <type_traits>
template<typename F>
struct scopeguard : F {
scopeguard(scopeguard&&) = delete;
~scopeguard() { (*this)(); }
};
template<typename F> scopeguard(F) -> scopeguard<std::decay_t<F>>;
#define PP_CAT_IMPL(x, y) x##y
#define PP_CAT(x, y) PP_CAT_IMPL(x, y)
#define at_scope_exit \
[[maybe_unused]] const auto PP_CAT(sg$, __COUNTER__) = scopeguard
auto foo::fn() const -> int { return 42; }
int main() try {
auto libfoo = dlopen("./libfoo.so", RTLD_NOW | RTLD_GLOBAL);
assert(libfoo);
at_scope_exit { [&] { dlclose(libfoo); } };
const auto new_foo =
reinterpret_cast<make_foo_fn<>>(dlsym(libfoo, "new_foo"));
assert(new_foo);
const auto f = std::unique_ptr<foo>{new_foo()};
std::cout << f->vfn() << std::endl;
} catch (...) { throw; }
==============================================================================
$ GXX='g++ -std=c++17 -Wall -Wextra -pedantic -O2'
$ ${GXX} -fPIC -shared foo.cpp -o libfoo.so
$ ${GXX} -rdynamic main.cpp -ldl
$ ./a.out
42
線上版:
http://coliru.stacked-crooked.com/a/0f8900f100523fc7
這裡在 foo.hpp 裡面宣告 foo 為一個 abstract class 並定義 foo 的 interface,
main() 可以透過這個 interface 操作 foo,
而 foo 的實做 foo_impl 定義在 foo.cpp 裡面,
並編譯成 libfoo.so 讓 main() 透過 dlopen("path/to/libfoo.so", ...) 載入,
但這會有一個問題,main() 根本就不知道 foo_impl 的存在,
所以 foo.cpp 會定義一個 make_foo 的 function 回傳一個 foo*,
而 main() 可以用 dlsym(..., "make_foo"); 拿到 foo*,
並透過呼叫 foo 的 virtual function 就可以 dispatch 到 foo_impl 的實做
這裡更有趣的就是:
foo_impl::vfn() 會呼叫 foo::fn() 這個不是 virtual 的 function,
而且他的定義在 main.cpp 裡面 (當然也有可能是別的 translation unit),
所以 libfoo.so 是看不到 foo:fn() 的定義的,
而 link 的時候要加上 -rdynamic (也就是 ld 的 --export-dynamic),
讓 linker 將 foo::fn() 加到 dynamic symbol table 裡面,
當 main() 用 dlopen() 呼叫 dynamic loader 將 libfoo.so 載入時,
在處理 run-time relocation 時便可以找到 foo::fn()
實際上去看 gcc 的實做,基本上是遵照 Itanium C++ ABI
foo 的 layout 是這樣的:
foo vtable for foo (_ZTV8foo_impl)
0x0 [vptr] - 0x0 [ offset to top ]
| 0x8 [ pointer to typeinfo ]
--------> 0x10 [ ptr to ~foo() D1 ]
0x18 [ ptr to ~foo() D0 ]
0x20 [ ptr to vfn() ]
而 libfoo.so 裡面的 foo_impl 的 vtbl:
$ nm libfoo.so | grep _ZTV8foo_impl
0000000000200dc0 V _ZTV8foo_impl
$ readelf -r libfoo.so
Offset Info Type Sym. Value Sym. Name + Addend
000000200dd0 000c00000001 R_X86_64_64 0000000000000a60 _ZN8foo_implD1Ev + 0
000000200dd8 000e00000001 R_X86_64_64 0000000000000a80 _ZN8foo_implD0Ev + 0
000000200de0 001800000001 R_X86_64_64 0000000000000a70 _ZNK8foo_impl3vfnEv + 0
當 dlopen 載入 libfoo.so 時,
會將 foo_impl 的 vtbl + 0x20 寫入 foo_impl::vfn() 的位置,
所以當執行到 main() 的 foo* f = make_foo(); 後,f 的 layout 就是:
(假設 f 在 0x100000,_ZTV8foo_impl 被 load 到 0x200dc0)
f @ 0x100000 vtable for foo_impl @ 0x200dc0
0x100000 [ 0x200dd0 ] - 0x200dc0 [ 0 ]
| 0x200dc8 [ _ZTI8foo_impl ]
--------> 0x200dd0 [ foo::~foo() D1 ]
0x200dd8 [ foo::~foo() D0 ]
0x200de0 [ foo_impl::vfn() ]
而 main 中呼叫 f->vfn() 的 code 則是這樣 (f = 0x100000 在 rax 裡面):
movq %rax, %rbx # rbx = 0x100000
movq (%rax), %rax # rax = *0x100000 = 0x200dd0
movq %rbx, %rdi # rdi = 0x100000 (this)
call *16(%rax) # call *(0x200de0)
這樣就會呼叫到 foo_impl::vfn()
而 foo_impl::vfn() 的實做需要呼叫 foo::fn(),
這部份就和一般透過 PLT 間接呼叫動態連結的 function 原理是一樣的:
0000000000000a70 <_ZNK8foo_impl3vfnEv>:
a70: e9 ab fe ff ff jmpq 920 <_ZNK3foo2fnEv@plt>
foo::fn() 的 PLT entry:
0000000000000920 <_ZNK3foo2fnEv@plt>:
920: ff 25 f2 06 20 00 jmpq *0x2006f2(%rip) # 201018 <_ZNK3foo2fnEv>
926: 68 00 00 00 00 pushq $0x0
92b: e9 e0 ff ff ff jmpq 910 <.plt>
$ readelf -r libfoo.so | grep _ZNK3foo2fnEv
000000201018 000100000007 R_X86_64_JUMP_SLOT 0000000000000000 _ZNK3foo2fnEv + 0
因為這裡有給 RTLD_NOW,(若是 RTLD_LAZY 會是第一次呼叫時才會做 binding)
所以 dlopen libfoo.so 時,便會找到執行時 foo::fn() 的位置,
並將 jump slot 改寫成直接 jump 至 foo::fn():
0x600000 <foo::fn()@plt>: 0x200000 <foo::fn()>
jmp foo::fn() ------------------> movl $42, %eax
ret
這也是為什麼 main.cpp 必須將 foo::fn() export 到 dynamic symbol table 中
這裡細節真的很多,基本上你把 C++ ABI 和 dynamic linking 的運作模式弄懂,
就知道如何在執行時動態載入 C++ 的 DSO
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.113.193.217
※ 文章網址: https://webptt.com/m.aspx?n=bbs/C_and_CPP/M.1507385491.A.794.html
1F:→ xam: 我覺得看得懂這篇的話, 沒道理google找的看不懂.. 10/07 23:00
2F:推 Bencrie: 推詳解 XD 10/07 23:10
3F:推 stucode: 推,這要解釋清楚真的需要一點篇幅。 10/07 23:17
4F:推 mabinogi805: 也太詳細QQ 10/08 00:03
※ 編輯: PkmX (140.113.193.217), 10/08/2017 01:08:17
5F:→ dreamboat66: 謝謝詳細的解說,努力理解中 10/08 02:37