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-07-19 22:14:24 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
10168
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
5334
class NODE_EXTERN IsolatePlatformDelegate {
284
 public:
285
  virtual std::shared_ptr<v8::TaskRunner> GetForegroundTaskRunner() = 0;
286
  virtual bool IdleTasksEnabled() = 0;
287
};
288
289
4935
class NODE_EXTERN MultiIsolatePlatform : public v8::Platform {
290
 public:
291
4928
  ~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
  // Set if Node.js should not run its own esm loader. This is needed by some
413
  // embedders, because it's possible for the Node.js esm loader to conflict
414
  // with another one in an embedder environment, e.g. Blink's in Chromium.
415
  kNoRegisterESMLoader = 1 << 3,
416
  // Set this flag to make Node.js track "raw" file descriptors, i.e. managed
417
  // by fs.open() and fs.close(), and close them during FreeEnvironment().
418
  kTrackUnmanagedFds = 1 << 4
419
};
420
}  // namespace EnvironmentFlags
421
422
563
struct InspectorParentHandle {
423
  virtual ~InspectorParentHandle();
424
};
425
426
// TODO(addaleax): Maybe move per-Environment options parsing here.
427
// Returns nullptr when the Environment cannot be created e.g. there are
428
// pending JavaScript exceptions.
429
// It is recommended to use the second variant taking a flags argument.
430
NODE_DEPRECATED("Use overload taking a flags argument",
431
    NODE_EXTERN Environment* CreateEnvironment(IsolateData* isolate_data,
432
                                               v8::Local<v8::Context> context,
433
                                               int argc,
434
                                               const char* const* argv,
435
                                               int exec_argc,
436
                                               const char* const* exec_argv));
437
NODE_EXTERN Environment* CreateEnvironment(
438
    IsolateData* isolate_data,
439
    v8::Local<v8::Context> context,
440
    const std::vector<std::string>& args,
441
    const std::vector<std::string>& exec_args,
442
    EnvironmentFlags::Flags flags = EnvironmentFlags::kDefaultFlags,
443
    ThreadId thread_id = {} /* allocates a thread id automatically */,
444
    std::unique_ptr<InspectorParentHandle> inspector_parent_handle = {});
445
446
// Returns a handle that can be passed to `LoadEnvironment()`, making the
447
// child Environment accessible to the inspector as if it were a Node.js Worker.
448
// `child_thread_id` can be created using `AllocateEnvironmentThreadId()`
449
// and then later passed on to `CreateEnvironment()` to create the child
450
// Environment, together with the inspector handle.
451
// This method should not be called while the parent Environment is active
452
// on another thread.
453
NODE_EXTERN std::unique_ptr<InspectorParentHandle> GetInspectorParentHandle(
454
    Environment* parent_env,
455
    ThreadId child_thread_id,
456
    const char* child_url);
457
458
struct StartExecutionCallbackInfo {
459
  v8::Local<v8::Object> process_object;
460
  v8::Local<v8::Function> native_require;
461
};
462
463
using StartExecutionCallback =
464
    std::function<v8::MaybeLocal<v8::Value>(const StartExecutionCallbackInfo&)>;
465
466
NODE_DEPRECATED("Use variants returning MaybeLocal<> instead",
467
    NODE_EXTERN void LoadEnvironment(Environment* env));
468
// The `InspectorParentHandle` arguments here are ignored and not used.
469
// For passing `InspectorParentHandle`, use `CreateEnvironment()`.
470
NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
471
    Environment* env,
472
    StartExecutionCallback cb,
473
    std::unique_ptr<InspectorParentHandle> ignored_donotuse_removeme = {});
474
NODE_EXTERN v8::MaybeLocal<v8::Value> LoadEnvironment(
475
    Environment* env,
476
    const char* main_script_source_utf8,
477
    std::unique_ptr<InspectorParentHandle> ignored_donotuse_removeme = {});
478
NODE_EXTERN void FreeEnvironment(Environment* env);
479
480
// Set a callback that is called when process.exit() is called from JS,
481
// overriding the default handler.
482
// It receives the Environment* instance and the exit code as arguments.
483
// This could e.g. call Stop(env); in order to terminate execution and stop
484
// the event loop.
485
// The default handler disposes of the global V8 platform instance, if one is
486
// being used, and calls exit().
487
NODE_EXTERN void SetProcessExitHandler(
488
    Environment* env,
489
    std::function<void(Environment*, int)>&& handler);
