GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.h Lines: 13 13 100.0 %
Date: 2021-10-02 04:13:01 Branches: 1 2 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
65
#include "v8-platform.h"  // NOLINT(build/include_order)
66
#include "node_version.h"  // NODE_MODULE_VERSION
67
68
#include <memory>
69
#include <functional>
70
71
// We cannot use __POSIX__ in this header because that's only defined when
72
// building Node.js.
73
#ifndef _WIN32
74
#include <signal.h>
75
#endif  // _WIN32
76
77
#define NODE_MAKE_VERSION(major, minor, patch)                                \
78
  ((major) * 0x1000 + (minor) * 0x100 + (patch))
79
80
#ifdef __clang__
81
# define NODE_CLANG_AT_LEAST(major, minor, patch)                             \
82
  (NODE_MAKE_VERSION(major, minor, patch) <=                                  \
83
      NODE_MAKE_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__))
84
#else
85
# define NODE_CLANG_AT_LEAST(major, minor, patch) (0)
86
#endif
87
88
#ifdef __GNUC__
89
# define NODE_GNUC_AT_LEAST(major, minor, patch)                              \
90
  (NODE_MAKE_VERSION(major, minor, patch) <=                                  \
91
      NODE_MAKE_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__))
92
#else
93
# define NODE_GNUC_AT_LEAST(major, minor, patch) (0)
94
#endif
95
96
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
97
# define NODE_DEPRECATED(message, declarator) declarator
98
#else  // NODE_WANT_INTERNALS
99
# if NODE_CLANG_AT_LEAST(2, 9, 0) || NODE_GNUC_AT_LEAST(4, 5, 0)
100
#  define NODE_DEPRECATED(message, declarator)                                 \
101
    __attribute__((deprecated(message))) declarator
102
# elif defined(_MSC_VER)
103
#  define NODE_DEPRECATED(message, declarator)                                 \
104
    __declspec(deprecated) declarator
