GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node.h Lines: 4 4 100.0 %
Date: 2019-08-17 22:35:23 Branches: 2 4 50.0 %

Line Branch Exec Source
1
// Copyright Joyent, Inc. and other Node contributors.
2
//
3
// Permission is hereby granted, free of charge, to any person obtaining a
4
// copy of this software and associated documentation files (the
5
// "Software"), to deal in the Software without restriction, including
6
// without limitation the rights to use, copy, modify, merge, publish,
7
// distribute, sublicense, and/or sell copies of the Software, and to permit
8
// persons to whom the Software is furnished to do so, subject to the
9
// following conditions:
10
//
11
// The above copyright notice and this permission notice shall be included
12
// in all copies or substantial portions of the Software.
13
//
14
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
19
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
20
// USE OR OTHER DEALINGS IN THE SOFTWARE.
21
22
#ifndef SRC_NODE_H_
23
#define SRC_NODE_H_
24
25
#ifdef _WIN32
26
# ifndef BUILDING_NODE_EXTENSION
27
#  define NODE_EXTERN __declspec(dllexport)
28
# else
29
#  define NODE_EXTERN __declspec(dllimport)
30
# endif
31
#else
32
# define NODE_EXTERN __attribute__((visibility("default")))
33
#endif
34
35
#ifdef BUILDING_NODE_EXTENSION
36
# undef BUILDING_V8_SHARED
37
# undef BUILDING_UV_SHARED
38
# define USING_V8_SHARED 1
39
# define USING_UV_SHARED 1
40
#endif
41
42
// This should be defined in make system.
43
// See issue https://github.com/nodejs/node-v0.x-archive/issues/1236
44
#if defined(__MINGW32__) || defined(_MSC_VER)
45
#ifndef _WIN32_WINNT
46
# define _WIN32_WINNT 0x0600  // Windows Server 2008
47
#endif
48
49
#ifndef NOMINMAX
50
# define NOMINMAX
51
#endif
52
53
#endif
54
55
#if defined(_MSC_VER)
56
#define PATH_MAX MAX_PATH
57
#endif
58
59
#ifdef _WIN32
60
# define SIGKILL 9
61
#endif
62
63
#include "v8.h"  // NOLINT(build/include_order)
64
#include "v8-platform.h"  // NOLINT(build/include_order)
65
#include "node_version.h"  // NODE_MODULE_VERSION
66
67
#include <memory>
68
69
// We cannot use __POSIX__ in this header because that's only defined when
70
// building Node.js.
71
#ifndef _WIN32
72
#include <signal.h>
73
#endif  // _WIN32
74
75
#define NODE_MAKE_VERSION(major, minor, patch)                                \
76
  ((major) * 0x1000 + (minor) * 0x100 + (patch))
77
78
#ifdef __clang__
79
# define NODE_CLANG_AT_LEAST(major, minor, patch)                             \
80
  (NODE_MAKE_VERSION(major, minor, patch) <=                                  \
81
      NODE_MAKE_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__))
82
#else
83
# define NODE_CLANG_AT_LEAST(major, minor, patch) (0)
84
#endif
85
86
#ifdef __GNUC__
87
# define NODE_GNUC_AT_LEAST(major, minor, patch)                              \
88
  (NODE_MAKE_VERSION(major, minor, patch) <=                                  \
89
      NODE_MAKE_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__))
90
#else
91
# define NODE_GNUC_AT_LEAST(major, minor, patch) (0)
92
#endif
93
94
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
95
# define NODE_DEPRECATED(message, declarator) declarator
96
#else  // NODE_WANT_INTERNALS
97
# if NODE_CLANG_AT_LEAST(2, 9, 0) || NODE_GNUC_AT_LEAST(4, 5, 0)
98
#  define NODE_DEPRECATED(message, declarator)                                 \
99
    __attribute__((deprecated(message))) declarator
100
# elif defined(_MSC_VER)
101
#  define NODE_DEPRECATED(message, declarator)                                 \
102
    __declspec(deprecated) declarator
