GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_api.cc Lines: 529 573 92.3 %
Date: 2022-11-10 04:21:28 Branches: 257 410 62.7 %

Line Branch Exec Source
1
#include "async_wrap-inl.h"
2
#include "env-inl.h"
3
#define NAPI_EXPERIMENTAL
4
#include "js_native_api_v8.h"
5
#include "memory_tracker-inl.h"
6
#include "node_api.h"
7
#include "node_api_internals.h"
8
#include "node_binding.h"
9
#include "node_buffer.h"
10
#include "node_errors.h"
11
#include "node_internals.h"
12
#include "node_process.h"
13
#include "node_url.h"
14
#include "threadpoolwork-inl.h"
15
#include "tracing/traced_value.h"
16
#include "util-inl.h"
17
18
#include <atomic>
19
#include <cstring>
20
#include <memory>
21
22
97
node_napi_env__::node_napi_env__(v8::Local<v8::Context> context,
23
97
                                 const std::string& module_filename)
24
97
    : napi_env__(context), filename(module_filename) {
25
97
  CHECK_NOT_NULL(node_env());
26
97
}
27
28
95
void node_napi_env__::DeleteMe() {
29
95
  destructing = true;
30
95
  napi_env__::DeleteMe();
31
95
}
32
33
118833
bool node_napi_env__::can_call_into_js() const {
34
118833
  return node_env()->can_call_into_js();
35
}
36
37
v8::Maybe<bool> node_napi_env__::mark_arraybuffer_as_untransferable(
38
    v8::Local<v8::ArrayBuffer> ab) const {
39
  return ab->SetPrivate(context(),
40
                        node_env()->untransferable_object_private_symbol(),
41
                        v8::True(isolate));
42
}
43
44
1579
void node_napi_env__::CallFinalizer(napi_finalize cb, void* data, void* hint) {
45
1579
  CallFinalizer<true>(cb, data, hint);
46
1579
}
47
48
template <bool enforceUncaughtExceptionPolicy>
49
1579
void node_napi_env__::CallFinalizer(napi_finalize cb, void* data, void* hint) {
50
1579
  if (destructing) {
51
    // we can not defer finalizers when the environment is being destructed.
52
1098
    v8::HandleScope handle_scope(isolate);
53
549
    v8::Context::Scope context_scope(context());
54
549
    CallbackIntoModule<enforceUncaughtExceptionPolicy>(
55
549
        [&](napi_env env) { cb(env, data, hint); });
56
549
    return;
57
  }
58
  // we need to keep the env live until the finalizer has been run
59
  // EnvRefHolder provides an exception safe wrapper to Ref and then
60
  // Unref once the lambda is freed
61
1030
  EnvRefHolder liveEnv(static_cast<napi_env>(this));
62
2060
  node_env()->SetImmediate(
63
1030
      [=, liveEnv = std::move(liveEnv)](node::Environment* node_env) {
64
1030
        node_napi_env__* env = static_cast<node_napi_env__*>(liveEnv.env());
65
2059
        v8::HandleScope handle_scope(env->isolate);
66
1030
        v8::Context::Scope context_scope(env->context());
67
1030
        env->CallbackIntoModule<enforceUncaughtExceptionPolicy>(
68
1030
            [&](napi_env env) { cb(env, data, hint); });
69
      });
70
}
71
72
8
void node_napi_env__::trigger_fatal_exception(v8::Local<v8::Value> local_err) {
73
  v8::Local<v8::Message> local_msg =
74
8
      v8::Exception::CreateMessage(isolate, local_err);
75
8
  node::errors::TriggerUncaughtException(isolate, local_err, local_msg);
76
6
}
77
78
// option enforceUncaughtExceptionPolicy is added for not breaking existing
79
// running n-api add-ons, and should be deprecated in the next major Node.js
80
// release.
81
template <bool enforceUncaughtExceptionPolicy, typename T>
82
232276
void node_napi_env__::CallbackIntoModule(T&& call) {
83
232285
  CallIntoModule(call, [](napi_env env_, v8::Local<v8::Value> local_err) {
84
9
    node_napi_env__* env = static_cast<node_napi_env__*>(env_);
85
9
    node::Environment* node_env = env->node_env();
86




9
    if (!node_env->options()->force_node_api_uncaught_exceptions_policy &&
87
        !enforceUncaughtExceptionPolicy) {
88
2
      ProcessEmitDeprecationWarning(
89
          node_env,
90
          "Uncaught N-API callback exception detected, please run node "
91
          "with option --force-node-api-uncaught-exceptions-policy=true"
92
          "to handle those exceptions properly.",
93
          "DEP0168");
94
2
      return;
95
    }
96
    // If there was an unhandled exception in the complete callback,
97
    // report it as a fatal exception. (There is no JavaScript on the
98
    // callstack that can possibly handle it.)
99
7
    env->trigger_fatal_exception(local_err);
100
  });
101
232272
}
102
103
namespace v8impl {
104
105
namespace {
106
107
class BufferFinalizer : private Finalizer {
108
 public:
109
  // node::Buffer::FreeCallback
110
14
  static void FinalizeBufferCallback(char* data, void* hint) {
111
    std::unique_ptr<BufferFinalizer, Deleter> finalizer{
112
14
        static_cast<BufferFinalizer*>(hint)};
113
14
    finalizer->_finalize_data = data;
114
115
14
    if (finalizer->_finalize_callback == nullptr) return;
116
26
    finalizer->_env->CallFinalizer(finalizer->_finalize_callback,
117
13
                                   finalizer->_finalize_data,
118
13
                                   finalizer->_finalize_hint);
119
  }
120
121
  struct Deleter {
122
14
    void operator()(BufferFinalizer* finalizer) {
123
14
      Finalizer::Delete(finalizer);
124
14
    }
125
  };
126
};
127
128
97
inline napi_env NewEnv(v8::Local<v8::Context> context,
129
                       const std::string& module_filename) {
130
  node_napi_env result;
131
132
97
  result = new node_napi_env__(context, module_filename);
133
  // TODO(addaleax): There was previously code that tried to delete the
134
  // napi_env when its v8::Context was garbage collected;
135
  // However, as long as N-API addons using this napi_env are in place,
136
  // the Context needs to be accessible and alive.
137
  // Ideally, we'd want an on-addon-unload hook that takes care of this
138
  // once all N-API addons using this napi_env are unloaded.
139
  // For now, a per-Environment cleanup hook is the best we can do.
140
97
  result->node_env()->AddCleanupHook(
141
95
      [](void* arg) { static_cast<napi_env>(arg)->Unref(); },
142
      static_cast<void*>(result));
143
144
97
  return result;
145
}
146
147
class ThreadSafeFunction : public node::AsyncResource {
148
 public:
149
20
  ThreadSafeFunction(v8::Local<v8::Function> func,
150
                     v8::Local<v8::Object> resource,
151
                     v8::Local<v8::String> name,
152
                     size_t thread_count_,
153
                     void* context_,
154
                     size_t max_queue_size_,
155
                     node_napi_env env_,
156
                     void* finalize_data_,
157
                     napi_finalize finalize_cb_,
158
                     napi_threadsafe_function_call_js call_js_cb_)
159
40
      : AsyncResource(env_->isolate,
160
                      resource,
161
40
                      *v8::String::Utf8Value(env_->isolate, name)),
162
        thread_count(thread_count_),
163
        is_closing(false),
164
        dispatch_state(kDispatchIdle),
165
        context(context_),
166
        max_queue_size(max_queue_size_),
167
        env(env_),
168
        finalize_data(finalize_data_),
169
        finalize_cb(finalize_cb_),
170
20
        call_js_cb(call_js_cb_ == nullptr ? CallJs : call_js_cb_),
171

60
        handles_closing(false) {
172
20
    ref.Reset(env->isolate, func);
173
20
    node::AddEnvironmentCleanupHook(env->isolate, Cleanup, this);
174
20
    env->Ref();
175
20
  }
176
177
120
  ~ThreadSafeFunction() override {
178
40
    node::RemoveEnvironmentCleanupHook(env->isolate, Cleanup, this);
179
40
    env->Unref();
180
80
  }
181
182
  // These methods can be called from any thread.
183
184
4603950
  napi_status Push(void* data, napi_threadsafe_function_call_mode mode) {
185
9207900
    node::Mutex::ScopedLock lock(this->mutex);
186
187

9163088
    while (queue.size() >= max_queue_size && max_queue_size > 0 &&
188
4524526
           !is_closing) {
189
4524523
      if (mode == napi_tsfn_nonblocking) {
190
4489911
        return napi_queue_full;
191
      }
192
34612
      cond->Wait(lock);
193
    }
194
195
114039
    if (is_closing) {
196
5
      if (thread_count == 0) {
197
        return napi_invalid_arg;
198
      } else {
199
5
        thread_count--;
200
5
        return napi_closing;
201
      }
202
    } else {
203
114034
      queue.push(data);
204
114034
      Send();
205
114034
      return napi_ok;
206
    }
207
  }
208
209
4
  napi_status Acquire() {
210
8
    node::Mutex::ScopedLock lock(this->mutex);
211
212
4
    if (is_closing) {
213
      return napi_closing;
214
    }
215
216
4
    thread_count++;
217
218
4
    return napi_ok;
219
  }
220
221
35
  napi_status Release(napi_threadsafe_function_release_mode mode) {
222
70
    node::Mutex::ScopedLock lock(this->mutex);
223
224
35
    if (thread_count == 0) {
225
      return napi_invalid_arg;
226
    }
227
228
35
    thread_count--;
229
230

35
    if (thread_count == 0 || mode == napi_tsfn_abort) {
231
18
      if (!is_closing) {
232
18
        is_closing = (mode == napi_tsfn_abort);
233

18
        if (is_closing && max_queue_size > 0) {
234
2
          cond->Signal(lock);
235
        }
236
18
        Send();
237
      }
238
    }
239
240
35
    return napi_ok;
241
  }
242
243
27
  void EmptyQueueAndDelete() {
244
27
    for (; !queue.empty(); queue.pop()) {
245
7
      call_js_cb(nullptr, nullptr, context, queue.front());
246
    }
247
20
    delete this;
248
20
  }
249
250
  // These methods must only be called from the loop thread.
251
252
20
  napi_status Init() {
253
20
    ThreadSafeFunction* ts_fn = this;
254
20
    uv_loop_t* loop = env->node_env()->event_loop();
255
256
20
    if (uv_async_init(loop, &async, AsyncCb) == 0) {
257
20
      if (max_queue_size > 0) {
258
12
        cond = std::make_unique<node::ConditionVariable>();
259
      }
260

20
      if (max_queue_size == 0 || cond) {
261
20
        return napi_ok;
262
      }
263
264
      env->node_env()->CloseHandle(
265
          reinterpret_cast<uv_handle_t*>(&async),
266
          [](uv_handle_t* handle) -> void {
267
            ThreadSafeFunction* ts_fn =
268
                node::ContainerOf(&ThreadSafeFunction::async,
269
                                  reinterpret_cast<uv_async_t*>(handle));
270
            delete ts_fn;
271
          });
272
273
      // Prevent the thread-safe function from being deleted here, because
274
      // the callback above will delete it.
275
      ts_fn = nullptr;
276
    }
277
278
    delete ts_fn;
279
280
    return napi_generic_failure;
281
  }
282
283
2
  napi_status Unref() {
284
2
    uv_unref(reinterpret_cast<uv_handle_t*>(&async));
285
286
2
    return napi_ok;
287
  }
288
289
  napi_status Ref() {
290
    uv_ref(reinterpret_cast<uv_handle_t*>(&async));
291
292
    return napi_ok;
293
  }
294
295
16
  inline void* Context() { return context; }
296
297
 protected:
298
537
  void Dispatch() {
299
537
    bool has_more = true;
300
301
    // Limit maximum synchronous iteration count to prevent event loop
302
    // starvation. See `src/node_messaging.cc` for an inspiration.
303
537
    unsigned int iterations_left = kMaxIterationCount;
304

114575
    while (has_more && --iterations_left != 0) {
305
114038
      dispatch_state = kDispatchRunning;
306
114038
      has_more = DispatchOne();
307
308
      // Send() was called while we were executing the JS function
309
114038
      if (dispatch_state.exchange(kDispatchIdle) != kDispatchRunning) {
310
73223
        has_more = true;
311
      }
312
    }
313
314
537
    if (has_more) {
315
94
      Send();
316
    }
317
537
  }
318
319
114038
  bool DispatchOne() {
320
114038
    void* data = nullptr;
321
114038
    bool popped_value = false;
322
114038
    bool has_more = false;
323
324
    {
325
228076
      node::Mutex::ScopedLock lock(this->mutex);
326
114038
      if (is_closing) {
327
3
        CloseHandlesAndMaybeDelete();
328
      } else {
329
114035
        size_t size = queue.size();
330
114035
        if (size > 0) {
331
114027
          data = queue.front();
332
114027
          queue.pop();
333
114027
          popped_value = true;
334

114027
          if (size == max_queue_size && max_queue_size > 0) {
335
84450
            cond->Signal(lock);
336
          }
337
114027
          size--;
338
        }
339
340
114035
        if (size == 0) {
341
2599
          if (thread_count == 0) {
342
15
            is_closing = true;
343
15
            if (max_queue_size > 0) {
344
9
              cond->Signal(lock);
345
            }
346
15
            CloseHandlesAndMaybeDelete();
347
          }
348
        } else {
349
111436
          has_more = true;
350
        }
351
      }
352
    }
353
354
114038
    if (popped_value) {
355
228054
      v8::HandleScope scope(env->isolate);
356
114027
      CallbackScope cb_scope(this);
357
114027
      napi_value js_callback = nullptr;
358
114027
      if (!ref.IsEmpty()) {
359
        v8::Local<v8::Function> js_cb =
360
208050
            v8::Local<v8::Function>::New(env->isolate, ref);
361
104025
        js_callback = v8impl::JsValueFromV8LocalValue(js_cb);
362
      }
363
114027
      env->CallbackIntoModule<false>(
364
114027
          [&](napi_env env) { call_js_cb(env, js_callback, context, data); });
365
    }
366
367
114038
    return has_more;
368
  }
369
370
20
  void Finalize() {
371
40
    v8::HandleScope scope(env->isolate);
372
20
    if (finalize_cb) {
373
20
      CallbackScope cb_scope(this);
374
      // Do not use CallFinalizer since it will defer the invocation, which
375
      // would lead to accessing a deleted ThreadSafeFunction.
376
20
      env->CallbackIntoModule<false>(
377
20
          [&](napi_env env) { finalize_cb(env, finalize_data, context); });
378
    }
379
20
    EmptyQueueAndDelete();
380
20
  }
381
382
20
  void CloseHandlesAndMaybeDelete(bool set_closing = false) {
383
20
    v8::HandleScope scope(env->isolate);
384
20
    if (set_closing) {
385
4
      node::Mutex::ScopedLock lock(this->mutex);
386
2
      is_closing = true;
387
2
      if (max_queue_size > 0) {
388
1
        cond->Signal(lock);
389
      }
390
    }
391
20
    if (handles_closing) {
392
      return;
393
    }
394
20
    handles_closing = true;
395
20
    env->node_env()->CloseHandle(
396
20
        reinterpret_cast<uv_handle_t*>(&async),
397
20
        [](uv_handle_t* handle) -> void {
398
          ThreadSafeFunction* ts_fn =
399
20
              node::ContainerOf(&ThreadSafeFunction::async,
400
20
                                reinterpret_cast<uv_async_t*>(handle));
401
20
          ts_fn->Finalize();
402
20
        });
403
  }
404
405
114146
  void Send() {
406
    // Ask currently running Dispatch() to make one more iteration
407
114146
    unsigned char current_state = dispatch_state.fetch_or(kDispatchPending);
408
114146
    if ((current_state & kDispatchRunning) == kDispatchRunning) {
409
102248
      return;
410
    }
411
412
11898
    CHECK_EQ(0, uv_async_send(&async));
413
  }
414
415
  // Default way of calling into JavaScript. Used when ThreadSafeFunction is
416
  //  without a call_js_cb_.
417
10002
  static void CallJs(napi_env env, napi_value cb, void* context, void* data) {
418

10002
    if (!(env == nullptr || cb == nullptr)) {
419
      napi_value recv;
420
      napi_status status;
421
422
10002
      status = napi_get_undefined(env, &recv);
423
10002
      if (status != napi_ok) {
424
        napi_throw_error(env,
425
                         "ERR_NAPI_TSFN_GET_UNDEFINED",
426
                         "Failed to retrieve undefined value");
427
        return;
428
      }
429
430
10002
      status = napi_call_function(env, recv, cb, 0, nullptr, nullptr);
431

10002
      if (status != napi_ok && status != napi_pending_exception) {
432
        napi_throw_error(
433
            env, "ERR_NAPI_TSFN_CALL_JS", "Failed to call JS callback");
434
        return;
435
      }
436
    }
437
  }
438
439
537
  static void AsyncCb(uv_async_t* async) {
440
    ThreadSafeFunction* ts_fn =
441
537
        node::ContainerOf(&ThreadSafeFunction::async, async);
442
537
    ts_fn->Dispatch();
443
537
  }
444
445
2
  static void Cleanup(void* data) {
446
2
    reinterpret_cast<ThreadSafeFunction*>(data)->CloseHandlesAndMaybeDelete(
447
        true);
448
2
  }
449
450
 private:
451
  static const unsigned char kDispatchIdle = 0;
452
  static const unsigned char kDispatchRunning = 1 << 0;
453
  static const unsigned char kDispatchPending = 1 << 1;
454
455
  static const unsigned int kMaxIterationCount = 1000;
456
457
  // These are variables protected by the mutex.
458
  node::Mutex mutex;
459
  std::unique_ptr<node::ConditionVariable> cond;
460
  std::queue<void*> queue;
461
  uv_async_t async;
462
  size_t thread_count;
463
  bool is_closing;
464
  std::atomic_uchar dispatch_state;
465
466
  // These are variables set once, upon creation, and then never again, which
467
  // means we don't need the mutex to read them.
468
  void* context;
469
  size_t max_queue_size;
470
471
  // These are variables accessed only from the loop thread.
472
  v8impl::Persistent<v8::Function> ref;
473
  node_napi_env env;
474
  void* finalize_data;
475
  napi_finalize finalize_cb;
476
  napi_threadsafe_function_call_js call_js_cb;
477
  bool handles_closing;
478
};
479
480
/**
481
 * Compared to node::AsyncResource, the resource object in AsyncContext is
482
 * gc-able. AsyncContext holds a weak reference to the resource object.
483
 * AsyncContext::MakeCallback doesn't implicitly set the receiver of the
484
 * callback to the resource object.
485
 */
486
class AsyncContext {
487
 public:
488
13
  AsyncContext(node_napi_env env,
489
               v8::Local<v8::Object> resource_object,
490
               const v8::Local<v8::String> resource_name,
491
               bool externally_managed_resource)
492
13
      : env_(env) {
493
13
    async_id_ = node_env()->new_async_id();
494
13
    trigger_async_id_ = node_env()->get_default_trigger_async_id();
495
13
    resource_.Reset(node_env()->isolate(), resource_object);
496
13
    lost_reference_ = false;
497
13
    if (externally_managed_resource) {
498
11
      resource_.SetWeak(
499
          this, AsyncContext::WeakCallback, v8::WeakCallbackType::kParameter);
500
    }
501
502
13
    node::AsyncWrap::EmitAsyncInit(node_env(),
503
                                   resource_object,
504
                                   resource_name,
505
                                   async_id_,
506
                                   trigger_async_id_);
507
13
  }
508
509
13
  ~AsyncContext() {
510
13
    resource_.Reset();
511
13
    lost_reference_ = true;
512
13
    node::AsyncWrap::EmitDestroy(node_env(), async_id_);
513
13
  }
514
515
8
  inline v8::MaybeLocal<v8::Value> MakeCallback(
516
      v8::Local<v8::Object> recv,
517
      const v8::Local<v8::Function> callback,
518
      int argc,
519
      v8::Local<v8::Value> argv[]) {
520
8
    EnsureReference();
521
    return node::InternalMakeCallback(node_env(),
522
                                      resource(),
523
                                      recv,
524
                                      callback,
525
                                      argc,
526
                                      argv,
527
8
                                      {async_id_, trigger_async_id_});
528
  }
529
530
4
  inline napi_callback_scope OpenCallbackScope() {
531
4
    EnsureReference();
532
    napi_callback_scope it =
533
4
        reinterpret_cast<napi_callback_scope>(new CallbackScope(this));
534
4
    env_->open_callback_scopes++;
535
4
    return it;
536
  }
537
538
12
  inline void EnsureReference() {
539
12
    if (lost_reference_) {
540
1
      const v8::HandleScope handle_scope(node_env()->isolate());
541
1
      resource_.Reset(node_env()->isolate(),
542
1
                      v8::Object::New(node_env()->isolate()));
543
1
      lost_reference_ = false;
544
    }
545
12
  }
546
547
92
  inline node::Environment* node_env() { return env_->node_env(); }
548
8
  inline v8::Local<v8::Object> resource() {
549
16
    return resource_.Get(node_env()->isolate());
550
  }
551
4
  inline node::async_context async_context() {
552
4
    return {async_id_, trigger_async_id_};
553
  }
554
555
4
  static inline void CloseCallbackScope(node_napi_env env,
556
                                        napi_callback_scope s) {
557
4
    CallbackScope* callback_scope = reinterpret_cast<CallbackScope*>(s);
558
4
    delete callback_scope;
559
4
    env->open_callback_scopes--;
560
4
  }
561
562
2
  static void WeakCallback(const v8::WeakCallbackInfo<AsyncContext>& data) {
563
2
    AsyncContext* async_context = data.GetParameter();
564
2
    async_context->resource_.Reset();
565
2
    async_context->lost_reference_ = true;
566
2
  }
567
568
 private:
569
  class CallbackScope : public node::CallbackScope {
570
   public:
571
4
    explicit CallbackScope(AsyncContext* async_context)
572
4
        : node::CallbackScope(async_context->node_env(),
573
                              async_context->resource_.Get(
574
                                  async_context->node_env()->isolate()),
575
8
                              async_context->async_context()) {}
576
  };
577
578
  node_napi_env env_;
579
  double async_id_;
580
  double trigger_async_id_;
581
  v8::Global<v8::Object> resource_;
582
  bool lost_reference_;
583
};
584
585
}  // end of anonymous namespace
586
587
}  // end of namespace v8impl
588
589
// Intercepts the Node-V8 module registration callback. Converts parameters
590
// to NAPI equivalents and then calls the registration callback specified
591
// by the NAPI module.
592
93
static void napi_module_register_cb(v8::Local<v8::Object> exports,
593
                                    v8::Local<v8::Value> module,
594
                                    v8::Local<v8::Context> context,
595
                                    void* priv) {
596
93
  napi_module_register_by_symbol(
597
      exports,
598
      module,
599
      context,
600
93
      static_cast<const napi_module*>(priv)->nm_register_func);
601
93
}
602
603
98
void napi_module_register_by_symbol(v8::Local<v8::Object> exports,
604
                                    v8::Local<v8::Value> module,
605
                                    v8::Local<v8::Context> context,
606
                                    napi_addon_register_func init) {
607
98
  node::Environment* node_env = node::Environment::GetCurrent(context);
608
98
  std::string module_filename = "";
609
98
  if (init == nullptr) {
610
1
    CHECK_NOT_NULL(node_env);
611
1
    node_env->ThrowError("Module has no declared entry point.");
612
1
    return;
613
  }
614
615
  // We set `env->filename` from `module.filename` here, but we could just as
616
  // easily add a private property to `exports` in `process.dlopen`, which
617
  // receives the file name from JS, and retrieve *that* here. Thus, we are not
618
  // endorsing commonjs here by making use of `module.filename`.
619
  v8::Local<v8::Value> filename_js;
620
  v8::Local<v8::Object> modobj;
621
97
  if (module->ToObject(context).ToLocal(&modobj) &&
622

485
      modobj->Get(context, node_env->filename_string()).ToLocal(&filename_js) &&
623
194
      filename_js->IsString()) {
624
92
    node::Utf8Value filename(node_env->isolate(), filename_js);
625
626
    // Turn the absolute path into a URL. Currently the absolute path is always
627
    // a file system path.
628
    // TODO(gabrielschulhof): Pass the `filename` through unchanged if/when we
629
    // receive it as a URL already.
630
92
    module_filename = node::url::URL::FromFilePath(filename.ToString()).href();
631
  }
632
633
  // Create a new napi_env for this specific module.
634
97
  napi_env env = v8impl::NewEnv(context, module_filename);
635
636
  napi_value _exports;
637
97
  env->CallIntoModule([&](napi_env env) {
638
97
    _exports = init(env, v8impl::JsValueFromV8LocalValue(exports));
639
97
  });
640
641
  // If register function returned a non-null exports object different from
642
  // the exports object we passed it, set that as the "exports" property of
643
  // the module.
644
188
  if (_exports != nullptr &&
645

188
      _exports != v8impl::JsValueFromV8LocalValue(exports)) {
646
4
    napi_value _module = v8impl::JsValueFromV8LocalValue(module);
647
4
    napi_set_named_property(env, _module, "exports", _exports);
648
  }
649
}
650
651
namespace node {
652
92
node_module napi_module_to_node_module(const napi_module* mod) {
653
  return {
654
      -1,
655
92
      mod->nm_flags | NM_F_DELETEME,
656
      nullptr,
657
92
      mod->nm_filename,
658
      nullptr,
659
      napi_module_register_cb,
660
92
      mod->nm_modname,
661
      const_cast<napi_module*>(mod),  // priv
662
      nullptr,
663
92
  };
664
}
665
}  // namespace node
666
667
// Registers a NAPI module.
668
89
void NAPI_CDECL napi_module_register(napi_module* mod) {
669
  node::node_module* nm =
670
89
      new node::node_module(node::napi_module_to_node_module(mod));
671
89
  node::node_module_register(nm);
672
89
}
673
674
2
napi_status NAPI_CDECL napi_add_env_cleanup_hook(
675
    napi_env env, void(NAPI_CDECL* fun)(void* arg), void* arg) {
676
2
  CHECK_ENV(env);
677
2
  CHECK_ARG(env, fun);
678
679
2
  node::AddEnvironmentCleanupHook(env->isolate, fun, arg);
680
681
2
  return napi_ok;
682
}
683
684
1
napi_status NAPI_CDECL napi_remove_env_cleanup_hook(
685
    napi_env env, void(NAPI_CDECL* fun)(void* arg), void* arg) {
686
1
  CHECK_ENV(env);
687
1
  CHECK_ARG(env, fun);
688
689
1
  node::RemoveEnvironmentCleanupHook(env->isolate, fun, arg);
690
691
1
  return napi_ok;
692
}
693
694
struct napi_async_cleanup_hook_handle__ {
695
6
  napi_async_cleanup_hook_handle__(napi_env env,
696
                                   napi_async_cleanup_hook user_hook,
697
                                   void* user_data)
698
6
      : env_(env), user_hook_(user_hook), user_data_(user_data) {
699
6
    handle_ = node::AddEnvironmentCleanupHook(env->isolate, Hook, this);
700
6
    env->Ref();
701
6
  }
702
703
18
  ~napi_async_cleanup_hook_handle__() {
704
6
    node::RemoveEnvironmentCleanupHook(std::move(handle_));
705
6
    if (done_cb_ != nullptr) done_cb_(done_data_);
706
707
    // Release the `env` handle asynchronously since it would be surprising if
708
    // a call to a N-API function would destroy `env` synchronously.
709
12
    static_cast<node_napi_env>(env_)->node_env()->SetImmediate(
710
12
        [env = env_](node::Environment*) { env->Unref(); });
711
6
  }
712
713
4
  static void Hook(void* data, void (*done_cb)(void*), void* done_data) {
714
4
    napi_async_cleanup_hook_handle__* handle =
715
        static_cast<napi_async_cleanup_hook_handle__*>(data);
716
4
    handle->done_cb_ = done_cb;
717
4
    handle->done_data_ = done_data;
718
4
    handle->user_hook_(handle, handle->user_data_);
719
4
  }
720
721
  node::AsyncCleanupHookHandle handle_;
722
  napi_env env_ = nullptr;
723
  napi_async_cleanup_hook user_hook_ = nullptr;
724
  void* user_data_ = nullptr;
725
  void (*done_cb_)(void*) = nullptr;
726
  void* done_data_ = nullptr;
727
};
728
729
napi_status NAPI_CDECL
730
6
napi_add_async_cleanup_hook(napi_env env,
731
                            napi_async_cleanup_hook hook,
732
                            void* arg,
733
                            napi_async_cleanup_hook_handle* remove_handle) {
734
6
  CHECK_ENV(env);
735
6
  CHECK_ARG(env, hook);
736
737
  napi_async_cleanup_hook_handle__* handle =
738
6
      new napi_async_cleanup_hook_handle__(env, hook, arg);
739
740
6
  if (remove_handle != nullptr) *remove_handle = handle;
741
742
6
  return napi_clear_last_error(env);
743
}
744
745
napi_status NAPI_CDECL
746
6
napi_remove_async_cleanup_hook(napi_async_cleanup_hook_handle remove_handle) {
747
6
  if (remove_handle == nullptr) return napi_invalid_arg;
748
749
6
  delete remove_handle;
750
751
6
  return napi_ok;
752
}
753
754
1
napi_status NAPI_CDECL napi_fatal_exception(napi_env env, napi_value err) {
755


2
  NAPI_PREAMBLE(env);
756
1
  CHECK_ARG(env, err);
757
758
1
  v8::Local<v8::Value> local_err = v8impl::V8LocalValueFromJsValue(err);
759
1
  static_cast<node_napi_env>(env)->trigger_fatal_exception(local_err);
760
761
1
  return napi_clear_last_error(env);
762
}
763
764
NAPI_NO_RETURN void NAPI_CDECL napi_fatal_error(const char* location,
765
                                                size_t location_len,
766
                                                const char* message,
767
                                                size_t message_len) {
768
  std::string location_string;
769
  std::string message_string;
770
771
  if (location_len != NAPI_AUTO_LENGTH) {
772
    location_string.assign(const_cast<char*>(location), location_len);
773
  } else {
774
    location_string.assign(const_cast<char*>(location), strlen(location));
775
  }
776
777
  if (message_len != NAPI_AUTO_LENGTH) {
778
    message_string.assign(const_cast<char*>(message), message_len);
779
  } else {
780
    message_string.assign(const_cast<char*>(message), strlen(message));
781
  }
782
783
  node::FatalError(location_string.c_str(), message_string.c_str());
784
}
785
786
napi_status NAPI_CDECL
787
4
napi_open_callback_scope(napi_env env,
788
                         napi_value /** ignored */,
789
                         napi_async_context async_context_handle,
790
                         napi_callback_scope* result) {
791
  // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
792
  // JS exceptions.
793
4
  CHECK_ENV(env);
794
4
  CHECK_ARG(env, result);
795
796
4
  v8impl::AsyncContext* node_async_context =
797
      reinterpret_cast<v8impl::AsyncContext*>(async_context_handle);
798
799
4
  *result = node_async_context->OpenCallbackScope();
800
801
4
  return napi_clear_last_error(env);
802
}
803
804
4
napi_status NAPI_CDECL napi_close_callback_scope(napi_env env,
805
                                                 napi_callback_scope scope) {
806
  // Omit NAPI_PREAMBLE and GET_RETURN_STATUS because V8 calls here cannot throw
807
  // JS exceptions.
808
4
  CHECK_ENV(env);
809
4
  CHECK_ARG(env, scope);
810
4
  if (env->open_callback_scopes == 0) {
811
    return napi_callback_scope_mismatch;
812
  }
813
814
4
  v8impl::AsyncContext::CloseCallbackScope(reinterpret_cast<node_napi_env>(env),
815
                                           scope);
816
817
4
  return napi_clear_last_error(env);
818
}
819
820
13
napi_status NAPI_CDECL napi_async_init(napi_env env,
821
                                       napi_value async_resource,
822
                                       napi_value async_resource_name,
823
                                       napi_async_context* result) {
824
13
  CHECK_ENV(env);
825
13
  CHECK_ARG(env, async_resource_name);
826
13
  CHECK_ARG(env, result);
827
828
13
  v8::Isolate* isolate = env->isolate;
829
13
  v8::Local<v8::Context> context = env->context();
830
831
  v8::Local<v8::Object> v8_resource;
832
  bool externally_managed_resource;
833
13
  if (async_resource != nullptr) {
834

22
    CHECK_TO_OBJECT(env, context, v8_resource, async_resource);
835
11
    externally_managed_resource = true;
836
  } else {
837
2
    v8_resource = v8::Object::New(isolate);
838
2
    externally_managed_resource = false;
839
  }
840
841
  v8::Local<v8::String> v8_resource_name;
842

26
  CHECK_TO_STRING(env, context, v8_resource_name, async_resource_name);
843
844
  v8impl::AsyncContext* async_context =
845
      new v8impl::AsyncContext(reinterpret_cast<node_napi_env>(env),
846
                               v8_resource,
847
                               v8_resource_name,
848
13
                               externally_managed_resource);
849
850
13
  *result = reinterpret_cast<napi_async_context>(async_context);
851
852
13
  return napi_clear_last_error(env);
853
}
854
855
13
napi_status NAPI_CDECL napi_async_destroy(napi_env env,
856
                                          napi_async_context async_context) {
857
13
  CHECK_ENV(env);
858
13
  CHECK_ARG(env, async_context);
859
860
13
  v8impl::AsyncContext* node_async_context =
861
      reinterpret_cast<v8impl::AsyncContext*>(async_context);
862
863
13
  delete node_async_context;
864
865
13
  return napi_clear_last_error(env);
866
}
867
868
25
napi_status NAPI_CDECL napi_make_callback(napi_env env,
869
                                          napi_async_context async_context,
870
                                          napi_value recv,
871
                                          napi_value func,
872
                                          size_t argc,
873
                                          const napi_value* argv,
874
                                          napi_value* result) {
875


50
  NAPI_PREAMBLE(env);
876
25
  CHECK_ARG(env, recv);
877
25
  if (argc > 0) {
878
4
    CHECK_ARG(env, argv);
879
  }
880
881
25
  v8::Local<v8::Context> context = env->context();
882
883
  v8::Local<v8::Object> v8recv;
884

75
  CHECK_TO_OBJECT(env, context, v8recv, recv);
885
886
  v8::Local<v8::Function> v8func;
887

75
  CHECK_TO_FUNCTION(env, v8func, func);
888
889
  v8::MaybeLocal<v8::Value> callback_result;
890
891
25
  if (async_context == nullptr) {
892
    callback_result = node::MakeCallback(
893
17
        env->isolate,
894
        v8recv,
895
        v8func,
896
        argc,
897
        reinterpret_cast<v8::Local<v8::Value>*>(const_cast<napi_value*>(argv)),
898
17
        {0, 0});
899
  } else {
900
8
    v8impl::AsyncContext* node_async_context =
901
        reinterpret_cast<v8impl::AsyncContext*>(async_context);
902
    callback_result = node_async_context->MakeCallback(
903
        v8recv,
904
        v8func,
905
        argc,
906
8
        reinterpret_cast<v8::Local<v8::Value>*>(const_cast<napi_value*>(argv)));
907
  }
908
909
25
  if (try_catch.HasCaught()) {
910
4
    return napi_set_last_error(env, napi_pending_exception);
911
  } else {
912
21
    CHECK_MAYBE_EMPTY(env, callback_result, napi_generic_failure);
913
21
    if (result != nullptr) {
914
8
      *result =
915
8
          v8impl::JsValueFromV8LocalValue(callback_result.ToLocalChecked());
916
    }
917
  }
918
919
21
  return GET_RETURN_STATUS(env);
920
}
921
922
1
napi_status NAPI_CDECL napi_create_buffer(napi_env env,
923
                                          size_t length,
924
                                          void** data,
925
                                          napi_value* result) {
926


2
  NAPI_PREAMBLE(env);
927
1
  CHECK_ARG(env, result);
928
929
1
  v8::MaybeLocal<v8::Object> maybe = node::Buffer::New(env->isolate, length);
930
931
1
  CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure);
