GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.h Lines: 13 13 100.0 %
Date: 2021-09-08 04:14:13 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
9708
  ~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
};
412
}  // namespace EnvironmentFlags
413
414
struct InspectorParentHandle {
415
  virtual ~InspectorParentHandle();
416
};
417
418
// TODO(addaleax): Maybe move per-Environment options parsing here.
419
// Returns nullptr when the Environment cannot be created e.g. there are
420
// pending JavaScript exceptions.
421
NODE_EXTERN Environment* CreateEnvironment(
422
    IsolateData* isolate_data,
423
    v8::Local<v8::Context> context,
424
    const std::vector<std::string>& args,
425
    const std::vector<std::string>& exec_args,
426
    EnvironmentFlags::Flags flags = EnvironmentFlags::kDefaultFlags,
427
    ThreadId thread_id = {} /* allocates a thread id automatically */,
428
    std::unique_ptr<InspectorParentHandle> inspector_parent_handle = {});
429
430
// Returns a handle that can be passed to `LoadEnvironment()`, making the
431
// child Environment accessible to the inspector as if it were a Node.js Worker.
432
// `child_thread_id` can be created using `AllocateEnvironmentThreadId()`
433
// and then later passed on to `CreateEnvironment()` to create the child
434
// Environment, together with the inspector handle.
435
// This method should not be called while the parent Environment is active
436
// on another thread.
437
NODE_EXTERN std::unique_ptr<InspectorParentHandle> GetInspectorParentHandle(
438
    Environment* parent_env,
439
    ThreadId child_thread_id,
440
    const char* child_url);
441
442
struct StartExecutionCallbackInfo {
443
  v8::Local<v8::Object> process_object;
444
  v8::Local<v8::Function> native_require;
445
};
446
447
using StartExecutionCallback =
448
    std::function<v8::MaybeLocal<v8::Value>(const StartExecutionCallbackInfo&)>;
449
450
NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
451
    Environment* env,
452
    StartExecutionCallback cb);
453
NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
454
    Environment* env,
455
    const char* main_script_source_utf8);
456
NODE_EXTERN void FreeEnvironment(Environment* env);
457
458
// Set a callback that is called when process.exit() is called from JS,
459
// overriding the default handler.
460
// It receives the Environment* instance and the exit code as arguments.
461
// This could e.g. call Stop(env); in order to terminate execution and stop
462
// the event loop.
463
// The default handler disposes of the global V8 platform instance, if one is
464
// being used, and calls exit().
465
NODE_EXTERN void SetProcessExitHandler(
466
    Environment* env,
467
    std::function<void(Environment*, int)>&& handler);
468
NODE_EXTERN void DefaultProcessExitHandler(Environment* env, int exit_code);
469
470
// This may return nullptr if context is not associated with a Node instance.
471
NODE_EXTERN Environment* GetCurrentEnvironment(v8::Local<v8::Context> context);
472
NODE_EXTERN IsolateData* GetEnvironmentIsolateData(Environment* env);
473
NODE_EXTERN ArrayBufferAllocator* GetArrayBufferAllocator(IsolateData* data);
474
475
NODE_EXTERN void OnFatalError(const char* location, const char* message);
476
NODE_EXTERN void PromiseRejectCallback(v8::PromiseRejectMessage message);
477
NODE_EXTERN bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context,
478
                                            v8::Local<v8::String>);
479
NODE_EXTERN bool ShouldAbortOnUncaughtException(v8::Isolate* isolate);
480
NODE_EXTERN v8::MaybeLocal<v8::Value> PrepareStackTraceCallback(
481
    v8::Local<v8::Context> context,
482
    v8::Local<v8::Value> exception,
483
    v8::Local<v8::Array> trace);
484
485
// This returns the MultiIsolatePlatform used for an Environment or IsolateData
486
// instance, if one exists.
487
NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(Environment* env);
488
NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env);
489
490
NODE_DEPRECATED("Use MultiIsolatePlatform::Create() instead",
491
    NODE_EXTERN MultiIsolatePlatform* CreatePlatform(
492
        int thread_pool_size,
493
        v8::TracingController* tracing_controller));
