Skip to content

Commit ad3ebed

Browse files
Gabriel Schulhofmhdawson
Gabriel Schulhof
andcommitted
node-api: allow retrieval of add-on file name
Unlike JS-only modules, native add-ons are always associated with a dynamic shared object from which they are loaded. Being able to retrieve its absolute path is important to native-only add-ons, i.e. add-ons that are not themselves being loaded from a JS-only module located in the same package as the native add-on itself. Currently, the file name is obtained at environment construction time from the JS `module.filename`. Nevertheless, the presence of `module` is not required, because the file name could also be passed in via a private property added onto `exports` from the `process.dlopen` binding. As an attempt at future-proofing, the file name is provided as a URL, i.e. prefixed with the `file://` protocol. Fixes: nodejs/node-addon-api#449 PR-URL: #37195 Co-authored-by: Michael Dawson <[email protected]> Reviewed-By: Michael Dawson <[email protected]>
1 parent 79d44ba commit ad3ebed

File tree

6 files changed

+87
-7
lines changed

6 files changed

+87
-7
lines changed

doc/api/n-api.md

+25
Original file line numberDiff line numberDiff line change
@@ -5958,6 +5958,31 @@ idempotent.
59585958

59595959
This API may only be called from the main thread.
59605960

5961+
## Miscellaneous utilities
5962+
5963+
## node_api_get_module_file_name
5964+
5965+
<!-- YAML
5966+
added: REPLACEME
5967+
-->
5968+
5969+
> Stability: 1 - Experimental
5970+
5971+
```c
5972+
NAPI_EXTERN napi_status
5973+
node_api_get_module_file_name(napi_env env, const char** result);
5974+
5975+
```
5976+
5977+
* `[in] env`: The environment that the API is invoked under.
5978+
* `[out] result`: A URL containing the absolute path of the
5979+
location from which the add-on was loaded. For a file on the local
5980+
file system it will start with `file://`. The string is null-terminated and
5981+
owned by `env` and must thus not be modified or freed.
5982+
5983+
`result` may be an empty string if the add-on loading process fails to establish
5984+
the add-on's file name during loading.
5985+
59615986
[ABI Stability]: https://nodejs.org/en/docs/guides/abi-stability/
59625987
[AppVeyor]: https://www.appveyor.com
59635988
[C++ Addons]: addons.md

src/env.h

+1
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,7 @@ constexpr size_t kFsStatsBufferLength =
253253
V(fd_string, "fd") \
254254
V(fields_string, "fields") \
255255
V(file_string, "file") \
256+
V(filename_string, "filename") \
256257
V(fingerprint256_string, "fingerprint256") \
257258
V(fingerprint_string, "fingerprint") \
258259
V(flags_string, "flags") \

src/node_api.cc

+39-6
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,9 @@
1515
#include <memory>
1616

1717
struct node_napi_env__ : public napi_env__ {
18-
explicit node_napi_env__(v8::Local<v8::Context> context):
19-
napi_env__(context) {
18+
explicit node_napi_env__(v8::Local<v8::Context> context,
19+
const std::string& module_filename):
20+
napi_env__(context), filename(module_filename) {
2021
CHECK_NOT_NULL(node_env());
2122
}
2223

@@ -46,6 +47,10 @@ struct node_napi_env__ : public napi_env__ {
4647
});
4748
});
4849
}
50+
51+
const char* GetFilename() const { return filename.c_str(); }
52+
53+
std::string filename;
4954
};
5055

5156
typedef node_napi_env__* node_napi_env;
@@ -87,10 +92,11 @@ class BufferFinalizer : private Finalizer {
8792
};
8893
};
8994