105
# else
106
#  define NODE_DEPRECATED(message, declarator) declarator
107
# endif
108
#endif
109
110
// Forward-declare libuv loop
111
struct uv_loop_s;
112
113
struct napi_module;
114
115
// Forward-declare these functions now to stop MSVS from becoming
116
// terminally confused when it's done in node_internals.h
117
namespace node {
118
119
namespace tracing {
120
121
class TracingController;
122
123
}
124
125
NODE_EXTERN v8::Local<v8::Value> ErrnoException(v8::Isolate* isolate,
126
                                                int errorno,
127
                                                const char* syscall = nullptr,
128
                                                const char* message = nullptr,
129
                                                const char* path = nullptr);
130
NODE_EXTERN v8::Local<v8::Value> UVException(v8::Isolate* isolate,
131
                                             int errorno,
132
                                             const char* syscall = nullptr,
133
                                             const char* message = nullptr,
134
                                             const char* path = nullptr,
135
                                             const char* dest = nullptr);
136
137
NODE_DEPRECATED("Use ErrnoException(isolate, ...)",
138
                inline v8::Local<v8::Value> ErrnoException(
139
      int errorno,
140
      const char* syscall = nullptr,
141
      const char* message = nullptr,
142
      const char* path = nullptr) {
143
  return ErrnoException(v8::Isolate::GetCurrent(),
144
                        errorno,
145
                        syscall,
146
                        message,
147
                        path);
148
})
149
150
NODE_DEPRECATED("Use UVException(isolate, ...)",
151
                inline v8::Local<v8::Value> UVException(int errorno,
152
                                        const char* syscall = nullptr,
153
                                        const char* message = nullptr,
154
                                        const char* path = nullptr) {
155
  return UVException(v8::Isolate::GetCurrent(),
156
                     errorno,
157
                     syscall,
158
                     message,
159
                     path);
160
})
161
162
/*
163
 * These methods need to be called in a HandleScope.
164
 *
165
 * It is preferred that you use the `MakeCallback` overloads taking
166
 * `async_context` arguments.
167
 */
168
169
NODE_DEPRECATED("Use MakeCallback(..., async_context)",
170
                NODE_EXTERN v8::Local<v8::Value> MakeCallback(
171
                    v8::Isolate* isolate,
172
                    v8::Local<v8::Object> recv,
173
                    const char* method,
174
                    int argc,
175
                    v8::Local<v8::Value>* argv));
176
NODE_DEPRECATED("Use MakeCallback(..., async_context)",
177
                NODE_EXTERN v8::Local<v8::Value> MakeCallback(
178
                    v8::Isolate* isolate,
179
                    v8::Local<v8::Object> recv,
180
                    v8::Local<v8::String> symbol,
181
                    int argc,
182
                    v8::Local<v8::Value>* argv));
183
NODE_DEPRECATED("Use MakeCallback(..., async_context)",
184
                NODE_EXTERN v8::Local<v8::Value> MakeCallback(
185
                    v8::Isolate* isolate,
186
                    v8::Local<v8::Object> recv,
187
                    v8::Local<v8::Function> callback,
188
                    int argc,
189
                    v8::Local<v8::Value>* argv));
190
191
}  // namespace node
192
193
#include <cassert>
194
#include <cstdint>
195
196
#ifndef NODE_STRINGIFY
197
# define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n)
198
# define NODE_STRINGIFY_HELPER(n) #n
199
#endif
200
201
#ifdef _WIN32
202
#if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED)
203
typedef intptr_t ssize_t;
204
# define _SSIZE_T_
205
# define _SSIZE_T_DEFINED
206
#endif
207
#else  // !_WIN32
208
# include <sys/types.h>  // size_t, ssize_t
209
#endif  // _WIN32
210
211
212
namespace node {
213
214
class IsolateData;
215
class Environment;
216
217
// TODO(addaleax): Officially deprecate this and replace it with something
218
// better suited for a public embedder API.
219
NODE_EXTERN int Start(int argc, char* argv[]);
220
221
// Tear down Node.js while it is running (there are active handles
222
// in the loop and / or actively executing JavaScript code).
223
NODE_EXTERN int Stop(Environment* env);
224
225
// Set up per-process state needed to run Node.js. This will consume arguments
226
// from argv, fill exec_argv, and possibly add errors resulting from parsing
227
// the arguments to `errors`. The return value is a suggested exit code for the
228
// program; If it is 0, then initializing Node.js succeeded.
229
NODE_EXTERN int InitializeNodeWithArgs(std::vector<std::string>* argv,
230
                                       std::vector<std::string>* exec_argv,
231
                                       std::vector<std::string>* errors);
232
233
enum OptionEnvvarSettings {
234
  kAllowedInEnvironment,
235
  kDisallowedInEnvironment
236
};
237
238
NODE_EXTERN int ProcessGlobalArgs(std::vector<std::string>* args,
239
                      std::vector<std::string>* exec_args,
240
                      std::vector<std::string>* errors,
241
                      OptionEnvvarSettings settings);
242
243
class NodeArrayBufferAllocator;
244
245
// An ArrayBuffer::Allocator class with some Node.js-specific tweaks. If you do
246
// not have to use another allocator, using this class is recommended:
247
// - It supports Buffer.allocUnsafe() and Buffer.allocUnsafeSlow() with
248
//   uninitialized memory.
249
// - It supports transferring, rather than copying, ArrayBuffers when using
250
//   MessagePorts.
251
class NODE_EXTERN ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
252
 public:
253
  // If `always_debug` is true, create an ArrayBuffer::Allocator instance
254
  // that performs additional integrity checks (e.g. make sure that only memory
255
  // that was allocated by the it is also freed by it).
256
  // This can also be set using the --debug-arraybuffer-allocations flag.
257
  static std::unique_ptr<ArrayBufferAllocator> Create(
258
      bool always_debug = false);
259
260
 private:
261
  virtual NodeArrayBufferAllocator* GetImpl() = 0;
262
263
  friend class IsolateData;
264
};
265
266
// Legacy equivalents for ArrayBufferAllocator::Create().
267
NODE_EXTERN ArrayBufferAllocator* CreateArrayBufferAllocator();
268
NODE_EXTERN void FreeArrayBufferAllocator(ArrayBufferAllocator* allocator);
269
270
class NODE_EXTERN IsolatePlatformDelegate {
271
 public:
272
  virtual std::shared_ptr<v8::TaskRunner> GetForegroundTaskRunner() = 0;
273
  virtual bool IdleTasksEnabled() = 0;
274
};
275
276
class NODE_EXTERN MultiIsolatePlatform : public v8::Platform {
277
 public:
278
9726
  ~MultiIsolatePlatform() override = default;
279
  // Returns true if work was dispatched or executed. New tasks that are
280
  // posted during flushing of the queue are postponed until the next
281
  // flushing.
282
  virtual bool FlushForegroundTasks(v8::Isolate* isolate) = 0;
283
  virtual void DrainTasks(v8::Isolate* isolate) = 0;
284
285
  // This needs to be called between the calls to `Isolate::Allocate()` and
286
  // `Isolate::Initialize()`, so that initialization can already start
287
  // using the platform.
288
  // When using `NewIsolate()`, this is taken care of by that function.
289
  // This function may only be called once per `Isolate`.
290
  virtual void RegisterIsolate(v8::Isolate* isolate,
291
                               struct uv_loop_s* loop) = 0;
292
  // This method can be used when an application handles task scheduling on its
293
  // own through `IsolatePlatformDelegate`. Upon registering an isolate with
294
  // this overload any other method in this class with the exception of
295
  // `UnregisterIsolate` *must not* be used on that isolate.
296
  virtual void RegisterIsolate(v8::Isolate* isolate,
297
                               IsolatePlatformDelegate* delegate) = 0;
298
299
  // This function may only be called once per `Isolate`, and discard any
300
  // pending delayed tasks scheduled for that isolate.
301
  // This needs to be called right before calling `Isolate::Dispose()`.
302
  virtual void UnregisterIsolate(v8::Isolate* isolate) = 0;
303
304
  // The platform should call the passed function once all state associated
305
  // with the given isolate has been cleaned up. This can, but does not have to,
306
  // happen asynchronously.
307
  virtual void AddIsolateFinishedCallback(v8::Isolate* isolate,
308
                                          void (*callback)(void*),
309
                                          void* data) = 0;
310
311
  static std::unique_ptr<MultiIsolatePlatform> Create(
312
      int thread_pool_size,
313
      v8::TracingController* tracing_controller = nullptr,
314
      v8::PageAllocator* page_allocator = nullptr);
315
};
316
317
enum IsolateSettingsFlags {
318
  MESSAGE_LISTENER_WITH_ERROR_LEVEL = 1 << 0,
319
  DETAILED_SOURCE_POSITIONS_FOR_PROFILING = 1 << 1,
320
  SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK = 1 << 2,
321
  SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK = 1 << 3
322
};
323
324
struct IsolateSettings {
325
  uint64_t flags = MESSAGE_LISTENER_WITH_ERROR_LEVEL |
326
      DETAILED_SOURCE_POSITIONS_FOR_PROFILING;
327
  v8::MicrotasksPolicy policy = v8::MicrotasksPolicy::kExplicit;
328
329
  // Error handling callbacks
330
  v8::Isolate::AbortOnUncaughtExceptionCallback
331
      should_abort_on_uncaught_exception_callback = nullptr;
332
  v8::FatalErrorCallback fatal_error_callback = nullptr;
333
  v8::PrepareStackTraceCallback prepare_stack_trace_callback = nullptr;
334
335
  // Miscellaneous callbacks
336
  v8::PromiseRejectCallback promise_reject_callback = nullptr;
337
  v8::AllowWasmCodeGenerationCallback
338
      allow_wasm_code_generation_callback = nullptr;
339
};
340
341
// Overriding IsolateSettings may produce unexpected behavior
342
// in Node.js core functionality, so proceed at your own risk.
343
NODE_EXTERN void SetIsolateUpForNode(v8::Isolate* isolate,
344
                                     const IsolateSettings& settings);