494
NODE_DEPRECATED("Use MultiIsolatePlatform::Create() instead",
495
    NODE_EXTERN void FreePlatform(MultiIsolatePlatform* platform));
496
497
// Get/set the currently active tracing controller. Using CreatePlatform()
498
// will implicitly set this by default. This is global and should be initialized
499
// along with the v8::Platform instance that is being used. `controller`
500
// is allowed to be `nullptr`.
501
// This is used for tracing events from Node.js itself. V8 uses the tracing
502
// controller returned from the active `v8::Platform` instance.
503
NODE_EXTERN v8::TracingController* GetTracingController();
504
NODE_EXTERN void SetTracingController(v8::TracingController* controller);
505
506
// Run `process.emit('beforeExit')` as it would usually happen when Node.js is
507
// run in standalone mode.
508
NODE_EXTERN v8::Maybe<bool> EmitProcessBeforeExit(Environment* env);
509
NODE_DEPRECATED("Use Maybe version (EmitProcessBeforeExit) instead",
510
    NODE_EXTERN void EmitBeforeExit(Environment* env));
511
// Run `process.emit('exit')` as it would usually happen when Node.js is run
512
// in standalone mode. The return value corresponds to the exit code.
513
NODE_EXTERN v8::Maybe<int> EmitProcessExit(Environment* env);
514
NODE_DEPRECATED("Use Maybe version (EmitProcessExit) instead",
515
    NODE_EXTERN int EmitExit(Environment* env));
516
517
// Runs hooks added through `AtExit()`. This is part of `FreeEnvironment()`,
518
// so calling it manually is typically not necessary.
519
NODE_EXTERN void RunAtExit(Environment* env);
520
521
// This may return nullptr if the current v8::Context is not associated
522
// with a Node instance.
523
NODE_EXTERN struct uv_loop_s* GetCurrentEventLoop(v8::Isolate* isolate);
524
525
// Runs the main loop for a given Environment. This roughly performs the
526
// following steps:
527
// 1. Call uv_run() on the event loop until it is drained.
528
// 2. Call platform->DrainTasks() on the associated platform/isolate.
529
//   3. If the event loop is alive again, go to Step 1.
530
// 4. Call EmitProcessBeforeExit().
531
//   5. If the event loop is alive again, go to Step 1.
532
// 6. Call EmitProcessExit() and forward the return value.
533
// If at any point node::Stop() is called, the function will attempt to return
534
// as soon as possible, returning an empty `Maybe`.
535
// This function only works if `env` has an associated `MultiIsolatePlatform`.
536
NODE_EXTERN v8::Maybe<int> SpinEventLoop(Environment* env);
537
538
class NODE_EXTERN CommonEnvironmentSetup {
539
 public:
540
  ~CommonEnvironmentSetup();
541
542
  // Create a new CommonEnvironmentSetup, that is, a group of objects that
543
  // together form the typical setup for a single Node.js Environment instance.
544
  // If any error occurs, `*errors` will be populated and the returned pointer
545
  // will be empty.
546
  // env_args will be passed through as arguments to CreateEnvironment(), after
547
  // `isolate_data` and `context`.
548
  template <typename... EnvironmentArgs>
549
  static std::unique_ptr<CommonEnvironmentSetup> Create(
550
      MultiIsolatePlatform* platform,
551
      std::vector<std::string>* errors,
552
      EnvironmentArgs&&... env_args);
553
554
  struct uv_loop_s* event_loop() const;
555
  std::shared_ptr<ArrayBufferAllocator> array_buffer_allocator() const;
556
  v8::Isolate* isolate() const;
557
  IsolateData* isolate_data() const;
558
  Environment* env() const;
559
  v8::Local<v8::Context> context() const;
560
561
  CommonEnvironmentSetup(const CommonEnvironmentSetup&) = delete;
562
  CommonEnvironmentSetup& operator=(const CommonEnvironmentSetup&) = delete;
563
  CommonEnvironmentSetup(CommonEnvironmentSetup&&) = delete;
564
  CommonEnvironmentSetup& operator=(CommonEnvironmentSetup&&) = delete;
565
566
 private:
567
  struct Impl;
568
  Impl* impl_;
569
  CommonEnvironmentSetup(
570
      MultiIsolatePlatform*,
571
      std::vector<std::string>*,
572
      std::function<Environment*(const CommonEnvironmentSetup*)>);
573
};
574
575
// Implementation for CommonEnvironmentSetup::Create
576
template <typename... EnvironmentArgs>
577
7
std::unique_ptr<CommonEnvironmentSetup> CommonEnvironmentSetup::Create(
578
    MultiIsolatePlatform* platform,
579
    std::vector<std::string>* errors,
580
    EnvironmentArgs&&... env_args) {
581
7
  auto ret = std::unique_ptr<CommonEnvironmentSetup>(new CommonEnvironmentSetup(
582
      platform, errors,
583
7
      [&](const CommonEnvironmentSetup* setup) -> Environment* {
584
21
        return CreateEnvironment(
585
            setup->isolate_data(), setup->context(),
586
14
            std::forward<EnvironmentArgs>(env_args)...);
587
      }));
588
7
  if (!errors->empty()) ret.reset();
589
7
  return ret;
590
}
591
592
/* Converts a unixtime to V8 Date */
593
NODE_DEPRECATED("Use v8::Date::New() directly",
594
                inline v8::Local<v8::Value> NODE_UNIXTIME_V8(double time) {
595
                  return v8::Date::New(
596
                             v8::Isolate::GetCurrent()->GetCurrentContext(),
597
                             1000 * time)
598
                      .ToLocalChecked();
599
                })
