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