Debugging random memory corruption with ASAN in a Node.js addon on Windows with MSVC

Momtchil Momtchev
2 min readSep 10, 2023

Since recently, MSVC has added built-in support for ASAN — a high-performance memory safety debugger developed by Google that is already included in clang (its original host) and g++.

Using it is as simple as adding the /fsanitize=address option when compiling. Since we are targetting a Node.js addon, this option would go in binding.gyp :

'msvs_settings': {
'VCCLCompilerTool': {
'AdditionalOptions': [
'/fsanitize=address'
],
}
}

Then we have to rebuild everything. Like, literally, everything. On Windows, it is not possible to link release and debug versions. This means that if your addon requires any libraries, you will have to rebuild them with the exactly same options.

Once you have your new magic self-debugging binary addon, you will be up for a very unpleasant surprise. Node.js refuses to load it with the absolutely awesome error message:

File not found

You can double- even triple-check all your path names — everything will be in order. Alas, this is the only excuse Node.js knows for not loading your library — whatever the error is — you will always get this message. Which will probably be the correct one in 99% of the cases.

The problem is that, just like on Linux and macOS, ASAN does not accept not being the very first DLL to be loaded. But unlike on Linux and macOS, it does not get the chance to tell you about it.

Head to https://github.com/microsoft/Detours — a free library for implementing interceptors for Windows by Microsoft Research. Clone the repository, then launch a Visual Studio Code shell and build it by simply launching in its root:

git clone https://github.com/microsoft/Detours
cd Detours
nmake

You need one of its samples, samples\setdll — you will find it in bin.X64\setdll.exe after building the library.

Now find this library:

clang_rt.asan_dbg_dynamic-x86_64.dll

It is usually located in some variation of this path:

C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.37.32822\bin\Hostx64\x64\clang_rt.asan_dbg_dynamic-x86_64.dll

Make a local copy of node.exe — it is usually located in Program Files :

copy "C:\Program Files\nodejs\node.exe" .

Then manually inject the ASAN DLL as a dependency:

setdll /d:clang_rt.asan_dbg_dynamic-x86_64.dll node.exe

Voilà, this custom Node.js will be able to load ASAN-enabled addons.

I am an unemployed IT engineer with a story to tell. I work on open-source software with a particular interest in Node.js addons and JavaScript / C++ interaction. You can find me on Github:

--

--