103
# else
104
#  define NODE_DEPRECATED(message, declarator) declarator
105
# endif
106
#endif
107
108
// Forward-declare libuv loop
109
struct uv_loop_s;
110
111
// Forward-declare these functions now to stop MSVS from becoming
112
// terminally confused when it's done in node_internals.h
113
namespace node {
114
115
namespace tracing {
116
117
class TracingController;
118
119
}
120
121
NODE_EXTERN v8::Local<v8::Value> ErrnoException(v8::Isolate* isolate,
122
                                                int errorno,
123
                                                const char* syscall = nullptr,
124
                                                const char* message = nullptr,
125
                                                const char* path = nullptr);
126
NODE_EXTERN v8::Local<v8::Value> UVException(v8::Isolate* isolate,
127
                                             int errorno,
128
                                             const char* syscall = nullptr,
129
                                             const char* message = nullptr,
130
                                             const char* path = nullptr,
131
                                             const char* dest = nullptr);
132
133
NODE_DEPRECATED("Use ErrnoException(isolate, ...)",
134
                inline v8::Local<v8::Value> ErrnoException(
135
      int errorno,
136
      const char* syscall = nullptr,
137
      const char* message = nullptr,
138
      const char* path = nullptr) {
139
  return ErrnoException(v8::Isolate::GetCurrent(),
140
                        errorno,
141
                        syscall,
142
                        message,
143
                        path);
144
})
145
146
NODE_DEPRECATED("Use UVException(isolate, ...)",
147
                inline v8::Local<v8::Value> UVException(int errorno,
148
                                        const char* syscall = nullptr,
149
                                        const char* message = nullptr,
150
                                        const char* path = nullptr) {
151
  return UVException(v8::Isolate::GetCurrent(),
152
                     errorno,
153
                     syscall,
154
                     message,
155
                     path);
156
})
157
158
/*
159
 * These methods need to be called in a HandleScope.
160
 *
161
 * It is preferred that you use the `MakeCallback` overloads taking
162
 * `async_context` arguments.
163
 */
164
165
NODE_DEPRECATED("Use MakeCallback(..., async_context)",
166
                NODE_EXTERN v8::Local<v8::Value> MakeCallback(
167
                    v8::Isolate* isolate,
168
                    v8::Local<v8::Object> recv,
169
                    const char* method,
170
                    int argc,
171
                    v8::Local<v8::Value>* argv));
172
NODE_DEPRECATED("Use MakeCallback(..., async_context)",
173
                NODE_EXTERN v8::Local<v8::Value> MakeCallback(
174
                    v8::Isolate* isolate,
175
                    v8::Local<v8::Object> recv,
176
                    v8::Local<v8::String> symbol,
177
                    int argc,
178
                    v8::Local<v8::Value>* argv));
179
NODE_DEPRECATED("Use MakeCallback(..., async_context)",
180
                NODE_EXTERN v8::Local<v8::Value> MakeCallback(
181
                    v8::Isolate* isolate,
182
                    v8::Local<v8::Object> recv,
183
                    v8::Local<v8::Function> callback,
184
                    int argc,
185
                    v8::Local<v8::Value>* argv));
186
187
}  // namespace node
188
189
#include <cassert>
190
#include <cstdint>
191
192
#ifndef NODE_STRINGIFY
193
# define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n)
194
# define NODE_STRINGIFY_HELPER(n) #n
195
#endif
196
197
#ifdef _WIN32
198
#if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED)
199
typedef intptr_t ssize_t;
200
# define _SSIZE_T_
201
# define _SSIZE_T_DEFINED
202
#endif
203
#else  // !_WIN32
204
# include <sys/types.h>  // size_t, ssize_t
205
#endif  // _WIN32
206
207
208
namespace node {
209
210
class IsolateData;
211
class Environment;
212
213
// TODO(addaleax): Officially deprecate this and replace it with something
214
// better suited for a public embedder API.
215
NODE_EXTERN int Start(int argc, char* argv[]);
216
217
// Tear down Node.js while it is running (there are active handles
218
// in the loop and / or actively executing JavaScript code).
219
NODE_EXTERN int Stop(Environment* env);
220
221
// TODO(addaleax): Officially deprecate this and replace it with something
222
// better suited for a public embedder API.
223
NODE_EXTERN void Init(int* argc,
224
                      const char** argv,
225
                      int* exec_argc,
226
                      const char*** exec_argv);
227
228
class NodeArrayBufferAllocator;
229
230
// An ArrayBuffer::Allocator class with some Node.js-specific tweaks. If you do
231
// not have to use another allocator, using this class is recommended:
232
// - It supports Buffer.allocUnsafe() and Buffer.allocUnsafeSlow() with
233
//   uninitialized memory.
234
// - It supports transferring, rather than copying, ArrayBuffers when using
235
//   MessagePorts.
236
9929
class NODE_EXTERN ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
237
 public:
238
  // If `always_debug` is true, create an ArrayBuffer::Allocator instance
239
  // that performs additional integrity checks (e.g. make sure that only memory
240
  // that was allocated by the it is also freed by it).
241
  // This can also be set using the --debug-arraybuffer-allocations flag.
242
  static std::unique_ptr<ArrayBufferAllocator> Create(
243
      bool always_debug = false);
244
245
 private:
246
  virtual NodeArrayBufferAllocator* GetImpl() = 0;
247
248
  friend class IsolateData;
249
};
250
251
// Legacy equivalents for ArrayBufferAllocator::Create().
252
NODE_EXTERN ArrayBufferAllocator* CreateArrayBufferAllocator();
253
NODE_EXTERN void FreeArrayBufferAllocator(ArrayBufferAllocator* allocator);
254
255
4957
class NODE_EXTERN MultiIsolatePlatform : public v8::Platform {
256
 public:
257
4953
  ~MultiIsolatePlatform() override = default;
258
  // Returns true if work was dispatched or executed. New tasks that are
259
  // posted during flushing of the queue are postponed until the next
260
  // flushing.
261
  virtual bool FlushForegroundTasks(v8::Isolate* isolate) = 0;
262
  virtual void DrainTasks(v8::Isolate* isolate) = 0;
263
  virtual void CancelPendingDelayedTasks(v8::Isolate* isolate) = 0;
264
265
  // This needs to be called between the calls to `Isolate::Allocate()` and
266
  // `Isolate::Initialize()`, so that initialization can already start
267
  // using the platform.
268
  // When using `NewIsolate()`, this is taken care of by that function.
269
  // This function may only be called once per `Isolate`.
270
  virtual void RegisterIsolate(v8::Isolate* isolate,
271
                               struct uv_loop_s* loop) = 0;
272
  // This needs to be called right before calling `Isolate::Dispose()`.
273
  // This function may only be called once per `Isolate`.
274
  virtual void UnregisterIsolate(v8::Isolate* isolate) = 0;
275
  // The platform should call the passed function once all state associated
276
  // with the given isolate has been cleaned up. This can, but does not have to,
277
  // happen asynchronously.
278
  virtual void AddIsolateFinishedCallback(v8::Isolate* isolate,
279
                                          void (*callback)(void*),
280
                                          void* data) = 0;
281
};
282
283
// Set up some Node.js-specific defaults for `params`, in particular
284
// the ArrayBuffer::Allocator if it is provided, memory limits, and
285
// possibly a code event handler.
286
NODE_EXTERN void SetIsolateCreateParams(v8::Isolate::CreateParams* params,
287
                                        ArrayBufferAllocator* allocator
288
                                            = nullptr);