490
NODE_EXTERN void DefaultProcessExitHandler(Environment* env, int exit_code);
491
492
// This may return nullptr if context is not associated with a Node instance.
493
NODE_EXTERN Environment* GetCurrentEnvironment(v8::Local<v8::Context> context);
494
495
// This returns the MultiIsolatePlatform used in the main thread of Node.js.
496
// If NODE_USE_V8_PLATFORM has not been defined when Node.js was built,
497
// it returns nullptr.
498
NODE_DEPRECATED("Use GetMultiIsolatePlatform(env) instead",
499
    NODE_EXTERN MultiIsolatePlatform* GetMainThreadMultiIsolatePlatform());
500
// This returns the MultiIsolatePlatform used for an Environment or IsolateData
501
// instance, if one exists.
502
NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(Environment* env);
503
NODE_EXTERN MultiIsolatePlatform* GetMultiIsolatePlatform(IsolateData* env);
504
505
// Legacy variants of MultiIsolatePlatform::Create().
506
NODE_DEPRECATED("Use variant taking a v8::TracingController* pointer instead",
507
    NODE_EXTERN MultiIsolatePlatform* CreatePlatform(
508
        int thread_pool_size,
509
        node::tracing::TracingController* tracing_controller));
510
NODE_EXTERN MultiIsolatePlatform* CreatePlatform(
511
    int thread_pool_size,
512
    v8::TracingController* tracing_controller);
513
NODE_EXTERN void FreePlatform(MultiIsolatePlatform* platform);
514
515
// Get/set the currently active tracing controller. Using CreatePlatform()
516
// will implicitly set this by default. This is global and should be initialized
517
// along with the v8::Platform instance that is being used. `controller`
518
// is allowed to be `nullptr`.
519
// This is used for tracing events from Node.js itself. V8 uses the tracing
520
// controller returned from the active `v8::Platform` instance.
521
NODE_EXTERN v8::TracingController* GetTracingController();
522
NODE_EXTERN void SetTracingController(v8::TracingController* controller);
523
524
NODE_EXTERN void EmitBeforeExit(Environment* env);
525
NODE_EXTERN int EmitExit(Environment* env);
526
NODE_EXTERN void RunAtExit(Environment* env);
527
528
// This may return nullptr if the current v8::Context is not associated
529
// with a Node instance.
530
NODE_EXTERN struct uv_loop_s* GetCurrentEventLoop(v8::Isolate* isolate);
531
532
/* Converts a unixtime to V8 Date */
533
NODE_DEPRECATED("Use v8::Date::New() directly",
534
                inline v8::Local<v8::Value> NODE_UNIXTIME_V8(double time) {
535
                  return v8::Date::New(
536
                             v8::Isolate::GetCurrent()->GetCurrentContext(),
537
                             1000 * time)
538
                      .ToLocalChecked();
539
                })
540
#define NODE_UNIXTIME_V8 node::NODE_UNIXTIME_V8
541
NODE_DEPRECATED("Use v8::Date::ValueOf() directly",
542
                inline double NODE_V8_UNIXTIME(v8::Local<v8::Date> date) {
543
  return date->ValueOf() / 1000;
544
})
545
#define NODE_V8_UNIXTIME node::NODE_V8_UNIXTIME
546
547
#define NODE_DEFINE_CONSTANT(target, constant)                                \
548
  do {                                                                        \
549
    v8::Isolate* isolate = target->GetIsolate();                              \
550
    v8::Local<v8::Context> context = isolate->GetCurrentContext();            \
551
    v8::Local<v8::String> constant_name =                                     \
552
        v8::String::NewFromUtf8(isolate, #constant,                           \
553
            v8::NewStringType::kInternalized).ToLocalChecked();               \
554
    v8::Local<v8::Number> constant_value =                                    \
555
        v8::Number::New(isolate, static_cast<double>(constant));              \
556
    v8::PropertyAttribute constant_attributes =                               \
557
        static_cast<v8::PropertyAttribute>(v8::ReadOnly | v8::DontDelete);    \
558
    (target)->DefineOwnProperty(context,                                      \
559
                                constant_name,                                \
560
                                constant_value,                               \
561
                                constant_attributes).Check();                 \
562
  }                                                                           \
