GCC Code Coverage Report
Directory: ../ Exec Total Coverage
File: /home/iojs/build/workspace/node-test-commit-linux-coverage-daily/nodes/benchmark/out/../src/node_internals.h Lines: 44 49 89.8 %
Date: 2020-09-06 22:14:11 Branches: 29 38 76.3 %

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_INTERNALS_H_
23
#define SRC_NODE_INTERNALS_H_
24
25
#if defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
26
27
#include "env.h"
28
#include "node.h"
29
#include "node_binding.h"
30
#include "node_mutex.h"
31
#include "tracing/trace_event.h"
32
#include "util.h"
33
#include "uv.h"
34
#include "v8.h"
35
36
#include <cstdint>
37
#include <cstdlib>
38
39
#include <string>
40
#include <vector>
41
42
// Custom constants used by both node_constants.cc and node_zlib.cc
43
#define Z_MIN_WINDOWBITS 8
44
#define Z_MAX_WINDOWBITS 15
45
#define Z_DEFAULT_WINDOWBITS 15
46
47
struct sockaddr;
48
49
namespace node {
50
51
namespace native_module {
52
class NativeModuleLoader;
53
}
54
55
namespace per_process {
56
extern Mutex env_var_mutex;
57
extern uint64_t node_start_time;
58
}  // namespace per_process
59
60
// Forward declaration
61
class Environment;
62
63
// Convert a struct sockaddr to a { address: '1.2.3.4', port: 1234 } JS object.
64
// Sets address and port properties on the info object and returns it.
65
// If |info| is omitted, a new object is returned.
66
v8::Local<v8::Object> AddressToJS(
67
    Environment* env,
68
    const sockaddr* addr,
69
    v8::Local<v8::Object> info = v8::Local<v8::Object>());
70
71
template <typename T, int (*F)(const typename T::HandleType*, sockaddr*, int*)>
72
4069
void GetSockOrPeerName(const v8::FunctionCallbackInfo<v8::Value>& args) {
73
  T* wrap;
74

4069
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
75
                          args.Holder(),
76
                          args.GetReturnValue().Set(UV_EBADF));
77

8138
  CHECK(args[0]->IsObject());
78
  sockaddr_storage storage;
79
4069
  int addrlen = sizeof(storage);
80
4069
  sockaddr* const addr = reinterpret_cast<sockaddr*>(&storage);
81
4069
  const int err = F(&wrap->handle_, addr, &addrlen);
82

4069
  if (err == 0)
83
8128
    AddressToJS(wrap->env(), addr, args[0].As<v8::Object>());
84
8138
  args.GetReturnValue().Set(err);
85
}
86
87
void PrintStackTrace(v8::Isolate* isolate, v8::Local<v8::StackTrace> stack);
88
void PrintCaughtException(v8::Isolate* isolate,
89
                          v8::Local<v8::Context> context,
90
                          const v8::TryCatch& try_catch);
