GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node_api.cc Lines: 529 573 92.3 %
Date: 2022-09-25 04:23:55 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
96
node_napi_env__::node_napi_env__(v8::Local<v8::Context> context,
23
96
                                 const std::string& module_filename)
24
96
    : napi_env__(context), filename(module_filename) {
25
96
  CHECK_NOT_NULL(node_env());
26
96
}
27
28
94
void node_napi_env__::DeleteMe() {
29
94
  destructing = true;
30
94
  napi_env__::DeleteMe();
31
94
}
32
33
119803
bool node_napi_env__::can_call_into_js() const {
34
119803
  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
1576
void node_napi_env__::CallFinalizer(napi_finalize cb, void* data, void* hint) {
45
1576
  CallFinalizer<true>(cb, data, hint);
46
1576
}
47
48
template <bool enforceUncaughtExceptionPolicy>
49
1576
void node_napi_env__::CallFinalizer(napi_finalize cb, void* data, void* hint) {
50
1576
  if (destructing) {
51
    // we can not defer finalizers when the environment is being destructed.
52
1092
    v8::HandleScope handle_scope(isolate);
53
546
    v8::Context::Scope context_scope(context());
54
546
    CallbackIntoModule<enforceUncaughtExceptionPolicy>(
55
546
        [&](napi_env env) { cb(env, data, hint); });
56
546
    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
234222
void node_napi_env__::CallbackIntoModule(T&& call) {
83
234231
  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
234218
}
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
96
inline napi_env NewEnv(v8::Local<v8::Context> context,
129
                       const std::string& module_filename) {
130
  node_napi_env result;
131
132
96
  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
96
  result->node_env()->AddCleanupHook(
141
94
      [](void* arg) { static_cast<napi_env>(arg)->Unref(); },
142
      static_cast<void*>(result));
143
144
96
  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
2847763
  napi_status Push(void* data, napi_threadsafe_function_call_mode mode) {
185
5695526
    node::Mutex::ScopedLock lock(this->mutex);
186
187

5684434
    while (queue.size() >= max_queue_size && max_queue_size > 0 &&
188
2784711
           !is_closing) {
189
2784708
      if (mode == napi_tsfn_nonblocking) {
190
2732748
        return napi_queue_full;
191
      }
192
51960
      cond->Wait(lock);
193
    }
194
195
115015
    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
115010
      queue.push(data);
204
115010
      Send();
205
115010
      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
165
  void Dispatch() {
299
165
    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
165
    unsigned int iterations_left = kMaxIterationCount;
304

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

115003
          if (size == max_queue_size && max_queue_size > 0) {
335
87971
            cond->Signal(lock);
336
          }
337
115003
          size--;
338
        }
339
340
115011
        if (size == 0) {
341
63
          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
114948
          has_more = true;
350
        }
351
      }
352
    }
353
354
115014
    if (popped_value) {
355
230006
      v8::HandleScope scope(env->isolate);
356
115003
      CallbackScope cb_scope(this);
357
115003
      napi_value js_callback = nullptr;
358
115003
      if (!ref.IsEmpty()) {
359
        v8::Local<v8::Function> js_cb =
360
210002
            v8::Local<v8::Function>::New(env->isolate, ref);
361
105001
        js_callback = v8impl::JsValueFromV8LocalValue(js_cb);
362
      }
363
115003
      env->CallbackIntoModule<false>(
364
115003
          [&](napi_env env) { call_js_cb(env, js_callback, context, data); });
365
    }
366
367
115014
    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
115138
  void Send() {
406
    // Ask currently running Dispatch() to make one more iteration
407
115138
    unsigned char current_state = dispatch_state.fetch_or(kDispatchPending);
408
115138
    if ((current_state & kDispatchRunning) == kDispatchRunning) {
409
105854
      return;
410
    }
411
412
9284
    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
165
  static void AsyncCb(uv_async_t* async) {
440
    ThreadSafeFunction* ts_fn =
441
165
        node::ContainerOf(&ThreadSafeFunction::async, async);
442
165
    ts_fn->Dispatch();
443
165
  }
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
92
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
92
  napi_module_register_by_symbol(
597
      exports,
598
      module,
599
      context,
600
92
      static_cast<const napi_module*>(priv)->nm_register_func);
601
92
}
602
603
97
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
97
  node::Environment* node_env = node::Environment::GetCurrent(context);
608
97
  std::string module_filename = "";
609
97
  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
96
  if (module->ToObject(context).ToLocal(&modobj) &&
622

480
      modobj->Get(context, node_env->filename_string()).ToLocal(&filename_js) &&
623
192
      filename_js->IsString()) {
624
91
    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
91
    module_filename = node::url::URL::FromFilePath(filename.ToString()).href();
631
  }
632
633
  // Create a new napi_env for this specific module.
634
96
  napi_env env = v8impl::NewEnv(context, module_filename);
635
636
  napi_value _exports;
637
96
  env->CallIntoModule([&](napi_env env) {
638
96
    _exports = init(env, v8impl::JsValueFromV8LocalValue(exports));
639
96
  });
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
186
  if (_exports != nullptr &&
645

186
      _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
91
node_module napi_module_to_node_module(const napi_module* mod) {
653
  return {
654
      -1,
655
91
      mod->nm_flags | NM_F_DELETEME,
656
      nullptr,
657
91
      mod->nm_filename,
658
      nullptr,
659
      napi_module_register_cb,
660
91
      mod->nm_modname,
661
      const_cast<napi_module*>(mod),  // priv
662
      nullptr,
663
91
  };
664
}
665
}  // namespace node
666
667
// Registers a NAPI module.
668
88
void NAPI_CDECL napi_module_register(napi_module* mod) {
669
  node::node_module* nm =
670
88
      new node::node_module(node::napi_module_to_node_module(mod));
671
88
  node::node_module_register(nm);
672
88
}
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
14
  v8::Isolate* isolate = env->isolate;
954
955
  // The finalizer object will delete itself after invoking the callback.
956
  v8impl::Finalizer* finalizer =
957
14
      v8impl::Finalizer::New(env,
958
                             finalize_cb,
959
                             nullptr,
960
                             finalize_hint,
961
                             v8impl::Finalizer::kKeepEnvReference);
962
963
  v8::MaybeLocal<v8::Object> maybe =
964
      node::Buffer::New(isolate,
965
                        static_cast<char*>(data),
966
                        length,
967
                        v8impl::BufferFinalizer::FinalizeBufferCallback,
968
14
                        finalizer);
969
970
14
  CHECK_MAYBE_EMPTY(env, maybe, napi_generic_failure);
971
972
14
  *result = v8impl::JsValueFromV8LocalValue(maybe.ToLocalChecked());
973
14
  return GET_RETURN_STATUS(env);
974
  // Tell coverity that 'finalizer' should not be freed when we return
975
  // as it will be deleted when the buffer to which it is associated
976
  // is finalized.
977
  // coverity[leaked_storage]
978
}
979
980
1
napi_status NAPI_CDECL napi_create_buffer_copy(napi_env env,
981
                                               size_t length,
982
                                               const void* data,
983
                                               void** result_data,
984
                                               napi_value* result) {
985


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

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

12
    CHECK_TO_OBJECT(env, context, resource, async_resource);
1148
  } else {
1149
508
    resource = v8::Object::New(env->isolate);
1150
  }
1151
1152
  v8::Local<v8::String> resource_name;
1153

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

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

6
    CHECK_TO_OBJECT(env, v8_context, v8_resource, async_resource);
1244
  }
1245
1246
  v8::Local<v8::String> v8_name;
1247

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