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