289
// Set a number of callbacks for the `isolate`, in particular the Node.js
290
// uncaught exception listener.
291
NODE_EXTERN void SetIsolateUpForNode(v8::Isolate* isolate);
292
// Creates a new isolate with Node.js-specific settings.
293
// This is a convenience method equivalent to using SetIsolateCreateParams(),
294
// Isolate::Allocate(), MultiIsolatePlatform::RegisterIsolate(),
295
// Isolate::Initialize(), and SetIsolateUpForNode().
296
NODE_EXTERN v8::Isolate* NewIsolate(ArrayBufferAllocator* allocator,
297
                                    struct uv_loop_s* event_loop);
298
NODE_EXTERN v8::Isolate* NewIsolate(ArrayBufferAllocator* allocator,
299
                                    struct uv_loop_s* event_loop,
300
                                    MultiIsolatePlatform* platform);
301
302
// Creates a new context with Node.js-specific tweaks.
303
NODE_EXTERN v8::Local<v8::Context> NewContext(
304
    v8::Isolate* isolate,
305
    v8::Local<v8::ObjectTemplate> object_template =
306
        v8::Local<v8::ObjectTemplate>());
307
308
// If `platform` is passed, it will be used to register new Worker instances.
309
// It can be `nullptr`, in which case creating new Workers inside of
310
// Environments that use this `IsolateData` will not work.
311
NODE_EXTERN IsolateData* CreateIsolateData(
312
    v8::Isolate* isolate,
313
    struct uv_loop_s* loop,
314
    MultiIsolatePlatform* platform = nullptr,
315
    ArrayBufferAllocator* allocator = nullptr);
316
NODE_EXTERN void FreeIsolateData(IsolateData* isolate_data);
317
318
// TODO(addaleax): Add an official variant using STL containers, and move
319
// per-Environment options parsing here.
320
// Returns nullptr when the Environment cannot be created e.g. there are
321
// pending JavaScript exceptions.
322
NODE_EXTERN Environment* CreateEnvironment(IsolateData* isolate_data,
323
                                           v8::Local<v8::Context> context,
324
                                           int argc,
325
                                           const char* const* argv,
326
                                           int exec_argc,
327
                                           const char* const* exec_argv);
