@downdraft/native-mobile-android-arm64 0.0.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/README.md +7 -0
  2. package/include/node/cppgc/allocation.h +308 -0
  3. package/include/node/cppgc/common.h +28 -0
  4. package/include/node/cppgc/cross-thread-persistent.h +462 -0
  5. package/include/node/cppgc/custom-space.h +97 -0
  6. package/include/node/cppgc/default-platform.h +68 -0
  7. package/include/node/cppgc/explicit-management.h +100 -0
  8. package/include/node/cppgc/garbage-collected.h +114 -0
  9. package/include/node/cppgc/heap-consistency.h +309 -0
  10. package/include/node/cppgc/heap-handle.h +48 -0
  11. package/include/node/cppgc/heap-state.h +82 -0
  12. package/include/node/cppgc/heap-statistics.h +126 -0
  13. package/include/node/cppgc/heap.h +202 -0
  14. package/include/node/cppgc/internal/api-constants.h +75 -0
  15. package/include/node/cppgc/internal/atomic-entry-flag.h +48 -0
  16. package/include/node/cppgc/internal/base-page-handle.h +43 -0
  17. package/include/node/cppgc/internal/caged-heap-local-data.h +117 -0
  18. package/include/node/cppgc/internal/caged-heap.h +64 -0
  19. package/include/node/cppgc/internal/compiler-specific.h +46 -0
  20. package/include/node/cppgc/internal/conditional-stack-allocated.h +41 -0
  21. package/include/node/cppgc/internal/finalizer-trait.h +93 -0
  22. package/include/node/cppgc/internal/gc-info.h +150 -0
  23. package/include/node/cppgc/internal/logging.h +50 -0
  24. package/include/node/cppgc/internal/member-storage.h +305 -0
  25. package/include/node/cppgc/internal/name-trait.h +141 -0
  26. package/include/node/cppgc/internal/persistent-node.h +219 -0
  27. package/include/node/cppgc/internal/pointer-policies.h +280 -0
  28. package/include/node/cppgc/internal/write-barrier.h +487 -0
  29. package/include/node/cppgc/liveness-broker.h +78 -0
  30. package/include/node/cppgc/macros.h +56 -0
  31. package/include/node/cppgc/member.h +669 -0
  32. package/include/node/cppgc/name-provider.h +75 -0
  33. package/include/node/cppgc/object-size-trait.h +58 -0
  34. package/include/node/cppgc/persistent.h +376 -0
  35. package/include/node/cppgc/platform.h +174 -0
  36. package/include/node/cppgc/prefinalizer.h +75 -0
  37. package/include/node/cppgc/process-heap-statistics.h +36 -0
  38. package/include/node/cppgc/sentinel-pointer.h +39 -0
  39. package/include/node/cppgc/source-location.h +16 -0
  40. package/include/node/cppgc/tagged-member.h +114 -0
  41. package/include/node/cppgc/testing.h +106 -0
  42. package/include/node/cppgc/trace-trait.h +127 -0
  43. package/include/node/cppgc/type-traits.h +272 -0
  44. package/include/node/cppgc/visitor.h +534 -0
  45. package/include/node/js_native_api.h +634 -0
  46. package/include/node/js_native_api_types.h +244 -0
  47. package/include/node/libplatform/libplatform-export.h +29 -0
  48. package/include/node/libplatform/libplatform.h +112 -0
  49. package/include/node/libplatform/v8-tracing.h +343 -0
  50. package/include/node/node.h +1744 -0
  51. package/include/node/node_api.h +265 -0
  52. package/include/node/node_api_types.h +58 -0
  53. package/include/node/node_buffer.h +94 -0
  54. package/include/node/node_object_wrap.h +145 -0
  55. package/include/node/node_version.h +116 -0
  56. package/include/node/uv/aix.h +32 -0
  57. package/include/node/uv/bsd.h +34 -0
  58. package/include/node/uv/darwin.h +61 -0
  59. package/include/node/uv/errno.h +483 -0
  60. package/include/node/uv/linux.h +34 -0
  61. package/include/node/uv/os390.h +33 -0
  62. package/include/node/uv/posix.h +31 -0
  63. package/include/node/uv/sunos.h +44 -0
  64. package/include/node/uv/threadpool.h +37 -0
  65. package/include/node/uv/tree.h +521 -0
  66. package/include/node/uv/unix.h +509 -0
  67. package/include/node/uv/version.h +43 -0
  68. package/include/node/uv/win.h +698 -0
  69. package/include/node/uv.h +1994 -0
  70. package/include/node/v8-array-buffer.h +646 -0
  71. package/include/node/v8-callbacks.h +533 -0
  72. package/include/node/v8-container.h +183 -0
  73. package/include/node/v8-context.h +580 -0
  74. package/include/node/v8-cpp-heap-external.h +56 -0
  75. package/include/node/v8-cppgc.h +194 -0
  76. package/include/node/v8-data.h +96 -0
  77. package/include/node/v8-date.h +57 -0
  78. package/include/node/v8-debug.h +210 -0
  79. package/include/node/v8-embedder-heap.h +54 -0
  80. package/include/node/v8-embedder-state-scope.h +52 -0
  81. package/include/node/v8-exception.h +298 -0
  82. package/include/node/v8-extension.h +60 -0
  83. package/include/node/v8-external-memory-accounter.h +60 -0
  84. package/include/node/v8-external.h +73 -0
  85. package/include/node/v8-fast-api-calls.h +784 -0
  86. package/include/node/v8-forward.h +82 -0
  87. package/include/node/v8-function-callback.h +708 -0
  88. package/include/node/v8-function.h +148 -0
  89. package/include/node/v8-handle-base.h +155 -0
  90. package/include/node/v8-initialization.h +343 -0
  91. package/include/node/v8-inspector-protocol.h +13 -0
  92. package/include/node/v8-inspector.h +458 -0
  93. package/include/node/v8-internal.h +1827 -0
  94. package/include/node/v8-isolate.h +1925 -0
  95. package/include/node/v8-json.h +54 -0
  96. package/include/node/v8-local-handle.h +884 -0
  97. package/include/node/v8-locker.h +138 -0
  98. package/include/node/v8-maybe.h +185 -0
  99. package/include/node/v8-memory-span.h +273 -0
  100. package/include/node/v8-message.h +215 -0
  101. package/include/node/v8-metrics.h +273 -0
  102. package/include/node/v8-microtask-queue.h +152 -0
  103. package/include/node/v8-microtask.h +28 -0
  104. package/include/node/v8-object.h +1134 -0
  105. package/include/node/v8-persistent-handle.h +556 -0
  106. package/include/node/v8-platform.h +1552 -0
  107. package/include/node/v8-primitive-object.h +118 -0
  108. package/include/node/v8-primitive.h +1056 -0
  109. package/include/node/v8-profiler.h +1401 -0
  110. package/include/node/v8-promise.h +185 -0
  111. package/include/node/v8-proxy.h +49 -0
  112. package/include/node/v8-regexp.h +105 -0
  113. package/include/node/v8-sandbox.h +170 -0
  114. package/include/node/v8-script.h +996 -0
  115. package/include/node/v8-snapshot.h +302 -0
  116. package/include/node/v8-source-location.h +91 -0
  117. package/include/node/v8-statistics.h +246 -0
  118. package/include/node/v8-template.h +1096 -0
  119. package/include/node/v8-trace-categories.h +28 -0
  120. package/include/node/v8-traced-handle.h +420 -0
  121. package/include/node/v8-typed-array.h +386 -0
  122. package/include/node/v8-unwinder-state.h +30 -0
  123. package/include/node/v8-unwinder.h +146 -0
  124. package/include/node/v8-util.h +549 -0
  125. package/include/node/v8-value-serializer-version.h +24 -0
  126. package/include/node/v8-value-serializer.h +316 -0
  127. package/include/node/v8-value.h +674 -0
  128. package/include/node/v8-version-string.h +38 -0
  129. package/include/node/v8-version.h +20 -0
  130. package/include/node/v8-wasm-trap-handler-posix.h +31 -0
  131. package/include/node/v8-wasm-trap-handler-win.h +28 -0
  132. package/include/node/v8-wasm.h +325 -0
  133. package/include/node/v8-weak-callback-info.h +88 -0
  134. package/include/node/v8.h +88 -0
  135. package/include/node/v8config.h +1077 -0
  136. package/lib/libc++_shared.so +0 -0
  137. package/lib/libnode.so +4 -0
  138. package/package.json +23 -3