932
933
1
  v8::Local<v8::Object> buffer = maybe.ToLocalChecked();
934
935
1
  *result = v8impl::JsValueFromV8LocalValue(buffer);
936
937
1
  if (data != nullptr) {
938
1
    *data = node::Buffer::Data(buffer);
939
  }
940
941
1
  return GET_RETURN_STATUS(env);
942
}
943
944
14
napi_status NAPI_CDECL napi_create_external_buffer(napi_env env,
945
                                                   size_t length,
946
                                                   void* data,
947
                                                   napi_finalize finalize_cb,
948
                                                   void* finalize_hint,
949
                                                   napi_value* result) {
950


28
  NAPI_PREAMBLE(env);
951
14
  CHECK_ARG(env, result);
952
953
#if defined(V8_ENABLE_SANDBOX)
954
  return napi_set_last_error(env, napi_no_external_buffers_allowed);
955
#endif
956
957
14
  v8::Isolate* isolate = env->isolate;
958
959
  // The finalizer object will delete itself after invoking the callback.
960
  v8impl::Finalizer* finalizer =
961
14
      v8impl::Finalizer::New(env,
962
                             finalize_cb,
963
                             nullptr,
964
                             finalize_hint,
965
                             v8impl::Finalizer::kKeepEnvReference);
966
967
  v8::MaybeLocal<v8::Object> maybe =
968
      node::Buffer::New(isolate,
969
                        static_cast<char*>(data),
970
                        length,
971
                        v8impl::BufferFinalizer::FinalizeBufferCallback,
972
14
                        finalizer);
973
974
14
  CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure);
