Skip to content

Commit 4b16b88

Browse files
authored
Throw exception if the native addon init gets called more than once. (#290)
* Throw exception if the native addon init gets called more than once.
1 parent e506b01 commit 4b16b88

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

source/module.c

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
#include <aws/common/clock.h>
2222
#include <aws/common/environment.h>
2323
#include <aws/common/logging.h>
24+
#include <aws/common/mutex.h>
2425
#include <aws/common/ref_count.h>
2526
#include <aws/common/system_info.h>
2627

@@ -33,7 +34,12 @@
3334

3435
#include <uv.h>
3536

36-
/* aws-crt-nodejs requires N-API version 4 or above for the threadsafe function API */
37+
/*
38+
* This is a multi-line comment to ensure that the static assert does not collide with the static asserts in
39+
* aws/common/macro.h.
40+
*
41+
* aws-crt-nodejs requires N-API version 4 or above for the threadsafe function API
42+
*/
3743
AWS_STATIC_ASSERT(NAPI_VERSION >= 4);
3844

3945
#define AWS_DEFINE_ERROR_INFO_CRT_NODEJS(CODE, STR) AWS_DEFINE_ERROR_INFO(CODE, STR, "aws-crt-nodejs")
@@ -578,7 +584,28 @@ static bool s_create_and_register_function(
578584
return true;
579585
}
580586

587+
/*
588+
* Temporary hack to detect multi-init so we can throw an exception because we haven't figured out the right way
589+
* to support it yet. Better than a hard crash in native code.
590+
*/
591+
static struct aws_mutex s_module_lock = AWS_MUTEX_INIT;
592+
static bool s_module_initialized = false;
593+
581594
/* napi_value */ NAPI_MODULE_INIT() /* (napi_env env, napi_value exports) */ {
595+
596+
bool already_initialized = false;
597+
aws_mutex_lock(&s_module_lock);
598+
if (s_module_initialized) {
599+
already_initialized = true;
600+
}
601+
s_module_initialized = true;
602+
aws_mutex_unlock(&s_module_lock);
603+
604+
if (already_initialized) {
605+
napi_throw_error(env, NULL, "Aws-crt-nodejs does not yet support multi-initialization.");
606+
return NULL;
607+
}
608+
582609
s_install_crash_handler();
583610

584611
struct aws_allocator *allocator = aws_napi_get_allocator();

0 commit comments

Comments
 (0)