600
#define NODE_UNIXTIME_V8 node::NODE_UNIXTIME_V8
601
NODE_DEPRECATED("Use v8::Date::ValueOf() directly",
602
                inline double NODE_V8_UNIXTIME(v8::Local<v8::Date> date) {
603
  return date->ValueOf() / 1000;
604
})
605
#define NODE_V8_UNIXTIME node::NODE_V8_UNIXTIME
606
607
#define NODE_DEFINE_CONSTANT(target, constant)                                \
608
  do {                                                                        \
609
    v8::Isolate* isolate = target->GetIsolate();                              \
610
    v8::Local<v8::Context> context = isolate->GetCurrentContext();            \
611
    v8::Local<v8::String> constant_name =                                     \
612
        v8::String::NewFromUtf8(isolate, #constant,                           \
613
            v8::NewStringType::kInternalized).ToLocalChecked();               \
614
    v8::Local<v8::Number> constant_value =                                    \
615
        v8::Number::New(isolate, static_cast<double>(constant));              \
616
    v8::PropertyAttribute constant_attributes =                               \
617
        static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete);    \
618
    (target)->DefineOwnProperty(context,                                      \
619
                                constant_name,                                \
620
                                constant_value,                               \
621
                                constant_attributes).Check();                 \
622
  }                                                                           \
623
  while (0)
624
625
#define NODE_DEFINE_HIDDEN_CONSTANT(target, constant)                         \
626
  do {                                                                        \
627
    v8::Isolate* isolate = target->GetIsolate();                              \
628
    v8::Local<v8::Context> context = isolate->GetCurrentContext();            \
629
    v8::Local<v8::String> constant_name =                                     \
630
        v8::String::NewFromUtf8(isolate, #constant,                           \
631
                                v8::NewStringType::kInternalized)             \
632
                                  .ToLocalChecked();                          \
633
    v8::Local<v8::Number> constant_value =                                    \
634
        v8::Number::New(isolate, static_cast<double>(constant));              \
635
    v8::PropertyAttribute constant_attributes =                               \
636
        static_cast<v8::PropertyAttribute>(v8::ReadOnly |                     \
637
                                           v8::DontDelete |                   \
638
                                           v8::DontEnum);                     \
639
    (target)->DefineOwnProperty(context,                                      \
640
                                constant_name,                                \
641
                                constant_value,                               \
642
                                constant_attributes).Check();                 \
643
  }                                                                           \
644
  while (0)
645
646
// Used to be a macro, hence the uppercase name.
647
inline void NODE_SET_METHOD(v8::Local<v8::Template> recv,
648
                            const char* name,
649
                            v8::FunctionCallback callback) {
650
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
651
  v8::HandleScope handle_scope(isolate);
652
  v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate,
653
                                                                callback);