328
329
NODE_EXTERN void LoadEnvironment(Environment* env);
330
NODE_EXTERN void FreeEnvironment(Environment* env);
331
332
// This may return nullptr if context is not associated with a Node instance.
333
NODE_EXTERN Environment* GetCurrentEnvironment(v8::Local<v8::Context> context);
334
335
// This returns the MultiIsolatePlatform used in the main thread of Node.js.
336
// If NODE_USE_V8_PLATFORM haven't been defined when Node.js was built,
337
// it returns nullptr.
338
NODE_EXTERN MultiIsolatePlatform* GetMainThreadMultiIsolatePlatform();
339
340
NODE_EXTERN MultiIsolatePlatform* CreatePlatform(
341
    int thread_pool_size,
342
    node::tracing::TracingController* tracing_controller);
343
MultiIsolatePlatform* InitializeV8Platform(int thread_pool_size);
344
NODE_EXTERN void FreePlatform(MultiIsolatePlatform* platform);
345
346
NODE_EXTERN void EmitBeforeExit(Environment* env);
347
NODE_EXTERN int EmitExit(Environment* env);
348
NODE_EXTERN void RunAtExit(Environment* env);
349
350
// This may return nullptr if the current v8::Context is not associated
351
// with a Node instance.
352
NODE_EXTERN struct uv_loop_s* GetCurrentEventLoop(v8::Isolate* isolate);
353
354
/* Converts a unixtime to V8 Date */
355
NODE_DEPRECATED("Use v8::Date::New() directly",
356
                inline v8::Local<v8::Value> NODE_UNIXTIME_V8(double time) {
357
                  return v8::Date::New(
358
                             v8::Isolate::GetCurrent()->GetCurrentContext(),
359
                             1000 * time)
360
                      .ToLocalChecked();
361
                })
362
#define NODE_UNIXTIME_V8 node::NODE_UNIXTIME_V8
363
NODE_DEPRECATED("Use v8::Date::ValueOf() directly",
364
                inline double NODE_V8_UNIXTIME(v8::Local<v8::Date> date) {
365
  return date->ValueOf() / 1000;
366
})
367
#define NODE_V8_UNIXTIME node::NODE_V8_UNIXTIME
368
369
#define NODE_DEFINE_CONSTANT(target, constant)                                \
370
  do {                                                                        \
371
    v8::Isolate* isolate = target->GetIsolate();                              \
372
    v8::Local<v8::Context> context = isolate->GetCurrentContext();            \
373
    v8::Local<v8::String> constant_name =                                     \
374
        v8::String::NewFromUtf8(isolate, #constant,                           \
375
            v8::NewStringType::kInternalized).ToLocalChecked();               \
376
    v8::Local<v8::Number> constant_value =                                    \
377
        v8::Number::New(isolate, static_cast<double>(constant));              \
378
    v8::PropertyAttribute constant_attributes =                               \
379
        static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete);    \
380
    (target)->DefineOwnProperty(context,                                      \
381
                                constant_name,                                \
382
                                constant_value,                               \
383
                                constant_attributes).Check();                 \
384
  }                                                                           \
385
  while (0)
386
387
#define NODE_DEFINE_HIDDEN_CONSTANT(target, constant)                         \
388
  do {                                                                        \
389
    v8::Isolate* isolate = target->GetIsolate();                              \
390
    v8::Local<v8::Context> context = isolate->GetCurrentContext();            \
391
    v8::Local<v8::String> constant_name =                                     \
392
        v8::String::NewFromUtf8(isolate, #constant,                           \
393
                                v8::NewStringType::kInternalized)             \
394
                                  .ToLocalChecked();                          \
395
    v8::Local<v8::Number> constant_value =                                    \
396
        v8::Number::New(isolate, static_cast<double>(constant));              \
397
    v8::PropertyAttribute constant_attributes =                               \
398
        static_cast<v8::PropertyAttribute>(v8::ReadOnly |                     \
399
                                           v8::DontDelete |                   \
400
                                           v8::DontEnum);                     \
401
    (target)->DefineOwnProperty(context,                                      \
402
                                constant_name,                                \
403
                                constant_value,                               \
404
                                constant_attributes).Check();                 \
405
  }                                                                           \
406
  while (0)
407
408
// Used to be a macro, hence the uppercase name.
409
inline void NODE_SET_METHOD(v8::Local<v8::Template> recv,
410
                            const char* name,
411
                            v8::FunctionCallback callback) {
412
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
413
  v8::HandleScope handle_scope(isolate);
414
  v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate,
415
                                                                callback);
