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: 47 50 94.0 %
Date: 2020-05-27 22:15:15 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
extern bool v8_is_profiling;
59
}  // namespace per_process
60
61
// Forward declaration
62
class Environment;
63
64
// Convert a struct sockaddr to a { address: '1.2.3.4', port: 1234 } JS object.
65
// Sets address and port properties on the info object and returns it.
66
// If |info| is omitted, a new object is returned.
67
v8::Local<v8::Object> AddressToJS(
68
    Environment* env,
69
    const sockaddr* addr,
70
    v8::Local<v8::Object> info = v8::Local<v8::Object>());
71
72
template <typename T, int (*F)(const typename T::HandleType*, sockaddr*, int*)>
73
3997
void GetSockOrPeerName(const v8::FunctionCallbackInfo<v8::Value>& args) {
74
  T* wrap;
75

3997
  ASSIGN_OR_RETURN_UNWRAP(&wrap,
76
                          args.Holder(),
77
                          args.GetReturnValue().Set(UV_EBADF));
78

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

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

7598
  if (buf->IsAllocated())
186
65
    ret = New(env, src, len_in_bytes, true);
187

7533
  else if (!buf->IsInvalidated())
188
7533
    ret = Copy(env, src, len_in_bytes);
189
190

7598
  if (ret.IsEmpty())
191
    return ret;
192
193

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

1666330
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(category_, name_, id_);
378
833165
  }
379
1666296
  ~TraceEventScope() {
380

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