Using memory sanitizer (asan) on C/C++ library loaded to python with ctypes

Question:

I have C++ library compiled with AddressSanitizer(asan) using g++ and cmake:

SET( AXULIARY_COMPILE_FLAGS "-g -Og -fsanitize=address -fno-omit-frame-pointer")

this works very well when running stand-alone C/C++ executable program. But I’m unable to make it work when loaded as shared/dynamic library (.so) into python with ctypes:

run.sh:

#!/bin/bash
#LD_PRELOAD=/usr/lib/gcc/x86_64-linux-gnu/11/libasan.so
LD_PRELOAD=$(g++ -print-file-name=libasan.so)
echo   $LD_PRELOAD
export $LD_PRELOAD
python3 run_asan.py

run_asan.py:

import ctypes ;print("DEBUG 1 ")
asan = ctypes.CDLL(  "/usr/lib/gcc/x86_64-linux-gnu/11/libasan.so", mode=ctypes.RTLD_LOCAL )                ;print("DEBUG 2 ")
lib  = ctypes.CDLL(  "../../cpp/Build/libs/Molecular/libMMFFsp3_lib.so", mode=ctypes.RTLD_LOCAL )           ;print("DEBUG 3 ")

Keep getting this error:

prokop@DesktopGTX3060:~/git/FireCore/tests/tMMFFsp3$ ./run.sh
/usr/lib/gcc/x86_64-linux-gnu/11/libasan.so
./run.sh-: line 7: export: `/usr/lib/gcc/x86_64-linux-gnu/11/libasan.so': not a valid identifier
DEBUG 1 
==20016==ASan runtime does not come first in initial library list; you should either link runtime to your application or manually preload it with LD_PRELOAD.

I was also trying to link asan statically with cmake, but that also does not work:

run_asan.py

import ctypes; print("DEBUG 1 ")
lib  = ctypes.CDLL(  "../../cpp/Build/libs/Molecular/libMMFFsp3_lib.so", mode=ctypes.RTLD_LOCAL )  
prokop@DesktopGTX3060:~/git/FireCore/tests/tMMFFsp3$ python3 run_asan.py
/usr/lib/gcc/x86_64-linux-gnu/11/libasan.so
./run.sh-: line 7: export: `/usr/lib/gcc/x86_64-linux-gnu/11/libasan.so': not a valid identifier
DEBUG 1 
Traceback (most recent call last):
  File "/home/prokop/git/FireCore/tests/tMMFFsp3/run_asan.py", line 3, in <module>
    lib  = ctypes.CDLL(  "../../cpp/Build/libs/Molecular/libMMFFsp3_lib.so", mode=ctypes.RTLD_LOCAL )           ;print("DEBUG 3 ")
  File "/usr/lib/python3.10/ctypes/__init__.py", line 374, in __init__
    self._handle = _dlopen(self._name, mode)
OSError: ../../cpp/Build/libs/Molecular/libMMFFsp3_lib.so: undefined symbol: __asan_option_detect_stack_use_after_return
Asked By: Prokop Hapala

||

Answers:

You should use

export LD_PRELOAD

instead of

export $LD_PRELOAD
Answered By: yugr