Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-09-15 09:02:40

0001 // Copyright Joyent, Inc. and other Node contributors.
0002 //
0003 // Permission is hereby granted, free of charge, to any person obtaining a
0004 // copy of this software and associated documentation files (the
0005 // "Software"), to deal in the Software without restriction, including
0006 // without limitation the rights to use, copy, modify, merge, publish,
0007 // distribute, sublicense, and/or sell copies of the Software, and to permit
0008 // persons to whom the Software is furnished to do so, subject to the
0009 // following conditions:
0010 //
0011 // The above copyright notice and this permission notice shall be included
0012 // in all copies or substantial portions of the Software.
0013 //
0014 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
0015 // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
0016 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
0017 // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
0018 // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
0019 // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
0020 // USE OR OTHER DEALINGS IN THE SOFTWARE.
0021 
0022 #ifndef SRC_NODE_H_
0023 #define SRC_NODE_H_
0024 
0025 #ifdef _WIN32
0026 # ifndef BUILDING_NODE_EXTENSION
0027 #  define NODE_EXTERN __declspec(dllexport)
0028 # else
0029 #  define NODE_EXTERN __declspec(dllimport)
0030 # endif
0031 #else
0032 # define NODE_EXTERN __attribute__((visibility("default")))
0033 #endif
0034 
0035 // Declarations annotated with NODE_EXTERN_PRIVATE do not form part of
0036 // the public API. They are implementation details that can and will
0037 // change between releases, even in semver patch releases. Do not use
0038 // any such symbol in external code.
0039 #ifdef NODE_SHARED_MODE
0040 #define NODE_EXTERN_PRIVATE NODE_EXTERN
0041 #else
0042 #define NODE_EXTERN_PRIVATE
0043 #endif
0044 
0045 #ifdef BUILDING_NODE_EXTENSION
0046 # undef BUILDING_V8_SHARED
0047 # undef BUILDING_UV_SHARED
0048 # define USING_V8_SHARED 1
0049 # define USING_UV_SHARED 1
0050 #endif
0051 
0052 // This should be defined in make system.
0053 // See issue https://github.com/nodejs/node-v0.x-archive/issues/1236
0054 #if defined(__MINGW32__) || defined(_MSC_VER)
0055 #ifndef _WIN32_WINNT
0056 # define _WIN32_WINNT 0x0600  // Windows Server 2008
0057 #endif
0058 
0059 #ifndef NOMINMAX
0060 # define NOMINMAX
0061 #endif
0062 
0063 #endif
0064 
0065 #if defined(_MSC_VER)
0066 #define PATH_MAX MAX_PATH
0067 #endif
0068 
0069 #ifdef _WIN32
0070 #define SIGQUIT 3
0071 #define SIGKILL 9
0072 #endif
0073 
0074 #include "v8.h"  // NOLINT(build/include_order)
0075 
0076 #include "v8-platform.h"  // NOLINT(build/include_order)
0077 #include "node_version.h"  // NODE_MODULE_VERSION
0078 
0079 #define NAPI_EXPERIMENTAL
0080 #include "node_api.h"
0081 
0082 #include <functional>
0083 #include <memory>
0084 #include <optional>
0085 #include <ostream>
0086 
0087 // We cannot use __POSIX__ in this header because that's only defined when
0088 // building Node.js.
0089 #ifndef _WIN32
0090 #include <signal.h>
0091 #endif  // _WIN32
0092 
0093 #define NODE_MAKE_VERSION(major, minor, patch)                                \
0094   ((major) * 0x1000 + (minor) * 0x100 + (patch))
0095 
0096 #ifdef __clang__
0097 # define NODE_CLANG_AT_LEAST(major, minor, patch)                             \
0098   (NODE_MAKE_VERSION(major, minor, patch) <=                                  \
0099       NODE_MAKE_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__))
0100 #else
0101 # define NODE_CLANG_AT_LEAST(major, minor, patch) (0)
0102 #endif
0103 
0104 #ifdef __GNUC__
0105 # define NODE_GNUC_AT_LEAST(major, minor, patch)                              \
0106   (NODE_MAKE_VERSION(major, minor, patch) <=                                  \
0107       NODE_MAKE_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__))
0108 #else
0109 # define NODE_GNUC_AT_LEAST(major, minor, patch) (0)
0110 #endif
0111 
0112 #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
0113 # define NODE_DEPRECATED(message, declarator) declarator
0114 #else  // NODE_WANT_INTERNALS
0115 # if NODE_CLANG_AT_LEAST(2, 9, 0) || NODE_GNUC_AT_LEAST(4, 5, 0)
0116 #  define NODE_DEPRECATED(message, declarator)                                 \
0117     __attribute__((deprecated(message))) declarator
0118 # elif defined(_MSC_VER)
0119 #  define NODE_DEPRECATED(message, declarator)                                 \
0120     __declspec(deprecated) declarator
0121 # else
0122 #  define NODE_DEPRECATED(message, declarator) declarator
0123 # endif
0124 #endif
0125 
0126 // Forward-declare libuv loop
0127 struct uv_loop_s;
0128 
0129 // Forward-declare these functions now to stop MSVS from becoming
0130 // terminally confused when it's done in node_internals.h
0131 namespace node {
0132 
0133 struct SnapshotData;
0134 
0135 namespace tracing {
0136 
0137 class TracingController;
0138 
0139 }
0140 
0141 NODE_EXTERN v8::Local<v8::Value> ErrnoException(v8::Isolate* isolate,
0142                                                 int errorno,
0143                                                 const char* syscall = nullptr,
0144                                                 const char* message = nullptr,
0145                                                 const char* path = nullptr);
0146 NODE_EXTERN v8::Local<v8::Value> UVException(v8::Isolate* isolate,
0147                                              int errorno,
0148                                              const char* syscall = nullptr,
0149                                              const char* message = nullptr,
0150                                              const char* path = nullptr,
0151                                              const char* dest = nullptr);
0152 
0153 NODE_DEPRECATED("Use ErrnoException(isolate, ...)",
0154                 inline v8::Local<v8::Value> ErrnoException(
0155       int errorno,
0156       const char* syscall = nullptr,
0157       const char* message = nullptr,
0158       const char* path = nullptr) {
0159   return ErrnoException(v8::Isolate::GetCurrent(),
0160                         errorno,
0161                         syscall,
0162                         message,
0163                         path);
0164 })
0165 
0166 NODE_DEPRECATED("Use UVException(isolate, ...)",
0167                 inline v8::Local<v8::Value> UVException(int errorno,
0168                                         const char* syscall = nullptr,
0169                                         const char* message = nullptr,
0170                                         const char* path = nullptr) {
0171   return UVException(v8::Isolate::GetCurrent(),
0172                      errorno,
0173                      syscall,
0174                      message,
0175                      path);
0176 })
0177 
0178 /*
0179  * These methods need to be called in a HandleScope.
0180  *
0181  * It is preferred that you use the `MakeCallback` overloads taking
0182  * `async_context` arguments.
0183  */
0184 
0185 NODE_DEPRECATED("Use MakeCallback(..., async_context)",
0186                 NODE_EXTERN v8::Local<v8::Value> MakeCallback(
0187                     v8::Isolate* isolate,
0188                     v8::Local<v8::Object> recv,
0189                     const char* method,
0190                     int argc,
0191                     v8::Local<v8::Value>* argv));
0192 NODE_DEPRECATED("Use MakeCallback(..., async_context)",
0193                 NODE_EXTERN v8::Local<v8::Value> MakeCallback(
0194                     v8::Isolate* isolate,
0195                     v8::Local<v8::Object> recv,
0196                     v8::Local<v8::String> symbol,
0197                     int argc,
0198                     v8::Local<v8::Value>* argv));
0199 NODE_DEPRECATED("Use MakeCallback(..., async_context)",
0200                 NODE_EXTERN v8::Local<v8::Value> MakeCallback(
0201                     v8::Isolate* isolate,
0202                     v8::Local<v8::Object> recv,
0203                     v8::Local<v8::Function> callback,
0204                     int argc,
0205                     v8::Local<v8::Value>* argv));
0206 
0207 }  // namespace node
0208 
0209 #include <cassert>
0210 #include <cstdint>
0211 
0212 #ifndef NODE_STRINGIFY
0213 # define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n)
0214 # define NODE_STRINGIFY_HELPER(n) #n
0215 #endif
0216 
0217 #ifdef _WIN32
0218 #if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED)
0219 typedef intptr_t ssize_t;
0220 # define _SSIZE_T_
0221 # define _SSIZE_T_DEFINED
0222 #endif
0223 #else  // !_WIN32
0224 # include <sys/types.h>  // size_t, ssize_t
0225 #endif  // _WIN32
0226 
0227 
0228 namespace node {
0229 
0230 class IsolateData;
0231 class Environment;
0232 class MultiIsolatePlatform;
0233 class InitializationResultImpl;
0234 
0235 namespace ProcessInitializationFlags {
0236 enum Flags : uint32_t {
0237   kNoFlags = 0,
0238   // Enable stdio inheritance, which is disabled by default.
0239   // This flag is also implied by kNoStdioInitialization.
0240   kEnableStdioInheritance = 1 << 0,
0241   // Disable reading the NODE_OPTIONS environment variable.
0242   kDisableNodeOptionsEnv = 1 << 1,
0243   // Do not parse CLI options.
0244   kDisableCLIOptions = 1 << 2,
0245   // Do not initialize ICU.
0246   kNoICU = 1 << 3,
0247   // Do not modify stdio file descriptor or TTY state.
0248   kNoStdioInitialization = 1 << 4,
0249   // Do not register Node.js-specific signal handlers
0250   // and reset other signal handlers to default state.
0251   kNoDefaultSignalHandling = 1 << 5,
0252   // Do not perform V8 initialization.
0253   kNoInitializeV8 = 1 << 6,
0254   // Do not initialize a default Node.js-provided V8 platform instance.
0255   kNoInitializeNodeV8Platform = 1 << 7,
0256   // Do not initialize OpenSSL config.
0257   kNoInitOpenSSL = 1 << 8,
0258   // Do not initialize Node.js debugging based on environment variables.
0259   kNoParseGlobalDebugVariables = 1 << 9,
0260   // Do not adjust OS resource limits for this process.
0261   kNoAdjustResourceLimits = 1 << 10,
0262   // Do not map code segments into large pages for this process.
0263   kNoUseLargePages = 1 << 11,
0264   // Skip printing output for --help, --version, --v8-options.
0265   kNoPrintHelpOrVersionOutput = 1 << 12,
0266   // Do not perform cppgc initialization. If set, the embedder must call
0267   // cppgc::InitializeProcess() before creating a Node.js environment
0268   // and call cppgc::ShutdownProcess() before process shutdown.
0269   kNoInitializeCppgc = 1 << 13,
0270   // Initialize the process for predictable snapshot generation.
0271   kGeneratePredictableSnapshot = 1 << 14,
0272 
0273   // Emulate the behavior of InitializeNodeWithArgs() when passing
0274   // a flags argument to the InitializeOncePerProcess() replacement
0275   // function.
0276   kLegacyInitializeNodeWithArgsBehavior =
0277       kNoStdioInitialization | kNoDefaultSignalHandling | kNoInitializeV8 |
0278       kNoInitializeNodeV8Platform | kNoInitOpenSSL |
0279       kNoParseGlobalDebugVariables | kNoAdjustResourceLimits |
0280       kNoUseLargePages | kNoPrintHelpOrVersionOutput | kNoInitializeCppgc,
0281 };
0282 }  // namespace ProcessInitializationFlags
0283 namespace ProcessFlags = ProcessInitializationFlags;  // Legacy alias.
0284 
0285 namespace StopFlags {
0286 enum Flags : uint32_t {
0287   kNoFlags = 0,
0288   // Do not explicitly terminate the Isolate
0289   // when exiting the Environment.
0290   kDoNotTerminateIsolate = 1 << 0,
0291 };
0292 }  // namespace StopFlags
0293 
0294 class NODE_EXTERN InitializationResult {
0295  public:
0296   virtual ~InitializationResult() = default;
0297 
0298   // Returns a suggested process exit code.
0299   virtual int exit_code() const = 0;
0300 
0301   // Returns 'true' if initialization was aborted early due to errors.
0302   virtual bool early_return() const = 0;
0303 
0304   // Returns the parsed list of non-Node.js arguments.
0305   virtual const std::vector<std::string>& args() const = 0;
0306 
0307   // Returns the parsed list of Node.js arguments.
0308   virtual const std::vector<std::string>& exec_args() const = 0;
0309 
0310   // Returns an array of errors. Note that these may be warnings
0311   // whose existence does not imply a non-zero exit code.
0312   virtual const std::vector<std::string>& errors() const = 0;
0313 
0314   // If kNoInitializeNodeV8Platform was not specified, the global Node.js
0315   // platform instance.
0316   virtual MultiIsolatePlatform* platform() const = 0;
0317 
0318  private:
0319   InitializationResult() = default;
0320   friend class InitializationResultImpl;
0321 };
0322 
0323 // TODO(addaleax): Officially deprecate this and replace it with something
0324 // better suited for a public embedder API.
0325 NODE_EXTERN int Start(int argc, char* argv[]);
0326 
0327 // Tear down Node.js while it is running (there are active handles
0328 // in the loop and / or actively executing JavaScript code).
0329 NODE_EXTERN int Stop(Environment* env,
0330                      StopFlags::Flags flags = StopFlags::kNoFlags);
0331 
0332 // Set up per-process state needed to run Node.js. This will consume arguments
0333 // from argv, fill exec_argv, and possibly add errors resulting from parsing
0334 // the arguments to `errors`. The return value is a suggested exit code for the
0335 // program; If it is 0, then initializing Node.js succeeded.
0336 // This runs a subset of the initialization performed by
0337 // InitializeOncePerProcess(), which supersedes this function.
0338 // The subset is roughly equivalent to the one given by
0339 // `ProcessInitializationFlags::kLegacyInitializeNodeWithArgsBehavior`.
0340 NODE_DEPRECATED("Use InitializeOncePerProcess() instead",
0341                 NODE_EXTERN int InitializeNodeWithArgs(
0342                     std::vector<std::string>* argv,
0343                     std::vector<std::string>* exec_argv,
0344                     std::vector<std::string>* errors,
0345                     ProcessInitializationFlags::Flags flags =
0346                         ProcessInitializationFlags::kNoFlags));
0347 
0348 // Set up per-process state needed to run Node.js. This will consume arguments
0349 // from args, and return information about the initialization success,
0350 // including the arguments split into argv/exec_argv, a list of potential
0351 // errors encountered during initialization, and a potential suggested
0352 // exit code.
0353 NODE_EXTERN std::shared_ptr<InitializationResult> InitializeOncePerProcess(
0354     const std::vector<std::string>& args,
0355     ProcessInitializationFlags::Flags flags =
0356         ProcessInitializationFlags::kNoFlags);
0357 // Undoes the initialization performed by InitializeOncePerProcess(),
0358 // where cleanup is necessary.
0359 NODE_EXTERN void TearDownOncePerProcess();
0360 // Convenience overload for specifying multiple flags without having
0361 // to worry about casts.
0362 inline std::shared_ptr<InitializationResult> InitializeOncePerProcess(
0363     const std::vector<std::string>& args,
0364     std::initializer_list<ProcessInitializationFlags::Flags> list) {
0365   uint64_t flags_accum = ProcessInitializationFlags::kNoFlags;
0366   for (const auto flag : list) flags_accum |= static_cast<uint64_t>(flag);
0367   return InitializeOncePerProcess(
0368       args, static_cast<ProcessInitializationFlags::Flags>(flags_accum));
0369 }
0370 
0371 enum OptionEnvvarSettings {
0372   // Allow the options to be set via the environment variable, like
0373   // `NODE_OPTIONS`.
0374   kAllowedInEnvvar = 0,
0375   // Disallow the options to be set via the environment variable, like
0376   // `NODE_OPTIONS`.
0377   kDisallowedInEnvvar = 1,
0378   // Deprecated, use kAllowedInEnvvar instead.
0379   kAllowedInEnvironment = kAllowedInEnvvar,
0380   // Deprecated, use kDisallowedInEnvvar instead.
0381   kDisallowedInEnvironment = kDisallowedInEnvvar,
0382 };
0383 
0384 // Process the arguments and set up the per-process options.
0385 // If the `settings` is set as OptionEnvvarSettings::kAllowedInEnvvar, the
0386 // options that are allowed in the environment variable are processed. Options
0387 // that are disallowed to be set via environment variable are processed as
0388 // errors.
0389 // Otherwise all the options that are disallowed (and those are allowed) to be
0390 // set via environment variable are processed.
0391 NODE_EXTERN int ProcessGlobalArgs(std::vector<std::string>* args,
0392                       std::vector<std::string>* exec_args,
0393                       std::vector<std::string>* errors,
0394                       OptionEnvvarSettings settings);
0395 
0396 class NodeArrayBufferAllocator;
0397 
0398 // An ArrayBuffer::Allocator class with some Node.js-specific tweaks. If you do
0399 // not have to use another allocator, using this class is recommended:
0400 // - It supports Buffer.allocUnsafe() and Buffer.allocUnsafeSlow() with
0401 //   uninitialized memory.
0402 // - It supports transferring, rather than copying, ArrayBuffers when using
0403 //   MessagePorts.
0404 class NODE_EXTERN ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
0405  public:
0406   // If `always_debug` is true, create an ArrayBuffer::Allocator instance
0407   // that performs additional integrity checks (e.g. make sure that only memory
0408   // that was allocated by the it is also freed by it).
0409   // This can also be set using the --debug-arraybuffer-allocations flag.
0410   static std::unique_ptr<ArrayBufferAllocator> Create(
0411       bool always_debug = false);
0412 
0413  private:
0414   virtual NodeArrayBufferAllocator* GetImpl() = 0;
0415 
0416   friend class IsolateData;
0417 };
0418 
0419 // Legacy equivalents for ArrayBufferAllocator::Create().
0420 NODE_EXTERN ArrayBufferAllocator* CreateArrayBufferAllocator();
0421 NODE_EXTERN void FreeArrayBufferAllocator(ArrayBufferAllocator* allocator);
0422 
0423 class NODE_EXTERN IsolatePlatformDelegate {
0424  public:
0425   virtual std::shared_ptr<v8::TaskRunner> GetForegroundTaskRunner() = 0;
0426   virtual bool IdleTasksEnabled() = 0;
0427 };
0428 
0429 class NODE_EXTERN MultiIsolatePlatform : public v8::Platform {
0430  public:
0431   ~MultiIsolatePlatform() override = default;
0432   // Returns true if work was dispatched or executed. New tasks that are
0433   // posted during flushing of the queue are postponed until the next
0434   // flushing.
0435   virtual bool FlushForegroundTasks(v8::Isolate* isolate) = 0;
0436   virtual void DrainTasks(v8::Isolate* isolate) = 0;
0437 
0438   // This needs to be called between the calls to `Isolate::Allocate()` and
0439   // `Isolate::Initialize()`, so that initialization can already start
0440   // using the platform.
0441   // When using `NewIsolate()`, this is taken care of by that function.
0442   // This function may only be called once per `Isolate`.
0443   virtual void RegisterIsolate(v8::Isolate* isolate,
0444                                struct uv_loop_s* loop) = 0;
0445   // This method can be used when an application handles task scheduling on its
0446   // own through `IsolatePlatformDelegate`. Upon registering an isolate with
0447   // this overload any other method in this class with the exception of
0448   // `UnregisterIsolate` *must not* be used on that isolate.
0449   virtual void RegisterIsolate(v8::Isolate* isolate,
0450                                IsolatePlatformDelegate* delegate) = 0;
0451 
0452   // This function may only be called once per `Isolate`, and discard any
0453   // pending delayed tasks scheduled for that isolate.
0454   // This needs to be called right before calling `Isolate::Dispose()`.
0455   virtual void UnregisterIsolate(v8::Isolate* isolate) = 0;
0456 
0457   // The platform should call the passed function once all state associated
0458   // with the given isolate has been cleaned up. This can, but does not have to,
0459   // happen asynchronously.
0460   virtual void AddIsolateFinishedCallback(v8::Isolate* isolate,
0461                                           void (*callback)(void*),
0462                                           void* data) = 0;
0463 
0464   static std::unique_ptr<MultiIsolatePlatform> Create(
0465       int thread_pool_size,
0466       v8::TracingController* tracing_controller = nullptr,
0467       v8::PageAllocator* page_allocator = nullptr);
0468 };
0469 
0470 enum IsolateSettingsFlags {
0471   MESSAGE_LISTENER_WITH_ERROR_LEVEL = 1 << 0,
0472   DETAILED_SOURCE_POSITIONS_FOR_PROFILING = 1 << 1,
0473   SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK = 1 << 2,
0474   SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK = 1 << 3,
0475   ALLOW_MODIFY_CODE_GENERATION_FROM_STRINGS_CALLBACK = 0, /* legacy no-op */
0476 };
0477 
0478 struct IsolateSettings {
0479   uint64_t flags = MESSAGE_LISTENER_WITH_ERROR_LEVEL |
0480       DETAILED_SOURCE_POSITIONS_FOR_PROFILING;
0481   v8::MicrotasksPolicy policy = v8::MicrotasksPolicy::kExplicit;
0482 
0483   // Error handling callbacks
0484   v8::Isolate::AbortOnUncaughtExceptionCallback
0485       should_abort_on_uncaught_exception_callback = nullptr;
0486   v8::FatalErrorCallback fatal_error_callback = nullptr;
0487   v8::OOMErrorCallback oom_error_callback = nullptr;
0488   v8::PrepareStackTraceCallback prepare_stack_trace_callback = nullptr;
0489 
0490   // Miscellaneous callbacks
0491   v8::PromiseRejectCallback promise_reject_callback = nullptr;
0492   v8::AllowWasmCodeGenerationCallback
0493       allow_wasm_code_generation_callback = nullptr;
0494   v8::ModifyCodeGenerationFromStringsCallback2
0495       modify_code_generation_from_strings_callback = nullptr;
0496 };
0497 
0498 // Represents a startup snapshot blob, e.g. created by passing
0499 // --node-snapshot-main=entry.js to the configure script at build time,
0500 // or by running Node.js with the --build-snapshot option.
0501 //
0502 // If used, the snapshot *must* have been built with the same Node.js
0503 // version and V8 flags as the version that is currently running, and will
0504 // be rejected otherwise.
0505 // The same EmbedderSnapshotData instance *must* be passed to both
0506 // `NewIsolate()` and `CreateIsolateData()`. The first `Environment` instance
0507 // should be created with an empty `context` argument and will then
0508 // use the main context included in the snapshot blob. It can be retrieved
0509 // using `GetMainContext()`. `LoadEnvironment` can receive an empty
0510 // `StartExecutionCallback` in this case.
0511 // If V8 was configured with the shared-readonly-heap option, it requires
0512 // all snapshots used to create `Isolate` instances to be identical.
0513 // This option *must* be unset by embedders who wish to use the startup
0514 // feature during the build step by passing the --disable-shared-readonly-heap
0515 // flag to the configure script.
0516 //
0517 // The snapshot *must* be kept alive during the execution of the Isolate
0518 // that was created using it.
0519 //
0520 // Snapshots are an *experimental* feature. In particular, the embedder API
0521 // exposed through this class is subject to change or removal between Node.js
0522 // versions, including possible API and ABI breakage.
0523 class EmbedderSnapshotData {
0524  public:
0525   struct DeleteSnapshotData {
0526     void operator()(const EmbedderSnapshotData*) const;
0527   };
0528   using Pointer =
0529       std::unique_ptr<const EmbedderSnapshotData, DeleteSnapshotData>;
0530 
0531   // Return an EmbedderSnapshotData object that refers to the built-in
0532   // snapshot of Node.js. This can have been configured through e.g.
0533   // --node-snapshot-main=entry.js.
0534   static Pointer BuiltinSnapshotData();
0535 
0536   // Return an EmbedderSnapshotData object that is based on an input file.
0537   // Calling this method will consume but not close the FILE* handle.
0538   // The FILE* handle can be closed immediately following this call.
0539   // If the snapshot is invalid, this returns an empty pointer.
0540   static Pointer FromFile(FILE* in);
0541   static Pointer FromBlob(const std::vector<char>& in);
0542   static Pointer FromBlob(std::string_view in);
0543 
0544   // Write this EmbedderSnapshotData object to an output file.
0545   // Calling this method will not close the FILE* handle.
0546   // The FILE* handle can be closed immediately following this call.
0547   void ToFile(FILE* out) const;
0548   std::vector<char> ToBlob() const;
0549 
0550   // Returns whether custom snapshots can be used. Currently, this means
0551   // that V8 was configured without the shared-readonly-heap feature.
0552   static bool CanUseCustomSnapshotPerIsolate();
0553 
0554   EmbedderSnapshotData(const EmbedderSnapshotData&) = delete;
0555   EmbedderSnapshotData& operator=(const EmbedderSnapshotData&) = delete;
0556   EmbedderSnapshotData(EmbedderSnapshotData&&) = delete;
0557   EmbedderSnapshotData& operator=(EmbedderSnapshotData&&) = delete;
0558 
0559  protected:
0560   EmbedderSnapshotData(const SnapshotData* impl, bool owns_impl);
0561 
0562  private:
0563   const SnapshotData* impl_;
0564   bool owns_impl_;
0565   friend struct SnapshotData;
0566   friend class CommonEnvironmentSetup;
0567 };
0568 
0569 // Overriding IsolateSettings may produce unexpected behavior
0570 // in Node.js core functionality, so proceed at your own risk.
0571 NODE_EXTERN void SetIsolateUpForNode(v8::Isolate* isolate,
0572                                      const IsolateSettings& settings);
0573 
0574 // Set a number of callbacks for the `isolate`, in particular the Node.js
0575 // uncaught exception listener.
0576 NODE_EXTERN void SetIsolateUpForNode(v8::Isolate* isolate);
0577 
0578 // Creates a new isolate with Node.js-specific settings.
0579 // This is a convenience method equivalent to using SetIsolateCreateParams(),
0580 // Isolate::Allocate(), MultiIsolatePlatform::RegisterIsolate(),
0581 // Isolate::Initialize(), and SetIsolateUpForNode().
0582 NODE_EXTERN v8::Isolate* NewIsolate(
0583     ArrayBufferAllocator* allocator,
0584     struct uv_loop_s* event_loop,
0585     MultiIsolatePlatform* platform,
0586     const EmbedderSnapshotData* snapshot_data = nullptr,
0587     const IsolateSettings& settings = {});
0588 NODE_EXTERN v8::Isolate* NewIsolate(
0589     std::shared_ptr<ArrayBufferAllocator> allocator,
0590     struct uv_loop_s* event_loop,
0591     MultiIsolatePlatform* platform,
0592     const EmbedderSnapshotData* snapshot_data = nullptr,
0593     const IsolateSettings& settings = {});
0594 
0595 // Creates a new context with Node.js-specific tweaks.
0596 NODE_EXTERN v8::Local<v8::Context> NewContext(
0597     v8::Isolate* isolate,
0598     v8::Local<v8::ObjectTemplate> object_template =
0599         v8::Local<v8::ObjectTemplate>());
0600 
0601 // Runs Node.js-specific tweaks on an already constructed context
0602 // Return value indicates success of operation
0603 NODE_EXTERN v8::Maybe<bool> InitializeContext(v8::Local<v8::Context> context);
0604 
0605 // If `platform` is passed, it will be used to register new Worker instances.
0606 // It can be `nullptr`, in which case creating new Workers inside of
0607 // Environments that use this `IsolateData` will not work.
0608 NODE_EXTERN IsolateData* CreateIsolateData(
0609     v8::Isolate* isolate,
0610     struct uv_loop_s* loop,
0611     MultiIsolatePlatform* platform = nullptr,
0612     ArrayBufferAllocator* allocator = nullptr,
0613     const EmbedderSnapshotData* snapshot_data = nullptr);
0614 NODE_EXTERN void FreeIsolateData(IsolateData* isolate_data);
0615 
0616 struct ThreadId {
0617   uint64_t id = static_cast<uint64_t>(-1);
0618 };
0619 NODE_EXTERN ThreadId AllocateEnvironmentThreadId();
0620 
0621 namespace EnvironmentFlags {
0622 enum Flags : uint64_t {
0623   kNoFlags = 0,
0624   // Use the default behaviour for Node.js instances.
0625   kDefaultFlags = 1 << 0,
0626   // Controls whether this Environment is allowed to affect per-process state
0627   // (e.g. cwd, process title, uid, etc.).
0628   // This is set when using kDefaultFlags.
0629   kOwnsProcessState = 1 << 1,
0630   // Set if this Environment instance is associated with the global inspector
0631   // handling code (i.e. listening on SIGUSR1).
0632   // This is set when using kDefaultFlags.
0633   kOwnsInspector = 1 << 2,
0634   // Set if Node.js should not run its own esm loader. This is needed by some
0635   // embedders, because it's possible for the Node.js esm loader to conflict
0636   // with another one in an embedder environment, e.g. Blink's in Chromium.
0637   kNoRegisterESMLoader = 1 << 3,
0638   // Set this flag to make Node.js track "raw" file descriptors, i.e. managed
0639   // by fs.open() and fs.close(), and close them during FreeEnvironment().
0640   kTrackUnmanagedFds = 1 << 4,
0641   // Set this flag to force hiding console windows when spawning child
0642   // processes. This is usually used when embedding Node.js in GUI programs on
0643   // Windows.
0644   kHideConsoleWindows = 1 << 5,
0645   // Set this flag to disable loading native addons via `process.dlopen`.
0646   // This environment flag is especially important for worker threads
0647   // so that a worker thread can't load a native addon even if `execArgv`
0648   // is overwritten and `--no-addons` is not specified but was specified
0649   // for this Environment instance.
0650   kNoNativeAddons = 1 << 6,
0651   // Set this flag to disable searching modules from global paths like
0652   // $HOME/.node_modules and $NODE_PATH. This is used by standalone apps that
0653   // do not expect to have their behaviors changed because of globally
0654   // installed modules.
0655   kNoGlobalSearchPaths = 1 << 7,
0656   // Do not export browser globals like setTimeout, console, etc.
0657   kNoBrowserGlobals = 1 << 8,
0658   // Controls whether or not the Environment should call V8Inspector::create().
0659   // This control is needed by embedders who may not want to initialize the V8
0660   // inspector in situations where one has already been created,
0661   // e.g. Blink's in Chromium.
0662   kNoCreateInspector = 1 << 9,
0663   // Controls whether or not the InspectorAgent for this Environment should
0664   // call StartDebugSignalHandler. This control is needed by embedders who may
0665   // not want to allow other processes to start the V8 inspector.
0666   kNoStartDebugSignalHandler = 1 << 10,
0667   // Controls whether the InspectorAgent created for this Environment waits for
0668   // Inspector frontend events during the Environment creation. It's used to
0669   // call node::Stop(env) on a Worker thread that is waiting for the events.
0670   kNoWaitForInspectorFrontend = 1 << 11
0671 };
0672 }  // namespace EnvironmentFlags
0673 
0674 enum class SnapshotFlags : uint32_t {
0675   kDefault = 0,
0676   // Whether code cache should be generated as part of the snapshot.
0677   // Code cache reduces the time spent on compiling functions included
0678   // in the snapshot at the expense of a bigger snapshot size and
0679   // potentially breaking portability of the snapshot.
0680   kWithoutCodeCache = 1 << 0,
0681 };
0682 
0683 struct SnapshotConfig {
0684   SnapshotFlags flags = SnapshotFlags::kDefault;
0685 
0686   // When builder_script_path is std::nullopt, the snapshot is generated as a
0687   // built-in snapshot instead of a custom one, and it's expected that the
0688   // built-in snapshot only contains states that reproduce in every run of the
0689   // application. The event loop won't be run when generating a built-in
0690   // snapshot, so asynchronous operations should be avoided.
0691   //
0692   // When builder_script_path is an std::string, it should match args[1]
0693   // passed to CreateForSnapshotting(). The embedder is also expected to use
0694   // LoadEnvironment() to run a script matching this path. In that case the
0695   // snapshot is generated as a custom snapshot and the event loop is run, so
0696   // the snapshot builder can execute asynchronous operations as long as they
0697   // are run to completion when the snapshot is taken.
0698   std::optional<std::string> builder_script_path;
0699 };
0700 
0701 struct InspectorParentHandle {
0702   virtual ~InspectorParentHandle() = default;
0703 };
0704 
0705 // TODO(addaleax): Maybe move per-Environment options parsing here.
0706 // Returns nullptr when the Environment cannot be created e.g. there are
0707 // pending JavaScript exceptions.
0708 // `context` may be empty if an `EmbedderSnapshotData` instance was provided
0709 // to `NewIsolate()` and `CreateIsolateData()`.
0710 NODE_EXTERN Environment* CreateEnvironment(
0711     IsolateData* isolate_data,
0712     v8::Local<v8::Context> context,
0713     const std::vector<std::string>& args,
0714     const std::vector<std::string>& exec_args,
0715     EnvironmentFlags::Flags flags = EnvironmentFlags::kDefaultFlags,
0716     ThreadId thread_id = {} /* allocates a thread id automatically */,
0717     std::unique_ptr<InspectorParentHandle> inspector_parent_handle = {});
0718 
0719 // Returns a handle that can be passed to `LoadEnvironment()`, making the
0720 // child Environment accessible to the inspector as if it were a Node.js Worker.
0721 // `child_thread_id` can be created using `AllocateEnvironmentThreadId()`
0722 // and then later passed on to `CreateEnvironment()` to create the child
0723 // Environment, together with the inspector handle.
0724 // This method should not be called while the parent Environment is active
0725 // on another thread.
0726 NODE_EXTERN std::unique_ptr<InspectorParentHandle> GetInspectorParentHandle(
0727     Environment* parent_env,
0728     ThreadId child_thread_id,
0729     const char* child_url);
0730 
0731 NODE_EXTERN std::unique_ptr<InspectorParentHandle> GetInspectorParentHandle(
0732     Environment* parent_env,
0733     ThreadId child_thread_id,
0734     const char* child_url,
0735     const char* name);
0736 
0737 struct StartExecutionCallbackInfo {
0738   v8::Local<v8::Object> process_object;
0739   v8::Local<v8::Function> native_require;
0740   v8::Local<v8::Function> run_cjs;
0741 };
0742 
0743 using StartExecutionCallback =
0744     std::function<v8::MaybeLocal<v8::Value>(const StartExecutionCallbackInfo&)>;
0745 using EmbedderPreloadCallback =
0746     std::function<void(Environment* env,
0747                        v8::Local<v8::Value> process,
0748                        v8::Local<v8::Value> require)>;
0749 
0750 // Run initialization for the environment.
0751 //
0752 // The |preload| function, usually used by embedders to inject scripts,
0753 // will be run by Node.js before Node.js executes the entry point.
0754 // The function is guaranteed to run before the user land module loader running
0755 // any user code, so it is safe to assume that at this point, no user code has
0756 // been run yet.
0757 // The function will be executed with preload(process, require), and the passed
0758 // require function has access to internal Node.js modules. There is no
0759 // stability guarantee about the internals exposed to the internal require
0760 // function. Expect breakages when updating Node.js versions if the embedder
0761 // imports internal modules with the internal require function.
0762 // Worker threads created in the environment will also respect The |preload|
0763 // function, so make sure the function is thread-safe.
0764 NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
0765     Environment* env,
0766     StartExecutionCallback cb,
0767     EmbedderPreloadCallback preload = nullptr);
0768 NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
0769     Environment* env,
0770     std::string_view main_script_source_utf8,
0771     EmbedderPreloadCallback preload = nullptr);
0772 NODE_EXTERN void FreeEnvironment(Environment* env);
0773 
0774 // Set a callback that is called when process.exit() is called from JS,
0775 // overriding the default handler.
0776 // It receives the Environment* instance and the exit code as arguments.
0777 // This could e.g. call Stop(env); in order to terminate execution and stop
0778 // the event loop.
0779 // The default handler disposes of the global V8 platform instance, if one is
0780 // being used, and calls exit().
0781 NODE_EXTERN void SetProcessExitHandler(
0782     Environment* env,
0783     std::function<void(Environment*, int)>&& handler);
0784 NODE_EXTERN void DefaultProcessExitHandler(Environment* env, int exit_code);
0785 
0786 // This may return nullptr if context is not associated with a Node instance.
0787 NODE_EXTERN Environment* GetCurrentEnvironment(v8::Local<v8::Context> context);
0788 NODE_EXTERN IsolateData* GetEnvironmentIsolateData(Environment* env);
0789 NODE_EXTERN ArrayBufferAllocator* GetArrayBufferAllocator(IsolateData* data);
0790 // This is mostly useful for Environment* instances that were created through
0791 // a snapshot and have a main context that was read from that snapshot.
0792 NODE_EXTERN v8::Local<v8::Context> GetMainContext(Environment* env);
0793 
0794 [[noreturn]] NODE_EXTERN void OnFatalError(const char* location,
0795                                            const char* message);
0796 NODE_EXTERN void PromiseRejectCallback(v8::PromiseRejectMessage message);
0797 NODE_EXTERN bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context,
0798                                             v8::Local<v8::String>);
0799 NODE_EXTERN bool ShouldAbortOnUncaughtException(v8::Isolate* isolate);
0800 NODE_EXTERN v8::MaybeLocal<v8::Value> PrepareStackTraceCallback(
0801     v8::Local<v8::Context> context,
0802     v8::Local<v8::Value> exception,
0803     v8::Local<v8::Array> trace);
0804 
0805 // Writes a diagnostic report to a file. If filename is not provided, the
0806 // default filename includes the date, time, PID, and a sequence number.
0807 // The report's JavaScript stack trace is taken from err, if present.
0808 // If isolate is nullptr, no information about the JavaScript environment
0809 // is included in the report.
0810 // Returns the filename of the written report.
0811 NODE_EXTERN std::string TriggerNodeReport(v8::Isolate* isolate,
0812                                           const char* message,
0813                                           const char* trigger,
0814                                           const std::string& filename,
0815                                           v8::Local<v8::Value> error);
0816 NODE_EXTERN std::string TriggerNodeReport(Environment* env,
0817                                           const char* message,
0818                                           const char* trigger,
0819                                           const std::string& filename,
0820                                           v8::Local<v8::Value> error);
0821 NODE_EXTERN void GetNodeReport(v8::Isolate* isolate,
0822                                const char* message,
0823                                const char* trigger,
0824                                v8::Local<v8::Value> error,
0825                                std::ostream& out);
0826 NODE_EXTERN void GetNodeReport(Environment* env,
0827                                const char* message,
0828                                const char* trigger,
0829                                v8::Local<v8::Value> error,
0830                                std::ostream& out);
0831 
0832 // This returns the MultiIsolatePlatform used for an Environment or IsolateData
0833 // instance, if one exists.
0834 NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(Environment* env);
0835 NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env);
0836 
0837 NODE_DEPRECATED("Use MultiIsolatePlatform::Create() instead",
0838     NODE_EXTERN MultiIsolatePlatform* CreatePlatform(
0839         int thread_pool_size,
0840         v8::TracingController* tracing_controller));
0841 NODE_DEPRECATED("Use MultiIsolatePlatform::Create() instead",
0842     NODE_EXTERN void FreePlatform(MultiIsolatePlatform* platform));
0843 
0844 // Get/set the currently active tracing controller. Using CreatePlatform()
0845 // will implicitly set this by default. This is global and should be initialized
0846 // along with the v8::Platform instance that is being used. `controller`
0847 // is allowed to be `nullptr`.
0848 // This is used for tracing events from Node.js itself. V8 uses the tracing
0849 // controller returned from the active `v8::Platform` instance.
0850 NODE_EXTERN v8::TracingController* GetTracingController();
0851 NODE_EXTERN void SetTracingController(v8::TracingController* controller);
0852 
0853 // Run `process.emit('beforeExit')` as it would usually happen when Node.js is
0854 // run in standalone mode.
0855 NODE_EXTERN v8::Maybe<bool> EmitProcessBeforeExit(Environment* env);
0856 NODE_DEPRECATED("Use Maybe version (EmitProcessBeforeExit) instead",
0857     NODE_EXTERN void EmitBeforeExit(Environment* env));
0858 // Run `process.emit('exit')` as it would usually happen when Node.js is run
0859 // in standalone mode. The return value corresponds to the exit code.
0860 NODE_EXTERN v8::Maybe<int> EmitProcessExit(Environment* env);
0861 NODE_DEPRECATED("Use Maybe version (EmitProcessExit) instead",
0862     NODE_EXTERN int EmitExit(Environment* env));
0863 
0864 // Runs hooks added through `AtExit()`. This is part of `FreeEnvironment()`,
0865 // so calling it manually is typically not necessary.
0866 NODE_EXTERN void RunAtExit(Environment* env);
0867 
0868 // This may return nullptr if the current v8::Context is not associated
0869 // with a Node instance.
0870 NODE_EXTERN struct uv_loop_s* GetCurrentEventLoop(v8::Isolate* isolate);
0871 
0872 // Runs the main loop for a given Environment. This roughly performs the
0873 // following steps:
0874 // 1. Call uv_run() on the event loop until it is drained.
0875 // 2. Call platform->DrainTasks() on the associated platform/isolate.
0876 //   3. If the event loop is alive again, go to Step 1.
0877 // 4. Call EmitProcessBeforeExit().
0878 //   5. If the event loop is alive again, go to Step 1.
0879 // 6. Call EmitProcessExit() and forward the return value.
0880 // If at any point node::Stop() is called, the function will attempt to return
0881 // as soon as possible, returning an empty `Maybe`.
0882 // This function only works if `env` has an associated `MultiIsolatePlatform`.
0883 NODE_EXTERN v8::Maybe<int> SpinEventLoop(Environment* env);
0884 
0885 NODE_EXTERN std::string GetAnonymousMainPath();
0886 
0887 class NODE_EXTERN CommonEnvironmentSetup {
0888  public:
0889   ~CommonEnvironmentSetup();
0890 
0891   // Create a new CommonEnvironmentSetup, that is, a group of objects that
0892   // together form the typical setup for a single Node.js Environment instance.
0893   // If any error occurs, `*errors` will be populated and the returned pointer
0894   // will be empty.
0895   // env_args will be passed through as arguments to CreateEnvironment(), after
0896   // `isolate_data` and `context`.
0897   template <typename... EnvironmentArgs>
0898   static std::unique_ptr<CommonEnvironmentSetup> Create(
0899       MultiIsolatePlatform* platform,
0900       std::vector<std::string>* errors,
0901       EnvironmentArgs&&... env_args);
0902   template <typename... EnvironmentArgs>
0903   static std::unique_ptr<CommonEnvironmentSetup> CreateFromSnapshot(
0904       MultiIsolatePlatform* platform,
0905       std::vector<std::string>* errors,
0906       const EmbedderSnapshotData* snapshot_data,
0907       EnvironmentArgs&&... env_args);
0908 
0909   // Create an embedding setup which will be used for creating a snapshot
0910   // using CreateSnapshot().
0911   //
0912   // This will create and attach a v8::SnapshotCreator to this instance,
0913   // and the same restrictions apply to this instance that also apply to
0914   // other V8 snapshotting environments.
0915   // Not all Node.js APIs are supported in this case. Currently, there is
0916   // no support for native/host objects other than Node.js builtins
0917   // in the snapshot.
0918   //
0919   // If the embedder wants to use LoadEnvironment() later to run a snapshot
0920   // builder script they should make sure args[1] contains the path of the
0921   // snapshot script, which will be used to create __filename and __dirname
0922   // in the context where the builder script is run. If they do not want to
0923   // include the build-time paths into the snapshot, use the string returned
0924   // by GetAnonymousMainPath() as args[1] to anonymize the script.
0925   //
0926   // Snapshots are an *experimental* feature. In particular, the embedder API
0927   // exposed through this class is subject to change or removal between Node.js
0928   // versions, including possible API and ABI breakage.
0929   static std::unique_ptr<CommonEnvironmentSetup> CreateForSnapshotting(
0930       MultiIsolatePlatform* platform,
0931       std::vector<std::string>* errors,
0932       const std::vector<std::string>& args = {},
0933       const std::vector<std::string>& exec_args = {},
0934       const SnapshotConfig& snapshot_config = {});
0935   EmbedderSnapshotData::Pointer CreateSnapshot();
0936 
0937   struct uv_loop_s* event_loop() const;
0938   v8::SnapshotCreator* snapshot_creator();
0939   // Empty for snapshotting environments.
0940   std::shared_ptr<ArrayBufferAllocator> array_buffer_allocator() const;
0941   v8::Isolate* isolate() const;
0942   IsolateData* isolate_data() const;
0943   Environment* env() const;
0944   v8::Local<v8::Context> context() const;
0945 
0946   CommonEnvironmentSetup(const CommonEnvironmentSetup&) = delete;
0947   CommonEnvironmentSetup& operator=(const CommonEnvironmentSetup&) = delete;
0948   CommonEnvironmentSetup(CommonEnvironmentSetup&&) = delete;
0949   CommonEnvironmentSetup& operator=(CommonEnvironmentSetup&&) = delete;
0950 
0951  private:
0952   enum Flags : uint32_t {
0953     kNoFlags = 0,
0954     kIsForSnapshotting = 1,
0955   };
0956 
0957   struct Impl;
0958   Impl* impl_;
0959 
0960   CommonEnvironmentSetup(
0961       MultiIsolatePlatform*,
0962       std::vector<std::string>*,
0963       std::function<Environment*(const CommonEnvironmentSetup*)>);
0964   CommonEnvironmentSetup(
0965       MultiIsolatePlatform*,
0966       std::vector<std::string>*,
0967       const EmbedderSnapshotData*,
0968       uint32_t flags,
0969       std::function<Environment*(const CommonEnvironmentSetup*)>,
0970       const SnapshotConfig* config = nullptr);
0971 };
0972 
0973 // Implementation for CommonEnvironmentSetup::Create
0974 template <typename... EnvironmentArgs>
0975 std::unique_ptr<CommonEnvironmentSetup> CommonEnvironmentSetup::Create(
0976     MultiIsolatePlatform* platform,
0977     std::vector<std::string>* errors,
0978     EnvironmentArgs&&... env_args) {
0979   auto ret = std::unique_ptr<CommonEnvironmentSetup>(new CommonEnvironmentSetup(
0980       platform, errors,
0981       [&](const CommonEnvironmentSetup* setup) -> Environment* {
0982         return CreateEnvironment(
0983             setup->isolate_data(), setup->context(),
0984             std::forward<EnvironmentArgs>(env_args)...);
0985       }));
0986   if (!errors->empty()) ret.reset();
0987   return ret;
0988 }
0989 
0990 // Implementation for ::CreateFromSnapshot -- the ::Create() method
0991 // could call this with a nullptr snapshot_data in a major version.
0992 template <typename... EnvironmentArgs>
0993 std::unique_ptr<CommonEnvironmentSetup>
0994 CommonEnvironmentSetup::CreateFromSnapshot(
0995     MultiIsolatePlatform* platform,
0996     std::vector<std::string>* errors,
0997     const EmbedderSnapshotData* snapshot_data,
0998     EnvironmentArgs&&... env_args) {
0999   auto ret = std::unique_ptr<CommonEnvironmentSetup>(new CommonEnvironmentSetup(
1000       platform,
1001       errors,
1002       snapshot_data,
1003       Flags::kNoFlags,
1004       [&](const CommonEnvironmentSetup* setup) -> Environment* {
1005         return CreateEnvironment(setup->isolate_data(),
1006                                  setup->context(),
1007                                  std::forward<EnvironmentArgs>(env_args)...);
1008       }));
1009   if (!errors->empty()) ret.reset();
1010   return ret;
1011 }
1012 
1013 /* Converts a unixtime to V8 Date */
1014 NODE_DEPRECATED("Use v8::Date::New() directly",
1015                 inline v8::Local<v8::Value> NODE_UNIXTIME_V8(double time) {
1016                   return v8::Date::New(
1017                              v8::Isolate::GetCurrent()->GetCurrentContext(),
1018                              1000 * time)
1019                       .ToLocalChecked();
1020                 })
1021 #define NODE_UNIXTIME_V8 node::NODE_UNIXTIME_V8
1022 NODE_DEPRECATED("Use v8::Date::ValueOf() directly",
1023                 inline double NODE_V8_UNIXTIME(v8::Local<v8::Date> date) {
1024   return date->ValueOf() / 1000;
1025 })
1026 #define NODE_V8_UNIXTIME node::NODE_V8_UNIXTIME
1027 
1028 #define NODE_DEFINE_CONSTANT(target, constant)                                 \
1029   do {                                                                         \
1030     v8::Isolate* isolate = target->GetIsolate();                               \
1031     v8::Local<v8::Context> context = isolate->GetCurrentContext();             \
1032     v8::Local<v8::String> constant_name = v8::String::NewFromUtf8Literal(      \
1033         isolate, #constant, v8::NewStringType::kInternalized);                 \
1034     v8::Local<v8::Number> constant_value =                                     \
1035         v8::Number::New(isolate, static_cast<double>(constant));               \
1036     v8::PropertyAttribute constant_attributes =                                \
1037         static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete);     \
1038     (target)                                                                   \
1039         ->DefineOwnProperty(                                                   \
1040             context, constant_name, constant_value, constant_attributes)       \
1041         .Check();                                                              \
1042   } while (0)
1043 
1044 #define NODE_DEFINE_HIDDEN_CONSTANT(target, constant)                          \
1045   do {                                                                         \
1046     v8::Isolate* isolate = target->GetIsolate();                               \
1047     v8::Local<v8::Context> context = isolate->GetCurrentContext();             \
1048     v8::Local<v8::String> constant_name = v8::String::NewFromUtf8Literal(      \
1049         isolate, #constant, v8::NewStringType::kInternalized);                 \
1050     v8::Local<v8::Number> constant_value =                                     \
1051         v8::Number::New(isolate, static_cast<double>(constant));               \
1052     v8::PropertyAttribute constant_attributes =                                \
1053         static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete |     \
1054                                            v8::DontEnum);                      \
1055     (target)                                                                   \
1056         ->DefineOwnProperty(                                                   \
1057             context, constant_name, constant_value, constant_attributes)       \
1058         .Check();                                                              \
1059   } while (0)
1060 
1061 // Used to be a macro, hence the uppercase name.
1062 inline void NODE_SET_METHOD(v8::Local<v8::Template> recv,
1063                             const char* name,
1064                             v8::FunctionCallback callback) {
1065   v8::Isolate* isolate = v8::Isolate::GetCurrent();
1066   v8::HandleScope handle_scope(isolate);
1067   v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate,
1068                                                                 callback);
1069   v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
1070       v8::NewStringType::kInternalized).ToLocalChecked();
1071   t->SetClassName(fn_name);
1072   recv->Set(fn_name, t);
1073 }
1074 
1075 // Used to be a macro, hence the uppercase name.
1076 inline void NODE_SET_METHOD(v8::Local<v8::Object> recv,
1077                             const char* name,
1078                             v8::FunctionCallback callback) {
1079   v8::Isolate* isolate = v8::Isolate::GetCurrent();
1080   v8::HandleScope handle_scope(isolate);
1081   v8::Local<v8::Context> context = isolate->GetCurrentContext();
1082   v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate,
1083                                                                 callback);
1084   v8::Local<v8::Function> fn = t->GetFunction(context).ToLocalChecked();
1085   v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
1086       v8::NewStringType::kInternalized).ToLocalChecked();
1087   fn->SetName(fn_name);
1088   recv->Set(context, fn_name, fn).Check();
1089 }
1090 #define NODE_SET_METHOD node::NODE_SET_METHOD
1091 
1092 // Used to be a macro, hence the uppercase name.
1093 // Not a template because it only makes sense for FunctionTemplates.
1094 inline void NODE_SET_PROTOTYPE_METHOD(v8::Local<v8::FunctionTemplate> recv,
1095                                       const char* name,
1096                                       v8::FunctionCallback callback) {
1097   v8::Isolate* isolate = v8::Isolate::GetCurrent();
1098   v8::HandleScope handle_scope(isolate);
1099   v8::Local<v8::Signature> s = v8::Signature::New(isolate, recv);
1100   v8::Local<v8::FunctionTemplate> t =
1101       v8::FunctionTemplate::New(isolate, callback, v8::Local<v8::Value>(), s);
1102   v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
1103       v8::NewStringType::kInternalized).ToLocalChecked();
1104   t->SetClassName(fn_name);
1105   recv->PrototypeTemplate()->Set(fn_name, t);
1106 }
1107 #define NODE_SET_PROTOTYPE_METHOD node::NODE_SET_PROTOTYPE_METHOD
1108 
1109 // BINARY is a deprecated alias of LATIN1.
1110 // BASE64URL is not currently exposed to the JavaScript side.
1111 enum encoding {
1112   ASCII,
1113   UTF8,
1114   BASE64,
1115   UCS2,
1116   BINARY,
1117   HEX,
1118   BUFFER,
1119   BASE64URL,
1120   LATIN1 = BINARY
1121 };
1122 
1123 NODE_EXTERN enum encoding ParseEncoding(
1124     v8::Isolate* isolate,
1125     v8::Local<v8::Value> encoding_v,
1126     enum encoding default_encoding = LATIN1);
1127 
1128 NODE_EXTERN void FatalException(v8::Isolate* isolate,
1129                                 const v8::TryCatch& try_catch);
1130 
1131 NODE_EXTERN v8::Local<v8::Value> Encode(v8::Isolate* isolate,
1132                                         const char* buf,
1133                                         size_t len,
1134                                         enum encoding encoding = LATIN1);
1135 
1136 // Warning: This reverses endianness on Big Endian platforms, even though the
1137 // signature using uint16_t implies that it should not.
1138 NODE_EXTERN v8::Local<v8::Value> Encode(v8::Isolate* isolate,
1139                                         const uint16_t* buf,
1140                                         size_t len);
1141 
1142 // Returns -1 if the handle was not valid for decoding
1143 NODE_EXTERN ssize_t DecodeBytes(v8::Isolate* isolate,
1144                                 v8::Local<v8::Value>,
1145                                 enum encoding encoding = LATIN1);
1146 // returns bytes written.
1147 NODE_EXTERN ssize_t DecodeWrite(v8::Isolate* isolate,
1148                                 char* buf,
1149                                 size_t buflen,
1150                                 v8::Local<v8::Value>,
1151                                 enum encoding encoding = LATIN1);
1152 #ifdef _WIN32
1153 NODE_EXTERN v8::Local<v8::Value> WinapiErrnoException(
1154     v8::Isolate* isolate,
1155     int errorno,
1156     const char* syscall = nullptr,
1157     const char* msg = "",
1158     const char* path = nullptr);
1159 #endif
1160 
1161 const char* signo_string(int errorno);
1162 
1163 
1164 typedef void (*addon_register_func)(
1165     v8::Local<v8::Object> exports,
1166     v8::Local<v8::Value> module,
1167     void* priv);
1168 
1169 typedef void (*addon_context_register_func)(
1170     v8::Local<v8::Object> exports,
1171     v8::Local<v8::Value> module,
1172     v8::Local<v8::Context> context,
1173     void* priv);
1174 
1175 enum ModuleFlags {
1176   kLinked = 0x02
1177 };
1178 
1179 struct node_module {
1180   int nm_version;
1181   unsigned int nm_flags;
1182   void* nm_dso_handle;
1183   const char* nm_filename;
1184   node::addon_register_func nm_register_func;
1185   node::addon_context_register_func nm_context_register_func;
1186   const char* nm_modname;
1187   void* nm_priv;
1188   struct node_module* nm_link;
1189 };
1190 
1191 extern "C" NODE_EXTERN void node_module_register(void* mod);
1192 
1193 #ifdef _WIN32
1194 # define NODE_MODULE_EXPORT __declspec(dllexport)
1195 #else
1196 # define NODE_MODULE_EXPORT __attribute__((visibility("default")))
1197 #endif
1198 
1199 #ifdef NODE_SHARED_MODE
1200 # define NODE_CTOR_PREFIX
1201 #else
1202 # define NODE_CTOR_PREFIX static
1203 #endif
1204 
1205 #if defined(_MSC_VER)
1206 #define NODE_C_CTOR(fn)                                               \
1207   NODE_CTOR_PREFIX void __cdecl fn(void);                             \
1208   namespace {                                                         \
1209   struct fn##_ {                                                      \
1210     fn##_() { fn(); };                                                \
1211   } fn##_v_;                                                          \
1212   }                                                                   \
1213   NODE_CTOR_PREFIX void __cdecl fn(void)
1214 #else
1215 #define NODE_C_CTOR(fn)                                               \
1216   NODE_CTOR_PREFIX void fn(void) __attribute__((constructor));        \
1217   NODE_CTOR_PREFIX void fn(void)
1218 #endif
1219 
1220 #define NODE_MODULE_X(modname, regfunc, priv, flags)                  \
1221   extern "C" {                                                        \
1222     static node::node_module _module =                                \
1223     {                                                                 \
1224       NODE_MODULE_VERSION,                                            \
1225       flags,                                                          \
1226       NULL,  /* NOLINT (readability/null_usage) */                    \
1227       __FILE__,                                                       \
1228       (node::addon_register_func) (regfunc),                          \
1229       NULL,  /* NOLINT (readability/null_usage) */                    \
1230       NODE_STRINGIFY(modname),                                        \
1231       priv,                                                           \
1232       NULL   /* NOLINT (readability/null_usage) */                    \
1233     };                                                                \
1234     NODE_C_CTOR(_register_ ## modname) {                              \
1235       node_module_register(&_module);                                 \
1236     }                                                                 \
1237   }
1238 
1239 #define NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, priv, flags)    \
1240   extern "C" {                                                        \
1241     static node::node_module _module =                                \
1242     {                                                                 \
1243       NODE_MODULE_VERSION,                                            \
1244       flags,                                                          \
1245       NULL,  /* NOLINT (readability/null_usage) */                    \
1246       __FILE__,                                                       \
1247       NULL,  /* NOLINT (readability/null_usage) */                    \
1248       (node::addon_context_register_func) (regfunc),                  \
1249       NODE_STRINGIFY(modname),                                        \
1250       priv,                                                           \
1251       NULL  /* NOLINT (readability/null_usage) */                     \
1252     };                                                                \
1253     NODE_C_CTOR(_register_ ## modname) {                              \
1254       node_module_register(&_module);                                 \
1255     }                                                                 \
1256   }
1257 
1258 // Usage: `NODE_MODULE(NODE_GYP_MODULE_NAME, InitializerFunction)`
1259 // If no NODE_MODULE is declared, Node.js looks for the well-known
1260 // symbol `node_register_module_v${NODE_MODULE_VERSION}`.
1261 #define NODE_MODULE(modname, regfunc)                                 \
1262   NODE_MODULE_X(modname, regfunc, NULL, 0)  // NOLINT (readability/null_usage)
1263 
1264 #define NODE_MODULE_CONTEXT_AWARE(modname, regfunc)                   \
1265   /* NOLINTNEXTLINE (readability/null_usage) */                       \
1266   NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL, 0)
1267 
1268 // Embedders can use this type of binding for statically linked native bindings.
1269 // It is used the same way addon bindings are used, except that linked bindings
1270 // can be accessed through `process._linkedBinding(modname)`.
1271 #define NODE_MODULE_LINKED(modname, regfunc)                               \
1272   /* NOLINTNEXTLINE (readability/null_usage) */                            \
1273   NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL,                      \
1274                               node::ModuleFlags::kLinked)
1275 
1276 /*
1277  * For backward compatibility in add-on modules.
1278  */
1279 #define NODE_MODULE_DECL /* nothing */
1280 
1281 #define NODE_MODULE_INITIALIZER_BASE node_register_module_v
1282 
1283 #define NODE_MODULE_INITIALIZER_X(base, version)                      \
1284     NODE_MODULE_INITIALIZER_X_HELPER(base, version)
1285 
1286 #define NODE_MODULE_INITIALIZER_X_HELPER(base, version) base##version
1287 
1288 #define NODE_MODULE_INITIALIZER                                       \
1289   NODE_MODULE_INITIALIZER_X(NODE_MODULE_INITIALIZER_BASE,             \
1290       NODE_MODULE_VERSION)
1291 
1292 #define NODE_MODULE_INIT()                                            \
1293   extern "C" NODE_MODULE_EXPORT void                                  \
1294   NODE_MODULE_INITIALIZER(v8::Local<v8::Object> exports,              \
1295                           v8::Local<v8::Value> module,                \
1296                           v8::Local<v8::Context> context);            \
1297   NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME,                     \
1298                             NODE_MODULE_INITIALIZER)                  \
1299   void NODE_MODULE_INITIALIZER(v8::Local<v8::Object> exports,         \
1300                                v8::Local<v8::Value> module,           \
1301                                v8::Local<v8::Context> context)
1302 
1303 // Allows embedders to add a binding to the current Environment* that can be
1304 // accessed through process._linkedBinding() in the target Environment and all
1305 // Worker threads that it creates.
1306 // In each variant, the registration function needs to be usable at least for
1307 // the time during which the Environment exists.
1308 NODE_EXTERN void AddLinkedBinding(Environment* env, const node_module& mod);
1309 NODE_EXTERN void AddLinkedBinding(Environment* env,
1310                                   const struct napi_module& mod);
1311 NODE_EXTERN void AddLinkedBinding(Environment* env,
1312                                   const char* name,
1313                                   addon_context_register_func fn,
1314                                   void* priv);
1315 NODE_EXTERN void AddLinkedBinding(
1316     Environment* env,
1317     const char* name,
1318     napi_addon_register_func fn,
1319     int32_t module_api_version = NODE_API_DEFAULT_MODULE_API_VERSION);
1320 
1321 /* Registers a callback with the passed-in Environment instance. The callback
1322  * is called after the event loop exits, but before the VM is disposed.
1323  * Callbacks are run in reverse order of registration, i.e. newest first.
1324  */
1325 NODE_EXTERN void AtExit(Environment* env,
1326                         void (*cb)(void* arg),
1327                         void* arg);
1328 
1329 typedef double async_id;
1330 struct async_context {
1331   ::node::async_id async_id;
1332   ::node::async_id trigger_async_id;
1333 };
1334 
1335 /* This is a lot like node::AtExit, except that the hooks added via this
1336  * function are run before the AtExit ones and will always be registered
1337  * for the current Environment instance.
1338  * These functions are safe to use in an addon supporting multiple
1339  * threads/isolates. */
1340 NODE_EXTERN void AddEnvironmentCleanupHook(v8::Isolate* isolate,
1341                                            void (*fun)(void* arg),
1342                                            void* arg);
1343 
1344 NODE_EXTERN void RemoveEnvironmentCleanupHook(v8::Isolate* isolate,
1345                                               void (*fun)(void* arg),
1346                                               void* arg);
1347 
1348 /* These are async equivalents of the above. After the cleanup hook is invoked,
1349  * `cb(cbarg)` *must* be called, and attempting to remove the cleanup hook will
1350  * have no effect. */
1351 struct ACHHandle;
1352 struct NODE_EXTERN DeleteACHHandle { void operator()(ACHHandle*) const; };
1353 typedef std::unique_ptr<ACHHandle, DeleteACHHandle> AsyncCleanupHookHandle;
1354 
1355 /* This function is not intended to be used externally, it exists to aid in
1356  * keeping ABI compatibility between Node and Electron. */
1357 NODE_EXTERN ACHHandle* AddEnvironmentCleanupHookInternal(
1358     v8::Isolate* isolate,
1359     void (*fun)(void* arg, void (*cb)(void*), void* cbarg),
1360     void* arg);
1361 inline AsyncCleanupHookHandle AddEnvironmentCleanupHook(
1362     v8::Isolate* isolate,
1363     void (*fun)(void* arg, void (*cb)(void*), void* cbarg),
1364     void* arg) {
1365   return AsyncCleanupHookHandle(AddEnvironmentCleanupHookInternal(isolate, fun,
1366       arg));
1367 }
1368 
1369 /* This function is not intended to be used externally, it exists to aid in
1370  * keeping ABI compatibility between Node and Electron. */
1371 NODE_EXTERN void RemoveEnvironmentCleanupHookInternal(ACHHandle* holder);
1372 inline void RemoveEnvironmentCleanupHook(AsyncCleanupHookHandle holder) {
1373   RemoveEnvironmentCleanupHookInternal(holder.get());
1374 }
1375 
1376 // This behaves like V8's Isolate::RequestInterrupt(), but also wakes up
1377 // the event loop if it is currently idle. Interrupt requests are drained
1378 // in `FreeEnvironment()`. The passed callback can not call back into
1379 // JavaScript.
1380 // This function can be called from any thread.
1381 NODE_EXTERN void RequestInterrupt(Environment* env,
1382                                   void (*fun)(void* arg),
1383                                   void* arg);
1384 
1385 /* Returns the id of the current execution context. If the return value is
1386  * zero then no execution has been set. This will happen if the user handles
1387  * I/O from native code. */
1388 NODE_EXTERN async_id AsyncHooksGetExecutionAsyncId(v8::Isolate* isolate);
1389 
1390 /* Returns the id of the current execution context. If the return value is
1391  * zero then no execution has been set. This will happen if the user handles
1392  * I/O from native code. */
1393 NODE_EXTERN async_id
1394 AsyncHooksGetExecutionAsyncId(v8::Local<v8::Context> context);
1395 
1396 /* Return same value as async_hooks.triggerAsyncId(); */
1397 NODE_EXTERN async_id AsyncHooksGetTriggerAsyncId(v8::Isolate* isolate);
1398 
1399 /* If the native API doesn't inherit from the helper class then the callbacks
1400  * must be triggered manually. This triggers the init() callback. The return
1401  * value is the async id assigned to the resource.
1402  *
1403  * The `trigger_async_id` parameter should correspond to the resource which is
1404  * creating the new resource, which will usually be the return value of
1405  * `AsyncHooksGetTriggerAsyncId()`. */
1406 NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate,
1407                                         v8::Local<v8::Object> resource,
1408                                         const char* name,
1409                                         async_id trigger_async_id = -1);
1410 
1411 NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate,
1412                                         v8::Local<v8::Object> resource,
1413                                         v8::Local<v8::String> name,
1414                                         async_id trigger_async_id = -1);
1415 
1416 /* Emit the destroy() callback. The overload taking an `Environment*` argument
1417  * should be used when the Isolate’s current Context is not associated with
1418  * a Node.js Environment, or when there is no current Context, for example
1419  * when calling this function during garbage collection. In that case, the
1420  * `Environment*` value should have been acquired previously, e.g. through
1421  * `GetCurrentEnvironment()`. */
1422 NODE_EXTERN void EmitAsyncDestroy(v8::Isolate* isolate,
1423                                   async_context asyncContext);
1424 NODE_EXTERN void EmitAsyncDestroy(Environment* env,
1425                                   async_context asyncContext);
1426 
1427 class InternalCallbackScope;
1428 
1429 /* This class works like `MakeCallback()` in that it sets up a specific
1430  * asyncContext as the current one and informs the async_hooks and domains
1431  * modules that this context is currently active.
1432  *
1433  * `MakeCallback()` is a wrapper around this class as well as
1434  * `Function::Call()`. Either one of these mechanisms needs to be used for
1435  * top-level calls into JavaScript (i.e. without any existing JS stack).
1436  *
1437  * This object should be stack-allocated to ensure that it is contained in a
1438  * valid HandleScope.
1439  *
1440  * Exceptions happening within this scope will be treated like uncaught
1441  * exceptions. If this behaviour is undesirable, a new `v8::TryCatch` scope
1442  * needs to be created inside of this scope.
1443  */
1444 class NODE_EXTERN CallbackScope {
1445  public:
1446   CallbackScope(v8::Isolate* isolate,
1447                 v8::Local<v8::Object> resource,
1448                 async_context asyncContext);
1449   CallbackScope(Environment* env,
1450                 v8::Local<v8::Object> resource,
1451                 async_context asyncContext);
1452   ~CallbackScope();
1453 
1454   void operator=(const CallbackScope&) = delete;
1455   void operator=(CallbackScope&&) = delete;
1456   CallbackScope(const CallbackScope&) = delete;
1457   CallbackScope(CallbackScope&&) = delete;
1458 
1459  private:
1460   InternalCallbackScope* private_;
1461   v8::TryCatch try_catch_;
1462 };
1463 
1464 /* An API specific to emit before/after callbacks is unnecessary because
1465  * MakeCallback will automatically call them for you.
1466  *
1467  * These methods may create handles on their own, so run them inside a
1468  * HandleScope.
1469  *
1470  * `asyncId` and `triggerAsyncId` should correspond to the values returned by
1471  * `EmitAsyncInit()` and `AsyncHooksGetTriggerAsyncId()`, respectively, when the
1472  * invoking resource was created. If these values are unknown, 0 can be passed.
1473  * */
1474 NODE_EXTERN
1475 v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
1476                                        v8::Local<v8::Object> recv,
1477                                        v8::Local<v8::Function> callback,
1478                                        int argc,
1479                                        v8::Local<v8::Value>* argv,
1480                                        async_context asyncContext);
1481 NODE_EXTERN
1482 v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
1483                                        v8::Local<v8::Object> recv,
1484                                        const char* method,
1485                                        int argc,
1486                                        v8::Local<v8::Value>* argv,
1487                                        async_context asyncContext);
1488 NODE_EXTERN
1489 v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
1490                                        v8::Local<v8::Object> recv,
1491                                        v8::Local<v8::String> symbol,
1492                                        int argc,
1493                                        v8::Local<v8::Value>* argv,
1494                                        async_context asyncContext);
1495 
1496 /* Helper class users can optionally inherit from. If
1497  * `AsyncResource::MakeCallback()` is used, then all four callbacks will be
1498  * called automatically. */
1499 class NODE_EXTERN AsyncResource {
1500  public:
1501   AsyncResource(v8::Isolate* isolate,
1502                 v8::Local<v8::Object> resource,
1503                 const char* name,
1504                 async_id trigger_async_id = -1);
1505 
1506   virtual ~AsyncResource();
1507 
1508   AsyncResource(const AsyncResource&) = delete;
1509   void operator=(const AsyncResource&) = delete;
1510 
1511   v8::MaybeLocal<v8::Value> MakeCallback(
1512       v8::Local<v8::Function> callback,
1513       int argc,
1514       v8::Local<v8::Value>* argv);
1515 
1516   v8::MaybeLocal<v8::Value> MakeCallback(
1517       const char* method,
1518       int argc,
1519       v8::Local<v8::Value>* argv);
1520 
1521   v8::MaybeLocal<v8::Value> MakeCallback(
1522       v8::Local<v8::String> symbol,
1523       int argc,
1524       v8::Local<v8::Value>* argv);
1525 
1526   v8::Local<v8::Object> get_resource();
1527   async_id get_async_id() const;
1528   async_id get_trigger_async_id() const;
1529 
1530  protected:
1531   class NODE_EXTERN CallbackScope : public node::CallbackScope {
1532    public:
1533     explicit CallbackScope(AsyncResource* res);
1534   };
1535 
1536  private:
1537   Environment* env_;
1538   v8::Global<v8::Object> resource_;
1539   async_context async_context_;
1540 };
1541 
1542 #ifndef _WIN32
1543 // Register a signal handler without interrupting any handlers that node
1544 // itself needs. This does override handlers registered through
1545 // process.on('SIG...', function() { ... }). The `reset_handler` flag indicates
1546 // whether the signal handler for the given signal should be reset to its
1547 // default value before executing the handler (i.e. it works like SA_RESETHAND).
1548 // The `reset_handler` flag is invalid when `signal` is SIGSEGV.
1549 NODE_EXTERN
1550 void RegisterSignalHandler(int signal,
1551                            void (*handler)(int signal,
1552                                            siginfo_t* info,
1553                                            void* ucontext),
1554                            bool reset_handler = false);
1555 #endif  // _WIN32
1556 
1557 // Configure the layout of the JavaScript object with a cppgc::GarbageCollected
1558 // instance so that when the JavaScript object is reachable, the garbage
1559 // collected instance would have its Trace() method invoked per the cppgc
1560 // contract. To make it work, the process must have called
1561 // cppgc::InitializeProcess() before, which is usually the case for addons
1562 // loaded by the stand-alone Node.js executable. Embedders of Node.js can use
1563 // either need to call it themselves or make sure that
1564 // ProcessInitializationFlags::kNoInitializeCppgc is *not* set for cppgc to
1565 // work.
1566 // If the CppHeap is owned by Node.js, which is usually the case for addon,
1567 // the object must be created with at least two internal fields available,
1568 // and the first two internal fields would be configured by Node.js.
1569 // This may be superseded by a V8 API in the future, see
1570 // https://bugs.chromium.org/p/v8/issues/detail?id=13960. Until then this
1571 // serves as a helper for Node.js isolates.
1572 NODE_EXTERN void SetCppgcReference(v8::Isolate* isolate,
1573                                    v8::Local<v8::Object> object,
1574                                    void* wrappable);
1575 
1576 }  // namespace node
1577 
1578 #endif  // SRC_NODE_H_