GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: js_native_api_v8.h Lines: 104 107 97.2 %
Date: 2021-12-25 04:14:02 Branches: 25 32 78.1 %

Line Branch Exec Source
1
#ifndef SRC_JS_NATIVE_API_V8_H_
2
#define SRC_JS_NATIVE_API_V8_H_
3
4
// This file needs to be compatible with C compilers.
5
#include <string.h>  // NOLINT(modernize-deprecated-headers)
6
#include "js_native_api_types.h"
7
#include "js_native_api_v8_internals.h"
8
9
static napi_status napi_clear_last_error(napi_env env);
10
11
namespace v8impl {
12
13
class RefTracker {
14
 public:
15
3248
  RefTracker() {}
16
6468
  virtual ~RefTracker() {}
17
  virtual void Finalize(bool isEnvTeardown) {}
18
19
  typedef RefTracker RefList;
20
21
3068
  inline void Link(RefList* list) {
22
3068
    prev_ = list;
23
3068
    next_ = list->next_;
24
3068
    if (next_ != nullptr) {
25
2442
      next_->prev_ = this;
26
    }
27
3068
    list->next_ = this;
28
3068
  }
29
30
3058
  inline void Unlink() {
31
3058
    if (prev_ != nullptr) {
32
3058
      prev_->next_ = next_;
33
    }
34
3058
    if (next_ != nullptr) {
35
1433
      next_->prev_ = prev_;
36
    }
37
3058
    prev_ = nullptr;
38
3058
    next_ = nullptr;
39
3058
  }
40
41
679
  static void FinalizeAll(RefList* list) {
42
679
    while (list->next_ != nullptr) {
43
503
      list->next_->Finalize(true);
44
    }
45
176
  }
46
47
 private:
48
  RefList* next_ = nullptr;
49
  RefList* prev_ = nullptr;
50
};
51
52
}  // end of namespace v8impl
53
54
struct napi_env__ {
55
90
  explicit napi_env__(v8::Local<v8::Context> context)
56
90
      : isolate(context->GetIsolate()),
57
360
        context_persistent(isolate, context) {
58
90
    CHECK_EQ(isolate, context->GetIsolate());
59
90
  }
60
352
  virtual ~napi_env__() {
61
    // First we must finalize those references that have `napi_finalizer`
62
    // callbacks. The reason is that addons might store other references which
63
    // they delete during their `napi_finalizer` callbacks. If we deleted such
64
    // references here first, they would be doubly deleted when the
65
    // `napi_finalizer` deleted them subsequently.
66
176
    v8impl::RefTracker::FinalizeAll(&finalizing_reflist);
67
176
    v8impl::RefTracker::FinalizeAll(&reflist);
68
  }
69
  v8::Isolate* const isolate;  // Shortcut for context()->GetIsolate()
70
  v8impl::Persistent<v8::Context> context_persistent;
71
72
243261
  inline v8::Local<v8::Context> context() const {
73
243261
    return v8impl::PersistentToLocal::Strong(context_persistent);
74
  }
75
76
1050
  inline void Ref() { refs++; }
77

1138
  inline void Unref() { if ( --refs == 0) delete this; }
78
79
2
  virtual bool can_call_into_js() const { return true; }
80
  virtual v8::Maybe<bool> mark_arraybuffer_as_untransferable(
81
      v8::Local<v8::ArrayBuffer> ab) const {
82
    return v8::Just(true);
83
  }
84
85
  static inline void
86
4
  HandleThrow(napi_env env, v8::Local<v8::Value> value) {
87
4
    env->isolate->ThrowException(value);
88
4
  }
89
90
  template <typename T, typename U = decltype(HandleThrow)>
91
238488
  inline void CallIntoModule(T&& call, U&& handle_exception = HandleThrow) {
92
238488
    int open_handle_scopes_before = open_handle_scopes;
93
238488
    int open_callback_scopes_before = open_callback_scopes;
94
238488
    napi_clear_last_error(this);
95
238488
    call(this);
96
238488
    CHECK_EQ(open_handle_scopes, open_handle_scopes_before);
97
238488
    CHECK_EQ(open_callback_scopes, open_callback_scopes_before);
98
238488
    if (!last_exception.IsEmpty()) {
99
2486
      handle_exception(this, last_exception.Get(this->isolate));
100
1241
      last_exception.Reset();
101
    }
102
238486
  }
103
104
491
  virtual void CallFinalizer(napi_finalize cb, void* data, void* hint) {
105
491
    v8::HandleScope handle_scope(isolate);
106
491
    CallIntoModule([&](napi_env env) {
107
491
      cb(env, data, hint);
108
491
    });
109
491
  }
110
111
  v8impl::Persistent<v8::Value> last_exception;
112
113
  // We store references in two different lists, depending on whether they have
114
  // `napi_finalizer` callbacks, because we must first finalize the ones that
115
  // have such a callback. See `~napi_env__()` above for details.
116
  v8impl::RefTracker::RefList reflist;
117
  v8impl::RefTracker::RefList finalizing_reflist;
118
  napi_extended_error_info last_error;
119
  int open_handle_scopes = 0;
120
  int open_callback_scopes = 0;
121
  int refs = 1;
122
  void* instance_data = nullptr;
123
};
124
125
// This class is used to keep a napi_env live in a way that
126
// is exception safe versus calling Ref/Unref directly
127
class EnvRefHolder {
128
 public:
129
1013
  explicit EnvRefHolder(napi_env env) : _env(env) {
130
1013
      _env->Ref();
131
1013
  }
132
133
  explicit EnvRefHolder(const EnvRefHolder& other): _env(other.env()) {
134
    _env->Ref();
135
  }
136
137
2026
  EnvRefHolder(EnvRefHolder&& other) {
138
2026
    _env = other._env;
139
2026
    other._env = nullptr;
140
2026
  }
141
142
6078
  ~EnvRefHolder() {
143
3039
    if (_env != nullptr) {
144
1013
      _env->Unref();
145
    }
146
3039
  }
147
148
1013
  napi_env env(void) const {
149
1013
    return _env;
150
  }
151
152
 private:
153
  napi_env _env;
154
};
155
156
603225
static inline napi_status napi_clear_last_error(napi_env env) {
157
603225
  env->last_error.error_code = napi_ok;
158
159
  // TODO(boingoing): Should this be a callback?
160
603225
  env->last_error.engine_error_code = 0;
161
603225
  env->last_error.engine_reserved = nullptr;
162
603225
  env->last_error.error_message = nullptr;
163
603225
  return napi_ok;
164
}
165
166
static inline
167
1346
napi_status napi_set_last_error(napi_env env, napi_status error_code,
168
                                uint32_t engine_error_code = 0,
169
                                void* engine_reserved = nullptr) {
170
1346
  env->last_error.error_code = error_code;
171
1346
  env->last_error.engine_error_code = engine_error_code;
172
1346
  env->last_error.engine_reserved = engine_reserved;
173
1346
  return error_code;
174
}
175
176
#define RETURN_STATUS_IF_FALSE(env, condition, status)                  \
177
  do {                                                                  \
178
    if (!(condition)) {                                                 \
179
      return napi_set_last_error((env), (status));                      \
180
    }                                                                   \
181
  } while (0)
