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