Explicit initialisation of Node-API addonsΒ #44853
Description
What is the problem this feature will solve?
I have been trying to build a Node-API module using the Tiny C Compiler (https://bellard.org/tcc/) . I've managed to do it (with a couple of work arounds) but I ran into some issues around the use of __attribute__((constructor)) . Is there a reason this particular API design was chosen? Could an explicitly known init function be called if a module failed to self register?
tcc has a couple of issues around the use of __attribute__((constructor)):
- support was not added until late 2019. Not an issue now, but easy to get caught out if you use the most recent "official" release of tcc from late 2017.
- including glibc headers (like string.h) will strip out all uses of
__attribute__((constructor))by tcc. I think this is a bug in the glibc headers, see https://lists.nongnu.org/archive/html/tinycc-devel/2022-10/msg00000.html
To work around this I used a newer version of tcc, and also had to expand out the NAPI_MODULE macro and move the _register_... declaration to the top of my source file: https://github.com/cosinusoidally/mishmashvm/blob/dev/tests/nodejs/stub.c (build script is https://github.com/cosinusoidally/mishmashvm/blob/dev/tests/nodejs/mk)
Having an explicit init function could also be useful for compilers for other languages that potentially do not have support for constructors in shared libraries.
What is the feature you are proposing to solve the problem?
The ability to define an explicit init funtion to avoid the use of __attribute__((constructor)) .
What alternatives have you considered?
No response
Activity
bnoordhuis commentedon Oct 2, 2022
You can export a function called
napi_register_module_v1with a function prototype ofnapi_value (*)(napi_env, napi_value). The second argument is the exports object.There's also
node_register_module_vXXfor "native" (non n-api) add-ons, see #18934 for an example.Are you including tcc.h? It contains an
#undef __attribute__.cosinusoidally commentedon Oct 3, 2022
Ah, I see NAPI_MODULE_INIT in the docs now, thanks (which seems to boil down to napi_register_module_v1). I am using the node.js v8.x node_api headers, which doesn't seem to have that macro. I needed to be able to use the official linux x86 nodejs binaries so I was using older headers. The following works for me (win32/linux x86) for >= v12.x (I assume v10.x will also work, but I didn't check):
For linux I just removed the
__declspec(dllexport). I'll probably stick to NAPI_MODULE for now and maybe move to NAPI_MODULE_INIT if/when I'm ready to bump my lowest supported version of nodejs.Nope I think the culprit is sys/cdefs.h (see tcc mailing list thread)
Thanks for your help, you can close off this ticket if you want.
bnoordhuis commentedon Oct 5, 2022
Glad to hear you found a working solution. Closing then.