182
183
#define RETURN_STATUS_IF_FALSE_WITH_PREAMBLE(env, condition, status)           \
184
  do {                                                                         \
185
    if (!(condition)) {                                                        \
186
      return napi_set_last_error(                                              \
187
          (env), try_catch.HasCaught() ? napi_pending_exception : (status));   \
188
    }                                                                          \
189
  } while (0)
190
191
#define CHECK_ENV(env)          \
192
  do {                          \
193
    if ((env) == nullptr) {     \
194
      return napi_invalid_arg;  \
195
    }                           \
196
  } while (0)
197
198
#define CHECK_ARG(env, arg) \
199
  RETURN_STATUS_IF_FALSE((env), ((arg) != nullptr), napi_invalid_arg)
200
201
#define CHECK_ARG_WITH_PREAMBLE(env, arg)                  \
202
  RETURN_STATUS_IF_FALSE_WITH_PREAMBLE((env),              \
203
                                       ((arg) != nullptr), \
204
                                       napi_invalid_arg)
205
206
#define CHECK_MAYBE_EMPTY(env, maybe, status) \
207
  RETURN_STATUS_IF_FALSE((env), !((maybe).IsEmpty()), (status))
208
209
#define CHECK_MAYBE_EMPTY_WITH_PREAMBLE(env, maybe, status)                    \
210
  RETURN_STATUS_IF_FALSE_WITH_PREAMBLE((env), !((maybe).IsEmpty()), (status))
211
212
// NAPI_PREAMBLE is not wrapped in do..while: try_catch must have function scope
213
#define NAPI_PREAMBLE(env)                                          \
214
  CHECK_ENV((env));                                                 \
215
  RETURN_STATUS_IF_FALSE((env),                                     \
216
      (env)->last_exception.IsEmpty() && (env)->can_call_into_js(), \
217
      napi_pending_exception);                                      \
218
  napi_clear_last_error((env));                                     \
