49

正如标题所提到的,我的问题很明显,我详细描述了这个场景。在singleton.h文件中有一个由单例模式实现的名为singleton的类,如下所示:

/*
 * singleton.h
 *
 *  Created on: 2011-12-24
 *      Author: bourneli
 */

#ifndef SINGLETON_H_
#define SINGLETON_H_

class singleton
{
private:
    singleton() {num = -1;}
    static singleton* pInstance;
public:
    static singleton& instance()
    {
        if (NULL == pInstance)
        {
            pInstance = new singleton();
        }
        return *pInstance;
    }
public:
    int num;
};

singleton* singleton::pInstance = NULL;

#endif /* SINGLETON_H_ */

然后,有一个名为 hello.cpp 的插件,如下所示:

#include <iostream>
#include "singleton.h"

extern "C" void hello() {
    std::cout << "singleton.num in hello.so : " << singleton::instance().num << std::endl;
    ++singleton::instance().num;
    std::cout << "singleton.num in hello.so after ++ : " << singleton::instance().num << std::endl;
}

您可以看到插件调用了单例并更改了单例中的属性 num。

最后,有一个使用单例和插件的主要功能如下:

#include <iostream>
#include <dlfcn.h>
#include "singleton.h"

int main() {
    using std::cout;
    using std::cerr;
    using std::endl;

    singleton::instance().num = 100; // call singleton
    cout << "singleton.num in main : " << singleton::instance().num << endl;// call singleton

    // open the library
    void* handle = dlopen("./hello.so", RTLD_LAZY);

    if (!handle) {
        cerr << "Cannot open library: " << dlerror() << '\n';
        return 1;
    }

    // load the symbol
    typedef void (*hello_t)();

    // reset errors
    dlerror();
    hello_t hello = (hello_t) dlsym(handle, "hello");
    const char *dlsym_error = dlerror();
    if (dlsym_error) {
        cerr << "Cannot load symbol 'hello': " << dlerror() << '\n';
        dlclose(handle);
        return 1;
    }

    hello(); // call plugin function hello

    cout << "singleton.num in main : " << singleton::instance().num << endl;// call singleton
    dlclose(handle);
}

并且makefile如下:

example1: main.cpp hello.so
    $(CXX) $(CXXFLAGS)  -o example1 main.cpp -ldl

hello.so: hello.cpp
    $(CXX) $(CXXFLAGS)  -shared -o hello.so hello.cpp

clean:
    rm -f example1 hello.so

.PHONY: clean

那么,输出是什么?我以为有以下几点:

singleton.num in main : 100
singleton.num in hello.so : 100
singleton.num in hello.so after ++ : 101
singleton.num in main : 101

但是,实际输出如下:

singleton.num in main : 100
singleton.num in hello.so : -1
singleton.num in hello.so after ++ : 0
singleton.num in main : 100

它证明了单例类有两个实例。

为什么?

4

4 回答 4

70

首先,在构建共享库时通常应该使用-fPIC标志。

不在 32 位 Linux 上使用它“工作”,但在 64 位 Linux 上会失败,并出现类似于以下的错误:

/usr/bin/ld: /tmp/ccUUrz9c.o: relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC

-rdynamic其次,在添加到主可执行文件的链接行后,您的程序将按预期工作:

singleton.num in main : 100
singleton.num in hello.so : 100
singleton.num in hello.so after ++ : 101
singleton.num in main : 101

为了理解为什么-rdynamic需要,您需要了解动态链接器解析符号的方式以及动态符号表。

首先,让我们看一下 的动态符号表hello.so

$ nm -C -D hello.so | grep singleton
0000000000000b8c W singleton::instance()
0000000000201068 B singleton::pInstance
0000000000000b78 W singleton::singleton()

这告诉我们有两个弱函数定义和一个singleton::pInstance对动态链接器可见的全局变量。

现在让我们看一下原始的静态和动态符号表example1(不带 链接-rdynamic):

$ nm -C  example1 | grep singleton
0000000000400d0f t global constructors keyed to singleton::pInstance
0000000000400d38 W singleton::instance()
00000000006022e0 B singleton::pInstance
0000000000400d24 W singleton::singleton()

$ nm -C -D example1 | grep singleton
$ 

没错:即使singleton::pInstance在可执行文件中作为全局变量存在,该符号也不存在于动态符号表中,因此对动态链接器“不可见”。

因为动态链接器“不知道”example1已经包含 的定义singleton::pInstance,所以它不会将该变量绑定hello.so到现有定义(这是您真正想要的)。

当我们添加-rdynamic到链接行时:

$ nm -C  example1-rdynamic | grep singleton
0000000000400fdf t global constructors keyed to singleton::pInstance
0000000000401008 W singleton::instance()
00000000006022e0 B singleton::pInstance
0000000000400ff4 W singleton::singleton()