91
92
void ResetStdio();  // Safe to call more than once and from signal handlers.
93
#ifdef __POSIX__
94
void SignalExit(int signal, siginfo_t* info, void* ucontext);
95
#endif
96
97
std::string GetProcessTitle(const char* default_title);
98
std::string GetHumanReadableProcessName();
99
100
void InitializeContextRuntime(v8::Local<v8::Context>);
101
bool InitializePrimordials(v8::Local<v8::Context> context);
102
103
namespace task_queue {
104
void PromiseRejectCallback(v8::PromiseRejectMessage message);
105
}  // namespace task_queue
106
107
13712
class NodeArrayBufferAllocator : public ArrayBufferAllocator {
108
 public:
109
1343215
  inline uint32_t* zero_fill_field() { return &zero_fill_field_; }
110
111
  void* Allocate(size_t size) override;  // Defined in src/node.cc
112
  void* AllocateUninitialized(size_t size) override;
113
  void Free(void* data, size_t size) override;
114
  void* Reallocate(void* data, size_t old_size, size_t size) override;
115
  virtual void RegisterPointer(void* data, size_t size) {
116
    total_mem_usage_.fetch_add(size, std::memory_order_relaxed);
117
  }
118
  virtual void UnregisterPointer(void* data, size_t size) {
119
    total_mem_usage_.fetch_sub(size, std::memory_order_relaxed);
120
  }
121
122
4832
  NodeArrayBufferAllocator* GetImpl() final { return this; }
123
527
  inline uint64_t total_mem_usage() const {
124
1054
    return total_mem_usage_.load(std::memory_order_relaxed);
125
  }
126
127
 private:
128
  uint32_t zero_fill_field_ = 1;  // Boolean but exposed as uint32 to JS land.
129
  std::atomic<size_t> total_mem_usage_ {0};
130
};
131
132
3
class DebuggingArrayBufferAllocator final : public NodeArrayBufferAllocator {
133
 public:
134
  ~DebuggingArrayBufferAllocator() override;
135
  void* Allocate(size_t size) override;
136
  void* AllocateUninitialized(size_t size) override;
137
  void Free(void* data, size_t size) override;
138
  void* Reallocate(void* data, size_t old_size, size_t size) override;
139
  void RegisterPointer(void* data, size_t size) override;
140
  void UnregisterPointer(void* data, size_t size) override;
141
142
 private:
143
  void RegisterPointerInternal(void* data, size_t size);
144
  void UnregisterPointerInternal(void* data, size_t size);
145
  Mutex mutex_;
146
  std::unordered_map<void*, size_t> allocations_;
147
};
148
149
namespace Buffer {
150
v8::MaybeLocal<v8::Object> Copy(Environment* env, const char* data, size_t len);
151
v8::MaybeLocal<v8::Object> New(Environment* env, size_t size);
152
// Takes ownership of |data|.
153
v8::MaybeLocal<v8::Object> New(Environment* env,
154
                               char* data,
155
                               size_t length,
156
                               void (*callback)(char* data, void* hint),
157
                               void* hint);
158
// Takes ownership of |data|.  Must allocate |data| with the current Isolate's
159
// ArrayBuffer::Allocator().
160
v8::MaybeLocal<v8::Object> New(Environment* env,
161
                               char* data,
162
                               size_t length);
163
// Creates a Buffer instance over an existing ArrayBuffer.
164
v8::MaybeLocal<v8::Uint8Array> New(Environment* env,
165
                                   v8::Local<v8::ArrayBuffer> ab,
166
                                   size_t byte_offset,
167
                                   size_t length);
168
// Construct a Buffer from a MaybeStackBuffer (and also its subclasses like
169
// Utf8Value and TwoByteValue).
170
// If |buf| is invalidated, an empty MaybeLocal is returned, and nothing is
171
// changed.
172
// If |buf| contains actual data, this method takes ownership of |buf|'s
173
// underlying buffer. However, |buf| itself can be reused even after this call,
174
// but its capacity, if increased through AllocateSufficientStorage, is not
175
// guaranteed to stay the same.
176
template <typename T>
177
7622
static v8::MaybeLocal<v8::Object> New(Environment* env,
178
                                      MaybeStackBuffer<T>* buf) {
179
  v8::MaybeLocal<v8::Object> ret;
180
7622
  char* src = reinterpret_cast<char*>(buf->out());
181
7622
  const size_t len_in_bytes = buf->length() * sizeof(buf->out()[0]);
182
183

7622
  if (buf->IsAllocated())
184
72
    ret = New(env, src, len_in_bytes);
185

7550
  else if (!buf->IsInvalidated())
186
7550
    ret = Copy(env, src, len_in_bytes);
187
188

7622
  if (ret.IsEmpty())
189
    return ret;
190
191

7622
  if (buf->IsAllocated())
192
72
    buf->Release();
193
194
7622
  return ret;
195
}
196
}  // namespace Buffer
197
198
v8::MaybeLocal<v8::Value> InternalMakeCallback(
199
    Environment* env,
200
    v8::Local<v8::Object> resource,
201
    v8::Local<v8::Object> recv,
202
    const v8::Local<v8::Function> callback,
203
    int argc,
204
    v8::Local<v8::Value> argv[],
205
    async_context asyncContext);