975
976
14
  *result = v8impl::JsValueFromV8LocalValue(maybe.ToLocalChecked());
977
14
  return GET_RETURN_STATUS(env);
978
  // Tell coverity that 'finalizer' should not be freed when we return
979
  // as it will be deleted when the buffer to which it is associated
980
  // is finalized.
981
  // coverity[leaked_storage]
982
}
983
984
1
napi_status NAPI_CDECL napi_create_buffer_copy(napi_env env,
985
                                               size_t length,
986
                                               const void* data,
987
                                               void** result_data,
988
                                               napi_value* result) {
989


2
  NAPI_PREAMBLE(env);
990
1
  CHECK_ARG(env, result);
991
992
  v8::MaybeLocal<v8::Object> maybe =
993
1
      node::Buffer::Copy(env->isolate, static_cast<const char*>(data), length);
994
995
1
  CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure);
996
997
1
  v8::Local<v8::Object> buffer = maybe.ToLocalChecked();
998
1
  *result = v8impl::JsValueFromV8LocalValue(buffer);
999
1000
1
  if (result_data != nullptr) {
1001
    *result_data = node::Buffer::Data(buffer);
1002
  }
1003
1004
1
  return GET_RETURN_STATUS(env);
1005
}
1006
1007
1
napi_status NAPI_CDECL napi_is_buffer(napi_env env,
1008
                                      napi_value value,
1009
                                      bool* result) {
1010
1
  CHECK_ENV(env);
1011
1
  CHECK_ARG(env, value);
1012
1
  CHECK_ARG(env, result);
1013
1014
1
  *result = node::Buffer::HasInstance(v8impl::V8LocalValueFromJsValue(value));
1015
1
  return napi_clear_last_error(env);
1016
}
1017
1018
1
napi_status NAPI_CDECL napi_get_buffer_info(napi_env env,
1019
                                            napi_value value,
1020
                                            void** data,
1021
                                            size_t* length) {
1022
1
  CHECK_ENV(env);
1023
1
  CHECK_ARG(env, value);
1024
1025
1
  v8::Local<v8::Value> buffer = v8impl::V8LocalValueFromJsValue(value);
1026
1027
1
  if (data != nullptr) {
1028
1
    *data = node::Buffer::Data(buffer);
1029
  }
1030
1
  if (length != nullptr) {
1031
1
    *length = node::Buffer::Length(buffer);
1032
  }
1033
1034
1
  return napi_clear_last_error(env);
1035
}
1036
1037
1
napi_status NAPI_CDECL napi_get_node_version(napi_env env,
1038
                                             const napi_node_version** result) {
1039
1
  CHECK_ENV(env);
1040
1
  CHECK_ARG(env, result);
1041
  static const napi_node_version version = {
1042
      NODE_MAJOR_VERSION, NODE_MINOR_VERSION, NODE_PATCH_VERSION, NODE_RELEASE};
1043
1
  *result = &version;
1044
1
  return napi_clear_last_error(env);
1045
}
1046
1047
namespace {
1048
namespace uvimpl {
1049
1050
513
static napi_status ConvertUVErrorCode(int code) {
1051

513
  switch (code) {
1052
512
    case 0:
1053
512
      return napi_ok;
1054
    case UV_EINVAL:
1055
      return napi_invalid_arg;
1056
1
    case UV_ECANCELED:
1057
1
      return napi_cancelled;
1058
    default:
1059
      return napi_generic_failure;
1060
  }
1061
}
1062
1063
// Wrapper around uv_work_t which calls user-provided callbacks.
1064
class Work : public node::AsyncResource, public node::ThreadPoolWork {
1065
 private:
1066
512
  explicit Work(node_napi_env env,
1067
                v8::Local<v8::Object> async_resource,
1068
                v8::Local<v8::String> async_resource_name,
1069
                napi_async_execute_callback execute,
1070
                napi_async_complete_callback complete = nullptr,
1071
                void* data = nullptr)
1072
512
      : AsyncResource(
1073
512
            env->isolate,
1074
            async_resource,
1075
1024
            *v8::String::Utf8Value(env->isolate, async_resource_name)),
1076
        ThreadPoolWork(env->node_env(), "node_api"),
1077
        _env(env),
1078
        _data(data),
1079
        _execute(execute),
1080
1536
        _complete(complete) {}
1081
1082
2032
  ~Work() override = default;
1083
1084
 public:
1085
512
  static Work* New(node_napi_env env,
1086
                   v8::Local<v8::Object> async_resource,
1087
                   v8::Local<v8::String> async_resource_name,
1088
                   napi_async_execute_callback execute,
1089
                   napi_async_complete_callback complete,
1090
                   void* data) {
1091
    return new Work(
1092
512
        env, async_resource, async_resource_name, execute, complete, data);
1093
  }
1094
1095
508
  static void Delete(Work* work) { delete work; }
1096
1097
511
  void DoThreadPoolWork() override { _execute(_env, _data); }
1098
1099
512
  void AfterThreadPoolWork(int status) override {
1100
512
    if (_complete == nullptr) return;
1101
1102
    // Establish a handle scope here so that every callback doesn't have to.
1103
    // Also it is needed for the exception-handling below.
1104
1023
    v8::HandleScope scope(_env->isolate);
1105
1106
512
    CallbackScope callback_scope(this);
1107
1108
512
    _env->CallbackIntoModule<true>([&](napi_env env) {
1109
512
      _complete(env, ConvertUVErrorCode(status), _data);
1110
512
    });
1111
1112
    // Note: Don't access `work` after this point because it was
1113
    // likely deleted by the complete callback.
1114
  }
1115
1116
 private:
1117
  node_napi_env _env;
1118
  void* _data;
1119
  napi_async_execute_callback _execute;
1120
  napi_async_complete_callback _complete;
1121
};
1122
1123
}  // end of namespace uvimpl
1124
}  // end of anonymous namespace
1125
1126
#define CALL_UV(env, condition)                                                \
1127
  do {                                                                         \
1128
    int result = (condition);                                                  \
1129
    napi_status status = uvimpl::ConvertUVErrorCode(result);                   \
1130
    if (status != napi_ok) {                                                   \
1131
      return napi_set_last_error(env, status, result);                         \
1132
    }                                                                          \
1133
  } while (0)
