Skip to content

Commit eca2317

Browse files
author
Gabriel Schulhof
committed
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. Fixes: nodejs/node-addon-api#449
1 parent b5f5c46 commit eca2317

File tree

6 files changed

+79
-7
lines changed

6 files changed

+79
-7
lines changed

doc/api/n-api.md

+24
Original file line numberDiff line numberDiff line change
@@ -5958,6 +5958,30 @@ 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 null-terminated string containing the absolute path of the
5979+
file from which the add-on was loaded. The string is owned by `env` and must
5980+
not be modified or freed.
5981+
5982+
`result` may be an empty string if the add-on loading process fails to establish
5983+
the add-on's file name during loading.
5984+
59615985
[ABI Stability]: https://nodejs.org/en/docs/guides/abi-stability/
59625986
[AppVeyor]: https://www.appveyor.com
59635987
[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

+34-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,30 @@ 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+
module_filename = *filename;
581+
}
582+
563583
// Create a new napi_env for this specific module.
564-
napi_env env = v8impl::NewEnv(context);
584+
napi_env env = v8impl::NewEnv(context, module_filename);
565585

566586
napi_value _exports;
567587
env->CallIntoModule([&](napi_env env) {
@@ -1257,3 +1277,11 @@ napi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func) {
12571277
CHECK_NOT_NULL(func);
12581278
return reinterpret_cast<v8impl::ThreadSafeFunction*>(func)->Ref();
12591279
}
1280+
1281+
napi_status node_api_get_module_file_name(napi_env env, const char** result) {
1282+
CHECK_ENV(env);
1283+
CHECK_ARG(env, result);
1284+
1285+
*result = static_cast<node_napi_env>(env)->GetFilename();
1286+
return napi_clear_last_error(env);
1287+
}

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

+4-1
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
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+
assert.strictEqual(test_general.filename, filename);
9+
710
const [ major, minor, patch, release ] = test_general.testGetNodeVersion();
811
assert.strictEqual(process.version.split('-')[0],
912
`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"
@@ -21,9 +22,21 @@ static napi_value testGetNodeVersion(napi_env env, napi_callback_info info) {
2122
return result;
2223
}
2324

25+
static napi_value GetFilename(napi_env env, napi_callback_info info) {
26+
const char* filename;
27+
napi_value result;
28+
29+
NAPI_CALL(env, node_api_get_module_file_name(env, &filename));
30+
NAPI_CALL(env,
31+
napi_create_string_utf8(env, filename, NAPI_AUTO_LENGTH, &result));
32+
33+
return result;
34+
}
35+
2436
static napi_value Init(napi_env env, napi_value exports) {
2537
napi_property_descriptor descriptors[] = {
2638
DECLARE_NAPI_PROPERTY("testGetNodeVersion", testGetNodeVersion),
39+
DECLARE_NAPI_GETTER("filename", GetFilename),
2740
};
2841

2942
NAPI_CALL(env, napi_define_properties(

0 commit comments

Comments
 (0)