206
207
class InternalCallbackScope {
208
 public:
209
  enum Flags {
210
    kNoFlags = 0,
211
    // Indicates whether 'before' and 'after' hooks should be skipped.
212
    kSkipAsyncHooks = 1,
213
    // Indicates whether nextTick and microtask queues should be skipped.
214
    // This should only be used when there is no call into JS in this scope.
215
    // (The HTTP parser also uses it for some weird backwards
216
    // compatibility issues, but it shouldn't.)
217
    kSkipTaskQueues = 2
218
  };
219
  InternalCallbackScope(Environment* env,
220
                        v8::Local<v8::Object> object,
221
                        const async_context& asyncContext,
222
                        int flags = kNoFlags);
223
  // Utility that can be used by AsyncWrap classes.
224
  explicit InternalCallbackScope(AsyncWrap* async_wrap, int flags = 0);
225
  ~InternalCallbackScope();
226
  void Close();
227
228
1256667
  inline bool Failed() const { return failed_; }
229
1049
  inline void MarkAsFailed() { failed_ = true; }
230
231
 private:
232
  Environment* env_;
233
  async_context async_context_;
234
  v8::Local<v8::Object> object_;
235
  bool skip_hooks_;
236
  bool skip_task_queues_;
237
  bool failed_ = false;
238
  bool pushed_ids_ = false;
239
  bool closed_ = false;
240
};
241
242
class DebugSealHandleScope {
243
 public:
244
1562950
  explicit inline DebugSealHandleScope(v8::Isolate* isolate = nullptr)
245
#ifdef DEBUG
246
    : actual_scope_(isolate != nullptr ? isolate : v8::Isolate::GetCurrent())
247
#endif
248
1562950
  {}
249
250
 private:
251
#ifdef DEBUG
252
  v8::SealHandleScope actual_scope_;
253
#endif
254
};
255
256
class ThreadPoolWork {
257
 public:
258
2591
  explicit inline ThreadPoolWork(Environment* env) : env_(env) {
259
2591
    CHECK_NOT_NULL(env);
260
2591
  }
261
2413
  inline virtual ~ThreadPoolWork() = default;
262
263
  inline void ScheduleWork();
264
  inline int CancelWork();
265
266
  virtual void DoThreadPoolWork() = 0;
267
  virtual void AfterThreadPoolWork(int status) = 0;
268
269
1981
  Environment* env() const { return env_; }
270
271
 private:
272
  Environment* env_;
273
  uv_work_t work_req_;
274
};
275
276
#define TRACING_CATEGORY_NODE "node"
277
#define TRACING_CATEGORY_NODE1(one)                                           \
278
    TRACING_CATEGORY_NODE ","                                                 \
279
    TRACING_CATEGORY_NODE "." #one
280
#define TRACING_CATEGORY_NODE2(one, two)                                      \
281
    TRACING_CATEGORY_NODE ","                                                 \
282
    TRACING_CATEGORY_NODE "." #one ","                                        \
283
    TRACING_CATEGORY_NODE "." #one "." #two
284
285
// Functions defined in node.cc that are exposed via the bootstrapper object
286
287
#if defined(__POSIX__) && !defined(__ANDROID__) && !defined(__CloudABI__)
288
#define NODE_IMPLEMENTS_POSIX_CREDENTIALS 1
289
#endif  // __POSIX__ && !defined(__ANDROID__) && !defined(__CloudABI__)
290
291
namespace credentials {
292
bool SafeGetenv(const char* key, std::string* text, Environment* env = nullptr);
293
}  // namespace credentials
294
295
void DefineZlibConstants(v8::Local<v8::Object> target);
296
v8::Isolate* NewIsolate(v8::Isolate::CreateParams* params,
297
                        uv_loop_t* event_loop,
298
                        MultiIsolatePlatform* platform);
