11cb0ef41Sopenharmony_ci#include <assert.h>
21cb0ef41Sopenharmony_ci#include <stdlib.h>
31cb0ef41Sopenharmony_ci#include "../../js-native-api/common.h"
41cb0ef41Sopenharmony_ci#include "node_api.h"
51cb0ef41Sopenharmony_ci#include "uv.h"
61cb0ef41Sopenharmony_ci
71cb0ef41Sopenharmony_cistatic int cleanup_hook_count = 0;
81cb0ef41Sopenharmony_cistatic void cleanup(void* arg) {
91cb0ef41Sopenharmony_ci  cleanup_hook_count++;
101cb0ef41Sopenharmony_ci  printf("cleanup(%d)\n", *(int*)(arg));
111cb0ef41Sopenharmony_ci}
121cb0ef41Sopenharmony_ci
131cb0ef41Sopenharmony_cistatic int secret = 42;
141cb0ef41Sopenharmony_cistatic int wrong_secret = 17;
151cb0ef41Sopenharmony_ci
161cb0ef41Sopenharmony_cistatic void ObjectFinalizer(napi_env env, void* data, void* hint) {
171cb0ef41Sopenharmony_ci  // cleanup is called once.
181cb0ef41Sopenharmony_ci  assert(cleanup_hook_count == 1);
191cb0ef41Sopenharmony_ci
201cb0ef41Sopenharmony_ci  napi_ref* ref = data;
211cb0ef41Sopenharmony_ci  NODE_API_CALL_RETURN_VOID(env, napi_delete_reference(env, *ref));
221cb0ef41Sopenharmony_ci  free(ref);
231cb0ef41Sopenharmony_ci}
241cb0ef41Sopenharmony_ci
251cb0ef41Sopenharmony_cistatic void CreateObjectWrap(napi_env env) {
261cb0ef41Sopenharmony_ci  napi_value js_obj;
271cb0ef41Sopenharmony_ci  napi_ref* ref = malloc(sizeof(*ref));
281cb0ef41Sopenharmony_ci  NODE_API_CALL_RETURN_VOID(env, napi_create_object(env, &js_obj));
291cb0ef41Sopenharmony_ci  NODE_API_CALL_RETURN_VOID(
301cb0ef41Sopenharmony_ci      env, napi_wrap(env, js_obj, ref, ObjectFinalizer, NULL, ref));
311cb0ef41Sopenharmony_ci  // create a strong reference so that the finalizer is called at shutdown.
321cb0ef41Sopenharmony_ci  NODE_API_CALL_RETURN_VOID(env, napi_reference_ref(env, *ref, NULL));
331cb0ef41Sopenharmony_ci}
341cb0ef41Sopenharmony_ci
351cb0ef41Sopenharmony_cistatic napi_value Init(napi_env env, napi_value exports) {
361cb0ef41Sopenharmony_ci  // Create object wrap before cleanup hooks.
371cb0ef41Sopenharmony_ci  CreateObjectWrap(env);
381cb0ef41Sopenharmony_ci
391cb0ef41Sopenharmony_ci  napi_add_env_cleanup_hook(env, cleanup, &wrong_secret);
401cb0ef41Sopenharmony_ci  napi_add_env_cleanup_hook(env, cleanup, &secret);
411cb0ef41Sopenharmony_ci  napi_remove_env_cleanup_hook(env, cleanup, &wrong_secret);
421cb0ef41Sopenharmony_ci
431cb0ef41Sopenharmony_ci  // Create object wrap after cleanup hooks.
441cb0ef41Sopenharmony_ci  CreateObjectWrap(env);
451cb0ef41Sopenharmony_ci
461cb0ef41Sopenharmony_ci  return NULL;
471cb0ef41Sopenharmony_ci}
481cb0ef41Sopenharmony_ci
491cb0ef41Sopenharmony_ciNAPI_MODULE(NODE_GYP_MODULE_NAME, Init)
50