345
346
// Set a number of callbacks for the `isolate`, in particular the Node.js
347
// uncaught exception listener.
348
NODE_EXTERN void SetIsolateUpForNode(v8::Isolate* isolate);
349
350
// Creates a new isolate with Node.js-specific settings.
351
// This is a convenience method equivalent to using SetIsolateCreateParams(),
352
// Isolate::Allocate(), MultiIsolatePlatform::RegisterIsolate(),
353
// Isolate::Initialize(), and SetIsolateUpForNode().
354
NODE_EXTERN v8::Isolate* NewIsolate(ArrayBufferAllocator* allocator,
355
                                    struct uv_loop_s* event_loop,
356
                                    MultiIsolatePlatform* platform = nullptr);
357
NODE_EXTERN v8::Isolate* NewIsolate(
358
    std::shared_ptr<ArrayBufferAllocator> allocator,
359
    struct uv_loop_s* event_loop,
360
    MultiIsolatePlatform* platform);
361
362
// Creates a new context with Node.js-specific tweaks.
363
NODE_EXTERN v8::Local<v8::Context> NewContext(
364
    v8::Isolate* isolate,
365
    v8::Local<v8::ObjectTemplate> object_template =
366
        v8::Local<v8::ObjectTemplate>());
367
368
// Runs Node.js-specific tweaks on an already constructed context
369
// Return value indicates success of operation
370
NODE_EXTERN v8::Maybe<bool> InitializeContext(v8::Local<v8::Context> context);
371
372
// If `platform` is passed, it will be used to register new Worker instances.
373
// It can be `nullptr`, in which case creating new Workers inside of
374
// Environments that use this `IsolateData` will not work.
375
NODE_EXTERN IsolateData* CreateIsolateData(
376
    v8::Isolate* isolate,
377
    struct uv_loop_s* loop,
378
    MultiIsolatePlatform* platform = nullptr,
379
    ArrayBufferAllocator* allocator = nullptr);
380
NODE_EXTERN void FreeIsolateData(IsolateData* isolate_data);
381
382
struct ThreadId {
383
  uint64_t id = static_cast<uint64_t>(-1);
384
};
385
NODE_EXTERN ThreadId AllocateEnvironmentThreadId();
386
387
namespace EnvironmentFlags {
388
enum Flags : uint64_t {
389
  kNoFlags = 0,
390
  // Use the default behaviour for Node.js instances.
391
  kDefaultFlags = 1 << 0,
392
  // Controls whether this Environment is allowed to affect per-process state
393
  // (e.g. cwd, process title, uid, etc.).
394
  // This is set when using kDefaultFlags.
395
  kOwnsProcessState = 1 << 1,
396
  // Set if this Environment instance is associated with the global inspector
397
  // handling code (i.e. listening on SIGUSR1).
398
  // This is set when using kDefaultFlags.
399
  kOwnsInspector = 1 << 2,
400
  // Set if Node.js should not run its own esm loader. This is needed by some
401
  // embedders, because it's possible for the Node.js esm loader to conflict
402
  // with another one in an embedder environment, e.g. Blink's in Chromium.
403
  kNoRegisterESMLoader = 1 << 3,
404
  // Set this flag to make Node.js track "raw" file descriptors, i.e. managed
405
  // by fs.open() and fs.close(), and close them during FreeEnvironment().
406
  kTrackUnmanagedFds = 1 << 4,
407
  // Set this flag to force hiding console windows when spawning child
408
  // processes. This is usually used when embedding Node.js in GUI programs on
409
  // Windows.
410
  kHideConsoleWindows = 1 << 5,
411
  // Set this flag to disable loading native addons via `process.dlopen`.
412
  // This environment flag is especially important for worker threads
413
  // so that a worker thread can't load a native addon even if `execArgv`
414
  // is overwritten and `--no-addons` is not specified but was specified
415
  // for this Environment instance.
416
  kNoNativeAddons = 1 << 6,
417
  // Set this flag to disable searching modules from global paths like
418
  // $HOME/.node_modules and $NODE_PATH. This is used by standalone apps that
419
  // do not expect to have their behaviors changed because of globally
420
  // installed modules.
421
  kNoGlobalSearchPaths = 1 << 7
422
};
423
}  // namespace EnvironmentFlags
424
425
struct InspectorParentHandle {
426
  virtual ~InspectorParentHandle();
427
};
428
429
// TODO(addaleax): Maybe move per-Environment options parsing here.
430
// Returns nullptr when the Environment cannot be created e.g. there are
431
// pending JavaScript exceptions.
432
NODE_EXTERN Environment* CreateEnvironment(
433
    IsolateData* isolate_data,
434
    v8::Local<v8::Context> context,
435
    const std::vector<std::string>& args,
436
    const std::vector<std::string>& exec_args,
437
    EnvironmentFlags::Flags flags = EnvironmentFlags::kDefaultFlags,
438
    ThreadId thread_id = {} /* allocates a thread id automatically */,
439
    std::unique_ptr<InspectorParentHandle> inspector_parent_handle = {});
440
441
// Returns a handle that can be passed to `LoadEnvironment()`, making the
442
// child Environment accessible to the inspector as if it were a Node.js Worker.
443
// `child_thread_id` can be created using `AllocateEnvironmentThreadId()`
444
// and then later passed on to `CreateEnvironment()` to create the child
445
// Environment, together with the inspector handle.
446
// This method should not be called while the parent Environment is active
447
// on another thread.
448
NODE_EXTERN std::unique_ptr<InspectorParentHandle> GetInspectorParentHandle(
449
    Environment* parent_env,
450
    ThreadId child_thread_id,
451
    const char* child_url);
452
453
struct StartExecutionCallbackInfo {
454
  v8::Local<v8::Object> process_object;
455
  v8::Local<v8::Function> native_require;
456
};
457
458
using StartExecutionCallback =
459
    std::function<v8::MaybeLocal<v8::Value>(const StartExecutionCallbackInfo&)>;
460
461
NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
462
    Environment* env,
463
    StartExecutionCallback cb);
464
NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
465
    Environment* env,
466
    const char* main_script_source_utf8);
467
NODE_EXTERN void FreeEnvironment(Environment* env);
468
469
// Set a callback that is called when process.exit() is called from JS,
470
// overriding the default handler.
471
// It receives the Environment* instance and the exit code as arguments.
472
// This could e.g. call Stop(env); in order to terminate execution and stop
473
// the event loop.
474
// The default handler disposes of the global V8 platform instance, if one is
475
// being used, and calls exit().
476
NODE_EXTERN void SetProcessExitHandler(
477
    Environment* env,
478
    std::function<void(Environment*, int)>&& handler);
