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