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: 48 53 90.6 %
Date: 2020-11-21 04:10:54 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
4425
void GetSockOrPeerName(const v8::FunctionCallbackInfo<v8::Value>& args) {
73
  T* wrap;
74

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

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

4425
  if (err == 0)
83
8844
    AddressToJS(wrap->env(), addr, args[0].As<v8::Object>());
84
8850
  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
14238
class NodeArrayBufferAllocator : public ArrayBufferAllocator {
104
 public:
105
1307030
  inline uint32_t* zero_fill_field() { return &zero_fill_field_; }
106
107
  void* Allocate(size_t size) override;  // Defined in src/node.cc
108
  void* AllocateUninitialized(size_t size) override;
109
  void Free(void* data, size_t size) override;
110
  void* Reallocate(void* data, size_t old_size, size_t size) override;
111
  virtual void RegisterPointer(void* data, size_t size) {
112
    total_mem_usage_.fetch_add(size, std::memory_order_relaxed);
113
  }
114
  virtual void UnregisterPointer(void* data, size_t size) {
115
    total_mem_usage_.fetch_sub(size, std::memory_order_relaxed);
116
  }
117
118
5009
  NodeArrayBufferAllocator* GetImpl() final { return this; }
119
527
  inline uint64_t total_mem_usage() const {
120
1054
    return total_mem_usage_.load(std::memory_order_relaxed);
121
  }
122
123
 private:
124
  uint32_t zero_fill_field_ = 1;  // Boolean but exposed as uint32 to JS land.
125
  std::atomic<size_t> total_mem_usage_ {0};
126
};
127
128
3
class DebuggingArrayBufferAllocator final : public NodeArrayBufferAllocator {
129
 public:
130
  ~DebuggingArrayBufferAllocator() override;
131
  void* Allocate(size_t size) override;
132
  void* AllocateUninitialized(size_t size) override;
133
  void Free(void* data, size_t size) override;
134
  void* Reallocate(void* data, size_t old_size, size_t size) override;
135
  void RegisterPointer(void* data, size_t size) override;
136
  void UnregisterPointer(void* data, size_t size) override;
137
138
 private:
139
  void RegisterPointerInternal(void* data, size_t size);
140
  void UnregisterPointerInternal(void* data, size_t size);
141
  Mutex mutex_;
142
  std::unordered_map<void*, size_t> allocations_;
143
};
144
145
namespace Buffer {
146
v8::MaybeLocal<v8::Object> Copy(Environment* env, const char* data, size_t len);
147
v8::MaybeLocal<v8::Object> New(Environment* env, size_t size);
148
// Takes ownership of |data|.
149
v8::MaybeLocal<v8::Object> New(Environment* env,
150
                               char* data,
151
                               size_t length,
152
                               void (*callback)(char* data, void* hint),
153
                               void* hint);
154
// Takes ownership of |data|.  Must allocate |data| with the current Isolate's
155
// ArrayBuffer::Allocator().
156
v8::MaybeLocal<v8::Object> New(Environment* env,
157
                               char* data,
158
                               size_t length);
159
// Creates a Buffer instance over an existing ArrayBuffer.
160
v8::MaybeLocal<v8::Uint8Array> New(Environment* env,
161
                                   v8::Local<v8::ArrayBuffer> ab,
162
                                   size_t byte_offset,
163
                                   size_t length);
164
// Construct a Buffer from a MaybeStackBuffer (and also its subclasses like
165
// Utf8Value and TwoByteValue).
166
// If |buf| is invalidated, an empty MaybeLocal is returned, and nothing is
167
// changed.
168
// If |buf| contains actual data, this method takes ownership of |buf|'s
169
// underlying buffer. However, |buf| itself can be reused even after this call,
170
// but its capacity, if increased through AllocateSufficientStorage, is not
171
// guaranteed to stay the same.
172
template <typename T>
173
1218
static v8::MaybeLocal<v8::Object> New(Environment* env,
174
                                      MaybeStackBuffer<T>* buf) {
175
  v8::MaybeLocal<v8::Object> ret;
176
1218
  char* src = reinterpret_cast<char*>(buf->out());
177
1218
  const size_t len_in_bytes = buf->length() * sizeof(buf->out()[0]);
178
179

1218
  if (buf->IsAllocated())
180
78
    ret = New(env, src, len_in_bytes);
181

1140
  else if (!buf->IsInvalidated())
182
1140
    ret = Copy(env, src, len_in_bytes);
183
184

1218
  if (ret.IsEmpty())
185
    return ret;
186
187

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

3140715
  }
380
381
4682
 private:
382
1046983
  const char* category_;
383
164
  const char* name_;
384
82
  void* id_;
385
82
};
386
164
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
node_module napi_module_to_node_module(const napi_module* mod);
402
403
}  // namespace node
404
405
#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS
406
407
#endif  // SRC_NODE_INTERNALS_H_