654
  v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
655
      v8::NewStringType::kInternalized).ToLocalChecked();
656
  t->SetClassName(fn_name);
657
  recv->Set(fn_name, t);
658
}
659
660
// Used to be a macro, hence the uppercase name.
661
inline void NODE_SET_METHOD(v8::Local<v8::Object> recv,
662
                            const char* name,
663
                            v8::FunctionCallback callback) {
664
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
665
  v8::HandleScope handle_scope(isolate);
666
  v8::Local<v8::Context> context = isolate->GetCurrentContext();
667
  v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate,
668
                                                                callback);
669
  v8::Local<v8::Function> fn = t->GetFunction(context).ToLocalChecked();
670
  v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
671
      v8::NewStringType::kInternalized).ToLocalChecked();
672
  fn->SetName(fn_name);
673
  recv->Set(context, fn_name, fn).Check();
674
}
675
#define NODE_SET_METHOD node::NODE_SET_METHOD
676
677
// Used to be a macro, hence the uppercase name.
678
// Not a template because it only makes sense for FunctionTemplates.
679
inline void NODE_SET_PROTOTYPE_METHOD(v8::Local<v8::FunctionTemplate> recv,
680
                                      const char* name,
681
                                      v8::FunctionCallback callback) {
682
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
683
  v8::HandleScope handle_scope(isolate);
684
  v8::Local<v8::Signature> s = v8::Signature::New(isolate, recv);
685
  v8::Local<v8::FunctionTemplate> t =
686
      v8::FunctionTemplate::New(isolate, callback, v8::Local<v8::Value>(), s);
687
  v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
688
      v8::NewStringType::kInternalized).ToLocalChecked();
689
  t->SetClassName(fn_name);
690
  recv->PrototypeTemplate()->Set(fn_name, t);
691
}
692
#define NODE_SET_PROTOTYPE_METHOD node::NODE_SET_PROTOTYPE_METHOD
693
694
// BINARY is a deprecated alias of LATIN1.
695
// BASE64URL is not currently exposed to the JavaScript side.
696
enum encoding {
697
  ASCII,
698
  UTF8,
699
  BASE64,
700
  UCS2,
701
  BINARY,
702
  HEX,
703
  BUFFER,
704
  BASE64URL,
705
  LATIN1 = BINARY
706
};
707
708
NODE_EXTERN enum encoding ParseEncoding(
709
    v8::Isolate* isolate,
710
    v8::Local<v8::Value> encoding_v,
711
    enum encoding default_encoding = LATIN1);
712
713
NODE_EXTERN void FatalException(v8::Isolate* isolate,
714
                                const v8::TryCatch& try_catch);
715
716
NODE_EXTERN v8::Local<v8::Value> Encode(v8::Isolate* isolate,
717
                                        const char* buf,
718
                                        size_t len,
719
                                        enum encoding encoding = LATIN1);
720
721
// Warning: This reverses endianness on Big Endian platforms, even though the
722
// signature using uint16_t implies that it should not.
723
NODE_EXTERN v8::Local<v8::Value> Encode(v8::Isolate* isolate,
724
                                        const uint16_t* buf,
725
                                        size_t len);
726
727
// Returns -1 if the handle was not valid for decoding
728
NODE_EXTERN ssize_t DecodeBytes(v8::Isolate* isolate,
729
                                v8::Local<v8::Value>,
730
                                enum encoding encoding = LATIN1);
731
// returns bytes written.
732
NODE_EXTERN ssize_t DecodeWrite(v8::Isolate* isolate,
733
                                char* buf,
734
                                size_t buflen,
735
                                v8::Local<v8::Value>,
736
                                enum encoding encoding = LATIN1);
737
#ifdef _WIN32
738
NODE_EXTERN v8::Local<v8::Value> WinapiErrnoException(
739
    v8::Isolate* isolate,
740
    int errorno,
741
    const char* syscall = nullptr,
742
    const char* msg = "",
743
    const char* path = nullptr);
744
#endif
745
746
const char* signo_string(int errorno);
747
748
749
typedef void (*addon_register_func)(
750
    v8::Local<v8::Object> exports,
751
    v8::Local<v8::Value> module,
752
    void* priv);
