From 3fb06f332c0e1f3a29fce238cc63ce5959009316 Mon Sep 17 00:00:00 2001 From: Jason Ginchereau Date: Fri, 5 May 2017 11:38:21 -0700 Subject: [PATCH] n-api: napi_get_cb_info should always fill array When the number of args requested is greater than the actual number of args supplied to the function call, the remainder of the args array should be filled in with `undefined` values. Because of this bug, the remainder of the array was left uninitialized, which could cause a crash. Refer to the documentation for the `argv` parameter at https://github.com/nodejs/node/blob/master/doc/api/n-api.md#napi_get_cb_info --- src/node_api.cc | 2 +- test/addons-napi/3_callbacks/binding.c | 17 +++++++++++++++-- test/addons-napi/test_function/test_function.c | 2 +- 3 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/node_api.cc b/src/node_api.cc index 3067050afbbccf..f846ba5410122f 100644 --- a/src/node_api.cc +++ b/src/node_api.cc @@ -1524,7 +1524,7 @@ napi_status napi_get_cb_info( if (argv != nullptr) { CHECK_ARG(env, argc); - info->Args(argv, std::min(*argc, info->ArgsLength())); + info->Args(argv, *argc); } if (argc != nullptr) { *argc = info->ArgsLength(); diff --git a/test/addons-napi/3_callbacks/binding.c b/test/addons-napi/3_callbacks/binding.c index 47360bd979ffc4..8640a936107d47 100644 --- a/test/addons-napi/3_callbacks/binding.c +++ b/test/addons-napi/3_callbacks/binding.c @@ -3,10 +3,23 @@ #include napi_value RunCallback(napi_env env, napi_callback_info info) { - size_t argc = 1; - napi_value args[1]; + size_t argc = 2; + napi_value args[2]; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, args, NULL, NULL)); + NAPI_ASSERT(env, argc == 1, + "Wrong number of arguments. Expects a single argument."); + + napi_valuetype valuetype0; + NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); + NAPI_ASSERT(env, valuetype0 == napi_function, + "Wrong type of arguments. Expects a function as first argument."); + + napi_valuetype valuetype1; + NAPI_CALL(env, napi_typeof(env, args[1], &valuetype1)); + NAPI_ASSERT(env, valuetype1 == napi_undefined, + "Additional arguments should be undefined."); + napi_value argv[1]; const char* str = "hello world"; size_t str_len = strlen(str); diff --git a/test/addons-napi/test_function/test_function.c b/test/addons-napi/test_function/test_function.c index 928f99c184cb57..4ce0203e7232dd 100644 --- a/test/addons-napi/test_function/test_function.c +++ b/test/addons-napi/test_function/test_function.c @@ -12,7 +12,7 @@ napi_value Test(napi_env env, napi_callback_info info) { NAPI_CALL(env, napi_typeof(env, args[0], &valuetype0)); NAPI_ASSERT(env, valuetype0 == napi_function, - "Wrong type of arguments. Expects a number as first argument."); + "Wrong type of arguments. Expects a function as first argument."); napi_value* argv = args + 1; argc = argc - 1;