479
NODE_EXTERN void DefaultProcessExitHandler(Environment* env, int exit_code);
480
481
// This may return nullptr if context is not associated with a Node instance.
482
NODE_EXTERN Environment* GetCurrentEnvironment(v8::Local<v8::Context> context);
483
NODE_EXTERN IsolateData* GetEnvironmentIsolateData(Environment* env);
484
NODE_EXTERN ArrayBufferAllocator* GetArrayBufferAllocator(IsolateData* data);
485
486
NODE_EXTERN void OnFatalError(const char* location, const char* message);
487
NODE_EXTERN void PromiseRejectCallback(v8::PromiseRejectMessage message);
488
NODE_EXTERN bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context,
489
                                            v8::Local<v8::String>);
490
NODE_EXTERN bool ShouldAbortOnUncaughtException(v8::Isolate* isolate);
491
NODE_EXTERN v8::MaybeLocal<v8::Value> PrepareStackTraceCallback(
492
    v8::Local<v8::Context> context,
493
    v8::Local<v8::Value> exception,
494
    v8::Local<v8::Array> trace);
495
496
// This returns the MultiIsolatePlatform used for an Environment or IsolateData
497
// instance, if one exists.
498
NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(Environment* env);
499
NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env);
500
501
NODE_DEPRECATED("Use MultiIsolatePlatform::Create() instead",
502
    NODE_EXTERN MultiIsolatePlatform* CreatePlatform(
503
        int thread_pool_size,
504
        v8::TracingController* tracing_controller));
505
NODE_DEPRECATED("Use MultiIsolatePlatform::Create() instead",
506
    NODE_EXTERN void FreePlatform(MultiIsolatePlatform* platform));
507
508
// Get/set the currently active tracing controller. Using CreatePlatform()
509
// will implicitly set this by default. This is global and should be initialized
510
// along with the v8::Platform instance that is being used. `controller`
511
// is allowed to be `nullptr`.
512
// This is used for tracing events from Node.js itself. V8 uses the tracing
513
// controller returned from the active `v8::Platform` instance.
514
NODE_EXTERN v8::TracingController* GetTracingController();
515
NODE_EXTERN void SetTracingController(v8::TracingController* controller);
516
517
// Run `process.emit('beforeExit')` as it would usually happen when Node.js is
518
// run in standalone mode.
519
NODE_EXTERN v8::Maybe<bool> EmitProcessBeforeExit(Environment* env);
520
NODE_DEPRECATED("Use Maybe version (EmitProcessBeforeExit) instead",
521
    NODE_EXTERN void EmitBeforeExit(Environment* env));
522
// Run `process.emit('exit')` as it would usually happen when Node.js is run
523
// in standalone mode. The return value corresponds to the exit code.
524
NODE_EXTERN v8::Maybe<int> EmitProcessExit(Environment* env);
525
NODE_DEPRECATED("Use Maybe version (EmitProcessExit) instead",
526
    NODE_EXTERN int EmitExit(Environment* env));
527
528
// Runs hooks added through `AtExit()`. This is part of `FreeEnvironment()`,
529
// so calling it manually is typically not necessary.
530
NODE_EXTERN void RunAtExit(Environment* env);
531
532
// This may return nullptr if the current v8::Context is not associated
533
// with a Node instance.
534
NODE_EXTERN struct uv_loop_s* GetCurrentEventLoop(v8::Isolate* isolate);
535
536
// Runs the main loop for a given Environment. This roughly performs the
537
// following steps:
538
// 1. Call uv_run() on the event loop until it is drained.
539
// 2. Call platform->DrainTasks() on the associated platform/isolate.
540
//   3. If the event loop is alive again, go to Step 1.
541
// 4. Call EmitProcessBeforeExit().
542
//   5. If the event loop is alive again, go to Step 1.
543
// 6. Call EmitProcessExit() and forward the return value.
544
// If at any point node::Stop() is called, the function will attempt to return
545
// as soon as possible, returning an empty `Maybe`.
546
// This function only works if `env` has an associated `MultiIsolatePlatform`.
547
NODE_EXTERN v8::Maybe<int> SpinEventLoop(Environment* env);
548
549
class NODE_EXTERN CommonEnvironmentSetup {
550
 public:
551
  ~CommonEnvironmentSetup();
552
553
  // Create a new CommonEnvironmentSetup, that is, a group of objects that
554
  // together form the typical setup for a single Node.js Environment instance.
555
  // If any error occurs, `*errors` will be populated and the returned pointer
556
  // will be empty.
557
  // env_args will be passed through as arguments to CreateEnvironment(), after
558
  // `isolate_data` and `context`.
559
  template <typename... EnvironmentArgs>
560
  static std::unique_ptr<CommonEnvironmentSetup> Create(
561
      MultiIsolatePlatform* platform,
562
      std::vector<std::string>* errors,
563
      EnvironmentArgs&&... env_args);
564
565
  struct uv_loop_s* event_loop() const;
566
  std::shared_ptr<ArrayBufferAllocator> array_buffer_allocator() const;
567
  v8::Isolate* isolate() const;
568
  IsolateData* isolate_data() const;
569
  Environment* env() const;
570
  v8::Local<v8::Context> context() const;
571
572
  CommonEnvironmentSetup(const CommonEnvironmentSetup&) = delete;
573
  CommonEnvironmentSetup& operator=(const CommonEnvironmentSetup&) = delete;
574
  CommonEnvironmentSetup(CommonEnvironmentSetup&&) = delete;
575
  CommonEnvironmentSetup& operator=(CommonEnvironmentSetup&&) = delete;
576
577
 private:
578
  struct Impl;
579
  Impl* impl_;
580
  CommonEnvironmentSetup(
581
      MultiIsolatePlatform*,
582
      std::vector<std::string>*,
583
      std::function<Environment*(const CommonEnvironmentSetup*)>);
584
};
585
586
// Implementation for CommonEnvironmentSetup::Create
587
template <typename... EnvironmentArgs>
588
7
std::unique_ptr<CommonEnvironmentSetup> CommonEnvironmentSetup::Create(
589
    MultiIsolatePlatform* platform,
590
    std::vector<std::string>* errors,
591
    EnvironmentArgs&&... env_args) {
592
7
  auto ret = std::unique_ptr<CommonEnvironmentSetup>(new CommonEnvironmentSetup(
593
      platform, errors,
594
7
      [&](const CommonEnvironmentSetup* setup) -> Environment* {
595
21
        return CreateEnvironment(
596
            setup->isolate_data(), setup->context(),
597
14
            std::forward<EnvironmentArgs>(env_args)...);
598
      }));
599
7
  if (!errors->empty()) ret.reset();
600
7
  return ret;
601
}
602
603
/* Converts a unixtime to V8 Date */
604
NODE_DEPRECATED("Use v8::Date::New() directly",
605
                inline v8::Local<v8::Value> NODE_UNIXTIME_V8(double time) {
606
                  return v8::Date::New(
607
                             v8::Isolate::GetCurrent()->GetCurrentContext(),
608
                             1000 * time)
609
                      .ToLocalChecked();
610
                })