753
754
typedef void (*addon_context_register_func)(
755
    v8::Local<v8::Object> exports,
756
    v8::Local<v8::Value> module,
757
    v8::Local<v8::Context> context,
758
    void* priv);
759
760
enum ModuleFlags {
761
  kLinked = 0x02
762
};
763
764
struct node_module {
765
  int nm_version;
766
  unsigned int nm_flags;
767
  void* nm_dso_handle;
768
  const char* nm_filename;
769
  node::addon_register_func nm_register_func;
770
  node::addon_context_register_func nm_context_register_func;
771
  const char* nm_modname;
772
  void* nm_priv;
773
  struct node_module* nm_link;
774
};
775
776
extern "C" NODE_EXTERN void node_module_register(void* mod);
777
778
#ifdef _WIN32
779
# define NODE_MODULE_EXPORT __declspec(dllexport)
780
#else
781
# define NODE_MODULE_EXPORT __attribute__((visibility("default")))
782
#endif
783
784
#ifdef NODE_SHARED_MODE
785
# define NODE_CTOR_PREFIX
786
#else
787
# define NODE_CTOR_PREFIX static
788
#endif
789
790
#if defined(_MSC_VER)
791
#pragma section(".CRT$XCU", read)
792
#define NODE_C_CTOR(fn)                                               \
793
  NODE_CTOR_PREFIX void __cdecl fn(void);                             \
794
  __declspec(dllexport, allocate(".CRT$XCU"))                         \
795
      void (__cdecl*fn ## _)(void) = fn;                              \
796
  NODE_CTOR_PREFIX void __cdecl fn(void)
797
#else
798
#define NODE_C_CTOR(fn)                                               \
799
  NODE_CTOR_PREFIX void fn(void) __attribute__((constructor));        \
800
  NODE_CTOR_PREFIX void fn(void)
801
#endif
802
803
#define NODE_MODULE_X(modname, regfunc, priv, flags)                  \
804
  extern "C" {                                                        \
805
    static node::node_module _module =                                \
806
    {                                                                 \
807
      NODE_MODULE_VERSION,                                            \
808
      flags,                                                          \
809
      NULL,  /* NOLINT (readability/null_usage) */                    \
810
      __FILE__,                                                       \
811
      (node::addon_register_func) (regfunc),                          \
812
      NULL,  /* NOLINT (readability/null_usage) */                    \
813
      NODE_STRINGIFY(modname),                                        \
814
      priv,                                                           \
815
      NULL   /* NOLINT (readability/null_usage) */                    \
816
    };                                                                \
817
    NODE_C_CTOR(_register_ ## modname) {                              \
818
      node_module_register(&_module);                                 \
819
    }                                                                 \
820
  }
821
822
#define NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, priv, flags)    \
823
  extern "C" {                                                        \
824
    static node::node_module _module =                                \
825
    {                                                                 \
826
      NODE_MODULE_VERSION,                                            \
827
      flags,                                                          \
828
      NULL,  /* NOLINT (readability/null_usage) */                    \
829
      __FILE__,                                                       \
830
      NULL,  /* NOLINT (readability/null_usage) */                    \
831
      (node::addon_context_register_func) (regfunc),                  \
832
      NODE_STRINGIFY(modname),                                        \
833
      priv,                                                           \
834
      NULL  /* NOLINT (readability/null_usage) */                     \
835
    };                                                                \
836
    NODE_C_CTOR(_register_ ## modname) {                              \
837
      node_module_register(&_module);                                 \
838
    }                                                                 \
839
  }
840
841
// Usage: `NODE_MODULE(NODE_GYP_MODULE_NAME, InitializerFunction)`
842
// If no NODE_MODULE is declared, Node.js looks for the well-known
843
// symbol `node_register_module_v${NODE_MODULE_VERSION}`.
844
#define NODE_MODULE(modname, regfunc)                                 \
845
  NODE_MODULE_X(modname, regfunc, NULL, 0)  // NOLINT (readability/null_usage)
846
847
#define NODE_MODULE_CONTEXT_AWARE(modname, regfunc)                   \
848
  /* NOLINTNEXTLINE (readability/null_usage) */                       \
849
  NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL, 0)