416
  v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
417
      v8::NewStringType::kInternalized).ToLocalChecked();
418
  t->SetClassName(fn_name);
419
  recv->Set(fn_name, t);
420
}
421
422
// Used to be a macro, hence the uppercase name.
423
inline void NODE_SET_METHOD(v8::Local<v8::Object> recv,
424
                            const char* name,
425
                            v8::FunctionCallback callback) {
426
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
427
  v8::HandleScope handle_scope(isolate);
428
  v8::Local<v8::Context> context = isolate->GetCurrentContext();
429
  v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate,
430
                                                                callback);
431
  v8::Local<v8::Function> fn = t->GetFunction(context).ToLocalChecked();
432
  v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
433
      v8::NewStringType::kInternalized).ToLocalChecked();
434
  fn->SetName(fn_name);
435
  recv->Set(context, fn_name, fn).Check();
436
}
437
#define NODE_SET_METHOD node::NODE_SET_METHOD
438
439
// Used to be a macro, hence the uppercase name.
440
// Not a template because it only makes sense for FunctionTemplates.
441
inline void NODE_SET_PROTOTYPE_METHOD(v8::Local<v8::FunctionTemplate> recv,
442
                                      const char* name,
443
                                      v8::FunctionCallback callback) {
444
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
445
  v8::HandleScope handle_scope(isolate);
446
  v8::Local<v8::Signature> s = v8::Signature::New(isolate, recv);
447
  v8::Local<v8::FunctionTemplate> t =
448
      v8::FunctionTemplate::New(isolate, callback, v8::Local<v8::Value>(), s);
449
  v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
450
      v8::NewStringType::kInternalized).ToLocalChecked();
451
  t->SetClassName(fn_name);
452
  recv->PrototypeTemplate()->Set(fn_name, t);
453
}
454
#define NODE_SET_PROTOTYPE_METHOD node::NODE_SET_PROTOTYPE_METHOD
455
456
// BINARY is a deprecated alias of LATIN1.
457
enum encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER, LATIN1 = BINARY};
458
459
NODE_EXTERN enum encoding ParseEncoding(
460
    v8::Isolate* isolate,
461
    v8::Local<v8::Value> encoding_v,
462
    enum encoding default_encoding = LATIN1);
463
464
NODE_EXTERN void FatalException(v8::Isolate* isolate,
465
                                const v8::TryCatch& try_catch);
466
467
NODE_EXTERN v8::Local<v8::Value> Encode(v8::Isolate* isolate,
468
                                        const char* buf,
469
                                        size_t len,
470
                                        enum encoding encoding = LATIN1);
471
472
// Warning: This reverses endianness on Big Endian platforms, even though the
473
// signature using uint16_t implies that it should not.
474
NODE_EXTERN v8::Local<v8::Value> Encode(v8::Isolate* isolate,
475
                                        const uint16_t* buf,
476
                                        size_t len);
477
478
// Returns -1 if the handle was not valid for decoding
479
NODE_EXTERN ssize_t DecodeBytes(v8::Isolate* isolate,
480
                                v8::Local<v8::Value>,
481
                                enum encoding encoding = LATIN1);
482
// returns bytes written.
483
NODE_EXTERN ssize_t DecodeWrite(v8::Isolate* isolate,
484
                                char* buf,
485
                                size_t buflen,
486
                                v8::Local<v8::Value>,
487
                                enum encoding encoding = LATIN1);
488
#ifdef _WIN32
489
NODE_EXTERN v8::Local<v8::Value> WinapiErrnoException(
490
    v8::Isolate* isolate,
491
    int errorno,
492
    const char* syscall = nullptr,
493
    const char* msg = "",
494
    const char* path = nullptr);
495
#endif
496
497
const char* signo_string(int errorno);
498
499
500
typedef void (*addon_register_func)(
501
    v8::Local<v8::Object> exports,
502
    v8::Local<v8::Value> module,
503
    void* priv);
504
505
typedef void (*addon_context_register_func)(
506
    v8::Local<v8::Object> exports,
507
    v8::Local<v8::Value> module,
508
    v8::Local<v8::Context> context,
509
    void* priv);
