How to debug binary module of nodejs?

╄→尐↘猪︶ㄣ 提交于 2019-12-03 00:12:17

I just found the answer to this in the node-gyp documentation. The solution is to invoke the build process with the --debug flag. That means to invoke node-gyp configure --debug and/or node-gyp build --debug. Then instead of a Release folder a Debug folder will be created. gdb will then automatically load the source files.

Shamelessly copied from an archive of the (now broken) link provided by @Peter Cordes

First, compile your add-on using node-gyp with the --debug flag.

$ node-gyp --debug configure rebuild

Second, if you're still in "playground" mode like I am, you're probably loading your module with something like

var ObjModule = require('./ObjModule/build/Release/objModule');

However, when you rebuild using node-gyp in debug mode, node-gyp throws away the Release version and creates a Debug version instead. So update the module path:

var ObjModule = require('./ObjModule/build/Debug/objModule');

Alright, now we're ready to debug our C++ add-on. Run gdb against the node binary, which is a C++ application. Now, node itself doesn't know about your add-on, so when you try to set a breakpoint on your add-on function (in this case, StringReverse) it complains that the specific function is not defined. Fear not, your add-on is part of the "future shared library load" it refers to, and will be loaded once you require() your add-on in JavaScript.

$ gdb node
...
Reading symbols from node...done.
(gdb) break StringReverse
Function "StringReverse" not defined.
Make breakpoint pending on future shared library load? (y or [n]) y  

OK, now we just have to run the application:

(gdb) run ../modTest.js 
...
Breakpoint 1, StringReverse (args=...) at ../objModule.cpp:49

You can add the directory containing the source of the module to gdb's search path:

(gdb) directory /path/to/source

See: http://sourceware.org/gdb/onlinedocs/gdb/Source-Path.html

Also, to get node-gyp debug symbols, install node-gyp-dbg/dev or equivalent, or compile it with -g

If you are a VSCode user, you may find this helpful inorder to debug your module.

Basic steps are:

  1. Install the vscode plugin https://github.com/vadimcn/vscode-lldb

  2. Setup your launch.json to look like this :

{ "version": "0.2.0", "configurations": [{ "type": "lldb", "request": "launch", "name": "Launch Program", "program": "/absolute/path/to/node", "args": [ "/absolute/path/to/your/index.js" ] }] }

Then setup breakpoints as you would in VS Code.

Happy debugging!

I have also published a detailed blog here if you want more detailed explanation.

https://medium.com/@atulanand94/debugging-nodejs-c-addons-using-vs-code-27e9940fc3ad

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!