GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: node.h Lines: 13 13 100.0 %
Date: 2022-07-31 04:16:25 Branches: 1 2 50.0 %

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