611
#define NODE_UNIXTIME_V8 node::NODE_UNIXTIME_V8
612
NODE_DEPRECATED("Use v8::Date::ValueOf() directly",
613
                inline double NODE_V8_UNIXTIME(v8::Local<v8::Date> date) {
614
  return date->ValueOf() / 1000;
615
})
616
#define NODE_V8_UNIXTIME node::NODE_V8_UNIXTIME
617
618
#define NODE_DEFINE_CONSTANT(target, constant)                                \
619
  do {                                                                        \
620
    v8::Isolate* isolate = target->GetIsolate();                              \
621
    v8::Local<v8::Context> context = isolate->GetCurrentContext();            \
622
    v8::Local<v8::String> constant_name =                                     \
623
        v8::String::NewFromUtf8(isolate, #constant,                           \
624
            v8::NewStringType::kInternalized).ToLocalChecked();               \
625
    v8::Local<v8::Number> constant_value =                                    \
626
        v8::Number::New(isolate, static_cast<double>(constant));              \
627
    v8::PropertyAttribute constant_attributes =                               \
628
        static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete);    \
629
    (target)->DefineOwnProperty(context,                                      \
630
                                constant_name,                                \
631
                                constant_value,                               \
632
                                constant_attributes).Check();                 \
633
  }                                                                           \
634
  while (0)
635
636
#define NODE_DEFINE_HIDDEN_CONSTANT(target, constant)                         \
637
  do {                                                                        \
638
    v8::Isolate* isolate = target->GetIsolate();                              \
639
    v8::Local<v8::Context> context = isolate->GetCurrentContext();            \
640
    v8::Local<v8::String> constant_name =                                     \
641
        v8::String::NewFromUtf8(isolate, #constant,                           \
642
                                v8::NewStringType::kInternalized)             \
643
                                  .ToLocalChecked();                          \
644
    v8::Local<v8::Number> constant_value =                                    \
645
        v8::Number::New(isolate, static_cast<double>(constant));              \
646
    v8::PropertyAttribute constant_attributes =                               \
647
        static_cast<v8::PropertyAttribute>(v8::ReadOnly |                     \
648
                                           v8::DontDelete |                   \
649
                                           v8::DontEnum);                     \
650
    (target)->DefineOwnProperty(context,                                      \
651
                                constant_name,                                \
652
                                constant_value,                               \
653
                                constant_attributes).Check();                 \
654
  }                                                                           \
655
  while (0)
656
657
// Used to be a macro, hence the uppercase name.
658
inline void NODE_SET_METHOD(v8::Local<v8::Template> recv,
659
                            const char* name,
660
                            v8::FunctionCallback callback) {
661
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
662
  v8::HandleScope handle_scope(isolate);
663
  v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate,
664
                                                                callback);
665
  v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
666
      v8::NewStringType::kInternalized).ToLocalChecked();
667
  t->SetClassName(fn_name);
668
  recv->Set(fn_name, t);
669
}
670
671
// Used to be a macro, hence the uppercase name.
672
inline void NODE_SET_METHOD(v8::Local<v8::Object> recv,
673
                            const char* name,
674
                            v8::FunctionCallback callback) {
675
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
676
  v8::HandleScope handle_scope(isolate);
677
  v8::Local<v8::Context> context = isolate->GetCurrentContext();
678
  v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate,
679
                                                                callback);
680
  v8::Local<v8::Function> fn = t->GetFunction(context).ToLocalChecked();
681
  v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
682
      v8::NewStringType::kInternalized).ToLocalChecked();
683
  fn->SetName(fn_name);
684
  recv->Set(context, fn_name, fn).Check();
685
}
686
#define NODE_SET_METHOD node::NODE_SET_METHOD
687
688
// Used to be a macro, hence the uppercase name.
689
// Not a template because it only makes sense for FunctionTemplates.
690
inline void NODE_SET_PROTOTYPE_METHOD(v8::Local<v8::FunctionTemplate> recv,
691
                                      const char* name,
692
                                      v8::FunctionCallback callback) {
693
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
694
  v8::HandleScope handle_scope(isolate);
695
  v8::Local<v8::Signature> s = v8::Signature::New(isolate, recv);
696
  v8::Local<v8::FunctionTemplate> t =
697
      v8::FunctionTemplate::New(isolate, callback, v8::Local<v8::Value>(), s);
698
  v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
699
      v8::NewStringType::kInternalized).ToLocalChecked();
700
  t->SetClassName(fn_name);
701
  recv->PrototypeTemplate()->Set(fn_name, t);
702
}
703
#define NODE_SET_PROTOTYPE_METHOD node::NODE_SET_PROTOTYPE_METHOD
704
705
// BINARY is a deprecated alias of LATIN1.
706
// BASE64URL is not currently exposed to the JavaScript side.
707
enum encoding {
708
  ASCII,
709
  UTF8,
710
  BASE64,
711
  UCS2,
712
  BINARY,
713
  HEX,
714
  BUFFER,
715
  BASE64URL,
716
  LATIN1 = BINARY
717
};
718
719
NODE_EXTERN enum encoding ParseEncoding(
720
    v8::Isolate* isolate,
721
    v8::Local<v8::Value> encoding_v,
722
    enum encoding default_encoding = LATIN1);