219
  v8impl::TryCatch try_catch((env))
220
221
#define CHECK_TO_TYPE(env, type, context, result, src, status)                \
222
  do {                                                                        \
223
    CHECK_ARG((env), (src));                                                  \
224
    auto maybe = v8impl::V8LocalValueFromJsValue((src))->To##type((context)); \
225
    CHECK_MAYBE_EMPTY((env), maybe, (status));                                \
226
    (result) = maybe.ToLocalChecked();                                        \
227
  } while (0)
228
229
#define CHECK_TO_TYPE_WITH_PREAMBLE(env, type, context, result, src, status)  \
230
  do {                                                                        \
231
    CHECK_ARG_WITH_PREAMBLE((env), (src));                                    \
232
    auto maybe = v8impl::V8LocalValueFromJsValue((src))->To##type((context)); \
233
    CHECK_MAYBE_EMPTY_WITH_PREAMBLE((env), maybe, (status));                  \
234
    (result) = maybe.ToLocalChecked();                                        \
235
  } while (0)
236
237
#define CHECK_TO_FUNCTION(env, result, src)                                 \
238
  do {                                                                      \
239
    CHECK_ARG((env), (src));                                                \
240
    v8::Local<v8::Value> v8value = v8impl::V8LocalValueFromJsValue((src));  \
241
    RETURN_STATUS_IF_FALSE((env), v8value->IsFunction(), napi_invalid_arg); \
242
    (result) = v8value.As<v8::Function>();                                  \
243
  } while (0)
244
245
#define CHECK_TO_OBJECT(env, context, result, src) \
246
  CHECK_TO_TYPE((env), Object, (context), (result), (src), napi_object_expected)
247
248
#define CHECK_TO_OBJECT_WITH_PREAMBLE(env, context, result, src) \
249
  CHECK_TO_TYPE_WITH_PREAMBLE((env),                             \
250
                              Object,                            \
251
                              (context),                         \
252
                              (result),                          \
253
                              (src),                             \
254
                              napi_object_expected)
255
256
#define CHECK_TO_STRING(env, context, result, src) \
257
  CHECK_TO_TYPE((env), String, (context), (result), (src), napi_string_expected)
258
259
#define GET_RETURN_STATUS(env)      \
260
  (!try_catch.HasCaught() ? napi_ok \
261
                         : napi_set_last_error((env), napi_pending_exception))
262
263
#define THROW_RANGE_ERROR_IF_FALSE(env, condition, error, message) \
264
  do {                                                             \
265
    if (!(condition)) {                                            \
266
      napi_throw_range_error((env), (error), (message));           \
267
      return napi_set_last_error((env), napi_generic_failure);     \
268
    }                                                              \
269
  } while (0)
270
271
#define RETURN_STATUS_IF_FALSE_WITH_PREAMBLE(env, condition, status)           \
272
  do {                                                                         \
273
    if (!(condition)) {                                                        \
274
      return napi_set_last_error(                                              \
275
          (env), try_catch.HasCaught() ? napi_pending_exception : (status));   \
276
    }                                                                          \
277
  } while (0)
278
279
#define CHECK_MAYBE_EMPTY_WITH_PREAMBLE(env, maybe, status)                    \
280
  RETURN_STATUS_IF_FALSE_WITH_PREAMBLE((env), !((maybe).IsEmpty()), (status))
