|
| 1 | +# Address Sanitizer (ASAN) Guide |
| 2 | + |
| 3 | +This project supports Address Sanitizer (ASAN) to help detect memory corruption, |
| 4 | +use-after-free, and buffer overflows in the C/C++ NetHack engine and its Python |
| 5 | +extensions. |
| 6 | + |
| 7 | +## Enabling ASAN |
| 8 | + |
| 9 | +ASAN is integrated into the CMake build system and can be enabled by editing |
| 10 | +`pyproject.toml`. |
| 11 | + |
| 12 | +### Current Configuration |
| 13 | + |
| 14 | +```toml |
| 15 | +[tool.scikit-build] |
| 16 | +cmake.build-type = "Release" |
| 17 | +cmake.args = ["-DHACKDIR=nle/nethackdir", "-DPYTHON_PACKAGE_NAME=nle"] |
| 18 | +``` |
| 19 | + |
| 20 | +To enable ASAN, add the cmake argument `-DENABLE_ASAN=On` and switch |
| 21 | +`cmake.build-type` to `Debug`. |
| 22 | + |
| 23 | +## Running Tests with ASAN |
| 24 | + |
| 25 | +Because the Python interpreter itself is not built with ASAN, you must preload |
| 26 | +the ASAN runtime library when running tests. |
| 27 | + |
| 28 | +```bash |
| 29 | +LD_PRELOAD=$(gcc -print-file-name=libasan.so):$(gcc -print-file-name=libstdc++.so) \ |
| 30 | +ASAN_OPTIONS=detect_leaks=0 \ |
| 31 | +uv run pytest |
| 32 | +``` |
| 33 | + |
| 34 | +_Note: Preloading `libstdc++.so` may be necessary on some platforms (like |
| 35 | +aarch64 Linux) to avoid crashes when C++ exceptions are thrown._ |
| 36 | + |
| 37 | +### Why `detect_leaks=0`? |
| 38 | + |
| 39 | +We disable the LeakSanitizer (`detect_leaks=0`) for several reasons: |
| 40 | + |
| 41 | +1. Python Shutdown: CPython does not free all memory at exit (e.g., global |
| 42 | + singletons, interned strings). This is intentional for performance but is |
| 43 | + flagged as a "leak" by ASAN. |
| 44 | +2. Pytest State: `pytest` keeps tracebacks, local variables, and fixture data in |
| 45 | + memory until the end of the session to generate reports. |
| 46 | +3. Standard Interpreter: Since we are running a sanitized C extension inside a |
| 47 | + non-sanitized Python interpreter, the leak detector cannot accurately track |
| 48 | + the ownership boundary between the two. |
| 49 | + |
| 50 | +Disabling leak detection still allows ASAN to catch critical memory corruption |
| 51 | +errors (Buffer Overflows, Use-After-Free, etc.) as they happen. |
| 52 | + |
| 53 | +## Other Sanitizers |
| 54 | + |
| 55 | +The build system also supports: |
| 56 | + |
| 57 | +- Thread Sanitizer (TSAN): Use `-DENABLE_TSAN=ON`. |
| 58 | +- Undefined Behavior Sanitizer (UBSAN): Use `-DENABLE_UBSAN=ON`. |
| 59 | + |
| 60 | +To use these, update `pyproject.toml` accordingly and preload the corresponding |
| 61 | +library (e.g., `libtsan.so`). |
0 commit comments