723
724
NODE_EXTERN void FatalException(v8::Isolate* isolate,
725
                                const v8::TryCatch& try_catch);
726
727
NODE_EXTERN v8::Local<v8::Value> Encode(v8::Isolate* isolate,
728
                                        const char* buf,
729
                                        size_t len,
730
                                        enum encoding encoding = LATIN1);
731
732
// Warning: This reverses endianness on Big Endian platforms, even though the
733
// signature using uint16_t implies that it should not.
734
NODE_EXTERN v8::Local<v8::Value> Encode(v8::Isolate* isolate,
735
                                        const uint16_t* buf,
736
                                        size_t len);
737
738
// Returns -1 if the handle was not valid for decoding
739
NODE_EXTERN ssize_t DecodeBytes(v8::Isolate* isolate,
740
                                v8::Local<v8::Value>,
741
                                enum encoding encoding = LATIN1);
742
// returns bytes written.
743
NODE_EXTERN ssize_t DecodeWrite(v8::Isolate* isolate,
744
                                char* buf,
745
                                size_t buflen,
746
                                v8::Local<v8::Value>,
747
                                enum encoding encoding = LATIN1);
748
#ifdef _WIN32
749
NODE_EXTERN v8::Local<v8::Value> WinapiErrnoException(
750
    v8::Isolate* isolate,
751
    int errorno,
752
    const char* syscall = nullptr,
753
    const char* msg = "",
754
    const char* path = nullptr);
755
#endif
756
757
const char* signo_string(int errorno);
758
759
760
typedef void (*addon_register_func)(
761
    v8::Local<v8::Object> exports,
762
    v8::Local<v8::Value> module,
763
    void* priv);
764
765
typedef void (*addon_context_register_func)(
766
    v8::Local<v8::Object> exports,
767
    v8::Local<v8::Value> module,
768
    v8::Local<v8::Context> context,
769
    void* priv);
770
771
enum ModuleFlags {
772
  kLinked = 0x02
773
};
774
775
struct node_module {
776
  int nm_version;
777
  unsigned int nm_flags;
778
  void* nm_dso_handle;
779
  const char* nm_filename;
780
  node::addon_register_func nm_register_func;
781
  node::addon_context_register_func nm_context_register_func;
782
  const char* nm_modname;
783
  void* nm_priv;
784
  struct node_module* nm_link;
785
};
786
787
extern "C" NODE_EXTERN void node_module_register(void* mod);
788
789
#ifdef _WIN32
790
# define NODE_MODULE_EXPORT __declspec(dllexport)
791
#else
792
# define NODE_MODULE_EXPORT __attribute__((visibility("default")))
793
#endif
794
795
#ifdef NODE_SHARED_MODE
796
# define NODE_CTOR_PREFIX
797
#else
798
# define NODE_CTOR_PREFIX static
799
#endif
800
801
#if defined(_MSC_VER)
802
#pragma section(".CRT$XCU", read)
803
#define NODE_C_CTOR(fn)                                               \
804
  NODE_CTOR_PREFIX void __cdecl fn(void);                             \
805
  __declspec(dllexport, allocate(".CRT$XCU"))                         \
806
      void (__cdecl*fn ## _)(void) = fn;                              \
807
  NODE_CTOR_PREFIX void __cdecl fn(void)
808
#else
809
#define NODE_C_CTOR(fn)                                               \
810
  NODE_CTOR_PREFIX void fn(void) __attribute__((constructor));        \
811
  NODE_CTOR_PREFIX void fn(void)
812
#endif
813
814
#define NODE_MODULE_X(modname, regfunc, priv, flags)                  \
815
  extern "C" {                                                        \
816
    static node::node_module _module =                                \
817
    {                                                                 \
818
      NODE_MODULE_VERSION,                                            \
819
      flags,                                                          \
820
      NULL,  /* NOLINT (readability/null_usage) */                    \
821
      __FILE__,                                                       \
822
      (node::addon_register_func) (regfunc),                          \
823
      NULL,  /* NOLINT (readability/null_usage) */                    \
824
      NODE_STRINGIFY(modname),                                        \
825
      priv,                                                           \
826
      NULL   /* NOLINT (readability/null_usage) */                    \
827
    };                                                                \
828
    NODE_C_CTOR(_register_ ## modname) {                              \
829
      node_module_register(&_module);                                 \
830
    }                                                                 \
831
  }
832
833
#define NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, priv, flags)    \
834
  extern "C" {                                                        \
835
    static node::node_module _module =                                \
836
    {                                                                 \
837
      NODE_MODULE_VERSION,                                            \
838
      flags,                                                          \
839
      NULL,  /* NOLINT (readability/null_usage) */                    \
840
      __FILE__,                                                       \
841
      NULL,  /* NOLINT (readability/null_usage) */                    \
842
      (node::addon_context_register_func) (regfunc),                  \
843
      NODE_STRINGIFY(modname),                                        \
844
      priv,                                                           \
845
      NULL  /* NOLINT (readability/null_usage) */                     \
846
    };                                                                \
847
    NODE_C_CTOR(_register_ ## modname) {                              \
848
      node_module_register(&_module);                                 \
849
    }                                                                 \
850
  }
851
852
// Usage: `NODE_MODULE(NODE_GYP_MODULE_NAME, InitializerFunction)`
853
// If no NODE_MODULE is declared, Node.js looks for the well-known
854
// symbol `node_register_module_v${NODE_MODULE_VERSION}`.
855
#define NODE_MODULE(modname, regfunc)                                 \
856
  NODE_MODULE_X(modname, regfunc, NULL, 0)  // NOLINT (readability/null_usage)
857
858
#define NODE_MODULE_CONTEXT_AWARE(modname, regfunc)                   \
859
  /* NOLINTNEXTLINE (readability/null_usage) */                       \
860
  NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL, 0)