299
// This overload automatically picks the right 'main_script_id' if no callback
300
// was provided by the embedder.
301
v8::MaybeLocal<v8::Value> StartExecution(Environment* env,
302
                                         StartExecutionCallback cb = nullptr);
303
v8::MaybeLocal<v8::Object> GetPerContextExports(v8::Local<v8::Context> context);
304
v8::MaybeLocal<v8::Value> ExecuteBootstrapper(
305
    Environment* env,
306
    const char* id,
307
    std::vector<v8::Local<v8::String>>* parameters,
308
    std::vector<v8::Local<v8::Value>>* arguments);
309
void MarkBootstrapComplete(const v8::FunctionCallbackInfo<v8::Value>& args);
310
311
8462
struct InitializationResult {
312
  int exit_code = 0;
313
  std::vector<std::string> args;
314
  std::vector<std::string> exec_args;
315
  bool early_return = false;
316
};
317
InitializationResult InitializeOncePerProcess(int argc, char** argv);
318
void TearDownOncePerProcess();
319
void SetIsolateErrorHandlers(v8::Isolate* isolate, const IsolateSettings& s);
320
void SetIsolateMiscHandlers(v8::Isolate* isolate, const IsolateSettings& s);
321
void SetIsolateCreateParamsForNode(v8::Isolate::CreateParams* params);
322
323
#if HAVE_INSPECTOR
324
namespace profiler {
325
void StartProfilers(Environment* env);
326
}
327
#endif  // HAVE_INSPECTOR
328
329
#ifdef __POSIX__
330
static constexpr unsigned kMaxSignal = 32;
331
#endif
332
333
bool HasSignalJSHandler(int signum);
334
335
#ifdef _WIN32
336
typedef SYSTEMTIME TIME_TYPE;
337
#else  // UNIX, OSX
338
typedef struct tm TIME_TYPE;
339
#endif
340
341
double GetCurrentTimeInMicroseconds();
342
int WriteFileSync(const char* path, uv_buf_t buf);
343
int WriteFileSync(v8::Isolate* isolate,
344
                  const char* path,
345
                  v8::Local<v8::String> string);
346
347
31
class DiagnosticFilename {
348
 public:
349
  static void LocalTime(TIME_TYPE* tm_struct);
350
351
  inline DiagnosticFilename(Environment* env,
352
                            const char* prefix,
353
                            const char* ext);
354
355
  inline DiagnosticFilename(uint64_t thread_id,
356
                            const char* prefix,
357
                            const char* ext);
358
359
  inline const char* operator*() const;
360
361
 private:
362
  static std::string MakeFilename(
363
      uint64_t thread_id,
364
      const char* prefix,
365
      const char* ext);
366
367
  std::string filename_;
368
};
369
370
class TraceEventScope {
371
 public:
372
899344
  TraceEventScope(const char* category,
373
                  const char* name,
374
899344
                  void* id) : category_(category), name_(name), id_(id) {
375

1798722
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(category_, name_, id_);
376
899361
  }
377
1798701
  ~TraceEventScope() {
378

1798716
    TRACE_EVENT_NESTABLE_ASYNC_END0(category_, name_, id_);
379
899358
  }
380
381
 private:
382
  const char* category_;
383
  const char* name_;
384
  void* id_;
385
};
386
387
namespace heap {
388
389
void DeleteHeapSnapshot(const v8::HeapSnapshot* snapshot);
390
using HeapSnapshotPointer =
391
  DeleteFnPtr<const v8::HeapSnapshot, DeleteHeapSnapshot>;
392
393
BaseObjectPtr<AsyncWrap> CreateHeapSnapshotStream(
394
    Environment* env, HeapSnapshotPointer&& snapshot);
395
}  // namespace heap
396
397
namespace fs {
398
std::string Basename(const std::string& str, const std::string& extension);
399
}  // namespace fs
400
401
}  // namespace node
402
403
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
404
405
#endif  // SRC_NODE_INTERNALS_H_