无法加载基于 CI 构建的 Dylib

Dylib built on CI can't be loaded

我正在 Travis CI 上构建 Rust 二进制文件 (liblonlat_bng.dylib),将其拉入 Cython 扩展(与 Cython 源 .c/.pyx 位于同一目录),并且也在 Travis CI 上测试它(在不同的回购和构建中)。但是,Python 包的测试失败了,我不确定为什么:

----------------------------------------------------------------------
Traceback (most recent call last):
  File "/Users/travis/build/urschrei/convertbng/venv/lib/python2.7/site-packages/nose/loader.py", line 418, in loadTestsFromName
    addr.filename, addr.module)
  File "/Users/travis/build/urschrei/convertbng/venv/lib/python2.7/site-packages/nose/importer.py", line 47, in importFromPath
    return self.importFromDir(dir_path, fqname)
  File "/Users/travis/build/urschrei/convertbng/venv/lib/python2.7/site-packages/nose/importer.py", line 94, in importFromDir
    mod = load_module(part_fqname, fh, filename, desc)
  File "/Users/travis/build/urschrei/convertbng/test/test_convertbng.py", line 15, in <module>
    from convertbng.cutil import convert_bng as cconvert_bng
ImportError: dlopen(/Users/travis/build/urschrei/convertbng/convertbng/cutil.so, 2): Library not loaded: /Users/travis/build/urschrei/lonlat_bng/target/x86_64-apple-darwin/release/liblonlat_bng.dylib
  Referenced from: /Users/travis/build/urschrei/convertbng/convertbng/cutil.so
  Reason: image not found

这是来自 Travis 的软件包的 OSX 构建输出:

Installing collected packages: convertbng
  Running setup.py develop for convertbng
    Running command /Users/travis/build/urschrei/convertbng/venv/bin/python2.7 -c "import setuptools, tokenize;__file__='/Users/travis/build/urschrei/convertbng/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" develop --no-deps
    running develop
    running egg_info
    writing requirements to convertbng.egg-info/requires.txt
    writing convertbng.egg-info/PKG-INFO
    writing top-level names to convertbng.egg-info/top_level.txt
    writing dependency_links to convertbng.egg-info/dependency_links.txt
    warning: manifest_maker: standard file '-c' not found
    reading manifest file 'convertbng.egg-info/SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    writing manifest file 'convertbng.egg-info/SOURCES.txt'
    running build_ext
    building 'convertbng.cutil' extension
    creating build
    creating build/temp.macosx-10.11-x86_64-2.7
    creating build/temp.macosx-10.11-x86_64-2.7/convertbng
    clang -fno-strict-aliasing -fno-common -dynamic -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I. -Iconvertbng -I/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c convertbng/cutil.c -o build/temp.macosx-10.11-x86_64-2.7/convertbng/cutil.o -O3
    [unused function warnings]
    creating build/lib.macosx-10.11-x86_64-2.7
    creating build/lib.macosx-10.11-x86_64-2.7/convertbng
    clang -bundle -undefined dynamic_lookup build/temp.macosx-10.11-x86_64-2.7/convertbng/cutil.o -L. -Lconvertbng -llonlat_bng -o build/lib.macosx-10.11-x86_64-2.7/convertbng/cutil.so
    copying build/lib.macosx-10.11-x86_64-2.7/convertbng/cutil.so -> convertbng
    Creating /Users/travis/build/urschrei/convertbng/venv/lib/python2.7/site-packages/convertbng.egg-link (link to .)
    Adding convertbng 0.4.14 to easy-install.pth file
    Installed /Users/travis/build/urschrei/convertbng
Successfully installed convertbng

这是 Linux Travis 的输出,它成功地将 dylib 定位在相对路径上。请注意 -R$ORIGIN 参数,它不能用于 OSX:

Installing collected packages: convertbng
  Running setup.py develop for convertbng
    Running command /usr/bin/python -c "import setuptools, tokenize;__file__='/home/travis/build/urschrei/convertbng/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" develop --no-deps
    running develop
    running egg_info
    writing requirements to convertbng.egg-info/requires.txt
    writing convertbng.egg-info/PKG-INFO
    writing top-level names to convertbng.egg-info/top_level.txt
    writing dependency_links to convertbng.egg-info/dependency_links.txt
    warning: manifest_maker: standard file '-c' not found
    reading manifest file 'convertbng.egg-info/SOURCES.txt'
    writing manifest file 'convertbng.egg-info/SOURCES.txt'
    running build_ext
    building 'convertbng.cutil' extension
    creating build
    creating build/temp.linux-x86_64-2.7
    creating build/temp.linux-x86_64-2.7/convertbng
    x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I. -Iconvertbng -I/usr/include/python2.7 -c convertbng/cutil.c -o build/temp.linux-x86_64-2.7/convertbng/cutil.o -O3
    creating build/lib.linux-x86_64-2.7
    creating build/lib.linux-x86_64-2.7/convertbng
    x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/convertbng/cutil.o -L. -Lconvertbng -Wl,-R$ORIGIN -llonlat_bng -o build/lib.linux-x86_64-2.7/convertbng/cutil.so
    copying build/lib.linux-x86_64-2.7/convertbng/cutil.so -> convertbng
    Creating /usr/local/lib/python2.7/dist-packages/convertbng.egg-link (link to .)
    Adding convertbng 0.4.14 to easy-install.pth file
    Installed /home/travis/build/urschrei/convertbng
Successfully installed convertbng

其他详情:

我对发生的事情感到很困惑。二进制文件中有什么我应该看的吗? otool -l 输出略有不同。例如:

本地:

cmd LC_LOAD_DYLIB
cmdsize 56
name /usr/lib/libSystem.B.dylib (offset 24)
time stamp 2 Thu Jan  1 01:00:02 1970
current version 1226.10.1

特拉维斯:

cmd LC_LOAD_DYLIB
cmdsize 56
name /usr/lib/libSystem.B.dylib (offset 24)
time stamp 2 Thu Jan  1 00:00:02 1970
current version 1225.1.1

Link 通过 Linux 工作:https://travis-ci.org/urschrei/convertbng/jobs/136730347
Link 失败 OSX 作业:https://travis-ci.org/urschrei/convertbng/jobs/136730348

更新: 这绝对是因为库名。如果我使用 install_name_tool 将 dylib 位置更改为 @loader_path/liblonlat_bng.dylib:

install_name_tool -change /Users/travis/build/urschrei/lonlat_bng/target/x86_64-apple-darwin/release/liblonlat_bng.dylib @loader_path/liblonlat_bng.dylib convertbng/cutil.so

Travis-built 可执行文件将 运行 在我的本地机器上。然而,Travis 似乎有一个损坏的 install_name_tool 安装,我无法将正确的调用从 setup.py 传递给 cutil.so。我尝试将 extra_link_args 设置为 ['-Wl,-rpath,'+'@loader_path/liblonlat_bng.dylib'],这会生成

/usr/bin/clang -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -g build/temp.macosx-10.6-intel-2.7/convertbng/cutil.o -L. -Lconvertbng -llonlat_bng -o build/lib.macosx-10.6-intel-2.7/convertbng/cutil.so -Wl,-rpath,@loader_path/liblonlat_bng.dylib

但如果我这样做,我的测试仍然会失败。

更新 2:我可以在使用 cargo 构建时在 link 阶段修复 dylib 的 install_name

RUSTFLAGS="-C link-args=-Wl,-install_name,@rpath/liblonlat_bng.dylib" cargo build --release

这行得通。但我怀疑我的 setup.py Extension 设置有误:

# only append the runtime dir on Linux
rdirs = []
ldirs = []
if sys.platform != 'darwin':
    # from 
    # the $ORIGIN trick is not perfect, though
    rdirs = ['$ORIGIN']
if sys.platform == 'darwin':
    ldirs = ['-Wl,-rpath,'+'@loader_path/liblonlat_bng.dylib']

extensions = Extension("convertbng.cutil",
                    sources=["convertbng/cutil" + suffix],
                    libraries=["lonlat_bng"],
                    include_dirs=['.', 'convertbng'],
                    library_dirs=['.', 'convertbng'],
                    runtime_library_dirs=rdirs,
                    extra_compile_args=["-O3"],
                    extra_link_args=ldirs
) 

使用install_name_tool.
有两种方法可以解决没有的问题 假设您的 dylib 与您的 Cython 扩展位于同一目录中(在本例中,cutil.so

  • 使用 rpath 支持编译 Rust 二进制文件,并在 setup.py Extension 实例中正确设置 rpath:
    • 最简洁的方法是在 cargo.toml 中的 [profile.release] 下设置 rpath=trueSee here.
    • 您还可以调用 RUSTFLAGS="-C rpath" cargo build --release.
  • 不太灵活的方法是编译 Rust 二进制文件并通过链接器标志传递路径。这在路径中烘烤(尽管使用动态引用),但是:
    • cargo rustc --release -- -C link-args=-Wl,-install_name,@rpath/libname.dylib

在你的 Rust dylib 中启用 rpath 支持后,编辑你的 setup.py

在您的 Extension 实例中设置(或添加)extra_link_args=["-Wl,-rpath", "-Wl,@loader_path/"]

如果你编译你的 Cython 扩展(例如使用 setup.py build_ext --inplace),你就会知道它是有效的,然后 运行 otool -l 在结果 .so 上:

   @rpath/liblonlat_bng.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1226.10.1)

如果你想要你的 Rust dylib 相对于你的 Cython 扩展,你需要相应地调整 setup.py 中的 @rpath/@loader_path/ 路径。

注意:上述仅适用于 OS X 上的相对路径。在 Linux 上,您可以在 setup.py Extension 实例中设置 extra_link_args=["-Wl,-rpath", "-Wl,$ORIGIN"](如果您的 Rust dylib 在其他地方,则相应地调整它,相对于您的扩展。)

我遇到了同样的问题,我认为这是 Distutils 中的错误。我已经提出了解决此问题的拉取请求,并且还提出了一种解决方法。参见 https://github.com/python/cpython/pull/12418

你可以在 setup.py 中尝试以下内容吗?

from Cython.Distutils.build_ext import new_build_ext as build_ext
# alternative:
# from distutils.command import build_ext

class my_build_ext(build_ext):
    """Workaround for rpath bug in distutils for OSX."""

    def finalize_options(self):
        super().finalize_options()
        # Special treatment of rpath in case of OSX, to work around python
        # distutils bug 36353. This constructs proper rpath arguments for clang.
        # See https://bugs.python.org/issue36353
        if sys.platform[:6] == "darwin":
            for path in self.rpath:
                for ext in self.extensions:
                    ext.extra_link_args.append("-Wl,-rpath," + path)
            self.rpath[:] = []

setup(
    cmdclass={'build_ext': my_build_ext}
    # ...
)