861
862
// Embedders can use this type of binding for statically linked native bindings.
863
// It is used the same way addon bindings are used, except that linked bindings
864
// can be accessed through `process._linkedBinding(modname)`.
865
#define NODE_MODULE_LINKED(modname, regfunc)                               \
866
  /* NOLINTNEXTLINE (readability/null_usage) */                            \
867
  NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL,                      \
868
                              node::ModuleFlags::kLinked)
869
870
/*
871
 * For backward compatibility in add-on modules.
872
 */
873
#define NODE_MODULE_DECL /* nothing */
874
875
#define NODE_MODULE_INITIALIZER_BASE node_register_module_v
876
877
#define NODE_MODULE_INITIALIZER_X(base, version)                      \
878
    NODE_MODULE_INITIALIZER_X_HELPER(base, version)
879
880
#define NODE_MODULE_INITIALIZER_X_HELPER(base, version) base##version
881
882
#define NODE_MODULE_INITIALIZER                                       \
883
  NODE_MODULE_INITIALIZER_X(NODE_MODULE_INITIALIZER_BASE,             \
884
      NODE_MODULE_VERSION)
885
886
#define NODE_MODULE_INIT()                                            \
887
  extern "C" NODE_MODULE_EXPORT void                                  \
888
  NODE_MODULE_INITIALIZER(v8::Local<v8::Object> exports,              \
889
                          v8::Local<v8::Value> module,                \
890
                          v8::Local<v8::Context> context);            \
891
  NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME,                     \
892
                            NODE_MODULE_INITIALIZER)                  \
893
  void NODE_MODULE_INITIALIZER(v8::Local<v8::Object> exports,         \
894
                               v8::Local<v8::Value> module,           \
895
                               v8::Local<v8::Context> context)
896
897
// Allows embedders to add a binding to the current Environment* that can be
898
// accessed through process._linkedBinding() in the target Environment and all
899
// Worker threads that it creates.
900
// In each variant, the registration function needs to be usable at least for
901
// the time during which the Environment exists.
902
NODE_EXTERN void AddLinkedBinding(Environment* env, const node_module& mod);
903
NODE_EXTERN void AddLinkedBinding(Environment* env,
904
                                  const struct napi_module& mod);
905
NODE_EXTERN void AddLinkedBinding(Environment* env,
906
                                  const char* name,
907
                                  addon_context_register_func fn,
908
                                  void* priv);
909
910
/* Registers a callback with the passed-in Environment instance. The callback
911
 * is called after the event loop exits, but before the VM is disposed.
912
 * Callbacks are run in reverse order of registration, i.e. newest first.
913
 */
914
NODE_EXTERN void AtExit(Environment* env,
915
                        void (*cb)(void* arg),
916
                        void* arg);
917
918
typedef double async_id;
919
struct async_context {
920
  ::node::async_id async_id;
921
  ::node::async_id trigger_async_id;
922
};
923
924
/* This is a lot like node::AtExit, except that the hooks added via this
925
 * function are run before the AtExit ones and will always be registered
926
 * for the current Environment instance.
927
 * These functions are safe to use in an addon supporting multiple
928
 * threads/isolates. */
929
NODE_EXTERN void AddEnvironmentCleanupHook(v8::Isolate* isolate,
930
                                           void (*fun)(void* arg),
931
                                           void* arg);
932
933
NODE_EXTERN void RemoveEnvironmentCleanupHook(v8::Isolate* isolate,
934
                                              void (*fun)(void* arg),
935
                                              void* arg);
936
937
/* These are async equivalents of the above. After the cleanup hook is invoked,
938
 * `cb(cbarg)` *must* be called, and attempting to remove the cleanup hook will
939
 * have no effect. */
940
struct ACHHandle;
941
struct NODE_EXTERN DeleteACHHandle { void operator()(ACHHandle*) const; };
942
typedef std::unique_ptr<ACHHandle, DeleteACHHandle> AsyncCleanupHookHandle;
943
944
/* This function is not intended to be used externally, it exists to aid in
945
 * keeping ABI compatibility between Node and Electron. */
946
NODE_EXTERN ACHHandle* AddEnvironmentCleanupHookInternal(
947
    v8::Isolate* isolate,
948
    void (*fun)(void* arg, void (*cb)(void*), void* cbarg),
949
    void* arg);
950
6
inline AsyncCleanupHookHandle AddEnvironmentCleanupHook(
951
    v8::Isolate* isolate,
952
    void (*fun)(void* arg, void (*cb)(void*), void* cbarg),
953
    void* arg) {
954
  return AsyncCleanupHookHandle(AddEnvironmentCleanupHookInternal(isolate, fun,
955
6
      arg));
956
}
957
958
/* This function is not intended to be used externally, it exists to aid in
959
 * keeping ABI compatibility between Node and Electron. */
960
NODE_EXTERN void RemoveEnvironmentCleanupHookInternal(ACHHandle* holder);
961
6
inline void RemoveEnvironmentCleanupHook(AsyncCleanupHookHandle holder) {
962
6
  RemoveEnvironmentCleanupHookInternal(holder.get());
963
6
}
964
965
/* Returns the id of the current execution context. If the return value is
966
 * zero then no execution has been set. This will happen if the user handles
967
 * I/O from native code. */
968
NODE_EXTERN async_id AsyncHooksGetExecutionAsyncId(v8::Isolate* isolate);
969
970
/* Return same value as async_hooks.triggerAsyncId(); */
971
NODE_EXTERN async_id AsyncHooksGetTriggerAsyncId(v8::Isolate* isolate);
972
973
/* If the native API doesn't inherit from the helper class then the callbacks
974
 * must be triggered manually. This triggers the init() callback. The return
975
 * value is the async id assigned to the resource.
976
 *
977
 * The `trigger_async_id` parameter should correspond to the resource which is
978
 * creating the new resource, which will usually be the return value of
979
 * `AsyncHooksGetTriggerAsyncId()`. */
980
NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate,
981
                                        v8::Local<v8::Object> resource,
982
                                        const char* name,
983
                                        async_id trigger_async_id = -1);
984
985
NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate,
986
                                        v8::Local<v8::Object> resource,
