Where Online Learning is simpler!
The C and C++ Include Header Files
/usr/include/node/node.h
$ cat -n /usr/include/node/node.h 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 SIGQUIT 3 71 #define SIGKILL 9 72 #endif 73 74 #include "v8.h" // NOLINT(build/include_order) 75 76 #include "v8-platform.h" // NOLINT(build/include_order) 77 #include "node_version.h" // NODE_MODULE_VERSION 78 79 #define NAPI_EXPERIMENTAL 80 #include "node_api.h" 81 82 #include
83 #include
84 #include
85 #include
86 87 // We cannot use __POSIX__ in this header because that's only defined when 88 // building Node.js. 89 #ifndef _WIN32 90 #include
91 #endif // _WIN32 92 93 #define NODE_MAKE_VERSION(major, minor, patch) \ 94 ((major) * 0x1000 + (minor) * 0x100 + (patch)) 95 96 #ifdef __clang__ 97 # define NODE_CLANG_AT_LEAST(major, minor, patch) \ 98 (NODE_MAKE_VERSION(major, minor, patch) <= \ 99 NODE_MAKE_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__)) 100 #else 101 # define NODE_CLANG_AT_LEAST(major, minor, patch) (0) 102 #endif 103 104 #ifdef __GNUC__ 105 # define NODE_GNUC_AT_LEAST(major, minor, patch) \ 106 (NODE_MAKE_VERSION(major, minor, patch) <= \ 107 NODE_MAKE_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__)) 108 #else 109 # define NODE_GNUC_AT_LEAST(major, minor, patch) (0) 110 #endif 111 112 #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS 113 # define NODE_DEPRECATED(message, declarator) declarator 114 #else // NODE_WANT_INTERNALS 115 # if NODE_CLANG_AT_LEAST(2, 9, 0) || NODE_GNUC_AT_LEAST(4, 5, 0) 116 # define NODE_DEPRECATED(message, declarator) \ 117 __attribute__((deprecated(message))) declarator 118 # elif defined(_MSC_VER) 119 # define NODE_DEPRECATED(message, declarator) \ 120 __declspec(deprecated) declarator 121 # else 122 # define NODE_DEPRECATED(message, declarator) declarator 123 # endif 124 #endif 125 126 // Forward-declare libuv loop 127 struct uv_loop_s; 128 129 // Forward-declare these functions now to stop MSVS from becoming 130 // terminally confused when it's done in node_internals.h 131 namespace node { 132 133 struct SnapshotData; 134 135 namespace tracing { 136 137 class TracingController; 138 139 } 140 141 NODE_EXTERN v8::Local
ErrnoException(v8::Isolate* isolate, 142 int errorno, 143 const char* syscall = nullptr, 144 const char* message = nullptr, 145 const char* path = nullptr); 146 NODE_EXTERN v8::Local
UVException(v8::Isolate* isolate, 147 int errorno, 148 const char* syscall = nullptr, 149 const char* message = nullptr, 150 const char* path = nullptr, 151 const char* dest = nullptr); 152 153 NODE_DEPRECATED("Use ErrnoException(isolate, ...)", 154 inline v8::Local
ErrnoException( 155 int errorno, 156 const char* syscall = nullptr, 157 const char* message = nullptr, 158 const char* path = nullptr) { 159 return ErrnoException(v8::Isolate::GetCurrent(), 160 errorno, 161 syscall, 162 message, 163 path); 164 }) 165 166 NODE_DEPRECATED("Use UVException(isolate, ...)", 167 inline v8::Local
UVException(int errorno, 168 const char* syscall = nullptr, 169 const char* message = nullptr, 170 const char* path = nullptr) { 171 return UVException(v8::Isolate::GetCurrent(), 172 errorno, 173 syscall, 174 message, 175 path); 176 }) 177 178 /* 179 * These methods need to be called in a HandleScope. 180 * 181 * It is preferred that you use the `MakeCallback` overloads taking 182 * `async_context` arguments. 183 */ 184 185 NODE_DEPRECATED("Use MakeCallback(..., async_context)", 186 NODE_EXTERN v8::Local
MakeCallback( 187 v8::Isolate* isolate, 188 v8::Local
recv, 189 const char* method, 190 int argc, 191 v8::Local
* argv)); 192 NODE_DEPRECATED("Use MakeCallback(..., async_context)", 193 NODE_EXTERN v8::Local
MakeCallback( 194 v8::Isolate* isolate, 195 v8::Local
recv, 196 v8::Local
symbol, 197 int argc, 198 v8::Local
* argv)); 199 NODE_DEPRECATED("Use MakeCallback(..., async_context)", 200 NODE_EXTERN v8::Local
MakeCallback( 201 v8::Isolate* isolate, 202 v8::Local
recv, 203 v8::Local
callback, 204 int argc, 205 v8::Local
* argv)); 206 207 } // namespace node 208 209 #include
210 #include
211 212 #ifndef NODE_STRINGIFY 213 # define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n) 214 # define NODE_STRINGIFY_HELPER(n) #n 215 #endif 216 217 #ifdef _WIN32 218 #if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED) 219 typedef intptr_t ssize_t; 220 # define _SSIZE_T_ 221 # define _SSIZE_T_DEFINED 222 #endif 223 #else // !_WIN32 224 # include
// size_t, ssize_t 225 #endif // _WIN32 226 227 228 namespace node { 229 230 class IsolateData; 231 class Environment; 232 class MultiIsolatePlatform; 233 class InitializationResultImpl; 234 235 namespace ProcessInitializationFlags { 236 enum Flags : uint32_t { 237 kNoFlags = 0, 238 // Enable stdio inheritance, which is disabled by default. 239 // This flag is also implied by kNoStdioInitialization. 240 kEnableStdioInheritance = 1 << 0, 241 // Disable reading the NODE_OPTIONS environment variable. 242 kDisableNodeOptionsEnv = 1 << 1, 243 // Do not parse CLI options. 244 kDisableCLIOptions = 1 << 2, 245 // Do not initialize ICU. 246 kNoICU = 1 << 3, 247 // Do not modify stdio file descriptor or TTY state. 248 kNoStdioInitialization = 1 << 4, 249 // Do not register Node.js-specific signal handlers 250 // and reset other signal handlers to default state. 251 kNoDefaultSignalHandling = 1 << 5, 252 // Do not perform V8 initialization. 253 kNoInitializeV8 = 1 << 6, 254 // Do not initialize a default Node.js-provided V8 platform instance. 255 kNoInitializeNodeV8Platform = 1 << 7, 256 // Do not initialize OpenSSL config. 257 kNoInitOpenSSL = 1 << 8, 258 // Do not initialize Node.js debugging based on environment variables. 259 kNoParseGlobalDebugVariables = 1 << 9, 260 // Do not adjust OS resource limits for this process. 261 kNoAdjustResourceLimits = 1 << 10, 262 // Do not map code segments into large pages for this process. 263 kNoUseLargePages = 1 << 11, 264 // Skip printing output for --help, --version, --v8-options. 265 kNoPrintHelpOrVersionOutput = 1 << 12, 266 // Do not perform cppgc initialization. If set, the embedder must call 267 // cppgc::InitializeProcess() before creating a Node.js environment 268 // and call cppgc::ShutdownProcess() before process shutdown. 269 kNoInitializeCppgc = 1 << 13, 270 // Initialize the process for predictable snapshot generation. 271 kGeneratePredictableSnapshot = 1 << 14, 272 273 // Emulate the behavior of InitializeNodeWithArgs() when passing 274 // a flags argument to the InitializeOncePerProcess() replacement 275 // function. 276 kLegacyInitializeNodeWithArgsBehavior = 277 kNoStdioInitialization | kNoDefaultSignalHandling | kNoInitializeV8 | 278 kNoInitializeNodeV8Platform | kNoInitOpenSSL | 279 kNoParseGlobalDebugVariables | kNoAdjustResourceLimits | 280 kNoUseLargePages | kNoPrintHelpOrVersionOutput | kNoInitializeCppgc, 281 }; 282 } // namespace ProcessInitializationFlags 283 namespace ProcessFlags = ProcessInitializationFlags; // Legacy alias. 284 285 namespace StopFlags { 286 enum Flags : uint32_t { 287 kNoFlags = 0, 288 // Do not explicitly terminate the Isolate 289 // when exiting the Environment. 290 kDoNotTerminateIsolate = 1 << 0, 291 }; 292 } // namespace StopFlags 293 294 class NODE_EXTERN InitializationResult { 295 public: 296 virtual ~InitializationResult() = default; 297 298 // Returns a suggested process exit code. 299 virtual int exit_code() const = 0; 300 301 // Returns 'true' if initialization was aborted early due to errors. 302 virtual bool early_return() const = 0; 303 304 // Returns the parsed list of non-Node.js arguments. 305 virtual const std::vector
& args() const = 0; 306 307 // Returns the parsed list of Node.js arguments. 308 virtual const std::vector
& exec_args() const = 0; 309 310 // Returns an array of errors. Note that these may be warnings 311 // whose existence does not imply a non-zero exit code. 312 virtual const std::vector
& errors() const = 0; 313 314 // If kNoInitializeNodeV8Platform was not specified, the global Node.js 315 // platform instance. 316 virtual MultiIsolatePlatform* platform() const = 0; 317 318 private: 319 InitializationResult() = default; 320 friend class InitializationResultImpl; 321 }; 322 323 // TODO(addaleax): Officially deprecate this and replace it with something 324 // better suited for a public embedder API. 325 NODE_EXTERN int Start(int argc, char* argv[]); 326 327 // Tear down Node.js while it is running (there are active handles 328 // in the loop and / or actively executing JavaScript code). 329 NODE_EXTERN int Stop(Environment* env, 330 StopFlags::Flags flags = StopFlags::kNoFlags); 331 332 // Set up per-process state needed to run Node.js. This will consume arguments 333 // from argv, fill exec_argv, and possibly add errors resulting from parsing 334 // the arguments to `errors`. The return value is a suggested exit code for the 335 // program; If it is 0, then initializing Node.js succeeded. 336 // This runs a subset of the initialization performed by 337 // InitializeOncePerProcess(), which supersedes this function. 338 // The subset is roughly equivalent to the one given by 339 // `ProcessInitializationFlags::kLegacyInitializeNodeWithArgsBehavior`. 340 NODE_DEPRECATED("Use InitializeOncePerProcess() instead", 341 NODE_EXTERN int InitializeNodeWithArgs( 342 std::vector
* argv, 343 std::vector
* exec_argv, 344 std::vector
* errors, 345 ProcessInitializationFlags::Flags flags = 346 ProcessInitializationFlags::kNoFlags)); 347 348 // Set up per-process state needed to run Node.js. This will consume arguments 349 // from args, and return information about the initialization success, 350 // including the arguments split into argv/exec_argv, a list of potential 351 // errors encountered during initialization, and a potential suggested 352 // exit code. 353 NODE_EXTERN std::shared_ptr
InitializeOncePerProcess( 354 const std::vector
& args, 355 ProcessInitializationFlags::Flags flags = 356 ProcessInitializationFlags::kNoFlags); 357 // Undoes the initialization performed by InitializeOncePerProcess(), 358 // where cleanup is necessary. 359 NODE_EXTERN void TearDownOncePerProcess(); 360 // Convenience overload for specifying multiple flags without having 361 // to worry about casts. 362 inline std::shared_ptr
InitializeOncePerProcess( 363 const std::vector
& args, 364 std::initializer_list
list) { 365 uint64_t flags_accum = ProcessInitializationFlags::kNoFlags; 366 for (const auto flag : list) flags_accum |= static_cast
(flag); 367 return InitializeOncePerProcess( 368 args, static_cast
(flags_accum)); 369 } 370 371 enum OptionEnvvarSettings { 372 // Allow the options to be set via the environment variable, like 373 // `NODE_OPTIONS`. 374 kAllowedInEnvvar = 0, 375 // Disallow the options to be set via the environment variable, like 376 // `NODE_OPTIONS`. 377 kDisallowedInEnvvar = 1, 378 // Deprecated, use kAllowedInEnvvar instead. 379 kAllowedInEnvironment = kAllowedInEnvvar, 380 // Deprecated, use kDisallowedInEnvvar instead. 381 kDisallowedInEnvironment = kDisallowedInEnvvar, 382 }; 383 384 // Process the arguments and set up the per-process options. 385 // If the `settings` is set as OptionEnvvarSettings::kAllowedInEnvvar, the 386 // options that are allowed in the environment variable are processed. Options 387 // that are disallowed to be set via environment variable are processed as 388 // errors. 389 // Otherwise all the options that are disallowed (and those are allowed) to be 390 // set via environment variable are processed. 391 NODE_EXTERN int ProcessGlobalArgs(std::vector
* args, 392 std::vector
* exec_args, 393 std::vector
* errors, 394 OptionEnvvarSettings settings); 395 396 class NodeArrayBufferAllocator; 397 398 // An ArrayBuffer::Allocator class with some Node.js-specific tweaks. If you do 399 // not have to use another allocator, using this class is recommended: 400 // - It supports Buffer.allocUnsafe() and Buffer.allocUnsafeSlow() with 401 // uninitialized memory. 402 // - It supports transferring, rather than copying, ArrayBuffers when using 403 // MessagePorts. 404 class NODE_EXTERN ArrayBufferAllocator : public v8::ArrayBuffer::Allocator { 405 public: 406 // If `always_debug` is true, create an ArrayBuffer::Allocator instance 407 // that performs additional integrity checks (e.g. make sure that only memory 408 // that was allocated by the it is also freed by it). 409 // This can also be set using the --debug-arraybuffer-allocations flag. 410 static std::unique_ptr
Create( 411 bool always_debug = false); 412 413 private: 414 virtual NodeArrayBufferAllocator* GetImpl() = 0; 415 416 friend class IsolateData; 417 }; 418 419 // Legacy equivalents for ArrayBufferAllocator::Create(). 420 NODE_EXTERN ArrayBufferAllocator* CreateArrayBufferAllocator(); 421 NODE_EXTERN void FreeArrayBufferAllocator(ArrayBufferAllocator* allocator); 422 423 class NODE_EXTERN IsolatePlatformDelegate { 424 public: 425 virtual std::shared_ptr
GetForegroundTaskRunner() = 0; 426 virtual bool IdleTasksEnabled() = 0; 427 }; 428 429 class NODE_EXTERN MultiIsolatePlatform : public v8::Platform { 430 public: 431 ~MultiIsolatePlatform() override = default; 432 // Returns true if work was dispatched or executed. New tasks that are 433 // posted during flushing of the queue are postponed until the next 434 // flushing. 435 virtual bool FlushForegroundTasks(v8::Isolate* isolate) = 0; 436 virtual void DrainTasks(v8::Isolate* isolate) = 0; 437 438 // This needs to be called between the calls to `Isolate::Allocate()` and 439 // `Isolate::Initialize()`, so that initialization can already start 440 // using the platform. 441 // When using `NewIsolate()`, this is taken care of by that function. 442 // This function may only be called once per `Isolate`. 443 virtual void RegisterIsolate(v8::Isolate* isolate, 444 struct uv_loop_s* loop) = 0; 445 // This method can be used when an application handles task scheduling on its 446 // own through `IsolatePlatformDelegate`. Upon registering an isolate with 447 // this overload any other method in this class with the exception of 448 // `UnregisterIsolate` *must not* be used on that isolate. 449 virtual void RegisterIsolate(v8::Isolate* isolate, 450 IsolatePlatformDelegate* delegate) = 0; 451 452 // This function may only be called once per `Isolate`, and discard any 453 // pending delayed tasks scheduled for that isolate. 454 // This needs to be called right before calling `Isolate::Dispose()`. 455 virtual void UnregisterIsolate(v8::Isolate* isolate) = 0; 456 457 // The platform should call the passed function once all state associated 458 // with the given isolate has been cleaned up. This can, but does not have to, 459 // happen asynchronously. 460 virtual void AddIsolateFinishedCallback(v8::Isolate* isolate, 461 void (*callback)(void*), 462 void* data) = 0; 463 464 static std::unique_ptr
Create( 465 int thread_pool_size, 466 v8::TracingController* tracing_controller = nullptr, 467 v8::PageAllocator* page_allocator = nullptr); 468 }; 469 470 enum IsolateSettingsFlags { 471 MESSAGE_LISTENER_WITH_ERROR_LEVEL = 1 << 0, 472 DETAILED_SOURCE_POSITIONS_FOR_PROFILING = 1 << 1, 473 SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK = 1 << 2, 474 SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK = 1 << 3, 475 ALLOW_MODIFY_CODE_GENERATION_FROM_STRINGS_CALLBACK = 0, /* legacy no-op */ 476 }; 477 478 struct IsolateSettings { 479 uint64_t flags = MESSAGE_LISTENER_WITH_ERROR_LEVEL | 480 DETAILED_SOURCE_POSITIONS_FOR_PROFILING; 481 v8::MicrotasksPolicy policy = v8::MicrotasksPolicy::kExplicit; 482 483 // Error handling callbacks 484 v8::Isolate::AbortOnUncaughtExceptionCallback 485 should_abort_on_uncaught_exception_callback = nullptr; 486 v8::FatalErrorCallback fatal_error_callback = nullptr; 487 v8::OOMErrorCallback oom_error_callback = nullptr; 488 v8::PrepareStackTraceCallback prepare_stack_trace_callback = nullptr; 489 490 // Miscellaneous callbacks 491 v8::PromiseRejectCallback promise_reject_callback = nullptr; 492 v8::AllowWasmCodeGenerationCallback 493 allow_wasm_code_generation_callback = nullptr; 494 v8::ModifyCodeGenerationFromStringsCallback2 495 modify_code_generation_from_strings_callback = nullptr; 496 }; 497 498 // Represents a startup snapshot blob, e.g. created by passing 499 // --node-snapshot-main=entry.js to the configure script at build time, 500 // or by running Node.js with the --build-snapshot option. 501 // 502 // If used, the snapshot *must* have been built with the same Node.js 503 // version and V8 flags as the version that is currently running, and will 504 // be rejected otherwise. 505 // The same EmbedderSnapshotData instance *must* be passed to both 506 // `NewIsolate()` and `CreateIsolateData()`. The first `Environment` instance 507 // should be created with an empty `context` argument and will then 508 // use the main context included in the snapshot blob. It can be retrieved 509 // using `GetMainContext()`. `LoadEnvironment` can receive an empty 510 // `StartExecutionCallback` in this case. 511 // If V8 was configured with the shared-readonly-heap option, it requires 512 // all snapshots used to create `Isolate` instances to be identical. 513 // This option *must* be unset by embedders who wish to use the startup 514 // feature during the build step by passing the --disable-shared-readonly-heap 515 // flag to the configure script. 516 // 517 // The snapshot *must* be kept alive during the execution of the Isolate 518 // that was created using it. 519 // 520 // Snapshots are an *experimental* feature. In particular, the embedder API 521 // exposed through this class is subject to change or removal between Node.js 522 // versions, including possible API and ABI breakage. 523 class EmbedderSnapshotData { 524 public: 525 struct DeleteSnapshotData { 526 void operator()(const EmbedderSnapshotData*) const; 527 }; 528 using Pointer = 529 std::unique_ptr
; 530 531 // Return an EmbedderSnapshotData object that refers to the built-in 532 // snapshot of Node.js. This can have been configured through e.g. 533 // --node-snapshot-main=entry.js. 534 static Pointer BuiltinSnapshotData(); 535 536 // Return an EmbedderSnapshotData object that is based on an input file. 537 // Calling this method will consume but not close the FILE* handle. 538 // The FILE* handle can be closed immediately following this call. 539 // If the snapshot is invalid, this returns an empty pointer. 540 static Pointer FromFile(FILE* in); 541 static Pointer FromBlob(const std::vector
& in); 542 static Pointer FromBlob(std::string_view in); 543 544 // Write this EmbedderSnapshotData object to an output file. 545 // Calling this method will not close the FILE* handle. 546 // The FILE* handle can be closed immediately following this call. 547 void ToFile(FILE* out) const; 548 std::vector
ToBlob() const; 549 550 // Returns whether custom snapshots can be used. Currently, this means 551 // that V8 was configured without the shared-readonly-heap feature. 552 static bool CanUseCustomSnapshotPerIsolate(); 553 554 EmbedderSnapshotData(const EmbedderSnapshotData&) = delete; 555 EmbedderSnapshotData& operator=(const EmbedderSnapshotData&) = delete; 556 EmbedderSnapshotData(EmbedderSnapshotData&&) = delete; 557 EmbedderSnapshotData& operator=(EmbedderSnapshotData&&) = delete; 558 559 protected: 560 EmbedderSnapshotData(const SnapshotData* impl, bool owns_impl); 561 562 private: 563 const SnapshotData* impl_; 564 bool owns_impl_; 565 friend struct SnapshotData; 566 friend class CommonEnvironmentSetup; 567 }; 568 569 // Overriding IsolateSettings may produce unexpected behavior 570 // in Node.js core functionality, so proceed at your own risk. 571 NODE_EXTERN void SetIsolateUpForNode(v8::Isolate* isolate, 572 const IsolateSettings& settings); 573 574 // Set a number of callbacks for the `isolate`, in particular the Node.js 575 // uncaught exception listener. 576 NODE_EXTERN void SetIsolateUpForNode(v8::Isolate* isolate); 577 578 // Creates a new isolate with Node.js-specific settings. 579 // This is a convenience method equivalent to using SetIsolateCreateParams(), 580 // Isolate::Allocate(), MultiIsolatePlatform::RegisterIsolate(), 581 // Isolate::Initialize(), and SetIsolateUpForNode(). 582 NODE_EXTERN v8::Isolate* NewIsolate( 583 ArrayBufferAllocator* allocator, 584 struct uv_loop_s* event_loop, 585 MultiIsolatePlatform* platform, 586 const EmbedderSnapshotData* snapshot_data = nullptr, 587 const IsolateSettings& settings = {}); 588 NODE_EXTERN v8::Isolate* NewIsolate( 589 std::shared_ptr
allocator, 590 struct uv_loop_s* event_loop, 591 MultiIsolatePlatform* platform, 592 const EmbedderSnapshotData* snapshot_data = nullptr, 593 const IsolateSettings& settings = {}); 594 595 // Creates a new context with Node.js-specific tweaks. 596 NODE_EXTERN v8::Local
NewContext( 597 v8::Isolate* isolate, 598 v8::Local
object_template = 599 v8::Local
()); 600 601 // Runs Node.js-specific tweaks on an already constructed context 602 // Return value indicates success of operation 603 NODE_EXTERN v8::Maybe
InitializeContext(v8::Local
context); 604 605 // If `platform` is passed, it will be used to register new Worker instances. 606 // It can be `nullptr`, in which case creating new Workers inside of 607 // Environments that use this `IsolateData` will not work. 608 NODE_EXTERN IsolateData* CreateIsolateData( 609 v8::Isolate* isolate, 610 struct uv_loop_s* loop, 611 MultiIsolatePlatform* platform = nullptr, 612 ArrayBufferAllocator* allocator = nullptr, 613 const EmbedderSnapshotData* snapshot_data = nullptr); 614 NODE_EXTERN void FreeIsolateData(IsolateData* isolate_data); 615 616 struct ThreadId { 617 uint64_t id = static_cast
(-1); 618 }; 619 NODE_EXTERN ThreadId AllocateEnvironmentThreadId(); 620 621 namespace EnvironmentFlags { 622 enum Flags : uint64_t { 623 kNoFlags = 0, 624 // Use the default behaviour for Node.js instances. 625 kDefaultFlags = 1 << 0, 626 // Controls whether this Environment is allowed to affect per-process state 627 // (e.g. cwd, process title, uid, etc.). 628 // This is set when using kDefaultFlags. 629 kOwnsProcessState = 1 << 1, 630 // Set if this Environment instance is associated with the global inspector 631 // handling code (i.e. listening on SIGUSR1). 632 // This is set when using kDefaultFlags. 633 kOwnsInspector = 1 << 2, 634 // Set if Node.js should not run its own esm loader. This is needed by some 635 // embedders, because it's possible for the Node.js esm loader to conflict 636 // with another one in an embedder environment, e.g. Blink's in Chromium. 637 kNoRegisterESMLoader = 1 << 3, 638 // Set this flag to make Node.js track "raw" file descriptors, i.e. managed 639 // by fs.open() and fs.close(), and close them during FreeEnvironment(). 640 kTrackUnmanagedFds = 1 << 4, 641 // Set this flag to force hiding console windows when spawning child 642 // processes. This is usually used when embedding Node.js in GUI programs on 643 // Windows. 644 kHideConsoleWindows = 1 << 5, 645 // Set this flag to disable loading native addons via `process.dlopen`. 646 // This environment flag is especially important for worker threads 647 // so that a worker thread can't load a native addon even if `execArgv` 648 // is overwritten and `--no-addons` is not specified but was specified 649 // for this Environment instance. 650 kNoNativeAddons = 1 << 6, 651 // Set this flag to disable searching modules from global paths like 652 // $HOME/.node_modules and $NODE_PATH. This is used by standalone apps that 653 // do not expect to have their behaviors changed because of globally 654 // installed modules. 655 kNoGlobalSearchPaths = 1 << 7, 656 // Do not export browser globals like setTimeout, console, etc. 657 kNoBrowserGlobals = 1 << 8, 658 // Controls whether or not the Environment should call V8Inspector::create(). 659 // This control is needed by embedders who may not want to initialize the V8 660 // inspector in situations where one has already been created, 661 // e.g. Blink's in Chromium. 662 kNoCreateInspector = 1 << 9, 663 // Controls whether or not the InspectorAgent for this Environment should 664 // call StartDebugSignalHandler. This control is needed by embedders who may 665 // not want to allow other processes to start the V8 inspector. 666 kNoStartDebugSignalHandler = 1 << 10, 667 // Controls whether the InspectorAgent created for this Environment waits for 668 // Inspector frontend events during the Environment creation. It's used to 669 // call node::Stop(env) on a Worker thread that is waiting for the events. 670 kNoWaitForInspectorFrontend = 1 << 11 671 }; 672 } // namespace EnvironmentFlags 673 674 enum class SnapshotFlags : uint32_t { 675 kDefault = 0, 676 // Whether code cache should be generated as part of the snapshot. 677 // Code cache reduces the time spent on compiling functions included 678 // in the snapshot at the expense of a bigger snapshot size and 679 // potentially breaking portability of the snapshot. 680 kWithoutCodeCache = 1 << 0, 681 }; 682 683 struct SnapshotConfig { 684 SnapshotFlags flags = SnapshotFlags::kDefault; 685 686 // When builder_script_path is std::nullopt, the snapshot is generated as a 687 // built-in snapshot instead of a custom one, and it's expected that the 688 // built-in snapshot only contains states that reproduce in every run of the 689 // application. The event loop won't be run when generating a built-in 690 // snapshot, so asynchronous operations should be avoided. 691 // 692 // When builder_script_path is an std::string, it should match args[1] 693 // passed to CreateForSnapshotting(). The embedder is also expected to use 694 // LoadEnvironment() to run a script matching this path. In that case the 695 // snapshot is generated as a custom snapshot and the event loop is run, so 696 // the snapshot builder can execute asynchronous operations as long as they 697 // are run to completion when the snapshot is taken. 698 std::optional
builder_script_path; 699 }; 700 701 struct InspectorParentHandle { 702 virtual ~InspectorParentHandle() = default; 703 }; 704 705 // TODO(addaleax): Maybe move per-Environment options parsing here. 706 // Returns nullptr when the Environment cannot be created e.g. there are 707 // pending JavaScript exceptions. 708 // `context` may be empty if an `EmbedderSnapshotData` instance was provided 709 // to `NewIsolate()` and `CreateIsolateData()`. 710 NODE_EXTERN Environment* CreateEnvironment( 711 IsolateData* isolate_data, 712 v8::Local
context, 713 const std::vector
& args, 714 const std::vector
& exec_args, 715 EnvironmentFlags::Flags flags = EnvironmentFlags::kDefaultFlags, 716 ThreadId thread_id = {} /* allocates a thread id automatically */, 717 std::unique_ptr
inspector_parent_handle = {}); 718 719 // Returns a handle that can be passed to `LoadEnvironment()`, making the 720 // child Environment accessible to the inspector as if it were a Node.js Worker. 721 // `child_thread_id` can be created using `AllocateEnvironmentThreadId()` 722 // and then later passed on to `CreateEnvironment()` to create the child 723 // Environment, together with the inspector handle. 724 // This method should not be called while the parent Environment is active 725 // on another thread. 726 NODE_EXTERN std::unique_ptr
GetInspectorParentHandle( 727 Environment* parent_env, 728 ThreadId child_thread_id, 729 const char* child_url); 730 731 NODE_EXTERN std::unique_ptr
GetInspectorParentHandle( 732 Environment* parent_env, 733 ThreadId child_thread_id, 734 const char* child_url, 735 const char* name); 736 737 struct StartExecutionCallbackInfo { 738 v8::Local
process_object; 739 v8::Local
native_require; 740 v8::Local
run_cjs; 741 }; 742 743 using StartExecutionCallback = 744 std::function
(const StartExecutionCallbackInfo&)>; 745 using EmbedderPreloadCallback = 746 std::function
process, 748 v8::Local
require)>; 749 750 // Run initialization for the environment. 751 // 752 // The |preload| function, usually used by embedders to inject scripts, 753 // will be run by Node.js before Node.js executes the entry point. 754 // The function is guaranteed to run before the user land module loader running 755 // any user code, so it is safe to assume that at this point, no user code has 756 // been run yet. 757 // The function will be executed with preload(process, require), and the passed 758 // require function has access to internal Node.js modules. There is no 759 // stability guarantee about the internals exposed to the internal require 760 // function. Expect breakages when updating Node.js versions if the embedder 761 // imports internal modules with the internal require function. 762 // Worker threads created in the environment will also respect The |preload| 763 // function, so make sure the function is thread-safe. 764 NODE_EXTERN v8::MaybeLocal
LoadEnvironment( 765 Environment* env, 766 StartExecutionCallback cb, 767 EmbedderPreloadCallback preload = nullptr); 768 NODE_EXTERN v8::MaybeLocal
LoadEnvironment( 769 Environment* env, 770 std::string_view main_script_source_utf8, 771 EmbedderPreloadCallback preload = nullptr); 772 NODE_EXTERN void FreeEnvironment(Environment* env); 773 774 // Set a callback that is called when process.exit() is called from JS, 775 // overriding the default handler. 776 // It receives the Environment* instance and the exit code as arguments. 777 // This could e.g. call Stop(env); in order to terminate execution and stop 778 // the event loop. 779 // The default handler disposes of the global V8 platform instance, if one is 780 // being used, and calls exit(). 781 NODE_EXTERN void SetProcessExitHandler( 782 Environment* env, 783 std::function
&& handler); 784 NODE_EXTERN void DefaultProcessExitHandler(Environment* env, int exit_code); 785 786 // This may return nullptr if context is not associated with a Node instance. 787 NODE_EXTERN Environment* GetCurrentEnvironment(v8::Local
context); 788 NODE_EXTERN IsolateData* GetEnvironmentIsolateData(Environment* env); 789 NODE_EXTERN ArrayBufferAllocator* GetArrayBufferAllocator(IsolateData* data); 790 // This is mostly useful for Environment* instances that were created through 791 // a snapshot and have a main context that was read from that snapshot. 792 NODE_EXTERN v8::Local
GetMainContext(Environment* env); 793 794 [[noreturn]] NODE_EXTERN void OnFatalError(const char* location, 795 const char* message); 796 NODE_EXTERN void PromiseRejectCallback(v8::PromiseRejectMessage message); 797 NODE_EXTERN bool AllowWasmCodeGenerationCallback(v8::Local
context, 798 v8::Local
); 799 NODE_EXTERN bool ShouldAbortOnUncaughtException(v8::Isolate* isolate); 800 NODE_EXTERN v8::MaybeLocal
PrepareStackTraceCallback( 801 v8::Local
context, 802 v8::Local
exception, 803 v8::Local
trace); 804 805 // Writes a diagnostic report to a file. If filename is not provided, the 806 // default filename includes the date, time, PID, and a sequence number. 807 // The report's JavaScript stack trace is taken from err, if present. 808 // If isolate is nullptr, no information about the JavaScript environment 809 // is included in the report. 810 // Returns the filename of the written report. 811 NODE_EXTERN std::string TriggerNodeReport(v8::Isolate* isolate, 812 const char* message, 813 const char* trigger, 814 const std::string& filename, 815 v8::Local
error); 816 NODE_EXTERN std::string TriggerNodeReport(Environment* env, 817 const char* message, 818 const char* trigger, 819 const std::string& filename, 820 v8::Local
error); 821 NODE_EXTERN void GetNodeReport(v8::Isolate* isolate, 822 const char* message, 823 const char* trigger, 824 v8::Local
error, 825 std::ostream& out); 826 NODE_EXTERN void GetNodeReport(Environment* env, 827 const char* message, 828 const char* trigger, 829 v8::Local
error, 830 std::ostream& out); 831 832 // This returns the MultiIsolatePlatform used for an Environment or IsolateData 833 // instance, if one exists. 834 NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(Environment* env); 835 NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env); 836 837 NODE_DEPRECATED("Use MultiIsolatePlatform::Create() instead", 838 NODE_EXTERN MultiIsolatePlatform* CreatePlatform( 839 int thread_pool_size, 840 v8::TracingController* tracing_controller)); 841 NODE_DEPRECATED("Use MultiIsolatePlatform::Create() instead", 842 NODE_EXTERN void FreePlatform(MultiIsolatePlatform* platform)); 843 844 // Get/set the currently active tracing controller. Using CreatePlatform() 845 // will implicitly set this by default. This is global and should be initialized 846 // along with the v8::Platform instance that is being used. `controller` 847 // is allowed to be `nullptr`. 848 // This is used for tracing events from Node.js itself. V8 uses the tracing 849 // controller returned from the active `v8::Platform` instance. 850 NODE_EXTERN v8::TracingController* GetTracingController(); 851 NODE_EXTERN void SetTracingController(v8::TracingController* controller); 852 853 // Run `process.emit('beforeExit')` as it would usually happen when Node.js is 854 // run in standalone mode. 855 NODE_EXTERN v8::Maybe
EmitProcessBeforeExit(Environment* env); 856 NODE_DEPRECATED("Use Maybe version (EmitProcessBeforeExit) instead", 857 NODE_EXTERN void EmitBeforeExit(Environment* env)); 858 // Run `process.emit('exit')` as it would usually happen when Node.js is run 859 // in standalone mode. The return value corresponds to the exit code. 860 NODE_EXTERN v8::Maybe
EmitProcessExit(Environment* env); 861 NODE_DEPRECATED("Use Maybe version (EmitProcessExit) instead", 862 NODE_EXTERN int EmitExit(Environment* env)); 863 864 // Runs hooks added through `AtExit()`. This is part of `FreeEnvironment()`, 865 // so calling it manually is typically not necessary. 866 NODE_EXTERN void RunAtExit(Environment* env); 867 868 // This may return nullptr if the current v8::Context is not associated 869 // with a Node instance. 870 NODE_EXTERN struct uv_loop_s* GetCurrentEventLoop(v8::Isolate* isolate); 871 872 // Runs the main loop for a given Environment. This roughly performs the 873 // following steps: 874 // 1. Call uv_run() on the event loop until it is drained. 875 // 2. Call platform->DrainTasks() on the associated platform/isolate. 876 // 3. If the event loop is alive again, go to Step 1. 877 // 4. Call EmitProcessBeforeExit(). 878 // 5. If the event loop is alive again, go to Step 1. 879 // 6. Call EmitProcessExit() and forward the return value. 880 // If at any point node::Stop() is called, the function will attempt to return 881 // as soon as possible, returning an empty `Maybe`. 882 // This function only works if `env` has an associated `MultiIsolatePlatform`. 883 NODE_EXTERN v8::Maybe
SpinEventLoop(Environment* env); 884 885 NODE_EXTERN std::string GetAnonymousMainPath(); 886 887 class NODE_EXTERN CommonEnvironmentSetup { 888 public: 889 ~CommonEnvironmentSetup(); 890 891 // Create a new CommonEnvironmentSetup, that is, a group of objects that 892 // together form the typical setup for a single Node.js Environment instance. 893 // If any error occurs, `*errors` will be populated and the returned pointer 894 // will be empty. 895 // env_args will be passed through as arguments to CreateEnvironment(), after 896 // `isolate_data` and `context`. 897 template
898 static std::unique_ptr
Create( 899 MultiIsolatePlatform* platform, 900 std::vector
* errors, 901 EnvironmentArgs&&... env_args); 902 template
903 static std::unique_ptr
CreateFromSnapshot( 904 MultiIsolatePlatform* platform, 905 std::vector
* errors, 906 const EmbedderSnapshotData* snapshot_data, 907 EnvironmentArgs&&... env_args); 908 909 // Create an embedding setup which will be used for creating a snapshot 910 // using CreateSnapshot(). 911 // 912 // This will create and attach a v8::SnapshotCreator to this instance, 913 // and the same restrictions apply to this instance that also apply to 914 // other V8 snapshotting environments. 915 // Not all Node.js APIs are supported in this case. Currently, there is 916 // no support for native/host objects other than Node.js builtins 917 // in the snapshot. 918 // 919 // If the embedder wants to use LoadEnvironment() later to run a snapshot 920 // builder script they should make sure args[1] contains the path of the 921 // snapshot script, which will be used to create __filename and __dirname 922 // in the context where the builder script is run. If they do not want to 923 // include the build-time paths into the snapshot, use the string returned 924 // by GetAnonymousMainPath() as args[1] to anonymize the script. 925 // 926 // Snapshots are an *experimental* feature. In particular, the embedder API 927 // exposed through this class is subject to change or removal between Node.js 928 // versions, including possible API and ABI breakage. 929 static std::unique_ptr
CreateForSnapshotting( 930 MultiIsolatePlatform* platform, 931 std::vector
* errors, 932 const std::vector
& args = {}, 933 const std::vector
& exec_args = {}, 934 const SnapshotConfig& snapshot_config = {}); 935 EmbedderSnapshotData::Pointer CreateSnapshot(); 936 937 struct uv_loop_s* event_loop() const; 938 v8::SnapshotCreator* snapshot_creator(); 939 // Empty for snapshotting environments. 940 std::shared_ptr
array_buffer_allocator() const; 941 v8::Isolate* isolate() const; 942 IsolateData* isolate_data() const; 943 Environment* env() const; 944 v8::Local
context() const; 945 946 CommonEnvironmentSetup(const CommonEnvironmentSetup&) = delete; 947 CommonEnvironmentSetup& operator=(const CommonEnvironmentSetup&) = delete; 948 CommonEnvironmentSetup(CommonEnvironmentSetup&&) = delete; 949 CommonEnvironmentSetup& operator=(CommonEnvironmentSetup&&) = delete; 950 951 private: 952 enum Flags : uint32_t { 953 kNoFlags = 0, 954 kIsForSnapshotting = 1, 955 }; 956 957 struct Impl; 958 Impl* impl_; 959 960 CommonEnvironmentSetup( 961 MultiIsolatePlatform*, 962 std::vector
*, 963 std::function
); 964 CommonEnvironmentSetup( 965 MultiIsolatePlatform*, 966 std::vector
*, 967 const EmbedderSnapshotData*, 968 uint32_t flags, 969 std::function
, 970 const SnapshotConfig* config = nullptr); 971 }; 972 973 // Implementation for CommonEnvironmentSetup::Create 974 template
975 std::unique_ptr
CommonEnvironmentSetup::Create( 976 MultiIsolatePlatform* platform, 977 std::vector
* errors, 978 EnvironmentArgs&&... env_args) { 979 auto ret = std::unique_ptr
(new CommonEnvironmentSetup( 980 platform, errors, 981 [&](const CommonEnvironmentSetup* setup) -> Environment* { 982 return CreateEnvironment( 983 setup->isolate_data(), setup->context(), 984 std::forward
(env_args)...); 985 })); 986 if (!errors->empty()) ret.reset(); 987 return ret; 988 } 989 990 // Implementation for ::CreateFromSnapshot -- the ::Create() method 991 // could call this with a nullptr snapshot_data in a major version. 992 template
993 std::unique_ptr
994 CommonEnvironmentSetup::CreateFromSnapshot( 995 MultiIsolatePlatform* platform, 996 std::vector
* errors, 997 const EmbedderSnapshotData* snapshot_data, 998 EnvironmentArgs&&... env_args) { 999 auto ret = std::unique_ptr
(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
(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
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
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
context = isolate->GetCurrentContext(); \ 1032 v8::Local
constant_name = v8::String::NewFromUtf8Literal( \ 1033 isolate, #constant, v8::NewStringType::kInternalized); \ 1034 v8::Local
constant_value = \ 1035 v8::Number::New(isolate, static_cast
(constant)); \ 1036 v8::PropertyAttribute constant_attributes = \ 1037 static_cast
(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
context = isolate->GetCurrentContext(); \ 1048 v8::Local
constant_name = v8::String::NewFromUtf8Literal( \ 1049 isolate, #constant, v8::NewStringType::kInternalized); \ 1050 v8::Local
constant_value = \ 1051 v8::Number::New(isolate, static_cast
(constant)); \ 1052 v8::PropertyAttribute constant_attributes = \ 1053 static_cast
(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
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
t = v8::FunctionTemplate::New(isolate, 1068 callback); 1069 v8::Local
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
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
context = isolate->GetCurrentContext(); 1082 v8::Local
t = v8::FunctionTemplate::New(isolate, 1083 callback); 1084 v8::Local
fn = t->GetFunction(context).ToLocalChecked(); 1085 v8::Local
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
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
s = v8::Signature::New(isolate, recv); 1100 v8::Local
t = 1101 v8::FunctionTemplate::New(isolate, callback, v8::Local
(), s); 1102 v8::Local
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
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
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
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
, 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
, 1151 enum encoding encoding = LATIN1); 1152 #ifdef _WIN32 1153 NODE_EXTERN v8::Local
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
exports, 1166 v8::Local
module, 1167 void* priv); 1168 1169 typedef void (*addon_context_register_func)( 1170 v8::Local
exports, 1171 v8::Local
module, 1172 v8::Local
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
exports, \ 1295 v8::Local
module, \ 1296 v8::Local
context); \ 1297 NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME, \ 1298 NODE_MODULE_INITIALIZER) \ 1299 void NODE_MODULE_INITIALIZER(v8::Local
exports, \ 1300 v8::Local
module, \ 1301 v8::Local
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
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
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
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
resource, 1413 v8::Local
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
resource, 1448 async_context asyncContext); 1449 CallbackScope(Environment* env, 1450 v8::Local
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
MakeCallback(v8::Isolate* isolate, 1476 v8::Local
recv, 1477 v8::Local
callback, 1478 int argc, 1479 v8::Local
* argv, 1480 async_context asyncContext); 1481 NODE_EXTERN 1482 v8::MaybeLocal
MakeCallback(v8::Isolate* isolate, 1483 v8::Local
recv, 1484 const char* method, 1485 int argc, 1486 v8::Local
* argv, 1487 async_context asyncContext); 1488 NODE_EXTERN 1489 v8::MaybeLocal
MakeCallback(v8::Isolate* isolate, 1490 v8::Local
recv, 1491 v8::Local
symbol, 1492 int argc, 1493 v8::Local
* 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
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
MakeCallback( 1512 v8::Local
callback, 1513 int argc, 1514 v8::Local
* argv); 1515 1516 v8::MaybeLocal
MakeCallback( 1517 const char* method, 1518 int argc, 1519 v8::Local
* argv); 1520 1521 v8::MaybeLocal
MakeCallback( 1522 v8::Local
symbol, 1523 int argc, 1524 v8::Local
* argv); 1525 1526 v8::Local
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
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
object, 1574 void* wrappable); 1575 1576 } // namespace node 1577 1578 #endif // SRC_NODE_H_
Contact us
|
About us
|
Term of use
|
Copyright © 2000-2025 MyWebUniversity.com ™