850
851
// Embedders can use this type of binding for statically linked native bindings.
852
// It is used the same way addon bindings are used, except that linked bindings
853
// can be accessed through `process._linkedBinding(modname)`.
854
#define NODE_MODULE_LINKED(modname, regfunc)                               \
855
  /* NOLINTNEXTLINE (readability/null_usage) */                            \
856
  NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL,                      \
857
                              node::ModuleFlags::kLinked)
858
859
/*
860
 * For backward compatibility in add-on modules.
861
 */
862
#define NODE_MODULE_DECL /* nothing */
863
864
#define NODE_MODULE_INITIALIZER_BASE node_register_module_v
865
866
#define NODE_MODULE_INITIALIZER_X(base, version)                      \
867
    NODE_MODULE_INITIALIZER_X_HELPER(base, version)
868
869
#define NODE_MODULE_INITIALIZER_X_HELPER(base, version) base##version
870
871
#define NODE_MODULE_INITIALIZER                                       \
872
  NODE_MODULE_INITIALIZER_X(NODE_MODULE_INITIALIZER_BASE,             \
873
      NODE_MODULE_VERSION)
874
875
#define NODE_MODULE_INIT()                                            \
876
  extern "C" NODE_MODULE_EXPORT void                                  \
877
  NODE_MODULE_INITIALIZER(v8::Local<v8::Object> exports,              \
878
                          v8::Local<v8::Value> module,                \
879
                          v8::Local<v8::Context> context);            \
880
  NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME,                     \
881
                            NODE_MODULE_INITIALIZER)                  \
882
  void NODE_MODULE_INITIALIZER(v8::Local<v8::Object> exports,         \
883
                               v8::Local<v8::Value> module,           \
884
                               v8::Local<v8::Context> context)
885
886
// Allows embedders to add a binding to the current Environment* that can be
887
// accessed through process._linkedBinding() in the target Environment and all
888
// Worker threads that it creates.
889
// In each variant, the registration function needs to be usable at least for
890
// the time during which the Environment exists.
891
NODE_EXTERN void AddLinkedBinding(Environment* env, const node_module& mod);
892
NODE_EXTERN void AddLinkedBinding(Environment* env,
893
                                  const struct napi_module& mod);
894
NODE_EXTERN void AddLinkedBinding(Environment* env,
895
                                  const char* name,
896
                                  addon_context_register_func fn,
897
                                  void* priv);
898
899
/* Registers a callback with the passed-in Environment instance. The callback
900
 * is called after the event loop exits, but before the VM is disposed.
901
 * Callbacks are run in reverse order of registration, i.e. newest first.
902
 */
903
NODE_EXTERN void AtExit(Environment* env,
904
                        void (*cb)(void* arg),
905
                        void* arg);
906
907
typedef double async_id;
908
struct async_context {
909
  ::node::async_id async_id;
910
  ::node::async_id trigger_async_id;
911
};
912
913
/* This is a lot like node::AtExit, except that the hooks added via this
914
 * function are run before the AtExit ones and will always be registered
915
 * for the current Environment instance.
916
 * These functions are safe to use in an addon supporting multiple
917
 * threads/isolates. */
918
NODE_EXTERN void AddEnvironmentCleanupHook(v8::Isolate* isolate,
919
                                           void (*fun)(void* arg),
920
                                           void* arg);
921
922
NODE_EXTERN void RemoveEnvironmentCleanupHook(v8::Isolate* isolate,
923
                                              void (*fun)(void* arg),
924
                                              void* arg);
925
926
/* These are async equivalents of the above. After the cleanup hook is invoked,
927
 * `cb(cbarg)` *must* be called, and attempting to remove the cleanup hook will
928
 * have no effect. */
929
struct ACHHandle;
930
struct NODE_EXTERN DeleteACHHandle { void operator()(ACHHandle*) const; };
931
typedef std::unique_ptr<ACHHandle, DeleteACHHandle> AsyncCleanupHookHandle;
932
933
/* This function is not intended to be used externally, it exists to aid in
934
 * keeping ABI compatibility between Node and Electron. */
