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 NODE_EXTERN Environment* CreateEnvironment( 720 IsolateData* isolate_data, 721 v8::Local
context, 722 const std::vector
& args, 723 const std::vector
& exec_args, 724 EnvironmentFlags::Flags flags, 725 ThreadId thread_id, 726 std::unique_ptr
inspector_parent_handle, 727 std::string_view thread_name); 728 729 // Returns a handle that can be passed to `LoadEnvironment()`, making the 730 // child Environment accessible to the inspector as if it were a Node.js Worker. 731 // `child_thread_id` can be created using `AllocateEnvironmentThreadId()` 732 // and then later passed on to `CreateEnvironment()` to create the child 733 // Environment, together with the inspector handle. 734 // This method should not be called while the parent Environment is active 735 // on another thread. 736 NODE_EXTERN std::unique_ptr
GetInspectorParentHandle( 737 Environment* parent_env, 738 ThreadId child_thread_id, 739 const char* child_url); 740 741 NODE_EXTERN std::unique_ptr
GetInspectorParentHandle( 742 Environment* parent_env, 743 ThreadId child_thread_id, 744 const char* child_url, 745 const char* name); 746 747 NODE_EXTERN std::unique_ptr
GetInspectorParentHandle( 748 Environment* parent_env, 749 ThreadId child_thread_id, 750 std::string_view child_url, 751 std::string_view name); 752 753 struct StartExecutionCallbackInfo { 754 v8::Local
process_object; 755 v8::Local
native_require; 756 v8::Local
run_cjs; 757 }; 758 759 using StartExecutionCallback = 760 std::function
(const StartExecutionCallbackInfo&)>; 761 using EmbedderPreloadCallback = 762 std::function
process, 764 v8::Local
require)>; 765 766 // Run initialization for the environment. 767 // 768 // The |preload| function, usually used by embedders to inject scripts, 769 // will be run by Node.js before Node.js executes the entry point. 770 // The function is guaranteed to run before the user land module loader running 771 // any user code, so it is safe to assume that at this point, no user code has 772 // been run yet. 773 // The function will be executed with preload(process, require), and the passed 774 // require function has access to internal Node.js modules. There is no 775 // stability guarantee about the internals exposed to the internal require 776 // function. Expect breakages when updating Node.js versions if the embedder 777 // imports internal modules with the internal require function. 778 // Worker threads created in the environment will also respect The |preload| 779 // function, so make sure the function is thread-safe. 780 NODE_EXTERN v8::MaybeLocal
LoadEnvironment( 781 Environment* env, 782 StartExecutionCallback cb, 783 EmbedderPreloadCallback preload = nullptr); 784 NODE_EXTERN v8::MaybeLocal
LoadEnvironment( 785 Environment* env, 786 std::string_view main_script_source_utf8, 787 EmbedderPreloadCallback preload = nullptr); 788 NODE_EXTERN void FreeEnvironment(Environment* env); 789 790 // Set a callback that is called when process.exit() is called from JS, 791 // overriding the default handler. 792 // It receives the Environment* instance and the exit code as arguments. 793 // This could e.g. call Stop(env); in order to terminate execution and stop 794 // the event loop. 795 // The default handler disposes of the global V8 platform instance, if one is 796 // being used, and calls exit(). 797 NODE_EXTERN void SetProcessExitHandler( 798 Environment* env, 799 std::function
&& handler); 800 NODE_EXTERN void DefaultProcessExitHandler(Environment* env, int exit_code); 801 802 // This may return nullptr if context is not associated with a Node instance. 803 NODE_EXTERN Environment* GetCurrentEnvironment(v8::Local
context); 804 NODE_EXTERN IsolateData* GetEnvironmentIsolateData(Environment* env); 805 NODE_EXTERN ArrayBufferAllocator* GetArrayBufferAllocator(IsolateData* data); 806 // This is mostly useful for Environment* instances that were created through 807 // a snapshot and have a main context that was read from that snapshot. 808 NODE_EXTERN v8::Local
GetMainContext(Environment* env); 809 810 [[noreturn]] NODE_EXTERN void OnFatalError(const char* location, 811 const char* message); 812 NODE_EXTERN void PromiseRejectCallback(v8::PromiseRejectMessage message); 813 NODE_EXTERN bool AllowWasmCodeGenerationCallback(v8::Local
context, 814 v8::Local
); 815 NODE_EXTERN bool ShouldAbortOnUncaughtException(v8::Isolate* isolate); 816 NODE_EXTERN v8::MaybeLocal
PrepareStackTraceCallback( 817 v8::Local
context, 818 v8::Local
exception, 819 v8::Local
trace); 820 821 // Writes a diagnostic report to a file. If filename is not provided, the 822 // default filename includes the date, time, PID, and a sequence number. 823 // The report's JavaScript stack trace is taken from err, if present. 824 // If isolate is nullptr, no information about the JavaScript environment 825 // is included in the report. 826 // Returns the filename of the written report. 827 NODE_EXTERN std::string TriggerNodeReport(v8::Isolate* isolate, 828 const char* message, 829 const char* trigger, 830 const std::string& filename, 831 v8::Local
error); 832 NODE_EXTERN std::string TriggerNodeReport(Environment* env, 833 const char* message, 834 const char* trigger, 835 const std::string& filename, 836 v8::Local
error); 837 NODE_EXTERN void GetNodeReport(v8::Isolate* isolate, 838 const char* message, 839 const char* trigger, 840 v8::Local
error, 841 std::ostream& out); 842 NODE_EXTERN void GetNodeReport(Environment* env, 843 const char* message, 844 const char* trigger, 845 v8::Local
error, 846 std::ostream& out); 847 848 // This returns the MultiIsolatePlatform used for an Environment or IsolateData 849 // instance, if one exists. 850 NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(Environment* env); 851 NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env); 852 853 NODE_DEPRECATED("Use MultiIsolatePlatform::Create() instead", 854 NODE_EXTERN MultiIsolatePlatform* CreatePlatform( 855 int thread_pool_size, 856 v8::TracingController* tracing_controller)); 857 NODE_DEPRECATED("Use MultiIsolatePlatform::Create() instead", 858 NODE_EXTERN void FreePlatform(MultiIsolatePlatform* platform)); 859 860 // Get/set the currently active tracing controller. Using CreatePlatform() 861 // will implicitly set this by default. This is global and should be initialized 862 // along with the v8::Platform instance that is being used. `controller` 863 // is allowed to be `nullptr`. 864 // This is used for tracing events from Node.js itself. V8 uses the tracing 865 // controller returned from the active `v8::Platform` instance. 866 NODE_EXTERN v8::TracingController* GetTracingController(); 867 NODE_EXTERN void SetTracingController(v8::TracingController* controller); 868 869 // Run `process.emit('beforeExit')` as it would usually happen when Node.js is 870 // run in standalone mode. 871 NODE_EXTERN v8::Maybe
EmitProcessBeforeExit(Environment* env); 872 NODE_DEPRECATED("Use Maybe version (EmitProcessBeforeExit) instead", 873 NODE_EXTERN void EmitBeforeExit(Environment* env)); 874 // Run `process.emit('exit')` as it would usually happen when Node.js is run 875 // in standalone mode. The return value corresponds to the exit code. 876 NODE_EXTERN v8::Maybe
EmitProcessExit(Environment* env); 877 NODE_DEPRECATED("Use Maybe version (EmitProcessExit) instead", 878 NODE_EXTERN int EmitExit(Environment* env)); 879 880 // Runs hooks added through `AtExit()`. This is part of `FreeEnvironment()`, 881 // so calling it manually is typically not necessary. 882 NODE_EXTERN void RunAtExit(Environment* env); 883 884 // This may return nullptr if the current v8::Context is not associated 885 // with a Node instance. 886 NODE_EXTERN struct uv_loop_s* GetCurrentEventLoop(v8::Isolate* isolate); 887 888 // Runs the main loop for a given Environment. This roughly performs the 889 // following steps: 890 // 1. Call uv_run() on the event loop until it is drained. 891 // 2. Call platform->DrainTasks() on the associated platform/isolate. 892 // 3. If the event loop is alive again, go to Step 1. 893 // 4. Call EmitProcessBeforeExit(). 894 // 5. If the event loop is alive again, go to Step 1. 895 // 6. Call EmitProcessExit() and forward the return value. 896 // If at any point node::Stop() is called, the function will attempt to return 897 // as soon as possible, returning an empty `Maybe`. 898 // This function only works if `env` has an associated `MultiIsolatePlatform`. 899 NODE_EXTERN v8::Maybe
SpinEventLoop(Environment* env); 900 901 NODE_EXTERN std::string GetAnonymousMainPath(); 902 903 class NODE_EXTERN CommonEnvironmentSetup { 904 public: 905 ~CommonEnvironmentSetup(); 906 907 // Create a new CommonEnvironmentSetup, that is, a group of objects that 908 // together form the typical setup for a single Node.js Environment instance. 909 // If any error occurs, `*errors` will be populated and the returned pointer 910 // will be empty. 911 // env_args will be passed through as arguments to CreateEnvironment(), after 912 // `isolate_data` and `context`. 913 template
914 static std::unique_ptr
Create( 915 MultiIsolatePlatform* platform, 916 std::vector
* errors, 917 EnvironmentArgs&&... env_args); 918 template
919 static std::unique_ptr
CreateFromSnapshot( 920 MultiIsolatePlatform* platform, 921 std::vector
* errors, 922 const EmbedderSnapshotData* snapshot_data, 923 EnvironmentArgs&&... env_args); 924 925 // Create an embedding setup which will be used for creating a snapshot 926 // using CreateSnapshot(). 927 // 928 // This will create and attach a v8::SnapshotCreator to this instance, 929 // and the same restrictions apply to this instance that also apply to 930 // other V8 snapshotting environments. 931 // Not all Node.js APIs are supported in this case. Currently, there is 932 // no support for native/host objects other than Node.js builtins 933 // in the snapshot. 934 // 935 // If the embedder wants to use LoadEnvironment() later to run a snapshot 936 // builder script they should make sure args[1] contains the path of the 937 // snapshot script, which will be used to create __filename and __dirname 938 // in the context where the builder script is run. If they do not want to 939 // include the build-time paths into the snapshot, use the string returned 940 // by GetAnonymousMainPath() as args[1] to anonymize the script. 941 // 942 // Snapshots are an *experimental* feature. In particular, the embedder API 943 // exposed through this class is subject to change or removal between Node.js 944 // versions, including possible API and ABI breakage. 945 static std::unique_ptr
CreateForSnapshotting( 946 MultiIsolatePlatform* platform, 947 std::vector
* errors, 948 const std::vector
& args = {}, 949 const std::vector
& exec_args = {}, 950 const SnapshotConfig& snapshot_config = {}); 951 EmbedderSnapshotData::Pointer CreateSnapshot(); 952 953 struct uv_loop_s* event_loop() const; 954 v8::SnapshotCreator* snapshot_creator(); 955 // Empty for snapshotting environments. 956 std::shared_ptr
array_buffer_allocator() const; 957 v8::Isolate* isolate() const; 958 IsolateData* isolate_data() const; 959 Environment* env() const; 960 v8::Local
context() const; 961 962 CommonEnvironmentSetup(const CommonEnvironmentSetup&) = delete; 963 CommonEnvironmentSetup& operator=(const CommonEnvironmentSetup&) = delete; 964 CommonEnvironmentSetup(CommonEnvironmentSetup&&) = delete; 965 CommonEnvironmentSetup& operator=(CommonEnvironmentSetup&&) = delete; 966 967 private: 968 enum Flags : uint32_t { 969 kNoFlags = 0, 970 kIsForSnapshotting = 1, 971 }; 972 973 struct Impl; 974 Impl* impl_; 975 976 CommonEnvironmentSetup( 977 MultiIsolatePlatform*, 978 std::vector
*, 979 std::function
); 980 CommonEnvironmentSetup( 981 MultiIsolatePlatform*, 982 std::vector
*, 983 const EmbedderSnapshotData*, 984 uint32_t flags, 985 std::function
, 986 const SnapshotConfig* config = nullptr); 987 }; 988 989 // Implementation for CommonEnvironmentSetup::Create 990 template
991 std::unique_ptr
CommonEnvironmentSetup::Create( 992 MultiIsolatePlatform* platform, 993 std::vector
* errors, 994 EnvironmentArgs&&... env_args) { 995 auto ret = std::unique_ptr
(new CommonEnvironmentSetup( 996 platform, errors, 997 [&](const CommonEnvironmentSetup* setup) -> Environment* { 998 return CreateEnvironment( 999 setup->isolate_data(), setup->context(), 1000 std::forward
(env_args)...); 1001 })); 1002 if (!errors->empty()) ret.reset(); 1003 return ret; 1004 } 1005 1006 // Implementation for ::CreateFromSnapshot -- the ::Create() method 1007 // could call this with a nullptr snapshot_data in a major version. 1008 template
1009 std::unique_ptr
1010 CommonEnvironmentSetup::CreateFromSnapshot( 1011 MultiIsolatePlatform* platform, 1012 std::vector
* errors, 1013 const EmbedderSnapshotData* snapshot_data, 1014 EnvironmentArgs&&... env_args) { 1015 auto ret = std::unique_ptr
(new CommonEnvironmentSetup( 1016 platform, 1017 errors, 1018 snapshot_data, 1019 Flags::kNoFlags, 1020 [&](const CommonEnvironmentSetup* setup) -> Environment* { 1021 return CreateEnvironment(setup->isolate_data(), 1022 setup->context(), 1023 std::forward
(env_args)...); 1024 })); 1025 if (!errors->empty()) ret.reset(); 1026 return ret; 1027 } 1028 1029 /* Converts a unixtime to V8 Date */ 1030 NODE_DEPRECATED("Use v8::Date::New() directly", 1031 inline v8::Local
NODE_UNIXTIME_V8(double time) { 1032 return v8::Date::New( 1033 v8::Isolate::GetCurrent()->GetCurrentContext(), 1034 1000 * time) 1035 .ToLocalChecked(); 1036 }) 1037 #define NODE_UNIXTIME_V8 node::NODE_UNIXTIME_V8 1038 NODE_DEPRECATED("Use v8::Date::ValueOf() directly", 1039 inline double NODE_V8_UNIXTIME(v8::Local
date) { 1040 return date->ValueOf() / 1000; 1041 }) 1042 #define NODE_V8_UNIXTIME node::NODE_V8_UNIXTIME 1043 1044 #define NODE_DEFINE_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 (target) \ 1055 ->DefineOwnProperty( \ 1056 context, constant_name, constant_value, constant_attributes) \ 1057 .Check(); \ 1058 } while (0) 1059 1060 #define NODE_DEFINE_HIDDEN_CONSTANT(target, constant) \ 1061 do { \ 1062 v8::Isolate* isolate = target->GetIsolate(); \ 1063 v8::Local
context = isolate->GetCurrentContext(); \ 1064 v8::Local
constant_name = v8::String::NewFromUtf8Literal( \ 1065 isolate, #constant, v8::NewStringType::kInternalized); \ 1066 v8::Local
constant_value = \ 1067 v8::Number::New(isolate, static_cast
(constant)); \ 1068 v8::PropertyAttribute constant_attributes = \ 1069 static_cast
(v8::ReadOnly | v8::DontDelete | \ 1070 v8::DontEnum); \ 1071 (target) \ 1072 ->DefineOwnProperty( \ 1073 context, constant_name, constant_value, constant_attributes) \ 1074 .Check(); \ 1075 } while (0) 1076 1077 // Used to be a macro, hence the uppercase name. 1078 inline void NODE_SET_METHOD(v8::Local
recv, 1079 const char* name, 1080 v8::FunctionCallback callback) { 1081 v8::Isolate* isolate = v8::Isolate::GetCurrent(); 1082 v8::HandleScope handle_scope(isolate); 1083 v8::Local
t = v8::FunctionTemplate::New(isolate, 1084 callback); 1085 v8::Local
fn_name = v8::String::NewFromUtf8(isolate, name, 1086 v8::NewStringType::kInternalized).ToLocalChecked(); 1087 t->SetClassName(fn_name); 1088 recv->Set(fn_name, t); 1089 } 1090 1091 // Used to be a macro, hence the uppercase name. 1092 inline void NODE_SET_METHOD(v8::Local
recv, 1093 const char* name, 1094 v8::FunctionCallback callback) { 1095 v8::Isolate* isolate = v8::Isolate::GetCurrent(); 1096 v8::HandleScope handle_scope(isolate); 1097 v8::Local
context = isolate->GetCurrentContext(); 1098 v8::Local
t = v8::FunctionTemplate::New(isolate, 1099 callback); 1100 v8::Local
fn = t->GetFunction(context).ToLocalChecked(); 1101 v8::Local
fn_name = v8::String::NewFromUtf8(isolate, name, 1102 v8::NewStringType::kInternalized).ToLocalChecked(); 1103 fn->SetName(fn_name); 1104 recv->Set(context, fn_name, fn).Check(); 1105 } 1106 #define NODE_SET_METHOD node::NODE_SET_METHOD 1107 1108 // Used to be a macro, hence the uppercase name. 1109 // Not a template because it only makes sense for FunctionTemplates. 1110 inline void NODE_SET_PROTOTYPE_METHOD(v8::Local
recv, 1111 const char* name, 1112 v8::FunctionCallback callback) { 1113 v8::Isolate* isolate = v8::Isolate::GetCurrent(); 1114 v8::HandleScope handle_scope(isolate); 1115 v8::Local
s = v8::Signature::New(isolate, recv); 1116 v8::Local
t = 1117 v8::FunctionTemplate::New(isolate, callback, v8::Local
(), s); 1118 v8::Local
fn_name = v8::String::NewFromUtf8(isolate, name, 1119 v8::NewStringType::kInternalized).ToLocalChecked(); 1120 t->SetClassName(fn_name); 1121 recv->PrototypeTemplate()->Set(fn_name, t); 1122 } 1123 #define NODE_SET_PROTOTYPE_METHOD node::NODE_SET_PROTOTYPE_METHOD 1124 1125 // BINARY is a deprecated alias of LATIN1. 1126 // BASE64URL is not currently exposed to the JavaScript side. 1127 enum encoding { 1128 ASCII, 1129 UTF8, 1130 BASE64, 1131 UCS2, 1132 BINARY, 1133 HEX, 1134 BUFFER, 1135 BASE64URL, 1136 LATIN1 = BINARY 1137 }; 1138 1139 NODE_EXTERN enum encoding ParseEncoding( 1140 v8::Isolate* isolate, 1141 v8::Local
encoding_v, 1142 enum encoding default_encoding = LATIN1); 1143 1144 NODE_EXTERN void FatalException(v8::Isolate* isolate, 1145 const v8::TryCatch& try_catch); 1146 1147 NODE_EXTERN v8::Local
Encode(v8::Isolate* isolate, 1148 const char* buf, 1149 size_t len, 1150 enum encoding encoding = LATIN1); 1151 1152 // Warning: This reverses endianness on Big Endian platforms, even though the 1153 // signature using uint16_t implies that it should not. 1154 NODE_EXTERN v8::Local
Encode(v8::Isolate* isolate, 1155 const uint16_t* buf, 1156 size_t len); 1157 1158 // Returns -1 if the handle was not valid for decoding 1159 NODE_EXTERN ssize_t DecodeBytes(v8::Isolate* isolate, 1160 v8::Local
, 1161 enum encoding encoding = LATIN1); 1162 // returns bytes written. 1163 NODE_EXTERN ssize_t DecodeWrite(v8::Isolate* isolate, 1164 char* buf, 1165 size_t buflen, 1166 v8::Local
, 1167 enum encoding encoding = LATIN1); 1168 #ifdef _WIN32 1169 NODE_EXTERN v8::Local
WinapiErrnoException( 1170 v8::Isolate* isolate, 1171 int errorno, 1172 const char* syscall = nullptr, 1173 const char* msg = "", 1174 const char* path = nullptr); 1175 #endif 1176 1177 const char* signo_string(int errorno); 1178 1179 1180 typedef void (*addon_register_func)( 1181 v8::Local
exports, 1182 v8::Local
module, 1183 void* priv); 1184 1185 typedef void (*addon_context_register_func)( 1186 v8::Local
exports, 1187 v8::Local
module, 1188 v8::Local
context, 1189 void* priv); 1190 1191 enum ModuleFlags { 1192 kLinked = 0x02 1193 }; 1194 1195 struct node_module { 1196 int nm_version; 1197 unsigned int nm_flags; 1198 void* nm_dso_handle; 1199 const char* nm_filename; 1200 node::addon_register_func nm_register_func; 1201 node::addon_context_register_func nm_context_register_func; 1202 const char* nm_modname; 1203 void* nm_priv; 1204 struct node_module* nm_link; 1205 }; 1206 1207 extern "C" NODE_EXTERN void node_module_register(void* mod); 1208 1209 #ifdef _WIN32 1210 # define NODE_MODULE_EXPORT __declspec(dllexport) 1211 #else 1212 # define NODE_MODULE_EXPORT __attribute__((visibility("default"))) 1213 #endif 1214 1215 #ifdef NODE_SHARED_MODE 1216 # define NODE_CTOR_PREFIX 1217 #else 1218 # define NODE_CTOR_PREFIX static 1219 #endif 1220 1221 #if defined(_MSC_VER) 1222 #define NODE_C_CTOR(fn) \ 1223 NODE_CTOR_PREFIX void __cdecl fn(void); \ 1224 namespace { \ 1225 struct fn##_ { \ 1226 fn##_() { fn(); }; \ 1227 } fn##_v_; \ 1228 } \ 1229 NODE_CTOR_PREFIX void __cdecl fn(void) 1230 #else 1231 #define NODE_C_CTOR(fn) \ 1232 NODE_CTOR_PREFIX void fn(void) __attribute__((constructor)); \ 1233 NODE_CTOR_PREFIX void fn(void) 1234 #endif 1235 1236 #define NODE_MODULE_X(modname, regfunc, priv, flags) \ 1237 extern "C" { \ 1238 static node::node_module _module = \ 1239 { \ 1240 NODE_MODULE_VERSION, \ 1241 flags, \ 1242 NULL, /* NOLINT (readability/null_usage) */ \ 1243 __FILE__, \ 1244 (node::addon_register_func) (regfunc), \ 1245 NULL, /* NOLINT (readability/null_usage) */ \ 1246 NODE_STRINGIFY(modname), \ 1247 priv, \ 1248 NULL /* NOLINT (readability/null_usage) */ \ 1249 }; \ 1250 NODE_C_CTOR(_register_ ## modname) { \ 1251 node_module_register(&_module); \ 1252 } \ 1253 } 1254 1255 #define NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, priv, flags) \ 1256 extern "C" { \ 1257 static node::node_module _module = \ 1258 { \ 1259 NODE_MODULE_VERSION, \ 1260 flags, \ 1261 NULL, /* NOLINT (readability/null_usage) */ \ 1262 __FILE__, \ 1263 NULL, /* NOLINT (readability/null_usage) */ \ 1264 (node::addon_context_register_func) (regfunc), \ 1265 NODE_STRINGIFY(modname), \ 1266 priv, \ 1267 NULL /* NOLINT (readability/null_usage) */ \ 1268 }; \ 1269 NODE_C_CTOR(_register_ ## modname) { \ 1270 node_module_register(&_module); \ 1271 } \ 1272 } 1273 1274 // Usage: `NODE_MODULE(NODE_GYP_MODULE_NAME, InitializerFunction)` 1275 // If no NODE_MODULE is declared, Node.js looks for the well-known 1276 // symbol `node_register_module_v${NODE_MODULE_VERSION}`. 1277 #define NODE_MODULE(modname, regfunc) \ 1278 NODE_MODULE_X(modname, regfunc, NULL, 0) // NOLINT (readability/null_usage) 1279 1280 #define NODE_MODULE_CONTEXT_AWARE(modname, regfunc) \ 1281 /* NOLINTNEXTLINE (readability/null_usage) */ \ 1282 NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL, 0) 1283 1284 // Embedders can use this type of binding for statically linked native bindings. 1285 // It is used the same way addon bindings are used, except that linked bindings 1286 // can be accessed through `process._linkedBinding(modname)`. 1287 #define NODE_MODULE_LINKED(modname, regfunc) \ 1288 /* NOLINTNEXTLINE (readability/null_usage) */ \ 1289 NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL, \ 1290 node::ModuleFlags::kLinked) 1291 1292 /* 1293 * For backward compatibility in add-on modules. 1294 */ 1295 #define NODE_MODULE_DECL /* nothing */ 1296 1297 #define NODE_MODULE_INITIALIZER_BASE node_register_module_v 1298 1299 #define NODE_MODULE_INITIALIZER_X(base, version) \ 1300 NODE_MODULE_INITIALIZER_X_HELPER(base, version) 1301 1302 #define NODE_MODULE_INITIALIZER_X_HELPER(base, version) base##version 1303 1304 #define NODE_MODULE_INITIALIZER \ 1305 NODE_MODULE_INITIALIZER_X(NODE_MODULE_INITIALIZER_BASE, \ 1306 NODE_MODULE_VERSION) 1307 1308 #define NODE_MODULE_INIT() \ 1309 extern "C" NODE_MODULE_EXPORT void \ 1310 NODE_MODULE_INITIALIZER(v8::Local
exports, \ 1311 v8::Local
module, \ 1312 v8::Local
context); \ 1313 NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME, \ 1314 NODE_MODULE_INITIALIZER) \ 1315 void NODE_MODULE_INITIALIZER(v8::Local
exports, \ 1316 v8::Local
module, \ 1317 v8::Local
context) 1318 1319 // Allows embedders to add a binding to the current Environment* that can be 1320 // accessed through process._linkedBinding() in the target Environment and all 1321 // Worker threads that it creates. 1322 // In each variant, the registration function needs to be usable at least for 1323 // the time during which the Environment exists. 1324 NODE_EXTERN void AddLinkedBinding(Environment* env, const node_module& mod); 1325 NODE_EXTERN void AddLinkedBinding(Environment* env, 1326 const struct napi_module& mod); 1327 NODE_EXTERN void AddLinkedBinding(Environment* env, 1328 const char* name, 1329 addon_context_register_func fn, 1330 void* priv); 1331 NODE_EXTERN void AddLinkedBinding( 1332 Environment* env, 1333 const char* name, 1334 napi_addon_register_func fn, 1335 int32_t module_api_version = NODE_API_DEFAULT_MODULE_API_VERSION); 1336 1337 /* Registers a callback with the passed-in Environment instance. The callback 1338 * is called after the event loop exits, but before the VM is disposed. 1339 * Callbacks are run in reverse order of registration, i.e. newest first. 1340 */ 1341 NODE_EXTERN void AtExit(Environment* env, 1342 void (*cb)(void* arg), 1343 void* arg); 1344 1345 typedef double async_id; 1346 struct async_context { 1347 ::node::async_id async_id; 1348 ::node::async_id trigger_async_id; 1349 }; 1350 1351 /* This is a lot like node::AtExit, except that the hooks added via this 1352 * function are run before the AtExit ones and will always be registered 1353 * for the current Environment instance. 1354 * These functions are safe to use in an addon supporting multiple 1355 * threads/isolates. */ 1356 NODE_EXTERN void AddEnvironmentCleanupHook(v8::Isolate* isolate, 1357 void (*fun)(void* arg), 1358 void* arg); 1359 1360 NODE_EXTERN void RemoveEnvironmentCleanupHook(v8::Isolate* isolate, 1361 void (*fun)(void* arg), 1362 void* arg); 1363 1364 /* These are async equivalents of the above. After the cleanup hook is invoked, 1365 * `cb(cbarg)` *must* be called, and attempting to remove the cleanup hook will 1366 * have no effect. */ 1367 struct ACHHandle; 1368 struct NODE_EXTERN DeleteACHHandle { void operator()(ACHHandle*) const; }; 1369 typedef std::unique_ptr
AsyncCleanupHookHandle; 1370 1371 /* This function is not intended to be used externally, it exists to aid in 1372 * keeping ABI compatibility between Node and Electron. */ 1373 NODE_EXTERN ACHHandle* AddEnvironmentCleanupHookInternal( 1374 v8::Isolate* isolate, 1375 void (*fun)(void* arg, void (*cb)(void*), void* cbarg), 1376 void* arg); 1377 inline AsyncCleanupHookHandle AddEnvironmentCleanupHook( 1378 v8::Isolate* isolate, 1379 void (*fun)(void* arg, void (*cb)(void*), void* cbarg), 1380 void* arg) { 1381 return AsyncCleanupHookHandle(AddEnvironmentCleanupHookInternal(isolate, fun, 1382 arg)); 1383 } 1384 1385 /* This function is not intended to be used externally, it exists to aid in 1386 * keeping ABI compatibility between Node and Electron. */ 1387 NODE_EXTERN void RemoveEnvironmentCleanupHookInternal(ACHHandle* holder); 1388 inline void RemoveEnvironmentCleanupHook(AsyncCleanupHookHandle holder) { 1389 RemoveEnvironmentCleanupHookInternal(holder.get()); 1390 } 1391 1392 // This behaves like V8's Isolate::RequestInterrupt(), but also wakes up 1393 // the event loop if it is currently idle. Interrupt requests are drained 1394 // in `FreeEnvironment()`. The passed callback can not call back into 1395 // JavaScript. 1396 // This function can be called from any thread. 1397 NODE_EXTERN void RequestInterrupt(Environment* env, 1398 void (*fun)(void* arg), 1399 void* arg); 1400 1401 /* Returns the id of the current execution context. If the return value is 1402 * zero then no execution has been set. This will happen if the user handles 1403 * I/O from native code. */ 1404 NODE_EXTERN async_id AsyncHooksGetExecutionAsyncId(v8::Isolate* isolate); 1405 1406 /* Returns the id of the current execution context. If the return value is 1407 * zero then no execution has been set. This will happen if the user handles 1408 * I/O from native code. */ 1409 NODE_EXTERN async_id 1410 AsyncHooksGetExecutionAsyncId(v8::Local
context); 1411 1412 /* Return same value as async_hooks.triggerAsyncId(); */ 1413 NODE_EXTERN async_id AsyncHooksGetTriggerAsyncId(v8::Isolate* isolate); 1414 1415 /* If the native API doesn't inherit from the helper class then the callbacks 1416 * must be triggered manually. This triggers the init() callback. The return 1417 * value is the async id assigned to the resource. 1418 * 1419 * The `trigger_async_id` parameter should correspond to the resource which is 1420 * creating the new resource, which will usually be the return value of 1421 * `AsyncHooksGetTriggerAsyncId()`. */ 1422 NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate, 1423 v8::Local
resource, 1424 const char* name, 1425 async_id trigger_async_id = -1); 1426 1427 NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate, 1428 v8::Local
resource, 1429 v8::Local
name, 1430 async_id trigger_async_id = -1); 1431 1432 /* Emit the destroy() callback. The overload taking an `Environment*` argument 1433 * should be used when the Isolate’s current Context is not associated with 1434 * a Node.js Environment, or when there is no current Context, for example 1435 * when calling this function during garbage collection. In that case, the 1436 * `Environment*` value should have been acquired previously, e.g. through 1437 * `GetCurrentEnvironment()`. */ 1438 NODE_EXTERN void EmitAsyncDestroy(v8::Isolate* isolate, 1439 async_context asyncContext); 1440 NODE_EXTERN void EmitAsyncDestroy(Environment* env, 1441 async_context asyncContext); 1442 1443 class InternalCallbackScope; 1444 1445 /* This class works like `MakeCallback()` in that it sets up a specific 1446 * asyncContext as the current one and informs the async_hooks and domains 1447 * modules that this context is currently active. 1448 * 1449 * `MakeCallback()` is a wrapper around this class as well as 1450 * `Function::Call()`. Either one of these mechanisms needs to be used for 1451 * top-level calls into JavaScript (i.e. without any existing JS stack). 1452 * 1453 * This object should be stack-allocated to ensure that it is contained in a 1454 * valid HandleScope. 1455 * 1456 * Exceptions happening within this scope will be treated like uncaught 1457 * exceptions. If this behaviour is undesirable, a new `v8::TryCatch` scope 1458 * needs to be created inside of this scope. 1459 */ 1460 class NODE_EXTERN CallbackScope { 1461 public: 1462 CallbackScope(v8::Isolate* isolate, 1463 v8::Local
resource, 1464 async_context asyncContext); 1465 CallbackScope(Environment* env, 1466 v8::Local
resource, 1467 async_context asyncContext); 1468 ~CallbackScope(); 1469 1470 void operator=(const CallbackScope&) = delete; 1471 void operator=(CallbackScope&&) = delete; 1472 CallbackScope(const CallbackScope&) = delete; 1473 CallbackScope(CallbackScope&&) = delete; 1474 1475 private: 1476 InternalCallbackScope* private_; 1477 v8::TryCatch try_catch_; 1478 }; 1479 1480 /* An API specific to emit before/after callbacks is unnecessary because 1481 * MakeCallback will automatically call them for you. 1482 * 1483 * These methods may create handles on their own, so run them inside a 1484 * HandleScope. 1485 * 1486 * `asyncId` and `triggerAsyncId` should correspond to the values returned by 1487 * `EmitAsyncInit()` and `AsyncHooksGetTriggerAsyncId()`, respectively, when the 1488 * invoking resource was created. If these values are unknown, 0 can be passed. 1489 * */ 1490 NODE_EXTERN 1491 v8::MaybeLocal
MakeCallback(v8::Isolate* isolate, 1492 v8::Local
recv, 1493 v8::Local
callback, 1494 int argc, 1495 v8::Local
* argv, 1496 async_context asyncContext); 1497 NODE_EXTERN 1498 v8::MaybeLocal
MakeCallback(v8::Isolate* isolate, 1499 v8::Local
recv, 1500 const char* method, 1501 int argc, 1502 v8::Local
* argv, 1503 async_context asyncContext); 1504 NODE_EXTERN 1505 v8::MaybeLocal
MakeCallback(v8::Isolate* isolate, 1506 v8::Local
recv, 1507 v8::Local
symbol, 1508 int argc, 1509 v8::Local
* argv, 1510 async_context asyncContext); 1511 1512 /* Helper class users can optionally inherit from. If 1513 * `AsyncResource::MakeCallback()` is used, then all four callbacks will be 1514 * called automatically. */ 1515 class NODE_EXTERN AsyncResource { 1516 public: 1517 AsyncResource(v8::Isolate* isolate, 1518 v8::Local
resource, 1519 const char* name, 1520 async_id trigger_async_id = -1); 1521 1522 virtual ~AsyncResource(); 1523 1524 AsyncResource(const AsyncResource&) = delete; 1525 void operator=(const AsyncResource&) = delete; 1526 1527 v8::MaybeLocal
MakeCallback( 1528 v8::Local
callback, 1529 int argc, 1530 v8::Local
* argv); 1531 1532 v8::MaybeLocal
MakeCallback( 1533 const char* method, 1534 int argc, 1535 v8::Local
* argv); 1536 1537 v8::MaybeLocal
MakeCallback( 1538 v8::Local
symbol, 1539 int argc, 1540 v8::Local
* argv); 1541 1542 v8::Local
get_resource(); 1543 async_id get_async_id() const; 1544 async_id get_trigger_async_id() const; 1545 1546 protected: 1547 class NODE_EXTERN CallbackScope : public node::CallbackScope { 1548 public: 1549 explicit CallbackScope(AsyncResource* res); 1550 }; 1551 1552 private: 1553 Environment* env_; 1554 v8::Global
resource_; 1555 async_context async_context_; 1556 }; 1557 1558 #ifndef _WIN32 1559 // Register a signal handler without interrupting any handlers that node 1560 // itself needs. This does override handlers registered through 1561 // process.on('SIG...', function() { ... }). The `reset_handler` flag indicates 1562 // whether the signal handler for the given signal should be reset to its 1563 // default value before executing the handler (i.e. it works like SA_RESETHAND). 1564 // The `reset_handler` flag is invalid when `signal` is SIGSEGV. 1565 NODE_EXTERN 1566 void RegisterSignalHandler(int signal, 1567 void (*handler)(int signal, 1568 siginfo_t* info, 1569 void* ucontext), 1570 bool reset_handler = false); 1571 #endif // _WIN32 1572 1573 // Configure the layout of the JavaScript object with a cppgc::GarbageCollected 1574 // instance so that when the JavaScript object is reachable, the garbage 1575 // collected instance would have its Trace() method invoked per the cppgc 1576 // contract. To make it work, the process must have called 1577 // cppgc::InitializeProcess() before, which is usually the case for addons 1578 // loaded by the stand-alone Node.js executable. Embedders of Node.js can use 1579 // either need to call it themselves or make sure that 1580 // ProcessInitializationFlags::kNoInitializeCppgc is *not* set for cppgc to 1581 // work. 1582 // If the CppHeap is owned by Node.js, which is usually the case for addon, 1583 // the object must be created with at least two internal fields available, 1584 // and the first two internal fields would be configured by Node.js. 1585 // This may be superseded by a V8 API in the future, see 1586 // https://bugs.chromium.org/p/v8/issues/detail?id=13960. Until then this 1587 // serves as a helper for Node.js isolates. 1588 NODE_EXTERN void SetCppgcReference(v8::Isolate* isolate, 1589 v8::Local
object, 1590 void* wrappable); 1591 1592 } // namespace node 1593 1594 #endif // SRC_NODE_H_
Contact us
|
About us
|
Term of use
|
Copyright © 2000-2026 MyWebUniversity.com ™