@@ -0,0 +1,1744 @@
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
+ #include "node_api_types.h" // napi_addon_register_func
80
+
81
+ #include <functional>
82
+ #include <memory>
83
+ #include <optional>
84
+ #include <ostream>
85
+
86
+ // We cannot use __POSIX__ in this header because that's only defined when
87
+ // building Node.js.
88
+ #ifndef _WIN32
89
+ #include <signal.h>
90
+ #endif // _WIN32
91
+
92
+ #define NODE_MAKE_VERSION(major, minor, patch) \
93
+ ((major) * 0x1000 + (minor) * 0x100 + (patch))
94
+
95
+ #ifdef __clang__
96
+ # define NODE_CLANG_AT_LEAST(major, minor, patch) \
97
+ (NODE_MAKE_VERSION(major, minor, patch) <= \
98
+ NODE_MAKE_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__))
99
+ #else
100
+ # define NODE_CLANG_AT_LEAST(major, minor, patch) (0)
101
+ #endif
102
+
103
+ #ifdef __GNUC__
104
+ # define NODE_GNUC_AT_LEAST(major, minor, patch) \
105
+ (NODE_MAKE_VERSION(major, minor, patch) <= \
106
+ NODE_MAKE_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__))
107
+ #else
108
+ # define NODE_GNUC_AT_LEAST(major, minor, patch) (0)
109
+ #endif
110
+
111
+ #if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
112
+ # define NODE_DEPRECATED(message, declarator) declarator
113
+ #else // NODE_WANT_INTERNALS
114
+ #define NODE_DEPRECATED(message, declarator) [[deprecated(message)]] declarator
115
+ #endif
116
+
117
+ // Forward-declare libuv loop
118
+ struct uv_loop_s;
119
+ struct napi_module;
120
+ struct ssl_ctx_st; // Forward declaration of SSL_CTX for OpenSSL.
121
+
122
+ // Forward-declare these functions now to stop MSVS from becoming
123
+ // terminally confused when it's done in node_internals.h
124
+ namespace node {
125
+
126
+ struct SnapshotData;
127
+
128
+ namespace tracing {
129
+
130
+ class TracingController;
131
+
132
+ }
133
+
134
+ NODE_EXTERN v8::Local<v8::Value> ErrnoException(v8::Isolate* isolate,
135
+ int errorno,
136
+ const char* syscall = nullptr,
137
+ const char* message = nullptr,
138
+ const char* path = nullptr);
139
+ NODE_EXTERN v8::Local<v8::Value> UVException(v8::Isolate* isolate,
140
+ int errorno,
141
+ const char* syscall = nullptr,
142
+ const char* message = nullptr,
143
+ const char* path = nullptr,
144
+ const char* dest = nullptr);
145
+
146
+ NODE_DEPRECATED("Use ErrnoException(isolate, ...)",
147
+ inline v8::Local<v8::Value> ErrnoException(
148
+ int errorno,
149
+ const char* syscall = nullptr,
150
+ const char* message = nullptr,
151
+ const char* path = nullptr) {
152
+ return ErrnoException(v8::Isolate::GetCurrent(),
153
+ errorno,
154
+ syscall,
155
+ message,
156
+ path);
157
+ })
158
+
159
+ NODE_DEPRECATED("Use UVException(isolate, ...)",
160
+ inline v8::Local<v8::Value> UVException(int errorno,
161
+ const char* syscall = nullptr,
162
+ const char* message = nullptr,
163
+ const char* path = nullptr) {
164
+ return UVException(v8::Isolate::GetCurrent(),
165
+ errorno,
166
+ syscall,
167
+ message,
168
+ path);
169
+ })
170
+
171
+ } // namespace node
172
+
173
+ #include <cassert>
174
+ #include <cstdint>
175
+
176
+ #ifndef NODE_STRINGIFY
177
+ # define NODE_STRINGIFY(n) NODE_STRINGIFY_HELPER(n)
178
+ # define NODE_STRINGIFY_HELPER(n) #n
179
+ #endif
180
+
181
+ #ifdef _WIN32
182
+ #if !defined(_SSIZE_T_) && !defined(_SSIZE_T_DEFINED)
183
+ typedef intptr_t ssize_t;
184
+ # define _SSIZE_T_
185
+ # define _SSIZE_T_DEFINED
186
+ #endif
187
+ #else // !_WIN32
188
+ # include <sys/types.h> // size_t, ssize_t
189
+ #endif // _WIN32
190
+
191
+
192
+ namespace node {
193
+
194
+ class IsolateData;
195
+ class Environment;
196
+ class MultiIsolatePlatform;
197
+ class InitializationResultImpl;
198
+
199
+ namespace ProcessInitializationFlags {
200
+ enum Flags : uint32_t {
201
+ kNoFlags = 0,
202
+ // Enable stdio inheritance, which is disabled by default.
203
+ // This flag is also implied by kNoStdioInitialization.
204
+ kEnableStdioInheritance = 1 << 0,
205
+ // Disable reading the NODE_OPTIONS environment variable.
206
+ kDisableNodeOptionsEnv = 1 << 1,
207
+ // Do not parse CLI options.
208
+ kDisableCLIOptions = 1 << 2,
209
+ // Do not initialize ICU.
210
+ kNoICU = 1 << 3,
211
+ // Do not modify stdio file descriptor or TTY state.
212
+ kNoStdioInitialization = 1 << 4,
213
+ // Do not register Node.js-specific signal handlers, reset other signal
214
+ // handlers to default state, or replace the calling thread's signal mask
215
+ // (without this flag, POSIX builds with the inspector set it to block
216
+ // SIGUSR1 and nothing else).
217
+ kNoDefaultSignalHandling = 1 << 5,
218
+ // Do not perform V8 initialization.
219
+ kNoInitializeV8 = 1 << 6,
220
+ // Do not initialize a default Node.js-provided V8 platform instance.
221
+ kNoInitializeNodeV8Platform = 1 << 7,
222
+ // Do not initialize OpenSSL config.
223
+ kNoInitOpenSSL = 1 << 8,
224
+ // Do not initialize Node.js debugging based on environment variables.
225
+ kNoParseGlobalDebugVariables = 1 << 9,
226
+ // Do not adjust OS resource limits for this process.
227
+ kNoAdjustResourceLimits = 1 << 10,
228
+ // Legacy flag for not mapping code segments into large pages for this
229
+ // process. The feature is no longer supported so this is just a no-op.
230
+ kNoUseLargePages = 1 << 11,
231
+ // Skip printing output for --help, --version, --v8-options.
232
+ kNoPrintHelpOrVersionOutput = 1 << 12,
233
+ // Do not perform cppgc initialization. If set, the embedder must call
234
+ // cppgc::InitializeProcess() before creating a Node.js environment
235
+ // and call cppgc::ShutdownProcess() before process shutdown.
236
+ kNoInitializeCppgc = 1 << 13,
237
+ // Initialize the process for predictable snapshot generation.
238
+ kGeneratePredictableSnapshot = 1 << 14,
239
+ // Do not serialize a code cache for builtins that had to be compiled without
240
+ // one. By default such caches are kept so that worker threads created later
241
+ // start faster; an embedder that supplies an EmbedderBuiltinCodeCache or
242
+ // never creates workers only pays for the serialization.
243
+ kNoHarvestBuiltinCodeCache = 1 << 15,
244
+
245
+ // Emulate the behavior of InitializeNodeWithArgs() when passing
246
+ // a flags argument to the InitializeOncePerProcess() replacement
247
+ // function.
248
+ kLegacyInitializeNodeWithArgsBehavior =
249
+ kNoStdioInitialization | kNoDefaultSignalHandling | kNoInitializeV8 |
250
+ kNoInitializeNodeV8Platform | kNoInitOpenSSL |
251
+ kNoParseGlobalDebugVariables | kNoAdjustResourceLimits |
252
+ kNoUseLargePages | kNoPrintHelpOrVersionOutput | kNoInitializeCppgc,
253
+ };
254
+ } // namespace ProcessInitializationFlags
255
+ namespace ProcessFlags = ProcessInitializationFlags; // Legacy alias.
256
+
257
+ namespace StopFlags {
258
+ enum Flags : uint32_t {
259
+ kNoFlags = 0,
260
+ // Do not explicitly terminate the Isolate
261
+ // when exiting the Environment.
262
+ kDoNotTerminateIsolate = 1 << 0,
263
+ };
264
+ } // namespace StopFlags
265
+
266
+ class NODE_EXTERN InitializationResult {
267
+ public:
268
+ virtual ~InitializationResult() = default;
269
+
270
+ // Returns a suggested process exit code.
271
+ virtual int exit_code() const = 0;
272
+
273
+ // Returns 'true' if initialization was aborted early due to errors.
274
+ virtual bool early_return() const = 0;
275
+
276
+ // Returns the parsed list of non-Node.js arguments.
277
+ virtual const std::vector<std::string>& args() const = 0;
278
+
279
+ // Returns the parsed list of Node.js arguments.
280
+ virtual const std::vector<std::string>& exec_args() const = 0;
281
+
282
+ // Returns an array of errors. Note that these may be warnings
283
+ // whose existence does not imply a non-zero exit code.
284
+ virtual const std::vector<std::string>& errors() const = 0;
285
+
286
+ // If kNoInitializeNodeV8Platform was not specified, the global Node.js
287
+ // platform instance.
288
+ virtual MultiIsolatePlatform* platform() const = 0;
289
+
290
+ private:
291
+ InitializationResult() = default;
292
+ friend class InitializationResultImpl;
293
+ };
294
+
295
+ // TODO(addaleax): Officially deprecate this and replace it with something
296
+ // better suited for a public embedder API.
297
+ NODE_EXTERN int Start(int argc, char* argv[]);
298
+
299
+ // Tear down Node.js while it is running (there are active handles
300
+ // in the loop and / or actively executing JavaScript code).
301
+ NODE_EXTERN int Stop(Environment* env,
302
+ StopFlags::Flags flags = StopFlags::kNoFlags);
303
+
304
+ // Set up per-process state needed to run Node.js. This will consume arguments
305
+ // from args, and return information about the initialization success,
306
+ // including the arguments split into argv/exec_argv, a list of potential
307
+ // errors encountered during initialization, and a potential suggested
308
+ // exit code.
309
+ NODE_EXTERN std::shared_ptr<InitializationResult> InitializeOncePerProcess(
310
+ const std::vector<std::string>& args,
311
+ ProcessInitializationFlags::Flags flags =
312
+ ProcessInitializationFlags::kNoFlags);
313
+ // Undoes the initialization performed by InitializeOncePerProcess(),
314
+ // where cleanup is necessary.
315
+ NODE_EXTERN void TearDownOncePerProcess();
316
+ // Convenience overload for specifying multiple flags without having
317
+ // to worry about casts.
318
+ inline std::shared_ptr<InitializationResult> InitializeOncePerProcess(
319
+ const std::vector<std::string>& args,
320
+ std::initializer_list<ProcessInitializationFlags::Flags> list) {
321
+ uint64_t flags_accum = ProcessInitializationFlags::kNoFlags;
322
+ for (const auto flag : list) flags_accum |= static_cast<uint64_t>(flag);
323
+ return InitializeOncePerProcess(
324
+ args, static_cast<ProcessInitializationFlags::Flags>(flags_accum));
325
+ }
326
+
327
+ enum OptionEnvvarSettings {
328
+ // Allow the options to be set via the environment variable, like
329
+ // `NODE_OPTIONS`.
330
+ kAllowedInEnvvar = 0,
331
+ // Disallow the options to be set via the environment variable, like
332
+ // `NODE_OPTIONS`.
333
+ kDisallowedInEnvvar = 1,
334
+ };
335
+
336
+ // Process the arguments and set up the per-process options.
337
+ // If the `settings` is set as OptionEnvvarSettings::kAllowedInEnvvar, the
338
+ // options that are allowed in the environment variable are processed. Options
339
+ // that are disallowed to be set via environment variable are processed as
340
+ // errors.
341
+ // Otherwise all the options that are disallowed (and those are allowed) to be
342
+ // set via environment variable are processed.
343
+ NODE_EXTERN int ProcessGlobalArgs(std::vector<std::string>* args,
344
+ std::vector<std::string>* exec_args,
345
+ std::vector<std::string>* errors,
346
+ OptionEnvvarSettings settings);
347
+
348
+ class NodeArrayBufferAllocator;
349
+
350
+ // An ArrayBuffer::Allocator class with some Node.js-specific tweaks. If you do
351
+ // not have to use another allocator, using this class is recommended:
352
+ // - It supports Buffer.allocUnsafe() and Buffer.allocUnsafeSlow() with
353
+ // uninitialized memory.
354
+ // - It supports transferring, rather than copying, ArrayBuffers when using
355
+ // MessagePorts.
356
+ class NODE_EXTERN ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
357
+ public:
358
+ // If `always_debug` is true, create an ArrayBuffer::Allocator instance
359
+ // that performs additional integrity checks (e.g. make sure that only memory
360
+ // that was allocated by the it is also freed by it).
361
+ // This can also be set using the --debug-arraybuffer-allocations flag.
362
+ static std::unique_ptr<ArrayBufferAllocator> Create(
363
+ bool always_debug = false);
364
+
365
+ private:
366
+ virtual NodeArrayBufferAllocator* GetImpl() = 0;
367
+
368
+ friend class IsolateData;
369
+ };
370
+
371
+ // Legacy equivalents for ArrayBufferAllocator::Create().
372
+ NODE_EXTERN ArrayBufferAllocator* CreateArrayBufferAllocator();
373
+ NODE_EXTERN void FreeArrayBufferAllocator(ArrayBufferAllocator* allocator);
374
+
375
+ class NODE_EXTERN IsolatePlatformDelegate {
376
+ public:
377
+ virtual std::shared_ptr<v8::TaskRunner> GetForegroundTaskRunner() = 0;
378
+ virtual bool IdleTasksEnabled() = 0;
379
+ };
380
+
381
+ class NODE_EXTERN MultiIsolatePlatform : public v8::Platform {
382
+ public:
383
+ ~MultiIsolatePlatform() override = default;
384
+ // Returns true if work was dispatched or executed. New tasks that are
385
+ // posted during flushing of the queue are postponed until the next
386
+ // flushing.
387
+ virtual bool FlushForegroundTasks(v8::Isolate* isolate) = 0;
388
+ virtual void DrainTasks(v8::Isolate* isolate) = 0;
389
+
390
+ // This needs to be called between the calls to `Isolate::Allocate()` and
391
+ // `Isolate::Initialize()`, so that initialization can already start
392
+ // using the platform.
393
+ // When using `NewIsolate()`, this is taken care of by that function.
394
+ // This function may only be called once per `Isolate`.
395
+ virtual void RegisterIsolate(v8::Isolate* isolate,
396
+ struct uv_loop_s* loop) = 0;
397
+ // This method can be used when an application handles task scheduling on its
398
+ // own through `IsolatePlatformDelegate`. Upon registering an isolate with
399
+ // this overload any other method in this class with the exception of
400
+ // `UnregisterIsolate` *must not* be used on that isolate.
401
+ virtual void RegisterIsolate(v8::Isolate* isolate,
402
+ IsolatePlatformDelegate* delegate) = 0;
403
+
404
+ // This function may only be called once per `Isolate`, and discard any
405
+ // pending delayed tasks scheduled for that isolate.
406
+ // This needs to be called right after calling `Isolate::Dispose()`.
407
+ virtual void UnregisterIsolate(v8::Isolate* isolate) = 0;
408
+ // This disposes, unregisters and frees up an isolate that's allocated using
409
+ // v8::Isolate::Allocate() in the correct order to prevent race conditions.
410
+ void DisposeIsolate(v8::Isolate* isolate);
411
+
412
+ // The platform should call the passed function once all state associated
413
+ // with the given isolate has been cleaned up. This can, but does not have to,
414
+ // happen asynchronously.
415
+ virtual void AddIsolateFinishedCallback(v8::Isolate* isolate,
416
+ void (*callback)(void*),
417
+ void* data) = 0;
418
+
419
+ static std::unique_ptr<MultiIsolatePlatform> Create(
420
+ int thread_pool_size,
421
+ v8::TracingController* tracing_controller = nullptr,
422
+ v8::PageAllocator* page_allocator = nullptr);
423
+ };
424
+
425
+ enum IsolateSettingsFlags {
426
+ MESSAGE_LISTENER_WITH_ERROR_LEVEL = 1 << 0,
427
+ DETAILED_SOURCE_POSITIONS_FOR_PROFILING = 1 << 1,
428
+ SHOULD_NOT_SET_PROMISE_REJECTION_CALLBACK = 1 << 2,
429
+ SHOULD_NOT_SET_PREPARE_STACK_TRACE_CALLBACK = 1 << 3,
430
+ ALLOW_MODIFY_CODE_GENERATION_FROM_STRINGS_CALLBACK = 0, /* legacy no-op */
431
+ };
432
+
433
+ struct IsolateSettings {
434
+ uint64_t flags = MESSAGE_LISTENER_WITH_ERROR_LEVEL |
435
+ DETAILED_SOURCE_POSITIONS_FOR_PROFILING;
436
+ v8::MicrotasksPolicy policy = v8::MicrotasksPolicy::kExplicit;
437
+
438
+ // Error handling callbacks
439
+ v8::Isolate::AbortOnUncaughtExceptionCallback
440
+ should_abort_on_uncaught_exception_callback = nullptr;
441
+ v8::FatalErrorCallback fatal_error_callback = nullptr;
442
+ v8::OOMErrorCallback oom_error_callback = nullptr;
443
+ v8::PrepareStackTraceCallback prepare_stack_trace_callback = nullptr;
444
+
445
+ // Miscellaneous callbacks
446
+ v8::PromiseRejectCallback promise_reject_callback = nullptr;
447
+ v8::AllowWasmCodeGenerationCallback
448
+ allow_wasm_code_generation_callback = nullptr;
449
+ v8::ModifyCodeGenerationFromStringsCallback2
450
+ modify_code_generation_from_strings_callback = nullptr;
451
+
452
+ // When the settings is passed to NewIsolate():
453
+ // - If cpp_heap is not nullptr, this CppHeap will be used to create
454
+ // the isolate and its ownership will be passed to V8.
455
+ // - If this is nullptr, Node.js will create a CppHeap that will be
456
+ // owned by V8.
457
+ //
458
+ // When the settings is passed to SetIsolateUpForNode():
459
+ // cpp_heap will be ignored. Embedders must ensure that the
460
+ // v8::Isolate has a CppHeap attached while it's still used by
461
+ // Node.js, for example using v8::CreateParams.
462
+ //
463
+ // See https://issues.chromium.org/issues/42203693. In future version
464
+ // of V8, this CppHeap will be created by V8 if not provided.
465
+ v8::CppHeap* cpp_heap = nullptr;
466
+ };
467
+
468
+ // Represents a startup snapshot blob, e.g. created by passing
469
+ // --node-snapshot-main=entry.js to the configure script at build time,
470
+ // or by running Node.js with the --build-snapshot option.
471
+ //
472
+ // If used, the snapshot *must* have been built with the same Node.js
473
+ // version and V8 flags as the version that is currently running, and will
474
+ // be rejected otherwise.
475
+ // The same EmbedderSnapshotData instance *must* be passed to both
476
+ // `NewIsolate()` and `CreateIsolateData()`. The first `Environment` instance
477
+ // should be created with an empty `context` argument and will then
478
+ // use the main context included in the snapshot blob. It can be retrieved
479
+ // using `GetMainContext()`. `LoadEnvironment` can receive an empty
480
+ // `StartExecutionCallback` in this case.
481
+ // If V8 was configured with the shared-readonly-heap option, it requires
482
+ // all snapshots used to create `Isolate` instances to be identical.
483
+ // This option *must* be unset by embedders who wish to use the startup
484
+ // feature during the build step by passing the --disable-shared-readonly-heap
485
+ // flag to the configure script.
486
+ //
487
+ // The snapshot *must* be kept alive during the execution of the Isolate
488
+ // that was created using it.
489
+ //
490
+ // Snapshots are an *experimental* feature. In particular, the embedder API
491
+ // exposed through this class is subject to change or removal between Node.js
492
+ // versions, including possible API and ABI breakage.
493
+ class EmbedderSnapshotData {
494
+ public:
495
+ struct DeleteSnapshotData {
496
+ void operator()(const EmbedderSnapshotData*) const;
497
+ };
498
+ using Pointer =
499
+ std::unique_ptr<const EmbedderSnapshotData, DeleteSnapshotData>;
500
+
501
+ // Return an EmbedderSnapshotData object that refers to the built-in
502
+ // snapshot of Node.js. This can have been configured through e.g.
503
+ // --node-snapshot-main=entry.js.
504
+ static Pointer BuiltinSnapshotData();
505
+
506
+ // Return an EmbedderSnapshotData object that is based on an input file.
507
+ // Calling this method will consume but not close the FILE* handle.
508
+ // The FILE* handle can be closed immediately following this call.
509
+ // If the snapshot is invalid, this returns an empty pointer.
510
+ static Pointer FromFile(FILE* in);
511
+ static Pointer FromBlob(const std::vector<char>& in);
512
+ static Pointer FromBlob(std::string_view in);
513
+
514
+ // Write this EmbedderSnapshotData object to an output file.
515
+ // Calling this method will not close the FILE* handle.
516
+ // The FILE* handle can be closed immediately following this call.
517
+ void ToFile(FILE* out) const;
518
+ std::vector<char> ToBlob() const;
519
+
520
+ // Returns whether custom snapshots can be used. Currently, this always
521
+ // returns false since V8 enforces shared readonly-heap.
522
+ static bool CanUseCustomSnapshotPerIsolate();
523
+
524
+ EmbedderSnapshotData(const EmbedderSnapshotData&) = delete;
525
+ EmbedderSnapshotData& operator=(const EmbedderSnapshotData&) = delete;
526
+ EmbedderSnapshotData(EmbedderSnapshotData&&) = delete;
527
+ EmbedderSnapshotData& operator=(EmbedderSnapshotData&&) = delete;
528
+
529
+ protected:
530
+ EmbedderSnapshotData(const SnapshotData* impl, bool owns_impl);
531
+
532
+ private:
533
+ const SnapshotData* impl_;
534
+ bool owns_impl_;
535
+ friend struct SnapshotData;
536
+ friend class CommonEnvironmentSetup;
537
+ };
538
+
539
+ // Overriding IsolateSettings may produce unexpected behavior
540
+ // in Node.js core functionality, so proceed at your own risk.
541
+ NODE_EXTERN void SetIsolateUpForNode(v8::Isolate* isolate,
542
+ const IsolateSettings& settings);
543
+
544
+ // Set a number of callbacks for the `isolate`, in particular the Node.js
545
+ // uncaught exception listener.
546
+ NODE_EXTERN void SetIsolateUpForNode(v8::Isolate* isolate);
547
+
548
+ // Creates a new isolate with Node.js-specific settings.
549
+ // This is a convenience method equivalent to using SetIsolateCreateParams(),
550
+ // Isolate::Allocate(), MultiIsolatePlatform::RegisterIsolate(),
551
+ // Isolate::Initialize(), and SetIsolateUpForNode().
552
+ NODE_EXTERN v8::Isolate* NewIsolate(
553
+ ArrayBufferAllocator* allocator,
554
+ struct uv_loop_s* event_loop,
555
+ MultiIsolatePlatform* platform,
556
+ const EmbedderSnapshotData* snapshot_data = nullptr,
557
+ const IsolateSettings& settings = {});
558
+ NODE_EXTERN v8::Isolate* NewIsolate(
559
+ std::shared_ptr<ArrayBufferAllocator> allocator,
560
+ struct uv_loop_s* event_loop,
561
+ MultiIsolatePlatform* platform,
562
+ const EmbedderSnapshotData* snapshot_data = nullptr,
563
+ const IsolateSettings& settings = {});
564
+
565
+ // Creates a new context with Node.js-specific tweaks.
566
+ // Call `RegisterContext` after the context been created to register
567
+ // the context with Node.js specific setups like the inspector.
568
+ NODE_EXTERN v8::Local<v8::Context> NewContext(
569
+ v8::Isolate* isolate,
570
+ v8::Local<v8::ObjectTemplate> object_template =
571
+ v8::Local<v8::ObjectTemplate>());
572
+
573
+ // Runs Node.js-specific tweaks on an already constructed context
574
+ // Return value indicates success of operation
575
+ NODE_EXTERN v8::Maybe<bool> InitializeContext(v8::Local<v8::Context> context);
576
+
577
+ // Associate the context with the given Environment. This registers the context
578
+ // as known to Node.js, makes it available to the inspector. This also registers
579
+ // Node.js promise hooks on the context.
580
+ NODE_EXTERN void RegisterContext(Environment* env,
581
+ v8::Local<v8::Context> context,
582
+ std::string_view name = "",
583
+ std::string_view origin = "");
584
+ // Unregister the context. Call this when the embedder finished all work with
585
+ // this context.
586
+ NODE_EXTERN void UnregisterContext(Environment* env,
587
+ v8::Local<v8::Context> context);
588
+
589
+ // If `platform` is passed, it will be used to register new Worker instances.
590
+ // It can be `nullptr`, in which case creating new Workers inside of
591
+ // Environments that use this `IsolateData` will not work.
592
+ NODE_EXTERN IsolateData* CreateIsolateData(
593
+ v8::Isolate* isolate,
594
+ struct uv_loop_s* loop,
595
+ MultiIsolatePlatform* platform = nullptr,
596
+ ArrayBufferAllocator* allocator = nullptr,
597
+ const EmbedderSnapshotData* snapshot_data = nullptr);
598
+ NODE_EXTERN void FreeIsolateData(IsolateData* isolate_data);
599
+
600
+ struct ThreadId {
601
+ uint64_t id = static_cast<uint64_t>(-1);
602
+ };
603
+ NODE_EXTERN ThreadId AllocateEnvironmentThreadId();
604
+
605
+ namespace EnvironmentFlags {
606
+ enum Flags : uint64_t {
607
+ kNoFlags = 0,
608
+ // Use the default behaviour for Node.js instances.
609
+ kDefaultFlags = 1 << 0,
610
+ // Controls whether this Environment is allowed to affect per-process state
611
+ // (e.g. cwd, process title, uid, etc.).
612
+ // This is set when using kDefaultFlags.
613
+ kOwnsProcessState = 1 << 1,
614
+ // Set if this Environment instance is associated with the global inspector
615
+ // handling code (i.e. listening on SIGUSR1).
616
+ // This is set when using kDefaultFlags.
617
+ kOwnsInspector = 1 << 2,
618
+ // Set if Node.js should not run its own esm loader. This is needed by some
619
+ // embedders, because it's possible for the Node.js esm loader to conflict
620
+ // with another one in an embedder environment, e.g. Blink's in Chromium.
621
+ kNoRegisterESMLoader = 1 << 3,
622
+ // Set this flag to make Node.js track "raw" file descriptors, i.e. managed
623
+ // by fs.open() and fs.close(), and close them during FreeEnvironment().
624
+ kTrackUnmanagedFds = 1 << 4,
625
+ // Set this flag to force hiding console windows when spawning child
626
+ // processes. This is usually used when embedding Node.js in GUI programs on
627
+ // Windows.
628
+ kHideConsoleWindows = 1 << 5,
629
+ // Set this flag to disable loading native addons via `process.dlopen`.
630
+ // This environment flag is especially important for worker threads
631
+ // so that a worker thread can't load a native addon even if `execArgv`
632
+ // is overwritten and `--no-addons` is not specified but was specified
633
+ // for this Environment instance.
634
+ kNoNativeAddons = 1 << 6,
635
+ // Set this flag to disable searching modules from global paths like
636
+ // $HOME/.node_modules and $NODE_PATH. This is used by standalone apps that
637
+ // do not expect to have their behaviors changed because of globally
638
+ // installed modules.
639
+ kNoGlobalSearchPaths = 1 << 7,
640
+ // Do not export browser globals like setTimeout, console, etc.
641
+ kNoBrowserGlobals = 1 << 8,
642
+ // Controls whether or not the Environment should call V8Inspector::create().
643
+ // This control is needed by embedders who may not want to initialize the V8
644
+ // inspector in situations where one has already been created,
645
+ // e.g. Blink's in Chromium.
646
+ kNoCreateInspector = 1 << 9,
647
+ // Controls whether or not the InspectorAgent for this Environment should
648
+ // call StartDebugSignalHandler. This control is needed by embedders who may
649
+ // not want to allow other processes to start the V8 inspector.
650
+ kNoStartDebugSignalHandler = 1 << 10,
651
+ // Controls whether the InspectorAgent created for this Environment waits for
652
+ // Inspector frontend events during the Environment creation. It's used to
653
+ // call node::Stop(env) on a Worker thread that is waiting for the events.
654
+ kNoWaitForInspectorFrontend = 1 << 11
655
+ };
656
+ } // namespace EnvironmentFlags
657
+
658
+ enum class SnapshotFlags : uint32_t {
659
+ kDefault = 0,
660
+ // Whether code cache should be generated as part of the snapshot.
661
+ // Code cache reduces the time spent on compiling functions included
662
+ // in the snapshot at the expense of a bigger snapshot size and
663
+ // potentially breaking portability of the snapshot.
664
+ kWithoutCodeCache = 1 << 0,
665
+ };
666
+
667
+ struct SnapshotConfig {
668
+ SnapshotFlags flags = SnapshotFlags::kDefault;
669
+
670
+ // When builder_script_path is std::nullopt, the snapshot is generated as a
671
+ // built-in snapshot instead of a custom one, and it's expected that the
672
+ // built-in snapshot only contains states that reproduce in every run of the
673
+ // application. The event loop won't be run when generating a built-in
674
+ // snapshot, so asynchronous operations should be avoided.
675
+ //
676
+ // When builder_script_path is an std::string, it should match args[1]
677
+ // passed to CreateForSnapshotting(). The embedder is also expected to use
678
+ // LoadEnvironment() to run a script matching this path. In that case the
679
+ // snapshot is generated as a custom snapshot and the event loop is run, so
680
+ // the snapshot builder can execute asynchronous operations as long as they
681
+ // are run to completion when the snapshot is taken.
682
+ std::optional<std::string> builder_script_path;
683
+ };
684
+
685
+ struct InspectorParentHandle {
686
+ virtual ~InspectorParentHandle() = default;
687
+ };
688
+
689
+ // Code cache for the built-in JavaScript of Environments that are bootstrapped
690
+ // rather than deserialized from a snapshot; see SetBuiltinCodeCache().
691
+ class NODE_EXTERN EmbedderBuiltinCodeCache {
692
+ public:
693
+ struct Entry {
694
+ std::string id; // e.g. "internal/bootstrap/node"
695
+ std::unique_ptr<v8::ScriptCompiler::CachedData> data;
696
+ };
697
+ explicit EmbedderBuiltinCodeCache(std::vector<Entry> entries);
698
+ ~EmbedderBuiltinCodeCache();
699
+
700
+ // Compiles every built-in module in `context`, which must come from
701
+ // NewContext(), and returns their code caches; empty on failure.
702
+ static std::vector<Entry> Generate(v8::Local<v8::Context> context);
703
+
704
+ v8::ScriptCompiler::CachedData::CompatibilityCheckResult CompatibilityCheck(
705
+ v8::Isolate* isolate) const;
706
+
707
+ EmbedderBuiltinCodeCache(const EmbedderBuiltinCodeCache&) = delete;
708
+ EmbedderBuiltinCodeCache& operator=(const EmbedderBuiltinCodeCache&) = delete;
709
+
710
+ struct Impl;
711
+
712
+ private:
713
+ std::unique_ptr<Impl> impl_;
714
+ friend NODE_EXTERN v8::ScriptCompiler::CachedData::CompatibilityCheckResult
715
+ SetBuiltinCodeCache(IsolateData*, const EmbedderBuiltinCodeCache*);
716
+ };
717
+
718
+ // Environments created from `isolate_data` afterwards start with `cache`'s
719
+ // entries (they share its buffers; `cache` itself may be freed after the call);
720
+ // nullptr clears it. Returns the result of `cache->CompatibilityCheck()` and
721
+ // leaves `isolate_data` unchanged unless that is kSuccess.
722
+ NODE_EXTERN v8::ScriptCompiler::CachedData::CompatibilityCheckResult
723
+ SetBuiltinCodeCache(IsolateData* isolate_data,
724
+ const EmbedderBuiltinCodeCache* cache);
725
+
726
+ // TODO(addaleax): Maybe move per-Environment options parsing here.
727
+ // Returns nullptr when the Environment cannot be created e.g. there are
728
+ // pending JavaScript exceptions.
729
+ // `context` may be empty if an `EmbedderSnapshotData` instance was provided
730
+ // to `NewIsolate()` and `CreateIsolateData()`.
731
+ NODE_EXTERN Environment* CreateEnvironment(
732
+ IsolateData* isolate_data,
733
+ v8::Local<v8::Context> context,
734
+ const std::vector<std::string>& args,
735
+ const std::vector<std::string>& exec_args,
736
+ EnvironmentFlags::Flags flags = EnvironmentFlags::kDefaultFlags,
737
+ ThreadId thread_id = {} /* allocates a thread id automatically */,
738
+ std::unique_ptr<InspectorParentHandle> inspector_parent_handle = {});
739
+
740
+ NODE_EXTERN Environment* CreateEnvironment(
741
+ IsolateData* isolate_data,
742
+ v8::Local<v8::Context> context,
743
+ const std::vector<std::string>& args,
744
+ const std::vector<std::string>& exec_args,
745
+ EnvironmentFlags::Flags flags,
746
+ ThreadId thread_id,
747
+ std::unique_ptr<InspectorParentHandle> inspector_parent_handle,
748
+ std::string_view thread_name);
749
+
750
+ // Returns a handle that can be passed to `LoadEnvironment()`, making the
751
+ // child Environment accessible to the inspector as if it were a Node.js Worker.
752
+ // `child_thread_id` can be created using `AllocateEnvironmentThreadId()`
753
+ // and then later passed on to `CreateEnvironment()` to create the child
754
+ // Environment, together with the inspector handle.
755
+ // This method should not be called while the parent Environment is active
756
+ // on another thread.
757
+ NODE_EXTERN std::unique_ptr<InspectorParentHandle> GetInspectorParentHandle(
758
+ Environment* parent_env,
759
+ ThreadId child_thread_id,
760
+ const char* child_url);
761
+
762
+ NODE_EXTERN std::unique_ptr<InspectorParentHandle> GetInspectorParentHandle(
763
+ Environment* parent_env,
764
+ ThreadId child_thread_id,
765
+ const char* child_url,
766
+ const char* name);
767
+
768
+ NODE_EXTERN std::unique_ptr<InspectorParentHandle> GetInspectorParentHandle(
769
+ Environment* parent_env,
770
+ ThreadId child_thread_id,
771
+ std::string_view child_url,
772
+ std::string_view name);
773
+
774
+ struct StartExecutionCallbackInfo {
775
+ v8::Local<v8::Object> process_object;
776
+ v8::Local<v8::Function> native_require;
777
+ v8::Local<v8::Function> run_cjs;
778
+ };
779
+
780
+ enum class ModuleFormat : uint8_t {
781
+ kCommonJS,
782
+ kModule, // i.e. ES Module/SourceTextModule
783
+ // TODO(joyeecheung): support TypeScriptModule, TypeScriptCommonJS
784
+ };
785
+
786
+ // Information passed to embedder callbacks during environment startup.
787
+ // This class is created by Node.js and passed to the embedder's callback.
788
+ // The layout is opaque to allow future additions without breaking ABI.
789
+ class NODE_EXTERN StartExecutionCallbackInfoWithModule {
790
+ public:
791
+ StartExecutionCallbackInfoWithModule();
792
+ ~StartExecutionCallbackInfoWithModule();
793
+
794
+ StartExecutionCallbackInfoWithModule(
795
+ const StartExecutionCallbackInfoWithModule&) = delete;
796
+ StartExecutionCallbackInfoWithModule& operator=(
797
+ const StartExecutionCallbackInfoWithModule&) = delete;
798
+ StartExecutionCallbackInfoWithModule(StartExecutionCallbackInfoWithModule&&);
799
+ StartExecutionCallbackInfoWithModule& operator=(
800
+ StartExecutionCallbackInfoWithModule&&);
801
+
802
+ Environment* env() const;
803
+ v8::Local<v8::Object> process_object() const;
804
+ v8::Local<v8::Function> native_require() const;
805
+ v8::Local<v8::Function> run_module() const;
806
+
807
+ void set_env(Environment* env);
808
+ void set_process_object(v8::Local<v8::Object> process_object);
809
+ void set_native_require(v8::Local<v8::Function> native_require);
810
+ void set_run_module(v8::Local<v8::Function> run_module);
811
+
812
+ private:
813
+ struct Impl;
814
+ std::unique_ptr<Impl> impl_;
815
+ };
816
+
817
+ using StartExecutionCallback =
818
+ std::function<v8::MaybeLocal<v8::Value>(const StartExecutionCallbackInfo&)>;
819
+ using StartExecutionCallbackWithModule =
820
+ std::function<v8::MaybeLocal<v8::Value>(
821
+ const StartExecutionCallbackInfoWithModule&)>;
822
+ using EmbedderPreloadCallback =
823
+ std::function<void(Environment* env,
824
+ v8::Local<v8::Value> process,
825
+ v8::Local<v8::Value> require)>;
826
+
827
+ // Run initialization for the environment.
828
+ //
829
+ // The |preload| function, usually used by embedders to inject scripts,
830
+ // will be run by Node.js before Node.js executes the entry point.
831
+ // The function is guaranteed to run before the user land module loader running
832
+ // any user code, so it is safe to assume that at this point, no user code has
833
+ // been run yet.
834
+ // The function will be executed with preload(process, require), and the passed
835
+ // require function has access to internal Node.js modules. There is no
836
+ // stability guarantee about the internals exposed to the internal require
837
+ // function. Expect breakages when updating Node.js versions if the embedder
838
+ // imports internal modules with the internal require function.
839
+ // Worker threads created in the environment will also respect The |preload|
840
+ // function, so make sure the function is thread-safe.
841
+ NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
842
+ Environment* env,
843
+ StartExecutionCallback cb,
844
+ EmbedderPreloadCallback preload = nullptr);
845
+
846
+ NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
847
+ Environment* env,
848
+ StartExecutionCallbackWithModule cb,
849
+ EmbedderPreloadCallback preload = nullptr);
850
+
851
+ NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
852
+ Environment* env,
853
+ std::string_view main_script_source_utf8,
854
+ EmbedderPreloadCallback preload = nullptr);
855
+
856
+ // Data for specifying an entry point script for LoadEnvironment().
857
+ // This class uses an opaque layout to allow future additions without
858
+ // breaking ABI. Use the setter methods to configure the entry point.
859
+ class NODE_EXTERN ModuleData {
860
+ public:
861
+ ModuleData();
862
+ ~ModuleData();
863
+
864
+ ModuleData(const ModuleData&) = delete;
865
+ ModuleData& operator=(const ModuleData&) = delete;
866
+ ModuleData(ModuleData&&);
867
+ ModuleData& operator=(ModuleData&&);
868
+
869
+ void set_source(std::string_view source);
870
+ void set_format(ModuleFormat format);
871
+ void set_resource_name(std::string_view name);
872
+
873
+ std::string_view source() const;
874
+ ModuleFormat format() const;
875
+ std::string_view resource_name() const;
876
+
877
+ private:
878
+ struct Impl;
879
+ std::unique_ptr<Impl> impl_;
880
+ };
881
+
882
+ NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
883
+ Environment* env,
884
+ const ModuleData* entry_point,
885
+ EmbedderPreloadCallback preload = nullptr);
886
+
887
+ // Runs `env`'s event loop until its handles have closed, with JavaScript
888
+ // execution disallowed on the isolate; see doc/api/embedding.md if that loop
889
+ // is shared with other Environments.
890
+ NODE_EXTERN void FreeEnvironment(Environment* env);
891
+
892
+ // Set a callback that is called when process.exit() is called from JS,
893
+ // overriding the default handler.
894
+ // It receives the Environment* instance and the exit code as arguments.
895
+ // This could e.g. call Stop(env); in order to terminate execution and stop
896
+ // the event loop.
897
+ // The default handler disposes of the global V8 platform instance, if one is
898
+ // being used, and calls exit().
899
+ NODE_EXTERN void SetProcessExitHandler(
900
+ Environment* env,
901
+ std::function<void(Environment*, int)>&& handler);
902
+ NODE_EXTERN void DefaultProcessExitHandler(Environment* env, int exit_code);
903
+
904
+ // Sets a process-global handler invoked when Node.js programmatically aborts.
905
+ // Nullable strings representing the location and reason for the abort may or
906
+ // may not be passed as a parameter to the handler. The handler should not
907
+ // return, but node will ensure that the process exits after the handler is
908
+ // called regardless of whether or not it returns. Passing nullptr restores the
909
+ // default handler. This is process-global and may be invoked before any Isolate
910
+ // or Environment exists.
911
+ using AbortHandler = void (*)(const char* location, const char* message);
912
+ NODE_EXTERN void SetAbortHandler(AbortHandler handler);
913
+
914
+ // This may return nullptr if context is not associated with a Node instance.
915
+ NODE_EXTERN Environment* GetCurrentEnvironment(v8::Local<v8::Context> context);
916
+ NODE_EXTERN IsolateData* GetEnvironmentIsolateData(Environment* env);
917
+ NODE_EXTERN ArrayBufferAllocator* GetArrayBufferAllocator(IsolateData* data);
918
+ // This is mostly useful for Environment* instances that were created through
919
+ // a snapshot and have a main context that was read from that snapshot.
920
+ NODE_EXTERN v8::Local<v8::Context> GetMainContext(Environment* env);
921
+
922
+ [[noreturn]] NODE_EXTERN void OnFatalError(const char* location,
923
+ const char* message);
924
+ NODE_EXTERN void PromiseRejectCallback(v8::PromiseRejectMessage message);
925
+ NODE_EXTERN bool AllowWasmCodeGenerationCallback(v8::Local<v8::Context> context,
926
+ v8::Local<v8::String>);
927
+ NODE_EXTERN bool ShouldAbortOnUncaughtException(v8::Isolate* isolate);
928
+ NODE_EXTERN v8::MaybeLocal<v8::Value> PrepareStackTraceCallback(
929
+ v8::Local<v8::Context> context,
930
+ v8::Local<v8::Value> exception,
931
+ v8::Local<v8::Array> trace);
932
+
933
+ // Writes a diagnostic report to a file. If filename is not provided, the
934
+ // default filename includes the date, time, PID, and a sequence number.
935
+ // The report's JavaScript stack trace is taken from err, if present.
936
+ // If isolate is nullptr, no information about the JavaScript environment
937
+ // is included in the report.
938
+ // Returns the filename of the written report.
939
+ NODE_EXTERN std::string TriggerNodeReport(v8::Isolate* isolate,
940
+ std::string_view message,
941
+ std::string_view trigger,
942
+ std::string_view filename,
943
+ v8::Local<v8::Value> error);
944
+ NODE_EXTERN std::string TriggerNodeReport(Environment* env,
945
+ std::string_view message,
946
+ std::string_view trigger,
947
+ std::string_view filename,
948
+ v8::Local<v8::Value> error);
949
+ NODE_EXTERN void GetNodeReport(v8::Isolate* isolate,
950
+ std::string_view message,
951
+ std::string_view trigger,
952
+ v8::Local<v8::Value> error,
953
+ std::ostream& out);
954
+ NODE_EXTERN void GetNodeReport(Environment* env,
955
+ std::string_view message,
956
+ std::string_view trigger,
957
+ v8::Local<v8::Value> error,
958
+ std::ostream& out);
959
+
960
+ // This returns the MultiIsolatePlatform used for an Environment or IsolateData
961
+ // instance, if one exists.
962
+ NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(Environment* env);
963
+ NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env);
964
+
965
+ // Get/set the currently active tracing controller. Using
966
+ // MultiIsolatePlatform::Create() will implicitly set this by default. This is
967
+ // global and should be initialized along with the v8::Platform instance that is
968
+ // being used. `controller` is allowed to be `nullptr`. This is used for tracing
969
+ // events from Node.js itself. V8 uses the tracing controller returned from the
970
+ // active `v8::Platform` instance.
971
+ NODE_EXTERN v8::TracingController* GetTracingController();
972
+ NODE_EXTERN void SetTracingController(v8::TracingController* controller);
973
+
974
+ // Run `process.emit('beforeExit')` as it would usually happen when Node.js is
975
+ // run in standalone mode.
976
+ NODE_EXTERN v8::Maybe<bool> EmitProcessBeforeExit(Environment* env);
977
+ // Run `process.emit('exit')` as it would usually happen when Node.js is run
978
+ // in standalone mode. The return value corresponds to the exit code.
979
+ NODE_EXTERN v8::Maybe<int> EmitProcessExit(Environment* env);
980
+
981
+ // Runs hooks added through `AtExit()`. This is part of `FreeEnvironment()`,
982
+ // so calling it manually is typically not necessary.
983
+ NODE_EXTERN void RunAtExit(Environment* env);
984
+
985
+ // This may return nullptr if the current v8::Context is not associated
986
+ // with a Node instance.
987
+ NODE_EXTERN struct uv_loop_s* GetCurrentEventLoop(v8::Isolate* isolate);
988
+
989
+ // Runs the main loop for a given Environment. This roughly performs the
990
+ // following steps:
991
+ // 1. Call uv_run() on the event loop until it is drained.
992
+ // 2. Call platform->DrainTasks() on the associated platform/isolate.
993
+ // 3. If the event loop is alive again, go to Step 1.
994
+ // 4. Call EmitProcessBeforeExit().
995
+ // 5. If the event loop is alive again, go to Step 1.
996
+ // 6. Call EmitProcessExit() and forward the return value.
997
+ // If at any point node::Stop() is called, the function will attempt to return
998
+ // as soon as possible, returning an empty `Maybe`.
999
+ // This function only works if `env` has an associated `MultiIsolatePlatform`.
1000
+ NODE_EXTERN v8::Maybe<int> SpinEventLoop(Environment* env);
1001
+
1002
+ NODE_EXTERN std::string GetAnonymousMainPath();
1003
+
1004
+ class NODE_EXTERN CommonEnvironmentSetup {
1005
+ public:
1006
+ ~CommonEnvironmentSetup();
1007
+
1008
+ // Create a new CommonEnvironmentSetup, that is, a group of objects that
1009
+ // together form the typical setup for a single Node.js Environment instance.
1010
+ // If any error occurs, `*errors` will be populated and the returned pointer
1011
+ // will be empty.
1012
+ // env_args will be passed through as arguments to CreateEnvironment(), after
1013
+ // `isolate_data` and `context`.
1014
+ // `snapshot_data` has to stay alive as long as the setup created from it,
1015
+ // and every setup in a process has to use the same snapshot: all isolates
1016
+ // are created from the blob the first one used.
1017
+ template <typename... EnvironmentArgs>
1018
+ static std::unique_ptr<CommonEnvironmentSetup> Create(
1019
+ MultiIsolatePlatform* platform,
1020
+ std::vector<std::string>* errors,
1021
+ EnvironmentArgs&&... env_args);
1022
+ template <typename... EnvironmentArgs>
1023
+ static std::unique_ptr<CommonEnvironmentSetup> CreateFromSnapshot(
1024
+ MultiIsolatePlatform* platform,
1025
+ std::vector<std::string>* errors,
1026
+ const EmbedderSnapshotData* snapshot_data,
1027
+ EnvironmentArgs&&... env_args);
1028
+
1029
+ // Create an embedding setup which will be used for creating a snapshot
1030
+ // using CreateSnapshot().
1031
+ //
1032
+ // This will create and attach a v8::SnapshotCreator to this instance,
1033
+ // and the same restrictions apply to this instance that also apply to
1034
+ // other V8 snapshotting environments.
1035
+ // Not all Node.js APIs are supported in this case. Currently, there is
1036
+ // no support for native/host objects other than Node.js builtins
1037
+ // in the snapshot.
1038
+ //
1039
+ // If the embedder wants to use LoadEnvironment() later to run a snapshot
1040
+ // builder script they should make sure args[1] contains the path of the
1041
+ // snapshot script, which will be used to create __filename and __dirname
1042
+ // in the context where the builder script is run. If they do not want to
1043
+ // include the build-time paths into the snapshot, use the string returned
1044
+ // by GetAnonymousMainPath() as args[1] to anonymize the script.
1045
+ //
1046
+ // Snapshots are an *experimental* feature. In particular, the embedder API
1047
+ // exposed through this class is subject to change or removal between Node.js
1048
+ // versions, including possible API and ABI breakage.
1049
+ static std::unique_ptr<CommonEnvironmentSetup> CreateForSnapshotting(
1050
+ MultiIsolatePlatform* platform,
1051
+ std::vector<std::string>* errors,
1052
+ const std::vector<std::string>& args = {},
1053
+ const std::vector<std::string>& exec_args = {},
1054
+ const SnapshotConfig& snapshot_config = {});
1055
+ EmbedderSnapshotData::Pointer CreateSnapshot();
1056
+
1057
+ struct uv_loop_s* event_loop() const;
1058
+ v8::SnapshotCreator* snapshot_creator();
1059
+ // Empty for snapshotting environments.
1060
+ std::shared_ptr<ArrayBufferAllocator> array_buffer_allocator() const;
1061
+ v8::Isolate* isolate() const;
1062
+ IsolateData* isolate_data() const;
1063
+ Environment* env() const;
1064
+ v8::Local<v8::Context> context() const;
1065
+
1066
+ CommonEnvironmentSetup(const CommonEnvironmentSetup&) = delete;
1067
+ CommonEnvironmentSetup& operator=(const CommonEnvironmentSetup&) = delete;
1068
+ CommonEnvironmentSetup(CommonEnvironmentSetup&&) = delete;
1069
+ CommonEnvironmentSetup& operator=(CommonEnvironmentSetup&&) = delete;
1070
+
1071
+ private:
1072
+ enum Flags : uint32_t {
1073
+ kNoFlags = 0,
1074
+ kIsForSnapshotting = 1,
1075
+ };
1076
+
1077
+ struct Impl;
1078
+ Impl* impl_;
1079
+
1080
+ CommonEnvironmentSetup(
1081
+ MultiIsolatePlatform*,
1082
+ std::vector<std::string>*,
1083
+ std::function<Environment*(const CommonEnvironmentSetup*)>);
1084
+ CommonEnvironmentSetup(
1085
+ MultiIsolatePlatform*,
1086
+ std::vector<std::string>*,
1087
+ const EmbedderSnapshotData*,
1088
+ uint32_t flags,
1089
+ std::function<Environment*(const CommonEnvironmentSetup*)>,
1090
+ const SnapshotConfig* config = nullptr);
1091
+ };
1092
+
1093
+ // Implementation for CommonEnvironmentSetup::Create
1094
+ template <typename... EnvironmentArgs>
1095
+ std::unique_ptr<CommonEnvironmentSetup> CommonEnvironmentSetup::Create(
1096
+ MultiIsolatePlatform* platform,
1097
+ std::vector<std::string>* errors,
1098
+ EnvironmentArgs&&... env_args) {
1099
+ auto ret = std::unique_ptr<CommonEnvironmentSetup>(new CommonEnvironmentSetup(
1100
+ platform, errors,
1101
+ [&](const CommonEnvironmentSetup* setup) -> Environment* {
1102
+ return CreateEnvironment(
1103
+ setup->isolate_data(), setup->context(),
1104
+ std::forward<EnvironmentArgs>(env_args)...);
1105
+ }));
1106
+ if (!errors->empty()) ret.reset();
1107
+ return ret;
1108
+ }
1109
+
1110
+ // Implementation for ::CreateFromSnapshot -- the ::Create() method
1111
+ // could call this with a nullptr snapshot_data in a major version.
1112
+ template <typename... EnvironmentArgs>
1113
+ std::unique_ptr<CommonEnvironmentSetup>
1114
+ CommonEnvironmentSetup::CreateFromSnapshot(
1115
+ MultiIsolatePlatform* platform,
1116
+ std::vector<std::string>* errors,
1117
+ const EmbedderSnapshotData* snapshot_data,
1118
+ EnvironmentArgs&&... env_args) {
1119
+ auto ret = std::unique_ptr<CommonEnvironmentSetup>(new CommonEnvironmentSetup(
1120
+ platform,
1121
+ errors,
1122
+ snapshot_data,
1123
+ Flags::kNoFlags,
1124
+ [&](const CommonEnvironmentSetup* setup) -> Environment* {
1125
+ return CreateEnvironment(setup->isolate_data(),
1126
+ setup->context(),
1127
+ std::forward<EnvironmentArgs>(env_args)...);
1128
+ }));
1129
+ if (!errors->empty()) ret.reset();
1130
+ return ret;
1131
+ }
1132
+
1133
+ /* Converts a unixtime to V8 Date */
1134
+ NODE_DEPRECATED("Use v8::Date::New() directly",
1135
+ inline v8::Local<v8::Value> NODE_UNIXTIME_V8(double time) {
1136
+ return v8::Date::New(
1137
+ v8::Isolate::GetCurrent()->GetCurrentContext(),
1138
+ 1000 * time)
1139
+ .ToLocalChecked();
1140
+ })
1141
+ #define NODE_UNIXTIME_V8 node::NODE_UNIXTIME_V8
1142
+ NODE_DEPRECATED("Use v8::Date::ValueOf() directly",
1143
+ inline double NODE_V8_UNIXTIME(v8::Local<v8::Date> date) {
1144
+ return date->ValueOf() / 1000;
1145
+ })
1146
+ #define NODE_V8_UNIXTIME node::NODE_V8_UNIXTIME
1147
+
1148
+ #define NODE_DEFINE_CONSTANT(target, constant) \
1149
+ do { \
1150
+ v8::Isolate* isolate = v8::Isolate::GetCurrent(); \
1151
+ v8::Local<v8::Context> context = isolate->GetCurrentContext(); \
1152
+ v8::Local<v8::String> constant_name = v8::String::NewFromUtf8Literal( \
1153
+ isolate, #constant, v8::NewStringType::kInternalized); \
1154
+ v8::Local<v8::Number> constant_value = \
1155
+ v8::Number::New(isolate, static_cast<double>(constant)); \
1156
+ v8::PropertyAttribute constant_attributes = \
1157
+ static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete); \
1158
+ (target) \
1159
+ ->DefineOwnProperty( \
1160
+ context, constant_name, constant_value, constant_attributes) \
1161
+ .Check(); \
1162
+ } while (0)
1163
+
1164
+ #define NODE_DEFINE_HIDDEN_CONSTANT(target, constant) \
1165
+ do { \
1166
+ v8::Isolate* isolate = v8::Isolate::GetCurrent(); \
1167
+ v8::Local<v8::Context> context = isolate->GetCurrentContext(); \
1168
+ v8::Local<v8::String> constant_name = v8::String::NewFromUtf8Literal( \
1169
+ isolate, #constant, v8::NewStringType::kInternalized); \
1170
+ v8::Local<v8::Number> constant_value = \
1171
+ v8::Number::New(isolate, static_cast<double>(constant)); \
1172
+ v8::PropertyAttribute constant_attributes = \
1173
+ static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete | \
1174
+ v8::DontEnum); \
1175
+ (target) \
1176
+ ->DefineOwnProperty( \
1177
+ context, constant_name, constant_value, constant_attributes) \
1178
+ .Check(); \
1179
+ } while (0)
1180
+
1181
+ // Used to be a macro, hence the uppercase name.
1182
+ inline void NODE_SET_METHOD(v8::Local<v8::Template> recv,
1183
+ const char* name,
1184
+ v8::FunctionCallback callback) {
1185
+ v8::Isolate* isolate = v8::Isolate::GetCurrent();
1186
+ v8::HandleScope handle_scope(isolate);
1187
+ v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate,
1188
+ callback);
1189
+ v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
1190
+ v8::NewStringType::kInternalized).ToLocalChecked();
1191
+ t->SetClassName(fn_name);
1192
+ recv->Set(fn_name, t);
1193
+ }
1194
+
1195
+ // Used to be a macro, hence the uppercase name.
1196
+ inline void NODE_SET_METHOD(v8::Local<v8::Object> recv,
1197
+ const char* name,
1198
+ v8::FunctionCallback callback) {
1199
+ v8::Isolate* isolate = v8::Isolate::GetCurrent();
1200
+ v8::HandleScope handle_scope(isolate);
1201
+ v8::Local<v8::Context> context = isolate->GetCurrentContext();
1202
+ v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate,
1203
+ callback);
1204
+ v8::Local<v8::Function> fn = t->GetFunction(context).ToLocalChecked();
1205
+ v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
1206
+ v8::NewStringType::kInternalized).ToLocalChecked();
1207
+ fn->SetName(fn_name);
1208
+ recv->Set(context, fn_name, fn).Check();
1209
+ }
1210
+ #define NODE_SET_METHOD node::NODE_SET_METHOD
1211
+
1212
+ // Used to be a macro, hence the uppercase name.
1213
+ // Not a template because it only makes sense for FunctionTemplates.
1214
+ inline void NODE_SET_PROTOTYPE_METHOD(v8::Local<v8::FunctionTemplate> recv,
1215
+ const char* name,
1216
+ v8::FunctionCallback callback) {
1217
+ v8::Isolate* isolate = v8::Isolate::GetCurrent();
1218
+ v8::HandleScope handle_scope(isolate);
1219
+ v8::Local<v8::Signature> s = v8::Signature::New(isolate, recv);
1220
+ v8::Local<v8::FunctionTemplate> t =
1221
+ v8::FunctionTemplate::New(isolate, callback, v8::Local<v8::Value>(), s);
1222
+ v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
1223
+ v8::NewStringType::kInternalized).ToLocalChecked();
1224
+ t->SetClassName(fn_name);
1225
+ recv->PrototypeTemplate()->Set(fn_name, t);
1226
+ }
1227
+ #define NODE_SET_PROTOTYPE_METHOD node::NODE_SET_PROTOTYPE_METHOD
1228
+
1229
+ // BINARY is a deprecated alias of LATIN1.
1230
+ // BASE64URL is not currently exposed to the JavaScript side.
1231
+ enum encoding {
1232
+ ASCII,
1233
+ UTF8,
1234
+ BASE64,
1235
+ UCS2,
1236
+ BINARY,
1237
+ HEX,
1238
+ BUFFER,
1239
+ BASE64URL,
1240
+ LATIN1 = BINARY
1241
+ };
1242
+
1243
+ NODE_EXTERN enum encoding ParseEncoding(
1244
+ v8::Isolate* isolate,
1245
+ v8::Local<v8::Value> encoding_v,
1246
+ enum encoding default_encoding = LATIN1);
1247
+
1248
+ NODE_EXTERN void FatalException(v8::Isolate* isolate,
1249
+ const v8::TryCatch& try_catch);
1250
+
1251
+ NODE_EXTERN v8::MaybeLocal<v8::Value> TryEncode(
1252
+ v8::Isolate* isolate,
1253
+ const char* buf,
1254
+ size_t len,
1255
+ enum encoding encoding = LATIN1);
1256
+
1257
+ // Warning: This reverses endianness on Big Endian platforms, even though the
1258
+ // signature using uint16_t implies that it should not.
1259
+ NODE_EXTERN v8::MaybeLocal<v8::Value> TryEncode(v8::Isolate* isolate,
1260
+ const uint16_t* buf,
1261
+ size_t len);
1262
+
1263
+ // The original Encode(...) functions are deprecated because they do not
1264
+ // appropriately propagate exceptions and instead rely on ToLocalChecked()
1265
+ // which crashes the process if an exception occurs. We cannot just remove
1266
+ // these as it would break ABI compatibility, so we keep them around but
1267
+ // deprecate them in favor of the TryEncode(...) variations which return
1268
+ // a MaybeLocal<> and do not crash the process if an exception occurs.
1269
+ NODE_DEPRECATED(
1270
+ "Use TryEncode(...) instead",
1271
+ NODE_EXTERN v8::Local<v8::Value> Encode(v8::Isolate* isolate,
1272
+ const char* buf,
1273
+ size_t len,
1274
+ enum encoding encoding = LATIN1));
1275
+
1276
+ // Warning: This reverses endianness on Big Endian platforms, even though the
1277
+ // signature using uint16_t implies that it should not.
1278
+ NODE_DEPRECATED("Use TryEncode(...) instead",
1279
+ NODE_EXTERN v8::Local<v8::Value> Encode(v8::Isolate* isolate,
1280
+ const uint16_t* buf,
1281
+ size_t len));
1282
+
1283
+ // Returns -1 if the handle was not valid for decoding
1284
+ NODE_EXTERN ssize_t DecodeBytes(v8::Isolate* isolate,
1285
+ v8::Local<v8::Value>,
1286
+ enum encoding encoding = LATIN1);
1287
+ // returns bytes written.
1288
+ NODE_EXTERN ssize_t DecodeWrite(v8::Isolate* isolate,
1289
+ char* buf,
1290
+ size_t buflen,
1291
+ v8::Local<v8::Value>,
1292
+ enum encoding encoding = LATIN1);
1293
+ #ifdef _WIN32
1294
+ NODE_EXTERN v8::Local<v8::Value> WinapiErrnoException(
1295
+ v8::Isolate* isolate,
1296
+ int errorno,
1297
+ const char* syscall = nullptr,
1298
+ const char* msg = "",
1299
+ const char* path = nullptr);
1300
+ #endif
1301
+
1302
+ const char* signo_string(int errorno);
1303
+
1304
+
1305
+ typedef void (*addon_register_func)(
1306
+ v8::Local<v8::Object> exports,
1307
+ v8::Local<v8::Value> module,
1308
+ void* priv);
1309
+
1310
+ typedef void (*addon_context_register_func)(
1311
+ v8::Local<v8::Object> exports,
1312
+ v8::Local<v8::Value> module,
1313
+ v8::Local<v8::Context> context,
1314
+ void* priv);
1315
+
1316
+ enum ModuleFlags {
1317
+ kLinked = 0x02
1318
+ };
1319
+
1320
+ struct node_module {
1321
+ int nm_version;
1322
+ unsigned int nm_flags;
1323
+ void* nm_dso_handle;
1324
+ const char* nm_filename;
1325
+ node::addon_register_func nm_register_func;
1326
+ node::addon_context_register_func nm_context_register_func;
1327
+ const char* nm_modname;
1328
+ void* nm_priv;
1329
+ struct node_module* nm_link;
1330
+ };
1331
+
1332
+ extern "C" NODE_EXTERN void node_module_register(void* mod);
1333
+
1334
+ #ifdef _WIN32
1335
+ # define NODE_MODULE_EXPORT __declspec(dllexport)
1336
+ #else
1337
+ # define NODE_MODULE_EXPORT __attribute__((visibility("default")))
1338
+ #endif
1339
+
1340
+ #ifdef NODE_SHARED_MODE
1341
+ # define NODE_CTOR_PREFIX
1342
+ #else
1343
+ # define NODE_CTOR_PREFIX static
1344
+ #endif
1345
+
1346
+ #if defined(_MSC_VER)
1347
+ #define NODE_C_CTOR(fn) \
1348
+ NODE_CTOR_PREFIX void __cdecl fn(void); \
1349
+ namespace { \
1350
+ struct fn##_ { \
1351
+ fn##_() { fn(); }; \
1352
+ } fn##_v_; \
1353
+ } \
1354
+ NODE_CTOR_PREFIX void __cdecl fn(void)
1355
+ #else
1356
+ #define NODE_C_CTOR(fn) \
1357
+ NODE_CTOR_PREFIX void fn(void) __attribute__((constructor)); \
1358
+ NODE_CTOR_PREFIX void fn(void)
1359
+ #endif
1360
+
1361
+ #define NODE_MODULE_X(modname, regfunc, priv, flags) \
1362
+ extern "C" { \
1363
+ static node::node_module _module = \
1364
+ { \
1365
+ NODE_MODULE_VERSION, \
1366
+ flags, \
1367
+ NULL, /* NOLINT (readability/null_usage) */ \
1368
+ __FILE__, \
1369
+ (node::addon_register_func) (regfunc), \
1370
+ NULL, /* NOLINT (readability/null_usage) */ \
1371
+ NODE_STRINGIFY(modname), \
1372
+ priv, \
1373
+ NULL /* NOLINT (readability/null_usage) */ \
1374
+ }; \
1375
+ NODE_C_CTOR(_register_ ## modname) { \
1376
+ node_module_register(&_module); \
1377
+ } \
1378
+ }
1379
+
1380
+ #define NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, priv, flags) \
1381
+ extern "C" { \
1382
+ static node::node_module _module = \
1383
+ { \
1384
+ NODE_MODULE_VERSION, \
1385
+ flags, \
1386
+ NULL, /* NOLINT (readability/null_usage) */ \
1387
+ __FILE__, \
1388
+ NULL, /* NOLINT (readability/null_usage) */ \
1389
+ (node::addon_context_register_func) (regfunc), \
1390
+ NODE_STRINGIFY(modname), \
1391
+ priv, \
1392
+ NULL /* NOLINT (readability/null_usage) */ \
1393
+ }; \
1394
+ NODE_C_CTOR(_register_ ## modname) { \
1395
+ node_module_register(&_module); \
1396
+ } \
1397
+ }
1398
+
1399
+ // Usage: `NODE_MODULE(NODE_GYP_MODULE_NAME, InitializerFunction)`
1400
+ // If no NODE_MODULE is declared, Node.js looks for the well-known
1401
+ // symbol `node_register_module_v${NODE_MODULE_VERSION}`.
1402
+ #define NODE_MODULE(modname, regfunc) \
1403
+ NODE_MODULE_X(modname, regfunc, NULL, 0) // NOLINT (readability/null_usage)
1404
+
1405
+ #define NODE_MODULE_CONTEXT_AWARE(modname, regfunc) \
1406
+ /* NOLINTNEXTLINE (readability/null_usage) */ \
1407
+ NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL, 0)
1408
+
1409
+ // Embedders can use this type of binding for statically linked native bindings.
1410
+ // It is used the same way addon bindings are used, except that linked bindings
1411
+ // can be accessed through `process._linkedBinding(modname)`.
1412
+ #define NODE_MODULE_LINKED(modname, regfunc) \
1413
+ /* NOLINTNEXTLINE (readability/null_usage) */ \
1414
+ NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL, \
1415
+ node::ModuleFlags::kLinked)
1416
+
1417
+ /*
1418
+ * For backward compatibility in add-on modules.
1419
+ */
1420
+ #define NODE_MODULE_DECL /* nothing */
1421
+
1422
+ #define NODE_MODULE_INITIALIZER_BASE node_register_module_v
1423
+
1424
+ #define NODE_MODULE_INITIALIZER_X(base, version) \
1425
+ NODE_MODULE_INITIALIZER_X_HELPER(base, version)
1426
+
1427
+ #define NODE_MODULE_INITIALIZER_X_HELPER(base, version) base##version
1428
+
1429
+ #define NODE_MODULE_INITIALIZER \
1430
+ NODE_MODULE_INITIALIZER_X(NODE_MODULE_INITIALIZER_BASE, \
1431
+ NODE_MODULE_VERSION)
1432
+
1433
+ #define NODE_MODULE_INIT() \
1434
+ extern "C" NODE_MODULE_EXPORT void \
1435
+ NODE_MODULE_INITIALIZER(v8::Local<v8::Object> exports, \
1436
+ v8::Local<v8::Value> module, \
1437
+ v8::Local<v8::Context> context); \
1438
+ NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME, \
1439
+ NODE_MODULE_INITIALIZER) \
1440
+ void NODE_MODULE_INITIALIZER(v8::Local<v8::Object> exports, \
1441
+ v8::Local<v8::Value> module, \
1442
+ v8::Local<v8::Context> context)
1443
+
1444
+ // Allows embedders to add a binding to the current Environment* that can be
1445
+ // accessed through process._linkedBinding() in the target Environment and all
1446
+ // Worker threads that it creates.
1447
+ // In each variant, the registration function needs to be usable at least for
1448
+ // the time during which the Environment exists.
1449
+ NODE_EXTERN void AddLinkedBinding(Environment* env, const node_module& mod);
1450
+ NODE_EXTERN void AddLinkedBinding(Environment* env,
1451
+ const struct napi_module& mod);
1452
+ NODE_EXTERN void AddLinkedBinding(Environment* env,
1453
+ const char* name,
1454
+ addon_context_register_func fn,
1455
+ void* priv);
1456
+ NODE_EXTERN void AddLinkedBinding(
1457
+ Environment* env,
1458
+ const char* name,
1459
+ napi_addon_register_func fn,
1460
+ int32_t module_api_version = NODE_API_DEFAULT_MODULE_API_VERSION);
1461
+
1462
+ /* Registers a callback with the passed-in Environment instance. The callback
1463
+ * is called after the event loop exits, but before the VM is disposed.
1464
+ * Callbacks are run in reverse order of registration, i.e. newest first.
1465
+ */
1466
+ NODE_EXTERN void AtExit(Environment* env,
1467
+ void (*cb)(void* arg),
1468
+ void* arg);
1469
+
1470
+ typedef double async_id;
1471
+ struct async_context {
1472
+ ::node::async_id async_id;
1473
+ ::node::async_id trigger_async_id;
1474
+ };
1475
+
1476
+ /* This is a lot like node::AtExit, except that the hooks added via this
1477
+ * function are run before the AtExit ones and will always be registered
1478
+ * for the current Environment instance.
1479
+ * These functions are safe to use in an addon supporting multiple
1480
+ * threads/isolates. */
1481
+ NODE_EXTERN void AddEnvironmentCleanupHook(v8::Isolate* isolate,
1482
+ void (*fun)(void* arg),
1483
+ void* arg);
1484
+
1485
+ NODE_EXTERN void RemoveEnvironmentCleanupHook(v8::Isolate* isolate,
1486
+ void (*fun)(void* arg),
1487
+ void* arg);
1488
+
1489
+ /* These are async equivalents of the above. After the cleanup hook is invoked,
1490
+ * `cb(cbarg)` *must* be called, and attempting to remove the cleanup hook will
1491
+ * have no effect. */
1492
+ struct ACHHandle;
1493
+ struct NODE_EXTERN DeleteACHHandle { void operator()(ACHHandle*) const; };
1494
+ typedef std::unique_ptr<ACHHandle, DeleteACHHandle> AsyncCleanupHookHandle;
1495
+
1496
+ /* This function is not intended to be used externally, it exists to aid in
1497
+ * keeping ABI compatibility between Node and Electron. */
1498
+ NODE_EXTERN ACHHandle* AddEnvironmentCleanupHookInternal(
1499
+ v8::Isolate* isolate,
1500
+ void (*fun)(void* arg, void (*cb)(void*), void* cbarg),
1501
+ void* arg);
1502
+ inline AsyncCleanupHookHandle AddEnvironmentCleanupHook(
1503
+ v8::Isolate* isolate,
1504
+ void (*fun)(void* arg, void (*cb)(void*), void* cbarg),
1505
+ void* arg) {
1506
+ return AsyncCleanupHookHandle(AddEnvironmentCleanupHookInternal(isolate, fun,
1507
+ arg));
1508
+ }
1509
+
1510
+ /* This function is not intended to be used externally, it exists to aid in
1511
+ * keeping ABI compatibility between Node and Electron. */
1512
+ NODE_EXTERN void RemoveEnvironmentCleanupHookInternal(ACHHandle* holder);
1513
+ inline void RemoveEnvironmentCleanupHook(AsyncCleanupHookHandle holder) {
1514
+ RemoveEnvironmentCleanupHookInternal(holder.get());
1515
+ }
1516
+
1517
+ // This behaves like V8's Isolate::RequestInterrupt(), but also wakes up
1518
+ // the event loop if it is currently idle. Interrupt requests are drained
1519
+ // in `FreeEnvironment()`. The passed callback can not call back into
1520
+ // JavaScript.
1521
+ // This function can be called from any thread.
1522
+ NODE_EXTERN void RequestInterrupt(Environment* env,
1523
+ void (*fun)(void* arg),
1524
+ void* arg);
1525
+
1526
+ /* Returns the id of the current execution context. If the return value is
1527
+ * zero then no execution has been set. This will happen if the user handles
1528
+ * I/O from native code. */
1529
+ NODE_EXTERN async_id AsyncHooksGetExecutionAsyncId(v8::Isolate* isolate);
1530
+
1531
+ /* Returns the id of the current execution context. If the return value is
1532
+ * zero then no execution has been set. This will happen if the user handles
1533
+ * I/O from native code. */
1534
+ NODE_EXTERN async_id
1535
+ AsyncHooksGetExecutionAsyncId(v8::Local<v8::Context> context);
1536
+
1537
+ /* Return same value as async_hooks.triggerAsyncId(); */
1538
+ NODE_EXTERN async_id AsyncHooksGetTriggerAsyncId(v8::Isolate* isolate);
1539
+
1540
+ /* If the native API doesn't inherit from the helper class then the callbacks
1541
+ * must be triggered manually. This triggers the init() callback. The return
1542
+ * value is the async id assigned to the resource.
1543
+ *
1544
+ * The `trigger_async_id` parameter should correspond to the resource which is
1545
+ * creating the new resource, which will usually be the return value of
1546
+ * `AsyncHooksGetTriggerAsyncId()`. */
1547
+ NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate,
1548
+ v8::Local<v8::Object> resource,
1549
+ const char* name,
1550
+ async_id trigger_async_id = -1);
1551
+ NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate,
1552
+ v8::Local<v8::Object> resource,
1553
+ std::string_view name,
1554
+ async_id trigger_async_id = -1);
1555
+
1556
+ NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate,
1557
+ v8::Local<v8::Object> resource,
1558
+ v8::Local<v8::String> name,
1559
+ async_id trigger_async_id = -1);
1560
+
1561
+ /* Emit the destroy() callback. The overload taking an `Environment*` argument
1562
+ * should be used when the Isolate’s current Context is not associated with
1563
+ * a Node.js Environment, or when there is no current Context, for example
1564
+ * when calling this function during garbage collection. In that case, the
1565
+ * `Environment*` value should have been acquired previously, e.g. through
1566
+ * `GetCurrentEnvironment()`. */
1567
+ NODE_EXTERN void EmitAsyncDestroy(v8::Isolate* isolate,
1568
+ async_context asyncContext);
1569
+ NODE_EXTERN void EmitAsyncDestroy(Environment* env,
1570
+ async_context asyncContext);
1571
+
1572
+ class InternalCallbackScope;
1573
+
1574
+ /* This class works like `MakeCallback()` in that it sets up a specific
1575
+ * asyncContext as the current one and informs the async_hooks and domains
1576
+ * modules that this context is currently active.
1577
+ *
1578
+ * `MakeCallback()` is a wrapper around this class as well as
1579
+ * `Function::Call()`. Either one of these mechanisms needs to be used for
1580
+ * top-level calls into JavaScript (i.e. without any existing JS stack).
1581
+ *
1582
+ * This object should be stack-allocated to ensure that it is contained in a
1583
+ * valid HandleScope.
1584
+ *
1585
+ * Exceptions happening within this scope will be treated like uncaught
1586
+ * exceptions. If this behaviour is undesirable, a new `v8::TryCatch` scope
1587
+ * needs to be created inside of this scope.
1588
+ */
1589
+ class NODE_EXTERN CallbackScope {
1590
+ public:
1591
+ CallbackScope(v8::Isolate* isolate,
1592
+ v8::Local<v8::Object> resource,
1593
+ async_context asyncContext);
1594
+ CallbackScope(Environment* env,
1595
+ v8::Local<v8::Object> resource,
1596
+ async_context asyncContext);
1597
+ // `resource` needs to outlive the scope in this case.
1598
+ // This is for the rare situation in which `CallbackScope` cannot be
1599
+ // stack-allocated. `resource` needs to outlive this scope.
1600
+ CallbackScope(Environment* env,
1601
+ v8::Global<v8::Object>* resource,
1602
+ async_context asyncContext);
1603
+ ~CallbackScope();
1604
+
1605
+ void operator=(const CallbackScope&) = delete;
1606
+ void operator=(CallbackScope&&) = delete;
1607
+ CallbackScope(const CallbackScope&) = delete;
1608
+ CallbackScope(CallbackScope&&) = delete;
1609
+
1610
+ private:
1611
+ [[maybe_unused]] void* reserved_;
1612
+ union {
1613
+ v8::Local<v8::Object> local;
1614
+ v8::Global<v8::Object>* global_ptr;
1615
+ } resource_storage_;
1616
+ InternalCallbackScope* private_;
1617
+ v8::TryCatch try_catch_;
1618
+ };
1619
+
1620
+ /* An API specific to emit before/after callbacks is unnecessary because
1621
+ * MakeCallback will automatically call them for you.
1622
+ *
1623
+ * These methods may create handles on their own, so run them inside a
1624
+ * HandleScope.
1625
+ *
1626
+ * `asyncId` and `triggerAsyncId` should correspond to the values returned by
1627
+ * `EmitAsyncInit()` and `AsyncHooksGetTriggerAsyncId()`, respectively, when the
1628
+ * invoking resource was created. If these values are unknown, 0 can be passed.
1629
+ * */
1630
+ NODE_EXTERN
1631
+ v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
1632
+ v8::Local<v8::Object> recv,
1633
+ v8::Local<v8::Function> callback,
1634
+ int argc,
1635
+ v8::Local<v8::Value>* argv,
1636
+ async_context asyncContext);
1637
+ NODE_EXTERN
1638
+ v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
1639
+ v8::Local<v8::Object> recv,
1640
+ const char* method,
1641
+ int argc,
1642
+ v8::Local<v8::Value>* argv,
1643
+ async_context asyncContext);
1644
+ NODE_EXTERN
1645
+ v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
1646
+ v8::Local<v8::Object> recv,
1647
+ v8::Local<v8::String> symbol,
1648
+ int argc,
1649
+ v8::Local<v8::Value>* argv,
1650
+ async_context asyncContext);
1651
+
1652
+ /* Helper class users can optionally inherit from. If
1653
+ * `AsyncResource::MakeCallback()` is used, then all four callbacks will be
1654
+ * called automatically. */
1655
+ class NODE_EXTERN AsyncResource {
1656
+ public:
1657
+ AsyncResource(v8::Isolate* isolate,
1658
+ v8::Local<v8::Object> resource,
1659
+ const char* name,
1660
+ async_id trigger_async_id = -1);
1661
+ AsyncResource(v8::Isolate* isolate,
1662
+ v8::Local<v8::Object> resource,
1663
+ std::string_view name,
1664
+ async_id trigger_async_id = -1);
1665
+
1666
+ virtual ~AsyncResource();
1667
+
1668
+ AsyncResource(const AsyncResource&) = delete;
1669
+ void operator=(const AsyncResource&) = delete;
1670
+
1671
+ v8::MaybeLocal<v8::Value> MakeCallback(
1672
+ v8::Local<v8::Function> callback,
1673
+ int argc,
1674
+ v8::Local<v8::Value>* argv);
1675
+
1676
+ v8::MaybeLocal<v8::Value> MakeCallback(
1677
+ const char* method,
1678
+ int argc,
1679
+ v8::Local<v8::Value>* argv);
1680
+
1681
+ v8::MaybeLocal<v8::Value> MakeCallback(
1682
+ v8::Local<v8::String> symbol,
1683
+ int argc,
1684
+ v8::Local<v8::Value>* argv);
1685
+
1686
+ v8::Local<v8::Object> get_resource();
1687
+ async_id get_async_id() const;
1688
+ async_id get_trigger_async_id() const;
1689
+
1690
+ protected:
1691
+ class NODE_EXTERN CallbackScope : public node::CallbackScope {
1692
+ public:
1693
+ explicit CallbackScope(AsyncResource* res);
1694
+ };
1695
+
1696
+ private:
1697
+ Environment* env_;
1698
+ v8::Global<v8::Object> resource_;
1699
+ v8::Global<v8::Value> context_frame_;
1700
+ async_context async_context_;
1701
+ };
1702
+
1703
+ #ifndef _WIN32
1704
+ // Register a signal handler without interrupting any handlers that node
1705
+ // itself needs. This does override handlers registered through
1706
+ // process.on('SIG...', function() { ... }). The `reset_handler` flag indicates
1707
+ // whether the signal handler for the given signal should be reset to its
1708
+ // default value before executing the handler (i.e. it works like SA_RESETHAND).
1709
+ // The `reset_handler` flag is invalid when `signal` is SIGSEGV.
1710
+ NODE_EXTERN
1711
+ void RegisterSignalHandler(int signal,
1712
+ void (*handler)(int signal,
1713
+ siginfo_t* info,
1714
+ void* ucontext),
1715
+ bool reset_handler = false);
1716
+ #endif // _WIN32
1717
+
1718
+ // This is kept as a compatibility layer for addons to wrap cppgc-managed
1719
+ // objects on Node.js versions without v8::Object::Wrap(). Addons created to
1720
+ // work with only Node.js versions with v8::Object::Wrap() should use that
1721
+ // instead.
1722
+ NODE_DEPRECATED(
1723
+ "Use v8::Object::Wrap()",
1724
+ NODE_EXTERN void SetCppgcReference(v8::Isolate* isolate,
1725
+ v8::Local<v8::Object> object,
1726
+ v8::Object::Wrappable* wrappable));
1727
+
1728
+ namespace crypto {
1729
+
1730
+ // Returns the SSL_CTX* from a SecureContext JS object, as returned by
1731
+ // tls.createSecureContext().
1732
+ // Returns nullptr if the value is not a SecureContext instance,
1733
+ // or if Node.js was built without OpenSSL.
1734
+ //
1735
+ // The returned pointer is not owned by the caller and must not be freed.
1736
+ // It is valid only while the SecureContext JS object remains alive.
1737
+ NODE_EXTERN struct ssl_ctx_st* GetSSLCtx(v8::Local<v8::Context> context,
1738
+ v8::Local<v8::Value> secure_context);
1739
+
1740
+ } // namespace crypto
1741
+
1742
+ } // namespace node
1743
+
1744
+ #endif // SRC_NODE_H_