935
NODE_EXTERN ACHHandle* AddEnvironmentCleanupHookInternal(
936
    v8::Isolate* isolate,
937
    void (*fun)(void* arg, void (*cb)(void*), void* cbarg),
938
    void* arg);
939
6
inline AsyncCleanupHookHandle AddEnvironmentCleanupHook(
940
    v8::Isolate* isolate,
941
    void (*fun)(void* arg, void (*cb)(void*), void* cbarg),
942
    void* arg) {
943
  return AsyncCleanupHookHandle(AddEnvironmentCleanupHookInternal(isolate, fun,
944
6
      arg));
945
}
946
947
/* This function is not intended to be used externally, it exists to aid in
948
 * keeping ABI compatibility between Node and Electron. */
949
NODE_EXTERN void RemoveEnvironmentCleanupHookInternal(ACHHandle* holder);
950
6
inline void RemoveEnvironmentCleanupHook(AsyncCleanupHookHandle holder) {
951
6
  RemoveEnvironmentCleanupHookInternal(holder.get());
952
6
}
953
954
/* Returns the id of the current execution context. If the return value is
955
 * zero then no execution has been set. This will happen if the user handles
956
 * I/O from native code. */
957
NODE_EXTERN async_id AsyncHooksGetExecutionAsyncId(v8::Isolate* isolate);
958
959
/* Return same value as async_hooks.triggerAsyncId(); */
960
NODE_EXTERN async_id AsyncHooksGetTriggerAsyncId(v8::Isolate* isolate);
961
962
/* If the native API doesn't inherit from the helper class then the callbacks
963
 * must be triggered manually. This triggers the init() callback. The return
964
 * value is the async id assigned to the resource.
965
 *
966
 * The `trigger_async_id` parameter should correspond to the resource which is
967
 * creating the new resource, which will usually be the return value of
968
 * `AsyncHooksGetTriggerAsyncId()`. */
969
NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate,
970
                                        v8::Local<v8::Object> resource,
971
                                        const char* name,
972
                                        async_id trigger_async_id = -1);
973
974
NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate,
975
                                        v8::Local<v8::Object> resource,
976
                                        v8::Local<v8::String> name,
977
                                        async_id trigger_async_id = -1);
978
979
/* Emit the destroy() callback. The overload taking an `Environment*` argument
980
 * should be used when the Isolate’s current Context is not associated with
981
 * a Node.js Environment, or when there is no current Context, for example
982
 * when calling this function during garbage collection. In that case, the
983
 * `Environment*` value should have been acquired previously, e.g. through
984
 * `GetCurrentEnvironment()`. */
985
NODE_EXTERN void EmitAsyncDestroy(v8::Isolate* isolate,
986
                                  async_context asyncContext);
987
NODE_EXTERN void EmitAsyncDestroy(Environment* env,
988
                                  async_context asyncContext);
989
990
class InternalCallbackScope;
991
992
/* This class works like `MakeCallback()` in that it sets up a specific
993
 * asyncContext as the current one and informs the async_hooks and domains
994
 * modules that this context is currently active.
995
 *
996
 * `MakeCallback()` is a wrapper around this class as well as
997
 * `Function::Call()`. Either one of these mechanisms needs to be used for
998
 * top-level calls into JavaScript (i.e. without any existing JS stack).
999
 *
1000
 * This object should be stack-allocated to ensure that it is contained in a
1001
 * valid HandleScope.
1002
 *
1003
 * Exceptions happening within this scope will be treated like uncaught
1004
 * exceptions. If this behaviour is undesirable, a new `v8::TryCatch` scope
1005
 * needs to be created inside of this scope.
1006
 */
