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