1134
1135
napi_status NAPI_CDECL
1136
512
napi_create_async_work(napi_env env,
1137
                       napi_value async_resource,
1138
                       napi_value async_resource_name,
1139
                       napi_async_execute_callback execute,
1140
                       napi_async_complete_callback complete,
1141
                       void* data,
1142
                       napi_async_work* result) {
1143
512
  CHECK_ENV(env);
1144
512
  CHECK_ARG(env, execute);
1145
512
  CHECK_ARG(env, result);
1146
1147
512
  v8::Local<v8::Context> context = env->context();
1148
1149
  v8::Local<v8::Object> resource;
1150
512
  if (async_resource != nullptr) {
1151

12
    CHECK_TO_OBJECT(env, context, resource, async_resource);
1152
  } else {
1153
508
    resource = v8::Object::New(env->isolate);
1154
  }
1155
1156
  v8::Local<v8::String> resource_name;
1157

1024
  CHECK_TO_STRING(env, context, resource_name, async_resource_name);
1158
1159
512
  uvimpl::Work* work = uvimpl::Work::New(reinterpret_cast<node_napi_env>(env),
1160
                                         resource,
1161
                                         resource_name,
1162
                                         execute,
1163
                                         complete,
1164
                                         data);
1165
1166
512
  *result = reinterpret_cast<napi_async_work>(work);
1167
1168
512
  return napi_clear_last_error(env);
1169
}
1170
1171
508
napi_status NAPI_CDECL napi_delete_async_work(napi_env env,
1172
                                              napi_async_work work) {
1173
508
  CHECK_ENV(env);
1174
508
  CHECK_ARG(env, work);
1175
1176
508
  uvimpl::Work::Delete(reinterpret_cast<uvimpl::Work*>(work));
1177
1178
508
  return napi_clear_last_error(env);
1179
}
1180
1181
518
napi_status NAPI_CDECL napi_get_uv_event_loop(napi_env env, uv_loop_t** loop) {
1182
518
  CHECK_ENV(env);
1183
518
  CHECK_ARG(env, loop);
1184
518
  *loop = reinterpret_cast<node_napi_env>(env)->node_env()->event_loop();
1185
518
  return napi_clear_last_error(env);
1186
}
1187
1188
512
napi_status NAPI_CDECL napi_queue_async_work(napi_env env,
1189
                                             napi_async_work work) {
1190
512
  CHECK_ENV(env);
1191
512
  CHECK_ARG(env, work);
1192
1193
512
  uv_loop_t* event_loop = nullptr;
1194
512
  STATUS_CALL(napi_get_uv_event_loop(env, &event_loop));
1195
1196
512
  uvimpl::Work* w = reinterpret_cast<uvimpl::Work*>(work);
1197
1198
512
  w->ScheduleWork();
1199
1200
512
  return napi_clear_last_error(env);
1201
}
1202
1203
1
napi_status NAPI_CDECL napi_cancel_async_work(napi_env env,
1204
                                              napi_async_work work) {
1205
1
  CHECK_ENV(env);
1206
1
  CHECK_ARG(env, work);
1207
1208
1
  uvimpl::Work* w = reinterpret_cast<uvimpl::Work*>(work);
1209
1210
1
  CALL_UV(env, w->CancelWork());
1211
1212
1
  return napi_clear_last_error(env);
1213
}
1214
1215
napi_status NAPI_CDECL
1216
20
napi_create_threadsafe_function(napi_env env,
1217
                                napi_value func,
1218
                                napi_value async_resource,
1219
                                napi_value async_resource_name,
1220
                                size_t max_queue_size,
1221
                                size_t initial_thread_count,
1222
                                void* thread_finalize_data,
1223
                                napi_finalize thread_finalize_cb,
1224
                                void* context,
1225
                                napi_threadsafe_function_call_js call_js_cb,
1226
                                napi_threadsafe_function* result) {
1227
20
  CHECK_ENV(env);
1228
20
  CHECK_ARG(env, async_resource_name);
1229
20
  RETURN_STATUS_IF_FALSE(env, initial_thread_count > 0, napi_invalid_arg);
1230
20
  CHECK_ARG(env, result);
1231
1232
20
  napi_status status = napi_ok;
1233
1234
  v8::Local<v8::Function> v8_func;
1235
20
  if (func == nullptr) {
1236
3
    CHECK_ARG(env, call_js_cb);
1237
  } else {
1238

51
    CHECK_TO_FUNCTION(env, v8_func, func);
1239
  }
1240
1241
20
  v8::Local<v8::Context> v8_context = env->context();
1242
1243
  v8::Local<v8::Object> v8_resource;
1244
20
  if (async_resource == nullptr) {
1245
18
    v8_resource = v8::Object::New(env->isolate);
1246
  } else {
1247

6
    CHECK_TO_OBJECT(env, v8_context, v8_resource, async_resource);
1248
  }
1249
1250
  v8::Local<v8::String> v8_name;
1251

40
  CHECK_TO_STRING(env, v8_context, v8_name, async_resource_name);
1252
1253
  v8impl::ThreadSafeFunction* ts_fn =
1254
      new v8impl::ThreadSafeFunction(v8_func,
1255
                                     v8_resource,
1256
                                     v8_name,
1257
                                     initial_thread_count,
1258
                                     context,
1259
                                     max_queue_size,
1260
                                     reinterpret_cast<node_napi_env>(env),
1261
                                     thread_finalize_data,
1262
                                     thread_finalize_cb,
1263
20
                                     call_js_cb);
1264
1265
20
  if (ts_fn == nullptr) {
1266
    status = napi_generic_failure;
1267
  } else {
1268
    // Init deletes ts_fn upon failure.
1269
20
    status = ts_fn->Init();
1270
20
    if (status == napi_ok) {
1271
20
      *result = reinterpret_cast<napi_threadsafe_function>(ts_fn);
1272
    }
1273
  }
1274
1275
20
  return napi_set_last_error(env, status);
1276
}
1277
1278
16
napi_status NAPI_CDECL napi_get_threadsafe_function_context(
1279
    napi_threadsafe_function func, void** result) {
1280
16
  CHECK_NOT_NULL(func);
1281
16
  CHECK_NOT_NULL(result);
1282
1283
16
  *result = reinterpret_cast<v8impl::ThreadSafeFunction*>(func)->Context();
1284
16
  return napi_ok;
1285
}
1286
1287
napi_status NAPI_CDECL
1288
4603950
napi_call_threadsafe_function(napi_threadsafe_function func,
1289
                              void* data,
1290
                              napi_threadsafe_function_call_mode is_blocking) {
1291
4603950
  CHECK_NOT_NULL(func);
1292
4603950
  return reinterpret_cast<v8impl::ThreadSafeFunction*>(func)->Push(data,
1293
4603950
                                                                   is_blocking);
1294
}
1295
1296
napi_status NAPI_CDECL
1297
4
napi_acquire_threadsafe_function(napi_threadsafe_function func) {
1298
4
  CHECK_NOT_NULL(func);
1299
4
  return reinterpret_cast<v8impl::ThreadSafeFunction*>(func)->Acquire();
1300
}
1301
1302
35
napi_status NAPI_CDECL napi_release_threadsafe_function(
1303
    napi_threadsafe_function func, napi_threadsafe_function_release_mode mode) {
1304
35
  CHECK_NOT_NULL(func);
1305
35
  return reinterpret_cast<v8impl::ThreadSafeFunction*>(func)->Release(mode);
1306
}
1307
1308
napi_status NAPI_CDECL
1309
2
napi_unref_threadsafe_function(napi_env env, napi_threadsafe_function func) {
1310
2
  CHECK_NOT_NULL(func);
1311
2
  return reinterpret_cast<v8impl::ThreadSafeFunction*>(func)->Unref();
1312
}
1313
1314
napi_status NAPI_CDECL
1315
napi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func) {
1316
  CHECK_NOT_NULL(func);
1317
  return reinterpret_cast<v8impl::ThreadSafeFunction*>(func)->Ref();
1318
}
1319
1320
2
napi_status NAPI_CDECL node_api_get_module_file_name(napi_env env,
1321
                                                     const char** result) {
1322
2
  CHECK_ENV(env);
1323
2
  CHECK_ARG(env, result);
1324
1325
2
  *result = static_cast<node_napi_env>(env)->GetFilename();
1326
2
  return napi_clear_last_error(env);
1327
}