我的项目包括一个大型的C++库和Python绑定(通过Boost.Python实现)。测试套件主要是基于Python绑定编写的,我想使用Sanitizers运行它,首先是ASAN。
我正在macOS(版本为10.13.1,但之前的版本也有此问题)上运行,并且似乎找不到一种方法来在Python模块上运行ASAN(我非常怀疑这与Boost.Python有关,我认为其他技术也会有相同的问题)。
这是一个简单的Python模块:
// hello_ext.cc
#include <boost/python.hpp>
char const* greet()
{
auto* res = new char[100];
std::strcpy(res, "Hello, world!");
delete [] res;
return res;
}
BOOST_PYTHON_MODULE(hello_ext)
{
using namespace boost::python;
def("greet", greet);
}
这是我使用的Makefile,为MacPorts制作:
// Makefile
CXX = clang++-mp-4.0
CXXFLAGS = -g -std=c++14 -fsanitize=address -fno-omit-frame-pointer
CPPFLAGS = -isystem/opt/local/include $$($(PYTHON_CONFIG) --includes)
LDFLAGS = -L/opt/local/lib
PYTHON = python3.5
PYTHON_CONFIG = python3.5-config
LIBS = -lboost_python3-mt $$($(PYTHON_CONFIG) --ldflags)
all: hello_ext.so
hello_ext.so: hello_ext.cc
$(CXX) $(CPPFLAGS) $(CXXFLAGS) $(LDFLAGS) -shared -o $@ $< $(LIBS)
check: all
$(ENV) $(PYTHON) -c 'import hello_ext; print(hello_ext.greet())'
clean:
-rm -f hello_ext.so
没有ASAN,一切运行良好(实际上是太好了...)。但使用ASAN后,我遇到了类似于LD_PRELOAD
的问题:
$ make check
python -c 'import hello_ext; print(hello_ext.greet())'
==19013==ERROR: Interceptors are not working. This may be because AddressSanitizer is loaded too late (e.g. via dlopen). Please launch the executable with:
DYLD_INSERT_LIBRARIES=/opt/local/libexec/llvm-4.0/lib/clang/4.0.1/lib/darwin/libclang_rt.asan_osx_dynamic.dylib
"interceptors not installed" && 0make: *** [check] Abort trap: 6
好的,让我们这样做:定义DYLD_INSERT_LIBRARIES
$ DYLD_INSERT_LIBRARIES=/opt/local/libexec/llvm-4.0/lib/clang/4.0.1/lib/darwin/libclang_rt.asan_osx_dynamic.dylib \
python -c 'import hello_ext; print(hello_ext.greet())'
==19023==ERROR: Interceptors are not working. This may be because AddressSanitizer is loaded too late (e.g. via dlopen). Please launch the executable with:
DYLD_INSERT_LIBRARIES=/opt/local/libexec/llvm-4.0/lib/clang/4.0.1/lib/darwin/libclang_rt.asan_osx_dynamic.dylib
"interceptors not installed" && 0zsh: abort DYLD_INSERT_LIBRARIES= python -c 'import hello_ext; print(hello_ext.greet())'
让我们对SIP保持怀疑,因此我在这里禁用了SIP,并解决符号链接:
$ DYLD_INSERT_LIBRARIES=/opt/local/libexec/llvm-4.0/lib/clang/4.0.1/lib/darwin/libclang_rt.asan_osx_dynamic.dylib \
/opt/local/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 -c 'import hello_ext; print(hello_ext.greet())'
==19026==ERROR: Interceptors are not working. This may be because AddressSanitizer is loaded too late (e.g. via dlopen). Please launch the executable with:
DYLD_INSERT_LIBRARIES=/opt/local/libexec/llvm-4.0/lib/clang/4.0.1/lib/darwin/libclang_rt.asan_osx_dynamic.dylib
"interceptors not installed" && 0zsh: abort DYLD_INSERT_LIBRARIES= -c 'import hello_ext; print(hello_ext.greet())'
怎么才是正确的方法?我还试过使用ctypes.PyDLL
加载libasan
,甚至使用sys.setdlopenflags(os.RTLD_NOW | os.RTLD_GLOBAL)
也无法使其工作。