987
                                        v8::Local<v8::String> name,
988
                                        async_id trigger_async_id = -1);
989
990
/* Emit the destroy() callback. The overload taking an `Environment*` argument
991
 * should be used when the Isolate’s current Context is not associated with
992
 * a Node.js Environment, or when there is no current Context, for example
993
 * when calling this function during garbage collection. In that case, the
994
 * `Environment*` value should have been acquired previously, e.g. through
995
 * `GetCurrentEnvironment()`. */
996
NODE_EXTERN void EmitAsyncDestroy(v8::Isolate* isolate,
997
                                  async_context asyncContext);
998
NODE_EXTERN void EmitAsyncDestroy(Environment* env,
999
                                  async_context asyncContext);
1000
1001
class InternalCallbackScope;
1002
1003
/* This class works like `MakeCallback()` in that it sets up a specific
1004
 * asyncContext as the current one and informs the async_hooks and domains
1005
 * modules that this context is currently active.
1006
 *
1007
 * `MakeCallback()` is a wrapper around this class as well as
1008
 * `Function::Call()`. Either one of these mechanisms needs to be used for
1009
 * top-level calls into JavaScript (i.e. without any existing JS stack).
1010
 *
1011
 * This object should be stack-allocated to ensure that it is contained in a
1012
 * valid HandleScope.
1013
 *
1014
 * Exceptions happening within this scope will be treated like uncaught
1015
 * exceptions. If this behaviour is undesirable, a new `v8::TryCatch` scope
1016
 * needs to be created inside of this scope.
1017
 */
1018
class NODE_EXTERN CallbackScope {
1019
 public:
1020
  CallbackScope(v8::Isolate* isolate,
1021
                v8::Local<v8::Object> resource,
1022
                async_context asyncContext);
1023
  CallbackScope(Environment* env,
1024
                v8::Local<v8::Object> resource,
1025
                async_context asyncContext);
1026
  ~CallbackScope();
1027
1028
  void operator=(const CallbackScope&) = delete;
1029
  void operator=(CallbackScope&&) = delete;
1030
  CallbackScope(const CallbackScope&) = delete;
1031
  CallbackScope(CallbackScope&&) = delete;
1032
1033
 private:
1034
  InternalCallbackScope* private_;
1035
  v8::TryCatch try_catch_;
1036
};
1037
1038
/* An API specific to emit before/after callbacks is unnecessary because
1039
 * MakeCallback will automatically call them for you.
1040
 *
1041
 * These methods may create handles on their own, so run them inside a
1042
 * HandleScope.
1043
 *
1044
 * `asyncId` and `triggerAsyncId` should correspond to the values returned by
1045
 * `EmitAsyncInit()` and `AsyncHooksGetTriggerAsyncId()`, respectively, when the
1046
 * invoking resource was created. If these values are unknown, 0 can be passed.
1047
 * */
1048
NODE_EXTERN
1049
v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
1050
                                       v8::Local<v8::Object> recv,
1051
                                       v8::Local<v8::Function> callback,
1052
                                       int argc,
1053
                                       v8::Local<v8::Value>* argv,
1054
                                       async_context asyncContext);
1055
NODE_EXTERN
1056
v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
1057
                                       v8::Local<v8::Object> recv,
1058
                                       const char* method,
1059
                                       int argc,
1060
                                       v8::Local<v8::Value>* argv,
1061
                                       async_context asyncContext);
1062
NODE_EXTERN
1063
v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
1064
                                       v8::Local<v8::Object> recv,
1065
                                       v8::Local<v8::String> symbol,
1066
                                       int argc,
1067
                                       v8::Local<v8::Value>* argv,
1068
                                       async_context asyncContext);
1069
1070
/* Helper class users can optionally inherit from. If
1071
 * `AsyncResource::MakeCallback()` is used, then all four callbacks will be
1072
 * called automatically. */
1073
class NODE_EXTERN AsyncResource {
1074
 public:
1075
  AsyncResource(v8::Isolate* isolate,
1076
                v8::Local<v8::Object> resource,
1077
                const char* name,
1078
                async_id trigger_async_id = -1);
1079
1080
  virtual ~AsyncResource();
1081
1082
  AsyncResource(const AsyncResource&) = delete;
1083
  void operator=(const AsyncResource&) = delete;
1084
1085
  v8::MaybeLocal<v8::Value> MakeCallback(
1086
      v8::Local<v8::Function> callback,
1087
      int argc,
1088
      v8::Local<v8::Value>* argv);
1089
1090
  v8::MaybeLocal<v8::Value> MakeCallback(
1091
      const char* method,
1092
      int argc,
1093
      v8::Local<v8::Value>* argv);
1094
1095
  v8::MaybeLocal<v8::Value> MakeCallback(
1096
      v8::Local<v8::String> symbol,
1097
      int argc,
1098
      v8::Local<v8::Value>* argv);
1099
1100
  v8::Local<v8::Object> get_resource();
1101
  async_id get_async_id() const;
1102
  async_id get_trigger_async_id() const;
1103
1104
 protected:
1105
  class NODE_EXTERN CallbackScope : public node::CallbackScope {
1106
   public:
1107
    explicit CallbackScope(AsyncResource* res);
1108
  };
1109
1110
 private:
1111
  Environment* env_;
1112
  v8::Global<v8::Object> resource_;
1113
  async_context async_context_;
1114
};
1115
1116
#ifndef _WIN32
1117
// Register a signal handler without interrupting any handlers that node
1118
// itself needs. This does override handlers registered through
1119
// process.on('SIG...', function() { ... }). The `reset_handler` flag indicates
1120
// whether the signal handler for the given signal should be reset to its
1121
// default value before executing the handler (i.e. it works like SA_RESETHAND).
1122
// The `reset_handler` flag is invalid when `signal` is SIGSEGV.
1123
NODE_EXTERN
1124
void RegisterSignalHandler(int signal,
1125
                           void (*handler)(int signal,
1126
                                           siginfo_t* info,
1127
                                           void* ucontext),
1128
                           bool reset_handler = false);
1129
#endif  // _WIN32
1130
1131
}  // namespace node
1132
1133
#endif  // SRC_NODE_H_