281
282
namespace v8impl {
283
284
//=== Conversion between V8 Handles and napi_value ========================
285
286
// This asserts v8::Local<> will always be implemented with a single
287
// pointer field so that we can pass it around as a void*.
288
static_assert(sizeof(v8::Local<v8::Value>) == sizeof(napi_value),
289
  "Cannot convert between v8::Local<v8::Value> and napi_value");
290
291
351013
inline napi_value JsValueFromV8LocalValue(v8::Local<v8::Value> local) {
292
351013
  return reinterpret_cast<napi_value>(*local);
293
}
294
295
243294
inline v8::Local<v8::Value> V8LocalValueFromJsValue(napi_value v) {
296
  v8::Local<v8::Value> local;
297
243294
  memcpy(static_cast<void*>(&local), &v, sizeof(v));
298
243294
  return local;
299
}
300
301
// Adapter for napi_finalize callbacks.
302
class Finalizer {
303
 public:
304
  // Some Finalizers are run during shutdown when the napi_env is destroyed,
305
  // and some need to keep an explicit reference to the napi_env because they
306
  // are run independently.
307
  enum EnvReferenceMode {
308
    kNoEnvReference,
309
    kKeepEnvReference
310
  };
311
312
 protected:
313
3081
  Finalizer(napi_env env,
314
            napi_finalize finalize_callback,
315
            void* finalize_data,
316
            void* finalize_hint,
317
            EnvReferenceMode refmode = kNoEnvReference)
318
3081
    : _env(env),
319
      _finalize_callback(finalize_callback),
320
      _finalize_data(finalize_data),
321
      _finalize_hint(finalize_hint),
322
3081
      _has_env_reference(refmode == kKeepEnvReference) {
323
3081
    if (_has_env_reference)
324
13
      _env->Ref();
325
3081
  }
326
327
6142
  ~Finalizer() {
328
3071
    if (_has_env_reference)
329
13
      _env->Unref();
330
3071
  }
331
332
 public:
333
13
  static Finalizer* New(napi_env env,
334
                        napi_finalize finalize_callback = nullptr,
335
                        void* finalize_data = nullptr,
336
                        void* finalize_hint = nullptr,
337
                        EnvReferenceMode refmode = kNoEnvReference) {
338
    return new Finalizer(
339
13
        env, finalize_callback, finalize_data, finalize_hint, refmode);
340
  }
341
342
13
  static void Delete(Finalizer* finalizer) {
343
13
    delete finalizer;
344
13
  }
345
346
 protected:
347
  napi_env _env;
348
  napi_finalize _finalize_callback;
349
  void* _finalize_data;
350
  void* _finalize_hint;
351
  bool _finalize_ran = false;
352
  bool _has_env_reference = false;
353
};
354
355
class TryCatch : public v8::TryCatch {
356
 public:
357
119538
  explicit TryCatch(napi_env env)
358
119538
      : v8::TryCatch(env->isolate), _env(env) {}
359
360
119538
  ~TryCatch() {
361
119538
    if (HasCaught()) {
362
2478
      _env->last_exception.Reset(_env->isolate, Exception());
363
    }
364
119538
  }
365
366
 private:
367
  napi_env _env;
368
};
369
370
// Wrapper around v8impl::Persistent that implements reference counting.
371
class RefBase : protected Finalizer, RefTracker {
372
 protected:
373
  RefBase(napi_env env,
374
          uint32_t initial_refcount,
375
          bool delete_self,
376
          napi_finalize finalize_callback,
377
          void* finalize_data,
378
          void* finalize_hint);
379
380
 public:
381
  static RefBase* New(napi_env env,
382
                      uint32_t initial_refcount,
383
                      bool delete_self,
384
                      napi_finalize finalize_callback,
385
                      void* finalize_data,
386
                      void* finalize_hint);
387
388
  static inline void Delete(RefBase* reference);
389
390
  virtual ~RefBase();
391
  void* Data();
392
  uint32_t Ref();
393
  uint32_t Unref();
394
  uint32_t RefCount();
395
396
 protected:
397
  void Finalize(bool is_env_teardown = false) override;
398
399
 private:
400
  uint32_t _refcount;
401
  bool _delete_self;
402
};
403
404
class Reference : public RefBase {
405
  using SecondPassCallParameterRef = Reference*;
406
407
 protected:
408
  template <typename... Args>
409
  Reference(napi_env env, v8::Local<v8::Value> value, Args&&... args);
410
411
 public:
412
  static Reference* New(napi_env env,
413
                        v8::Local<v8::Value> value,
414
                        uint32_t initial_refcount,
415
                        bool delete_self,
416
                        napi_finalize finalize_callback = nullptr,
417
                        void* finalize_data = nullptr,
418
                        void* finalize_hint = nullptr);
419
420
  virtual ~Reference();
421
  uint32_t Ref();
422
  uint32_t Unref();
423
  v8::Local<v8::Value> Get();
424
425
 protected:
426
  void Finalize(bool is_env_teardown = false) override;
427
428
 private:
429
  void ClearWeak();
430
  void SetWeak();
431
432
  static void FinalizeCallback(
433
      const v8::WeakCallbackInfo<SecondPassCallParameterRef>& data);
434
  static void SecondPassCallback(
435
      const v8::WeakCallbackInfo<SecondPassCallParameterRef>& data);
436
437
  v8impl::Persistent<v8::Value> _persistent;
438
  SecondPassCallParameterRef* _secondPassParameter;
439
  bool _secondPassScheduled;
440
441
  FRIEND_TEST(JsNativeApiV8Test, Reference);
442
};
443
444
}  // end of namespace v8impl
445
446
#define STATUS_CALL(call)                 \
447
  do {                                    \
448
    napi_status status = (call);          \
449
    if (status != napi_ok) return status; \
450
  } while (0)
451
452
#endif  // SRC_JS_NATIVE_API_V8_H_