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