563
  while (0)
564
565
#define NODE_DEFINE_HIDDEN_CONSTANT(target, constant)                         \
566
  do {                                                                        \
567
    v8::Isolate* isolate = target->GetIsolate();                              \
568
    v8::Local<v8::Context> context = isolate->GetCurrentContext();            \
569
    v8::Local<v8::String> constant_name =                                     \
570
        v8::String::NewFromUtf8(isolate, #constant,                           \
571
                                v8::NewStringType::kInternalized)             \
572
                                  .ToLocalChecked();                          \
573
    v8::Local<v8::Number> constant_value =                                    \
574
        v8::Number::New(isolate, static_cast<double>(constant));              \
575
    v8::PropertyAttribute constant_attributes =                               \
576
        static_cast<v8::PropertyAttribute>(v8::ReadOnly |                     \
577
                                           v8::DontDelete |                   \
578
                                           v8::DontEnum);                     \
579
    (target)->DefineOwnProperty(context,                                      \
580
                                constant_name,                                \
581
                                constant_value,                               \
582
                                constant_attributes).Check();                 \
583
  }                                                                           \
584
  while (0)
585
586
// Used to be a macro, hence the uppercase name.
587
inline void NODE_SET_METHOD(v8::Local<v8::Template> recv,
588
                            const char* name,
589
                            v8::FunctionCallback callback) {
590
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
591
  v8::HandleScope handle_scope(isolate);
592
  v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate,
593
                                                                callback);
594
  v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
595
      v8::NewStringType::kInternalized).ToLocalChecked();
596
  t->SetClassName(fn_name);
597
  recv->Set(fn_name, t);
598
}
599
600
// Used to be a macro, hence the uppercase name.
601
inline void NODE_SET_METHOD(v8::Local<v8::Object> recv,
602
                            const char* name,
603
                            v8::FunctionCallback callback) {
604
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
605
  v8::HandleScope handle_scope(isolate);
606
  v8::Local<v8::Context> context = isolate->GetCurrentContext();
607
  v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate,
608
                                                                callback);
609
  v8::Local<v8::Function> fn = t->GetFunction(context).ToLocalChecked();
610
  v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
611
      v8::NewStringType::kInternalized).ToLocalChecked();
612
  fn->SetName(fn_name);
613
  recv->Set(context, fn_name, fn).Check();
614
}
615
#define NODE_SET_METHOD node::NODE_SET_METHOD
616
617
// Used to be a macro, hence the uppercase name.
618
// Not a template because it only makes sense for FunctionTemplates.
619
inline void NODE_SET_PROTOTYPE_METHOD(v8::Local<v8::FunctionTemplate> recv,
620
                                      const char* name,
621
                                      v8::FunctionCallback callback) {
622
  v8::Isolate* isolate = v8::Isolate::GetCurrent();
623
  v8::HandleScope handle_scope(isolate);
624
  v8::Local<v8::Signature> s = v8::Signature::New(isolate, recv);
625
  v8::Local<v8::FunctionTemplate> t =
626
      v8::FunctionTemplate::New(isolate, callback, v8::Local<v8::Value>(), s);
627
  v8::Local<v8::String> fn_name = v8::String::NewFromUtf8(isolate, name,
628
      v8::NewStringType::kInternalized).ToLocalChecked();
629
  t->SetClassName(fn_name);
630
  recv->PrototypeTemplate()->Set(fn_name, t);
631
}
632
#define NODE_SET_PROTOTYPE_METHOD node::NODE_SET_PROTOTYPE_METHOD
633
634
// BINARY is a deprecated alias of LATIN1.
635
enum encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER, LATIN1 = BINARY};
636
637
NODE_EXTERN enum encoding ParseEncoding(
638
    v8::Isolate* isolate,
639
    v8::Local<v8::Value> encoding_v,
640
    enum encoding default_encoding = LATIN1);
641
642
NODE_EXTERN void FatalException(v8::Isolate* isolate,
643
                                const v8::TryCatch& try_catch);