510
511
enum ModuleFlags {
512
  kLinked = 0x02
513
};
514
515
struct node_module {
516
  int nm_version;
517
  unsigned int nm_flags;
518
  void* nm_dso_handle;
519
  const char* nm_filename;
520
  node::addon_register_func nm_register_func;
521
  node::addon_context_register_func nm_context_register_func;
522
  const char* nm_modname;
523
  void* nm_priv;
524
  struct node_module* nm_link;
525
};
526
527
extern "C" NODE_EXTERN void node_module_register(void* mod);
528
529
#ifdef _WIN32
530
# define NODE_MODULE_EXPORT __declspec(dllexport)
531
#else
532
# define NODE_MODULE_EXPORT __attribute__((visibility("default")))
533
#endif
534
535
#ifdef NODE_SHARED_MODE
536
# define NODE_CTOR_PREFIX
537
#else
538
# define NODE_CTOR_PREFIX static
539
#endif
540
541
#if defined(_MSC_VER)
542
#pragma section(".CRT$XCU", read)
543
#define NODE_C_CTOR(fn)                                               \
544
  NODE_CTOR_PREFIX void __cdecl fn(void);                             \
545
  __declspec(dllexport, allocate(".CRT$XCU"))                         \
546
      void (__cdecl*fn ## _)(void) = fn;                              \
547
  NODE_CTOR_PREFIX void __cdecl fn(void)
548
#else
549
#define NODE_C_CTOR(fn)                                               \
550
  NODE_CTOR_PREFIX void fn(void) __attribute__((constructor));        \
551
  NODE_CTOR_PREFIX void fn(void)
552
#endif
553
554
#define NODE_MODULE_X(modname, regfunc, priv, flags)                  \
555
  extern "C" {                                                        \
556
    static node::node_module _module =                                \
557
    {                                                                 \
558
      NODE_MODULE_VERSION,                                            \
559
      flags,                                                          \
560
      NULL,  /* NOLINT (readability/null_usage) */                    \
561
      __FILE__,                                                       \
562
      (node::addon_register_func) (regfunc),                          \
563
      NULL,  /* NOLINT (readability/null_usage) */                    \
564
      NODE_STRINGIFY(modname),                                        \
565
      priv,                                                           \
566
      NULL   /* NOLINT (readability/null_usage) */                    \
567
    };                                                                \
568
    NODE_C_CTOR(_register_ ## modname) {                              \
569
      node_module_register(&_module);                                 \
570
    }                                                                 \
571
  }
572
573
#define NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, priv, flags)    \
574
  extern "C" {                                                        \
575
    static node::node_module _module =                                \
576
    {                                                                 \
577
      NODE_MODULE_VERSION,                                            \
578
      flags,                                                          \
579
      NULL,  /* NOLINT (readability/null_usage) */                    \
580
      __FILE__,                                                       \
581
      NULL,  /* NOLINT (readability/null_usage) */                    \
582
      (node::addon_context_register_func) (regfunc),                  \
583
      NODE_STRINGIFY(modname),                                        \
584
      priv,                                                           \
585
      NULL  /* NOLINT (readability/null_usage) */                     \
586
    };                                                                \
587
    NODE_C_CTOR(_register_ ## modname) {                              \
588
      node_module_register(&_module);                                 \
589
    }                                                                 \
590
  }
591
592
// Usage: `NODE_MODULE(NODE_GYP_MODULE_NAME, InitializerFunction)`
593
// If no NODE_MODULE is declared, Node.js looks for the well-known
594
// symbol `node_register_module_v${NODE_MODULE_VERSION}`.
595
#define NODE_MODULE(modname, regfunc)                                 \
596
  NODE_MODULE_X(modname, regfunc, NULL, 0)  // NOLINT (readability/null_usage)
597
598
#define NODE_MODULE_CONTEXT_AWARE(modname, regfunc)                   \
599
  /* NOLINTNEXTLINE (readability/null_usage) */                       \
600
  NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL, 0)
601
602
// Embedders can use this type of binding for statically linked native bindings.
603
// It is used the same way addon bindings are used, except that linked bindings
604
// can be accessed through `process._linkedBinding(modname)`.
605
#define NODE_MODULE_LINKED(modname, regfunc)                               \
606
  /* NOLINTNEXTLINE (readability/null_usage) */                            \
607
  NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL,                      \
608
                              node::ModuleFlags::kLinked)
609
610
/*
611
 * For backward compatibility in add-on modules.
612
 */
613
#define NODE_MODULE_DECL /* nothing */
614
615
#define NODE_MODULE_INITIALIZER_BASE node_register_module_v
616
617
#define NODE_MODULE_INITIALIZER_X(base, version)                      \
618
    NODE_MODULE_INITIALIZER_X_HELPER(base, version)