$ nm -C -D  example1-rdynamic | grep singleton
0000000000401008 W singleton::instance()
00000000006022e0 B singleton::pInstance
0000000000400ff4 W singleton::singleton()

现在singleton::pInstance主可执行文件内部的定义对动态链接器是可见的,因此它将在加载时“重用”该定义hello.so

LD_DEBUG=bindings ./example1-rdynamic |& grep pInstance
     31972: binding file ./hello.so [0] to ./example1-rdynamic [0]: normal symbol `_ZN9singleton9pInstanceE'
于 2011-12-24T21:16:11.690 回答
5

使用运行时加载的共享库时必须小心。这种构造严格来说不是 C++ 标准的一部分,您必须仔细考虑这种过程的语义。

首先,发生的事情是共享库看到了它自己的、单独的全局变量singleton::pInstance。这是为什么?在运行时加载的库本质上是一个单独的、独立的程序,只是碰巧没有入口点。但是其他的一切真的就像一个单独的程序,动态加载器会这样对待它,例如初始化全局变量等。

动态加载器是与静态加载器无关的运行时工具。静态加载器是 C++ 标准实现的一部分,在主程序启动之前解析所有主程序的符号。另一方面,动态加载器仅在主程序已经启动后运行。特别是,主程序的所有符号都必须解析!根本没有办法从主程序中动态地自动替换符号。本机程序不会以任何允许系统重新链接的方式“管理”。(也许某些东西可以被黑客入侵,但不能以系统的、可移植的方式。)

所以真正的问题是如何解决你正在尝试的设计问题。这里的解决方案是将所有全局变量的句柄传递给插件函数。让您的主程序定义全局变量的原始(且唯一)副本,并使用指向该变量的指针初始化您的库。

例如,您的共享库可能如下所示。首先,向单例类添加一个指向指针的指针:

class singleton
{
    static singleton * pInstance;
public:
    static singleton ** ppinstance;
    // ...
};

singleton ** singleton::ppInstance(&singleton::pInstance);

现在使用*ppInstance而不是pInstance到处使用。

在插件中,将单例配置为来自主程序的指针:

void init(singleton ** p)
{
    singleton::ppInsance = p;
}

而main函数,调用插件初始化:

init_fn init;
hello_fn hello;
*reinterpret_cast<void**>(&init) = dlsym(lib, "init");
*reinterpret_cast<void**>(&hello) = dlsym(lib, "hello");

init(singleton::ppInstance);
hello();

现在插件与程序的其余部分共享指向单例实例的相同指针。

于 2011-12-24T11:35:00.290 回答
3

我认为简单的答案就在这里: http ://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html

当您有一个静态变量时,它存储在对象中(.o、.a 和/或 .so)

如果要执行的最终对象包含该对象的两个版本,则行为是出乎意料的,例如调用 Singleton 对象的析构函数。

使用正确的设计,例如在主文件中声明静态成员并使用 -rdynamic/fpic 和使用 "" 编译器指令将为您完成技巧部分。

示例生成文件语句:

$ g++ -rdynamic -o appexe $(OBJ) $(LINKFLAGS) -Wl,--whole-archive -L./Singleton/ -lsingleton -Wl,--no-whole-archive $(LIBS) 

希望这有效!

于 2012-07-26T19:19:50.580 回答
1

谢谢大家的答案!

作为 Linux 的后续,您还可以使用RTLD_GLOBALwith dlopen(...)、 per man dlopen(以及它的示例)。我在此目录中制作了 OP 示例的变体:github tree 示例输出:output.txt

又快又脏:

  • 如果您不想手动将每个符号链接到您的main,请保留共享对象。(例如,如果您将*.so对象导入 Python)
  • 您可以最初加载到全局符号表中,或者执行NOLOAD+GLOBAL重新打开。

代码:

#if MODE == 1
// Add to static symbol table.
#include "producer.h"
#endif
...
    #if MODE == 0 || MODE == 1
        handle = dlopen(lib, RTLD_LAZY);
    #elif MODE == 2
        handle = dlopen(lib, RTLD_LAZY | RTLD_GLOBAL);
    #elif MODE == 3
        handle = dlopen(lib, RTLD_LAZY);
        handle = dlopen(lib, RTLD_LAZY | RTLD_NOLOAD | RTLD_GLOBAL);
    #endif

模式:

  • 模式 0:名义上的延迟加载(不起作用)
  • 模式1:包含文件添加到静态符号表。
  • 模式 2:最初使用 RTLD_GLOBAL 加载
  • 模式 3:使用 RTLD_NOLOAD 重新加载 | RTLD_GLOBAL
于 2017-08-03T01:39:24.030 回答