644
645
NODE_EXTERN v8::Local<v8::Value> Encode(v8::Isolate* isolate,
646
                                        const char* buf,
647
                                        size_t len,
648
                                        enum encoding encoding = LATIN1);
649
650
// Warning: This reverses endianness on Big Endian platforms, even though the
651
// signature using uint16_t implies that it should not.
652
NODE_EXTERN v8::Local<v8::Value> Encode(v8::Isolate* isolate,
653
                                        const uint16_t* buf,
654
                                        size_t len);
655
656
// Returns -1 if the handle was not valid for decoding
657
NODE_EXTERN ssize_t DecodeBytes(v8::Isolate* isolate,
658
                                v8::Local<v8::Value>,
659
                                enum encoding encoding = LATIN1);
660
// returns bytes written.
661
NODE_EXTERN ssize_t DecodeWrite(v8::Isolate* isolate,
662
                                char* buf,
663
                                size_t buflen,
664
                                v8::Local<v8::Value>,
665
                                enum encoding encoding = LATIN1);
666
#ifdef _WIN32
667
NODE_EXTERN v8::Local<v8::Value> WinapiErrnoException(
668
    v8::Isolate* isolate,
669
    int errorno,
670
    const char* syscall = nullptr,
671
    const char* msg = "",
672
    const char* path = nullptr);
673
#endif
674
675
const char* signo_string(int errorno);
676
677
678
typedef void (*addon_register_func)(
679
    v8::Local<v8::Object> exports,
680
    v8::Local<v8::Value> module,
681
    void* priv);
682
683
typedef void (*addon_context_register_func)(
684
    v8::Local<v8::Object> exports,
685
    v8::Local<v8::Value> module,
686
    v8::Local<v8::Context> context,
687
    void* priv);
688
689
enum ModuleFlags {
690
  kLinked = 0x02
691
};
692
693
struct node_module {
694
  int nm_version;
695
  unsigned int nm_flags;
696
  void* nm_dso_handle;
697
  const char* nm_filename;
698
  node::addon_register_func nm_register_func;
699
  node::addon_context_register_func nm_context_register_func;
700
  const char* nm_modname;
701
  void* nm_priv;
702
  struct node_module* nm_link;
703
};
704
705
extern "C" NODE_EXTERN void node_module_register(void* mod);
706
707
#ifdef _WIN32
708
# define NODE_MODULE_EXPORT __declspec(dllexport)
709
#else
710
# define NODE_MODULE_EXPORT __attribute__((visibility("default")))
711
#endif
712
713
#ifdef NODE_SHARED_MODE
714
# define NODE_CTOR_PREFIX
715
#else
716
# define NODE_CTOR_PREFIX static
717
#endif
718
719
#if defined(_MSC_VER)
720
#pragma section(".CRT$XCU", read)
721
#define NODE_C_CTOR(fn)                                               \
722
  NODE_CTOR_PREFIX void __cdecl fn(void);                             \
723
  __declspec(dllexport, allocate(".CRT$XCU"))                         \