619
620
#define NODE_MODULE_INITIALIZER_X_HELPER(base, version) base##version
621
622
#define NODE_MODULE_INITIALIZER                                       \
623
  NODE_MODULE_INITIALIZER_X(NODE_MODULE_INITIALIZER_BASE,             \
624
      NODE_MODULE_VERSION)
625
626
#define NODE_MODULE_INIT()                                            \
627
  extern "C" NODE_MODULE_EXPORT void                                  \
628
  NODE_MODULE_INITIALIZER(v8::Local<v8::Object> exports,              \
629
                          v8::Local<v8::Value> module,                \
630
                          v8::Local<v8::Context> context);            \
631
  NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME,                     \
632
                            NODE_MODULE_INITIALIZER)                  \
633
  void NODE_MODULE_INITIALIZER(v8::Local<v8::Object> exports,         \
634
                               v8::Local<v8::Value> module,           \
635
                               v8::Local<v8::Context> context)
636
637
/* Called after the event loop exits but before the VM is disposed.
638
 * Callbacks are run in reverse order of registration, i.e. newest first.
639
 */
640
NODE_EXTERN void AtExit(void (*cb)(void* arg), void* arg = nullptr);
641
642
/* Registers a callback with the passed-in Environment instance. The callback
643
 * is called after the event loop exits, but before the VM is disposed.
644
 * Callbacks are run in reverse order of registration, i.e. newest first.
645
 */
646
NODE_EXTERN void AtExit(Environment* env,
647
                        void (*cb)(void* arg),
648
                        void* arg = nullptr);
649
650
typedef double async_id;
651
struct async_context {
652
  ::node::async_id async_id;
653
  ::node::async_id trigger_async_id;
654
};
655
656
/* This is a lot like node::AtExit, except that the hooks added via this
657
 * function are run before the AtExit ones and will always be registered
658
 * for the current Environment instance.
659
 * These functions are safe to use in an addon supporting multiple
660
 * threads/isolates. */
661
NODE_EXTERN void AddEnvironmentCleanupHook(v8::Isolate* isolate,
662
                                           void (*fun)(void* arg),
663
                                           void* arg);
664
665
NODE_EXTERN void RemoveEnvironmentCleanupHook(v8::Isolate* isolate,
666
                                              void (*fun)(void* arg),
667
                                              void* arg);
668
669
/* Returns the id of the current execution context. If the return value is
670
 * zero then no execution has been set. This will happen if the user handles
671
 * I/O from native code. */
672
NODE_EXTERN async_id AsyncHooksGetExecutionAsyncId(v8::Isolate* isolate);
673
674
/* Return same value as async_hooks.triggerAsyncId(); */
675
NODE_EXTERN async_id AsyncHooksGetTriggerAsyncId(v8::Isolate* isolate);
676
677
/* If the native API doesn't inherit from the helper class then the callbacks
678
 * must be triggered manually. This triggers the init() callback. The return
679
 * value is the async id assigned to the resource.
680
 *
681
 * The `trigger_async_id` parameter should correspond to the resource which is
682
 * creating the new resource, which will usually be the return value of
683
 * `AsyncHooksGetTriggerAsyncId()`. */
684
NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate,
685
                                        v8::Local<v8::Object> resource,
686
                                        const char* name,
687
                                        async_id trigger_async_id = -1);
688
689
NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate,
690
                                        v8::Local<v8::Object> resource,
691
                                        v8::Local<v8::String> name,
692
                                        async_id trigger_async_id = -1);
693
694
/* Emit the destroy() callback. The overload taking an `Environment*` argument
695
 * should be used when the Isolate’s current Context is not associated with
696
 * a Node.js Environment, or when there is no current Context, for example
697
 * when calling this function during garbage collection. In that case, the
698
 * `Environment*` value should have been acquired previously, e.g. through
699
 * `GetCurrentEnvironment()`. */
700
NODE_EXTERN void EmitAsyncDestroy(v8::Isolate* isolate,
701
                                  async_context asyncContext);
702
NODE_EXTERN void EmitAsyncDestroy(Environment* env,
703
                                  async_context asyncContext);
704
705
class InternalCallbackScope;
706
707
/* This class works like `MakeCallback()` in that it sets up a specific
708
 * asyncContext as the current one and informs the async_hooks and domains
709
 * modules that this context is currently active.
710
 *
711
 * `MakeCallback()` is a wrapper around this class as well as
712
 * `Function::Call()`. Either one of these mechanisms needs to be used for
713
 * top-level calls into JavaScript (i.e. without any existing JS stack).
714
 *
715
 * This object should be stack-allocated to ensure that it is contained in a
716
 * valid HandleScope.
717
 *
718
 * Exceptions happening within this scope will be treated like uncaught
719
 * exceptions. If this behaviour is undesirable, a new `v8::TryCatch` scope
720
 * needs to be created inside of this scope.
721
 */