90-
static inline napi_env NewEnv(v8::Local<v8::Context> context) {
95+
static inline napi_env
96+
NewEnv(v8::Local<v8::Context> context, const std::string& module_filename) {
9197
node_napi_env result;
9298

93-
result = new node_napi_env__(context);
99+
result = new node_napi_env__(context, module_filename);
94100
// TODO(addaleax): There was previously code that tried to delete the
95101
// napi_env when its v8::Context was garbage collected;
96102
// However, as long as N-API addons using this napi_env are in place,
@@ -552,16 +558,35 @@ void napi_module_register_by_symbol(v8::Local<v8::Object> exports,
552558
v8::Local<v8::Value> module,
553559
v8::Local<v8::Context> context,
554560
napi_addon_register_func init) {
561+
node::Environment* node_env = node::Environment::GetCurrent(context);
562+
std::string module_filename = "";
555563
if (init == nullptr) {
556-
node::Environment* node_env = node::Environment::GetCurrent(context);
557564
CHECK_NOT_NULL(node_env);
558565
node_env->ThrowError(
559566
"Module has no declared entry point.");
560567
return;
561568
}
562569

570+
// We set `env->filename` from `module.filename` here, but we could just as
571+
// easily add a private property to `exports` in `process.dlopen`, which
572+
// receives the file name from JS, and retrieve *that* here. Thus, we are not
573+
// endorsing commonjs here by making use of `module.filename`.
574+
v8::Local<v8::Value> filename_js;
575+
v8::Local<v8::Object> modobj;
576+
if (module->ToObject(context).ToLocal(&modobj) &&
577+
modobj->Get(context, node_env->filename_string()).ToLocal(&filename_js) &&
578+
filename_js->IsString()) {
579+
node::Utf8Value filename(node_env->isolate(), filename_js); // Cast
580+
581+
// Turn the absolute path into a URL. Currently the absolute path is always
582+
// a file system path.
583+
// TODO(gabrielschulhof): Pass the `filename` through unchanged if/when we
584+
// receive it as a URL already.
585+
module_filename = std::string("file://") + (*filename);
586+
}
587+
563588
// Create a new napi_env for this specific module.
564-
napi_env env = v8impl::NewEnv(context);
589+
napi_env env = v8impl::NewEnv(context, module_filename);
565590

566591
napi_value _exports;
567592
env->CallIntoModule([&](napi_env env) {
@@ -1257,3 +1282,11 @@ napi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func) {
12571282
CHECK_NOT_NULL(func);
12581283
return reinterpret_cast<v8impl::ThreadSafeFunction*>(func)->Ref();
12591284
}
1285+
1286+
napi_status node_api_get_module_file_name(napi_env env, const char** result) {
1287+
CHECK_ENV(env);
1288+
CHECK_ARG(env, result);
1289+
1290+
*result = static_cast<node_napi_env>(env)->GetFilename();
1291+
return napi_clear_last_error(env);
1292+
}

src/node_api.h

+3
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,9 @@ NAPI_EXTERN napi_status napi_add_async_cleanup_hook(
261261
NAPI_EXTERN napi_status napi_remove_async_cleanup_hook(
262262
napi_async_cleanup_hook_handle remove_handle);
263263

264+
NAPI_EXTERN napi_status
265+
node_api_get_module_file_name(napi_env env, const char** result);
266+
264267
#endif // NAPI_EXPERIMENTAL
265268

266269
EXTERN_C_END

test/node-api/test_general/test.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,14 @@
11
'use strict';
22

33
const common = require('../../common');
4-
const test_general = require(`./build/${common.buildType}/test_general`);
4+
const filename = require.resolve(`./build/${common.buildType}/test_general`);
5+
const test_general = require(filename);
56
const assert = require('assert');
67

8+
// TODO(gabrielschulhof): This test may need updating if/when the filename
9+
// becomes a full-fledged URL.
10+
assert.strictEqual(test_general.filename, `file://${filename}`);
11+
712
const [ major, minor, patch, release ] = test_general.testGetNodeVersion();
813
assert.strictEqual(process.version.split('-')[0],
914
`v${major}.${minor}.${patch}`);

test/node-api/test_general/test_general.c

+13
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#define NAPI_EXPERIMENTAL
12
#include <node_api.h>
23
#include <stdlib.h>
34
#include "../../js-native-api/common.h"
@@ -20,9 +21,21 @@ static napi_value testGetNodeVersion(napi_env env, napi_callback_info info) {
2021
return result;
2122
}
2223

24+
static napi_value GetFilename(napi_env env, napi_callback_info info) {
25+
const char* filename;
26+
napi_value result;
27+
28+
NODE_API_CALL(env, node_api_get_module_file_name(env, &filename));
29+
NODE_API_CALL(env,
30+
napi_create_string_utf8(env, filename, NAPI_AUTO_LENGTH, &result));
31+
32+
return result;
33+
}
34+
2335
static napi_value Init(napi_env env, napi_value exports) {
2436
napi_property_descriptor descriptors[] = {
2537
DECLARE_NODE_API_PROPERTY("testGetNodeVersion", testGetNodeVersion),
38+
DECLARE_NODE_API_GETTER("filename", GetFilename),
2639
};
2740

2841
NODE_API_CALL(env, napi_define_properties(

0 commit comments

Comments
 (0)