1007
class NODE_EXTERN CallbackScope {
1008
 public:
1009
  CallbackScope(v8::Isolate* isolate,
1010
                v8::Local<v8::Object> resource,
1011
                async_context asyncContext);
1012
  CallbackScope(Environment* env,
1013
                v8::Local<v8::Object> resource,
1014
                async_context asyncContext);
1015
  ~CallbackScope();
1016
1017
  void operator=(const CallbackScope&) = delete;
1018
  void operator=(CallbackScope&&) = delete;
1019
  CallbackScope(const CallbackScope&) = delete;
1020
  CallbackScope(CallbackScope&&) = delete;
1021
1022
 private:
1023
  InternalCallbackScope* private_;
1024
  v8::TryCatch try_catch_;
1025
};
1026
1027
/* An API specific to emit before/after callbacks is unnecessary because
1028
 * MakeCallback will automatically call them for you.
1029
 *
1030
 * These methods may create handles on their own, so run them inside a
1031
 * HandleScope.
1032
 *
1033
 * `asyncId` and `triggerAsyncId` should correspond to the values returned by
1034
 * `EmitAsyncInit()` and `AsyncHooksGetTriggerAsyncId()`, respectively, when the
1035
 * invoking resource was created. If these values are unknown, 0 can be passed.
1036
 * */
1037
NODE_EXTERN
1038
v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
1039
                                       v8::Local<v8::Object> recv,
1040
                                       v8::Local<v8::Function> callback,
1041
                                       int argc,
1042
                                       v8::Local<v8::Value>* argv,
1043
                                       async_context asyncContext);
1044
NODE_EXTERN
1045
v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
1046
                                       v8::Local<v8::Object> recv,
1047
                                       const char* method,
1048
                                       int argc,
1049
                                       v8::Local<v8::Value>* argv,
1050
                                       async_context asyncContext);
1051
NODE_EXTERN
1052
v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
1053
                                       v8::Local<v8::Object> recv,
1054
                                       v8::Local<v8::String> symbol,
1055
                                       int argc,
1056
                                       v8::Local<v8::Value>* argv,
1057
                                       async_context asyncContext);
1058
1059
/* Helper class users can optionally inherit from. If
1060
 * `AsyncResource::MakeCallback()` is used, then all four callbacks will be
1061
 * called automatically. */
1062
class NODE_EXTERN AsyncResource {
1063
 public:
1064
  AsyncResource(v8::Isolate* isolate,
1065
                v8::Local<v8::Object> resource,
1066
                const char* name,
1067
                async_id trigger_async_id = -1);
1068
1069
  virtual ~AsyncResource();
1070
1071
  AsyncResource(const AsyncResource&) = delete;
1072
  void operator=(const AsyncResource&) = delete;
1073
1074
  v8::MaybeLocal<v8::Value> MakeCallback(
1075
      v8::Local<v8::Function> callback,
1076
      int argc,
1077
      v8::Local<v8::Value>* argv);
1078
1079
  v8::MaybeLocal<v8::Value> MakeCallback(
1080
      const char* method,
1081
      int argc,
1082
      v8::Local<v8::Value>* argv);
1083
1084
  v8::MaybeLocal<v8::Value> MakeCallback(
1085
      v8::Local<v8::String> symbol,
1086
      int argc,
1087
      v8::Local<v8::Value>* argv);
1088
1089
  v8::Local<v8::Object> get_resource();
1090
  async_id get_async_id() const;
1091
  async_id get_trigger_async_id() const;
1092
1093
 protected:
1094
  class NODE_EXTERN CallbackScope : public node::CallbackScope {
1095
   public:
1096
    explicit CallbackScope(AsyncResource* res);
1097
  };
1098
1099
 private:
1100
  Environment* env_;
1101
  v8::Global<v8::Object> resource_;
1102
  async_context async_context_;
1103
};
1104
1105
#ifndef _WIN32
1106
// Register a signal handler without interrupting any handlers that node
1107
// itself needs. This does override handlers registered through
1108
// process.on('SIG...', function() { ... }). The `reset_handler` flag indicates
1109
// whether the signal handler for the given signal should be reset to its
1110
// default value before executing the handler (i.e. it works like SA_RESETHAND).
1111
// The `reset_handler` flag is invalid when `signal` is SIGSEGV.
1112
NODE_EXTERN
1113
void RegisterSignalHandler(int signal,
1114
                           void (*handler)(int signal,
1115
                                           siginfo_t* info,
1116
                                           void* ucontext),
1117
                           bool reset_handler = false);
1118
#endif  // _WIN32
1119
1120
}  // namespace node
1121
1122
#endif  // SRC_NODE_H_