722
class NODE_EXTERN CallbackScope {
723
 public:
724
  CallbackScope(v8::Isolate* isolate,
725
                v8::Local<v8::Object> resource,
726
                async_context asyncContext);
727
  ~CallbackScope();
728
729
  void operator=(const CallbackScope&) = delete;
730
  void operator=(CallbackScope&&) = delete;
731
  CallbackScope(const CallbackScope&) = delete;
732
  CallbackScope(CallbackScope&&) = delete;
733
734
 private:
735
  InternalCallbackScope* private_;
736
  v8::TryCatch try_catch_;
737
};
738
739
/* An API specific to emit before/after callbacks is unnecessary because
740
 * MakeCallback will automatically call them for you.
741
 *
742
 * These methods may create handles on their own, so run them inside a
743
 * HandleScope.
744
 *
745
 * `asyncId` and `triggerAsyncId` should correspond to the values returned by
746
 * `EmitAsyncInit()` and `AsyncHooksGetTriggerAsyncId()`, respectively, when the
747
 * invoking resource was created. If these values are unknown, 0 can be passed.
748
 * */
749
NODE_EXTERN
750
v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
751
                                       v8::Local<v8::Object> recv,
752
                                       v8::Local<v8::Function> callback,
753
                                       int argc,
754
                                       v8::Local<v8::Value>* argv,
755
                                       async_context asyncContext);
756
NODE_EXTERN
757
v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
758
                                       v8::Local<v8::Object> recv,
759
                                       const char* method,
760
                                       int argc,
761
                                       v8::Local<v8::Value>* argv,
762
                                       async_context asyncContext);
763
NODE_EXTERN
764
v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
765
                                       v8::Local<v8::Object> recv,
766
                                       v8::Local<v8::String> symbol,
767
                                       int argc,
768
                                       v8::Local<v8::Value>* argv,
769
                                       async_context asyncContext);
770
771
/* Helper class users can optionally inherit from. If
772
 * `AsyncResource::MakeCallback()` is used, then all four callbacks will be
773
 * called automatically. */
774
class NODE_EXTERN AsyncResource {
775
 public:
776
  AsyncResource(v8::Isolate* isolate,
777
                v8::Local<v8::Object> resource,
778
                const char* name,
779
                async_id trigger_async_id = -1);
780
781
  virtual ~AsyncResource();
782
783
  AsyncResource(const AsyncResource&) = delete;
784
  void operator=(const AsyncResource&) = delete;
785
786
  v8::MaybeLocal<v8::Value> MakeCallback(
787
      v8::Local<v8::Function> callback,
788
      int argc,
789
      v8::Local<v8::Value>* argv);
790
791
  v8::MaybeLocal<v8::Value> MakeCallback(
792
      const char* method,
793
      int argc,
794
      v8::Local<v8::Value>* argv);
795
796
  v8::MaybeLocal<v8::Value> MakeCallback(
797
      v8::Local<v8::String> symbol,
798
      int argc,
799
      v8::Local<v8::Value>* argv);
800
801
  v8::Local<v8::Object> get_resource();
802
  async_id get_async_id() const;
803
  async_id get_trigger_async_id() const;
804
805
 protected:
806
638
  class NODE_EXTERN CallbackScope : public node::CallbackScope {
807
   public:
808
    explicit CallbackScope(AsyncResource* res);
809
  };
810
811
 private:
812
  Environment* env_;
813
  v8::Persistent<v8::Object> resource_;
814
  async_context async_context_;
815
};
816
817
#ifndef _WIN32
818
// Register a signal handler without interrupting any handlers that node
819
// itself needs. This does override handlers registered through
820
// process.on('SIG...', function() { ... }). The `reset_handler` flag indicates
821
// whether the signal handler for the given signal should be reset to its
822
// default value before executing the handler (i.e. it works like SA_RESETHAND).
823
// The `reset_handler` flag is invalid when `signal` is SIGSEGV.
824
NODE_EXTERN
825
void RegisterSignalHandler(int signal,
826
                           void (*handler)(int signal,
827
                                           siginfo_t* info,
828
                                           void* ucontext),
829
                           bool reset_handler = false);
830
#endif  // _WIN32
831
832
}  // namespace node
833
834
#endif  // SRC_NODE_H_