724
      void (__cdecl*fn ## _)(void) = fn;                              \
725
  NODE_CTOR_PREFIX void __cdecl fn(void)
726
#else
727
#define NODE_C_CTOR(fn)                                               \
728
  NODE_CTOR_PREFIX void fn(void) __attribute__((constructor));        \
729
  NODE_CTOR_PREFIX void fn(void)
730
#endif
731
732
#define NODE_MODULE_X(modname, regfunc, priv, flags)                  \
733
  extern "C" {                                                        \
734
    static node::node_module _module =                                \
735
    {                                                                 \
736
      NODE_MODULE_VERSION,                                            \
737
      flags,                                                          \
738
      NULL,  /* NOLINT (readability/null_usage) */                    \
739
      __FILE__,                                                       \
740
      (node::addon_register_func) (regfunc),                          \
741
      NULL,  /* NOLINT (readability/null_usage) */                    \
742
      NODE_STRINGIFY(modname),                                        \
743
      priv,                                                           \
744
      NULL   /* NOLINT (readability/null_usage) */                    \
745
    };                                                                \
746
    NODE_C_CTOR(_register_ ## modname) {                              \
747
      node_module_register(&_module);                                 \
748
    }                                                                 \
749
  }
750
751
#define NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, priv, flags)    \
752
  extern "C" {                                                        \
753
    static node::node_module _module =                                \
754
    {                                                                 \
755
      NODE_MODULE_VERSION,                                            \
756
      flags,                                                          \
757
      NULL,  /* NOLINT (readability/null_usage) */                    \
758
      __FILE__,                                                       \
759
      NULL,  /* NOLINT (readability/null_usage) */                    \
760
      (node::addon_context_register_func) (regfunc),                  \
761
      NODE_STRINGIFY(modname),                                        \
762
      priv,                                                           \
763
      NULL  /* NOLINT (readability/null_usage) */                     \
764
    };                                                                \
765
    NODE_C_CTOR(_register_ ## modname) {                              \
766
      node_module_register(&_module);                                 \
767
    }                                                                 \
768
  }
769
770
// Usage: `NODE_MODULE(NODE_GYP_MODULE_NAME, InitializerFunction)`
771
// If no NODE_MODULE is declared, Node.js looks for the well-known
772
// symbol `node_register_module_v${NODE_MODULE_VERSION}`.
773
#define NODE_MODULE(modname, regfunc)                                 \
774
  NODE_MODULE_X(modname, regfunc, NULL, 0)  // NOLINT (readability/null_usage)
775
776
#define NODE_MODULE_CONTEXT_AWARE(modname, regfunc)                   \
777
  /* NOLINTNEXTLINE (readability/null_usage) */                       \
778
  NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL, 0)
779
780
// Embedders can use this type of binding for statically linked native bindings.
781
// It is used the same way addon bindings are used, except that linked bindings
782
// can be accessed through `process._linkedBinding(modname)`.
783
#define NODE_MODULE_LINKED(modname, regfunc)                               \
784
  /* NOLINTNEXTLINE (readability/null_usage) */                            \
785
  NODE_MODULE_CONTEXT_AWARE_X(modname, regfunc, NULL,                      \
786
                              node::ModuleFlags::kLinked)
787
788
/*
789
 * For backward compatibility in add-on modules.
790
 */
791
#define NODE_MODULE_DECL /* nothing */
792
793
#define NODE_MODULE_INITIALIZER_BASE node_register_module_v
794
795
#define NODE_MODULE_INITIALIZER_X(base, version)                      \
796
    NODE_MODULE_INITIALIZER_X_HELPER(base, version)
797
798
#define NODE_MODULE_INITIALIZER_X_HELPER(base, version) base##version
799
800
#define NODE_MODULE_INITIALIZER                                       \
801
  NODE_MODULE_INITIALIZER_X(NODE_MODULE_INITIALIZER_BASE,             \
802
      NODE_MODULE_VERSION)
803
804
#define NODE_MODULE_INIT()                                            \
805
  extern "C" NODE_MODULE_EXPORT void                                  \
806
  NODE_MODULE_INITIALIZER(v8::Local<v8::Object> exports,              \
807
                          v8::Local<v8::Value> module,                \
808
                          v8::Local<v8::Context> context);            \
809
  NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME,                     \
810
                            NODE_MODULE_INITIALIZER)                  \
811
  void NODE_MODULE_INITIALIZER(v8::Local<v8::Object> exports,         \
812
                               v8::Local<v8::Value> module,           \
813
                               v8::Local<v8::Context> context)
814
815
// Allows embedders to add a binding to the current Environment* that can be
816
// accessed through process._linkedBinding() in the target Environment and all
817
// Worker threads that it creates.
818
// In each variant, the registration function needs to be usable at least for
819
// the time during which the Environment exists.
820
NODE_EXTERN void AddLinkedBinding(Environment* env, const node_module& mod);
821
NODE_EXTERN void AddLinkedBinding(Environment* env,
822
                                  const char* name,
823
                                  addon_context_register_func fn,
824
                                  void* priv);
825
826
/* Called after the event loop exits but before the VM is disposed.
827
 * Callbacks are run in reverse order of registration, i.e. newest first.
828
 *
829
 * You should always use the three-argument variant (or, for addons,
830
 * AddEnvironmentCleanupHook) in order to avoid relying on global state.
831
 */
832
NODE_DEPRECATED(
833
    "Use the three-argument variant of AtExit() or AddEnvironmentCleanupHook()",
834
    NODE_EXTERN void AtExit(void (*cb)(void* arg), void* arg = nullptr));
835
836
/* Registers a callback with the passed-in Environment instance. The callback
837
 * is called after the event loop exits, but before the VM is disposed.
838
 * Callbacks are run in reverse order of registration, i.e. newest first.
839
 */
840
NODE_EXTERN void AtExit(Environment* env,
841
                        void (*cb)(void* arg),
842
                        void* arg);
843
5
NODE_DEPRECATED(
844
    "Use the three-argument variant of AtExit() or AddEnvironmentCleanupHook()",
845
    inline void AtExit(Environment* env,
846
                       void (*cb)(void* arg)) {
847
      AtExit(env, cb, nullptr);
848
    })
849
850
typedef double async_id;
851
struct async_context {
852
  ::node::async_id async_id;
853
  ::node::async_id trigger_async_id;
854
};
855
856
/* This is a lot like node::AtExit, except that the hooks added via this
857
 * function are run before the AtExit ones and will always be registered
858
 * for the current Environment instance.
859
 * These functions are safe to use in an addon supporting multiple
860
 * threads/isolates. */
861
NODE_EXTERN void AddEnvironmentCleanupHook(v8::Isolate* isolate,
862
                                           void (*fun)(void* arg),
863
                                           void* arg);
864
865
NODE_EXTERN void RemoveEnvironmentCleanupHook(v8::Isolate* isolate,
866
                                              void (*fun)(void* arg),
867
                                              void* arg);
868
869
/* Returns the id of the current execution context. If the return value is
870
 * zero then no execution has been set. This will happen if the user handles
871
 * I/O from native code. */
872
NODE_EXTERN async_id AsyncHooksGetExecutionAsyncId(v8::Isolate* isolate);
873
874
/* Return same value as async_hooks.triggerAsyncId(); */
875
NODE_EXTERN async_id AsyncHooksGetTriggerAsyncId(v8::Isolate* isolate);
876
877
/* If the native API doesn't inherit from the helper class then the callbacks
878
 * must be triggered manually. This triggers the init() callback. The return
879
 * value is the async id assigned to the resource.
880
 *
881
 * The `trigger_async_id` parameter should correspond to the resource which is
882
 * creating the new resource, which will usually be the return value of
883
 * `AsyncHooksGetTriggerAsyncId()`. */
884
NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate,
885
                                        v8::Local<v8::Object> resource,
886
                                        const char* name,
887
                                        async_id trigger_async_id = -1);
888
889
NODE_EXTERN async_context EmitAsyncInit(v8::Isolate* isolate,
890
                                        v8::Local<v8::Object> resource,
891
                                        v8::Local<v8::String> name,
892
                                        async_id trigger_async_id = -1);
893
894
/* Emit the destroy() callback. The overload taking an `Environment*` argument
895
 * should be used when the Isolate’s current Context is not associated with
896
 * a Node.js Environment, or when there is no current Context, for example
897
 * when calling this function during garbage collection. In that case, the
898
 * `Environment*` value should have been acquired previously, e.g. through
899
 * `GetCurrentEnvironment()`. */
900
NODE_EXTERN void EmitAsyncDestroy(v8::Isolate* isolate,
901
                                  async_context asyncContext);
902
NODE_EXTERN void EmitAsyncDestroy(Environment* env,
903
                                  async_context asyncContext);
904
905
class InternalCallbackScope;
906
907
/* This class works like `MakeCallback()` in that it sets up a specific
908
 * asyncContext as the current one and informs the async_hooks and domains
909
 * modules that this context is currently active.
910
 *
911
 * `MakeCallback()` is a wrapper around this class as well as
912
 * `Function::Call()`. Either one of these mechanisms needs to be used for
913
 * top-level calls into JavaScript (i.e. without any existing JS stack).
914
 *
915
 * This object should be stack-allocated to ensure that it is contained in a
916
 * valid HandleScope.
917
 *
918
 * Exceptions happening within this scope will be treated like uncaught
919
 * exceptions. If this behaviour is undesirable, a new `v8::TryCatch` scope
920
 * needs to be created inside of this scope.
921
 */
922
class NODE_EXTERN CallbackScope {
923
 public:
924
  CallbackScope(v8::Isolate* isolate,
925
                v8::Local<v8::Object> resource,
926
                async_context asyncContext);
927
  ~CallbackScope();
928
929
  void operator=(const CallbackScope&) = delete;
930
  void operator=(CallbackScope&&) = delete;
931
  CallbackScope(const CallbackScope&) = delete;
932
  CallbackScope(CallbackScope&&) = delete;
933
934
 private:
935
  InternalCallbackScope* private_;
936
  v8::TryCatch try_catch_;
937
};
938
939
/* An API specific to emit before/after callbacks is unnecessary because
940
 * MakeCallback will automatically call them for you.
941
 *
942
 * These methods may create handles on their own, so run them inside a
943
 * HandleScope.
944
 *
945
 * `asyncId` and `triggerAsyncId` should correspond to the values returned by
946
 * `EmitAsyncInit()` and `AsyncHooksGetTriggerAsyncId()`, respectively, when the
947
 * invoking resource was created. If these values are unknown, 0 can be passed.
948
 * */
949
NODE_EXTERN
950
v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
951
                                       v8::Local<v8::Object> recv,
952
                                       v8::Local<v8::Function> callback,
953
                                       int argc,
954
                                       v8::Local<v8::Value>* argv,
955
                                       async_context asyncContext);
956
NODE_EXTERN
957
v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
958
                                       v8::Local<v8::Object> recv,
959
                                       const char* method,
960
                                       int argc,
961
                                       v8::Local<v8::Value>* argv,
962
                                       async_context asyncContext);
963
NODE_EXTERN
964
v8::MaybeLocal<v8::Value> MakeCallback(v8::Isolate* isolate,
965
                                       v8::Local<v8::Object> recv,
966
                                       v8::Local<v8::String> symbol,
967
                                       int argc,
968
                                       v8::Local<v8::Value>* argv,
969
                                       async_context asyncContext);
970
971
/* Helper class users can optionally inherit from. If
972
 * `AsyncResource::MakeCallback()` is used, then all four callbacks will be
973
 * called automatically. */
974
class NODE_EXTERN AsyncResource {
975
 public:
976
  AsyncResource(v8::Isolate* isolate,
977
                v8::Local<v8::Object> resource,
978
                const char* name,
979
                async_id trigger_async_id = -1);
980
981
  virtual ~AsyncResource();
982
983
  AsyncResource(const AsyncResource&) = delete;
984
  void operator=(const AsyncResource&) = delete;
985
986
  v8::MaybeLocal<v8::Value> MakeCallback(
987
      v8::Local<v8::Function> callback,
988
      int argc,
989
      v8::Local<v8::Value>* argv);
990
991
  v8::MaybeLocal<v8::Value> MakeCallback(
992
      const char* method,
993
      int argc,
994
      v8::Local<v8::Value>* argv);
995
996
  v8::MaybeLocal<v8::Value> MakeCallback(
997
      v8::Local<v8::String> symbol,
998
      int argc,
999
      v8::Local<v8::Value>* argv);
1000
1001
  v8::Local<v8::Object> get_resource();
1002
  async_id get_async_id() const;
1003
  async_id get_trigger_async_id() const;
1004
1005
 protected:
1006
638
  class NODE_EXTERN CallbackScope : public node::CallbackScope {
1007
   public:
1008
    explicit CallbackScope(AsyncResource* res);
1009
  };
1010
1011
 private:
1012
  Environment* env_;
1013
  v8::Global<v8::Object> resource_;
1014
  async_context async_context_;
1015
};
1016
1017
#ifndef _WIN32
1018
// Register a signal handler without interrupting any handlers that node
1019
// itself needs. This does override handlers registered through
1020
// process.on('SIG...', function() { ... }). The `reset_handler` flag indicates
1021
// whether the signal handler for the given signal should be reset to its
1022
// default value before executing the handler (i.e. it works like SA_RESETHAND).
1023
// The `reset_handler` flag is invalid when `signal` is SIGSEGV.
1024
NODE_EXTERN
1025
void RegisterSignalHandler(int signal,
1026
                           void (*handler)(int signal,
1027
                                           siginfo_t* info,
1028
                                           void* ucontext),
1029
                           bool reset_handler = false);
1030
#endif  // _WIN32
1031
1032
}  // namespace node
1033
1034
#endif  // SRC_NODE_H_